/* Copyright 2009 Palm, Inc.  All rights reserved. */

var SoundsalertsconfigAssistant = Class.create({
	
	initialize: function() {
		
	},
	
	ToggleOpt: {
        modelProperty: 'value',
        enableProp: 'enabled',        
    },
    
    vibrateOffModel: {
        value: 'vibrate',
    },
	
	vibrateOnModel: {
        value: 'vibrate',
    },
	
	systemUISoundsModel: {
        value: true,
    },
			
	vibrateChargingModel: {
        value: true,
    },
	
	//Model for Timer Selection List
	soundOptionModel: {'value': 'Always'},
	
	//Available Timer Values.
	availableOptions: [{label: $L('Ringer switch controls sounds'), value:"RingerOn"},{label: $L('Always play sounds'), value:"Always"},{label: $L('Never play sounds'), value:"Never"}],
	
	//Available Timer Values.
	availableOffSettings: [{label: $L('Vibrate'), value:'vibrate'},{label: $L('Mute'), value:'mute'}],
	availableOnSettings: [{label: $L('Sound & Vibrate'), value:'vibrate'},{label: $L('Sound'), value:'mute'}],
	
	setup: function() {
		this.attributes = {
			modelProperty: 'value',
			maxValue: 100,
			minValue: 0,
			round: true
		};
		this.attributes1 = {
			modelProperty: 'value',
			maxValue: 100,
			minValue: 0,
			round: true
		};
				
    	this.ringtoneVolumeModel = {
     	 'value' : 50
  		  };
		  
		 this.systemVolumeModel = {
     	 'value' : 50
  		  };
		  
		/*this.controller.setupWidget('soundWhenCharging', {
			choices: this.availableOptions,
			modelProperty: 'value'
		}, this.soundOptionModel);
		
		$('soundWhenCharging').observe('mojo-property-change', this.handleSelection.bindAsEventListener(this));*/
	
        this.controller.setupWidget('ringvolume', this.attributes,this.ringtoneVolumeModel);
		this.controller.setupWidget('systemvolume', this.attributes1,this.systemVolumeModel);
		$('ringvolume').observe('mojo-property-change', this.handleRingtoneVolumeChange.bindAsEventListener(this));
		$('systemvolume').observe('mojo-property-change', this.handleSystemVolumeChange.bindAsEventListener(this));
				
	
		//added to the assistant so that the when charging vibrate widget is shown
		//this.controller.setupWidget('vibrate_off', this.ToggleOpt, this.vibrateOffModel);
		this.controller.setupWidget('vibrate_off', {
			label: $L("Rings & Alerts"),
			choices: this.availableOffSettings,
			modelProperty: 'value',
			multiline: true
		}, this.vibrateOffModel);
		
		//this.controller.setupWidget('vibrate_on', this.ToggleOpt, this.vibrateOnModel);
		this.controller.setupWidget('vibrate_on', {
			label: $L("Rings & Alerts"),
			choices: this.availableOnSettings,
			modelProperty: 'value',
			multiline: true
		}, this.vibrateOnModel);
		
		this.controller.setupWidget('system_ui_sounds', this.ToggleOpt, this.systemUISoundsModel);
			
		$('vibrate_off').observe('mojo-property-change', this.toggleVibrateOff.bindAsEventListener(this));
		$('vibrate_on').observe('mojo-property-change', this.toggleVibrateOn.bindAsEventListener(this));
		$('system_ui_sounds').observe('mojo-property-change', this.toggleSystemUISounds.bindAsEventListener(this));
		
		$('currentringtonerow').observe(Mojo.Event.tap, this.showAudioFilePicker.bindAsEventListener(this));
				
		this.getCurrentVolumes();
		this.getCurrentRingtone();
		this.getVibrateSettings();	
		this.getOtherSettings();
		
		//App Menu - Remove default items and add only Edit & Help items.
		var appMenuModel = {
	        visible: true,
	        items: [Mojo.Menu.editItem,{label:$L('Help'), command:Mojo.Menu.helpCmd}
	            ]
	        };
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, appMenuModel);								
	},
	
	cleanup : function() {
		if(this.getRingtoneVolumeSubscribe)
			this.getRingtoneVolumeSubscribe.cancel();
	},	
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			if(event.command == Mojo.Menu.helpCmd) {
				this.controller.serviceRequest('palm://com.palm.applicationManager', {
					method: 'open',
					parameters: {'id': 'com.palm.app.help',params: {'target': 'http://help.palm.com/sounds_ringtones/index.html'}}});
			}
		}
	},	
	
	
	toggleVibrateOff: function(event) {
		
		if(!event || !event.value)
			return;
		
		var vibrateOff = event.value == "vibrate" ? true : false;
		var vibrateOn = this.vibrateOnModel.value == 'vibrate' ? true : false; 
				
		AudioService.setVibrateSettings(vibrateOn,vibrateOff,null,this);
	},
	
	toggleVibrateOn: function(event) {
		if(!event)
			return;
		
		var vibrateOff = this.vibrateOffModel.value == "vibrate" ? true : false;
		var vibrateOn = event.value == "vibrate" ? true : false;
		
		AudioService.setVibrateSettings(vibrateOn,vibrateOff,null,this);
	},
	
	handleRingtoneVolumeChange: function(event) {
		if(event.value == undefined)
			return;
		this.setRingtoneVolumeReq = AudioService.setRingtoneVolume(event.value,this.setVolumeDone.bind(this),this);		
	},
		
	setVolumeDone: function() {		
		try{                                                                                                       
               if (this.ringtonePlayerTimer) {
			   	this.controller.window.clearTimeout(this.ringtonePlayerTimer);
			   	this.audio.pause();
			   	this.audio.currentTime = 0;
			   }                                           
           }catch(e) {}                                                          
           this.ringtonePlayerTimer = null;                                             
		   if (!this.audio) {                                                                                       
                 this.audio = new Audio();                                            
                 this.audio.addEventListener('play', this.playEvent.bindAsEventListener(this));
				 this.audio.addEventListener('x-palm-connect', this.audioConnectedEvent.bindAsEventListener(this));
				 this.audio.addEventListener('x-palm-disconnect', this.audioDisconnectedEvent.bindAsEventListener(this));
			}                                                                                     
            else {                                                                                
                 if(this.audio.currentSrc != this.currRingtonePath) {                                                                          
                    this.audio.src = this.currRingtonePath;                                                                                    
                    this.audio.load();                                                            
                 }                                                                                   
                 else                                                                                
				    this.audio.play();                                                                            
           }                   
	},
	
	audioConnectedEvent: function(event) {
		 this.audio.palm.audioClass = Media.AudioClass.RINGTONE;
		 this.audio.src = this.currRingtonePath;                                                            
         this.audio.play();  
	},
	
	audioDisconnectedEvent: function(event) {
		this.audio = null;
	},
	
	playEvent: function(event) {
		if(!this.ringtonePlayerTimer)
			this.ringtonePlayerTimer = this.controller.window.setTimeout(this.stopPlay.bind(this), 3000);
	},
	
	stopPlay: function() {
		try {
			this.audio.pause();
			this.audio.currentTime = 0;
		} catch(e) {}
		this.ringtonePlayerTimer = null;		
	},
	
	handleSystemVolumeChange: function(event) {
		if(event.value == undefined)
			return;
		this.setSystemVolumeReq = AudioService.setSystemVolume(event.value,this.setSystemVolumeResponse.bind(this),this); 
	},
	
	setSystemVolumeResponse: function(response) {
		if(!response.returnValue)
			return;
		this.controller.serviceRequest('palm://com.palm.audio/systemsounds', {
			method: 'playFeedback',
			parameters : {"name":"shutter"}
		})
	},
		
	getCurrentVolumes: function() {		
		this.getSystemVolumeReq = AudioService.getSystemVolume(this.systemVolumeCB.bind(this),this);
		//Subscribe to Ringtone Volume
		this.getRingtoneVolumeSubscribe = AudioService.subscribeToRingtoneVolume(this.ringtoneVolumeCB.bind(this));
	},
	
	systemVolumeCB: function(payload) {
		if(payload.returnValue) {
			this.systemVolumeModel.value = payload.volume;
			this.controller.modelChanged(this.systemVolumeModel,this);
		}
		else {			
			Mojo.log("getVolume Failed"+payload.errorText);			
		}
		
	},
	
	ringtoneVolumeCB: function(payload) {
		if(payload.returnValue) {
			Mojo.log("Ringtone Volume "+ payload.volume);
			this.ringtoneVolumeModel.value = payload.volume;
			this.controller.modelChanged(this.ringtoneVolumeModel,this);
			/*if(payload.subscribed == undefined) 
				this.setVolumeDone();*/
		}
		else {
			Mojo.log("getVolume Failed"+payload.errorText);			
		}
	},
	
	getCurrentRingtone: function() {
		this.getCurrentRingtoneReq = SystemService.getRingtone(this.getCurrentRingtoneQuery.bind(this));
	},
	
	getCurrentRingtoneQuery: function(payload) {		
		if (payload.ringtone) {
			$('currentringtone').innerHTML = payload.ringtone.name;
			this.currRingtonePath = payload.ringtone.fullPath;	
		}
		else 
			$('currentringtone').innerHTML = $L("Pick a ringtone");
		
	},
	
	showAudioFilePicker: function(event) {
		var params = {"kinds": ["ringtone"],"filePath":this.currRingtonePath,"onSelect":this.selectedAudioFile.bind(this),"onAppMenuCommand":this.handleCommand.bind(this),actionType:"attach",actionName: $L("Done")};
		Mojo.FilePicker.pickFile(params,Mojo.Controller.stageController);
	},
	
	selectedAudioFile: function(file) {		
		//var params = {"fullPath": encodeURIComponent(file.fullPath), "name":file.name};
		this.setRingtoneReq = SystemService.setRingtone(file);
		$('currentringtone').innerHTML = file.name;
	},
	
	getVibrateSettings: function() {
		this.getVibrateSettingsReq = AudioService.getVibrateSettings(this.vibrateSettingsCB.bind(this),this);
	},
	
	vibrateSettingsCB: function(payload) {
		if(!payload.returnValue)
			return;
		if(payload.VibrateWhenRingerOn != undefined) {
			this.vibrateOnModel.value = payload.VibrateWhenRingerOn ? "vibrate" : "mute";
			this.controller.modelChanged(this.vibrateOnModel,this);
		}
		if(payload.VibrateWhenRingerOff != undefined) {
			this.vibrateOffModel.value = payload.VibrateWhenRingerOff ? "vibrate" : "mute";
			this.controller.modelChanged(this.vibrateOffModel,this);
		}
			
	},
	
	getOtherSettings: function() {
		this.getSystemUISoundsReq = SystemService.getSystemUISounds(this.getSystemUISoundsQuery.bind(this));
		//this.getVibrateChargingQueryReq = SystemService.getVibrateCharging(this.getVibrateChargingQuery.bind(this));
		//this.getSoundWhenOnCradleReq = SystemService.getSoundWhenOnCradle(this.getSoundWhenOnCradleQuery.bind(this));
	},
	
	getSystemUISoundsQuery: function(payload) {	
	    
		if(payload.systemSounds != undefined) {
			this.systemUISoundsModel.value = payload.systemSounds;
			this.controller.modelChanged(this.systemUISoundsModel,this);
		}			
	},
		
	getVibrateChargingQuery: function(payload) {
		
		if(payload.vibrateWhenCharging != undefined) {
			this.vibrateChargingModel.value = payload.vibrateWhenCharging;
			this.controller.modelChanged(this.vibrateChargingModel,this);
		}
	},
	
	toggleSystemUISounds: function(event) {
		if(!event)
			return;
		this.setUISoundsReq = SystemService.setSystemUISounds(event.value);
		this.setaudioSystemsoundReq = AudioService.muteSystemSound(!event.value);
	},
		
	toggleVibrateCharging: function(event) {
		if(!event)
			return;
		this.setVibrateChargingReq = SystemService.setVibrateCharging(event.value);
	},
	
	getSoundWhenOnCradleQuery: function(payload) {
		if(payload.playSoundWhenCharging) {
			this.soundOptionModel.value = payload.playSoundWhenCharging;
			this.controller.modelChanged(this.soundOptionModel,this);
		}
	},
	
	handleSelection: function(event) {
     	if(!event)
			return;
		SystemService.setSoundWhenOnCradle(event.value);
  	},
	
});
