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

var PoundDataAssistant = Class.create({
	initialize: function() {
		TelephonyCommands.pdpSlotQuery(this.slotQueryDone.bind(this));		
		this.appControl = Mojo.Controller.getAppController();
		this.appAssistant = this.appControl.assistant;
						
	},
	
	fieldMap: $H({nai: "Username", aaapassword : "AAA Password", hapassword: "HA Password", haspi: "SPI HA",
					aaaspi: "SPI AAA",revtunnel: "Rev Tunneling",
					homeaddr: "M Home Address",primha: "Primary Home", secha: "Secondary Home" }),
	dataList: [],
		
	setup: function() {
		
		// Model to use for the command menu.
		this.cmdMenuModel = {
			items: [{}, {}, {}, {label: 'Menu', submenu:'category-menu'}]};
		// Set up view menu with scene header
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined, this.cmdMenuModel);
		this.controller.setupWidget('category-menu', undefined, this.categoryMenuModel);
		this.controller.document.body.addClassName("no-wallpaper");	
		
		this.dataListModel = {
            items: PoundData.poundPdpProfileList			
        };
		       
        this.template = {
			itemTemplate: 'poundData/listitem',            		          
        };		
					
        this.controller.setupWidget('datalist', this.template, this.dataListModel);
		Mojo.Event.listen(this.controller.get('datalist'), Mojo.Event.propertyChange, this.listChangeHandler.bindAsEventListener(this));
		Mojo.Event.listen(this.controller.get('datalist'), Mojo.Event.listTap, this.verifyMSL.bindAsEventListener(this));			
		
		this.textAttributes = {
			enterSubmits: true,
			focus: false,
			multiline: false,       
			focusMode: Mojo.Widget.focusSelectMode,
			textCase: Mojo.Widget.steModeLowerCase,
			maxLength: 40,
			modelProperty: "FIELDVALUE",
			disabledProperty: 'DISABLED',
		};
		
		this.controller.setupWidget('datafield', this.textAttributes, {});	
	},	
	
	activate: function() {
		if (PoundData.mslVerified) {
			for (var i = 0; i < PoundData.poundPdpProfileList.length; i++) {
				PoundData.poundPdpProfileList[i].DISABLED = false;
			}				
			this.controller.modelChanged(this.dataListModel, this);
		}
	},
	
	cleanup: function() {
		
		//If any fields is in focus then propertychange event will be sent out.
		this.controller.commitChanges();
		
		if (PoundData.edited) {
			QDLogger.log( "##DATA::Cleanup", "IsEdited: " , PoundData.edited);
			if (this.appAssistant.rebootOnRadioSettingsChanged) {
				this.appControl.showBanner(
					{
						messageText: "Phone will now reboot to save changes",
						soundClass: 'notifications'
					}, 
					{}, 'poundDataReboot'
				);
			}
			TelephonyCommands.exitProgramMode(this.rebootIfNecessary.bind(this));
		}	
		
		this.controller.document.body.removeClassName("no-wallpaper");
		
		PoundData.poundPdpProfileList.clear();	
		PoundData.mslVerified = false;
		PoundData.edited = false;		
	},
	
	rebootIfNecessary: function() {
		if (this.appAssistant.rebootOnRadioSettingsChanged) {
			TelephonyCommands.rebootPhone();
		}
	},
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {		
			switch (event.command) {
				case 'debug-Browser': this.controller.stageController.pushScene('poundDataBrowser','browser');
										break;
				case 'debug-MMSCURL': this.controller.stageController.pushScene('poundDataBrowser','mmscurl');
										break;
				case 'debug-Multimedia': this.controller.stageController.pushScene('poundDataBrowser', 'multimedia');
										break;
				case 'debug-Advannced': this.controller.stageController.pushScene('poundDataAdvanced');
										break;				
				case 'debug-Restore': if (PoundData.mslVerified) 
										this.showRestoreDialog();
									  else {
									  	this.showRestoreNow = true;
										this.showMSLDialog();
										}
									  break;				
			}
		}
	},
	
	dataQueryDone: function(success, status, dataInfo) {
							
		if(!dataInfo)
			return;
			
		if (success) {
			var fields = $H(dataInfo);
			
			this.fieldMap.each(function(pair) {
				var obj = new Object();
				obj.FIELDNAME = pair.value;
				obj.FIELDVALUE = fields.get(pair.key);
				if(PoundData.mslVerified) 
					obj.DISABLED = false;
				else
					obj.DISABLED = true;
				
				//Don't show the aaapassword and hapassword.				
				if((pair.key == "aaapassword" || pair.key == 'hapassword') ) { 
					if(pair.key == "aaapassword")
						this.aaapassword = obj.FIELDVALUE;
					else
						this.hapassword = obj.FIELDVALUE;
					var temp = '';
					for(var i = 0;i<pair.value.length;i++)
						temp += 'x';
					obj.FIELDVALUE = temp;					
				}					
				PoundData.poundPdpProfileList.push(obj);
				
			}.bind(this));					
		}		
		 else {
			this.controller.showAlertDialog({
		    onChoose: function(value){},
		    message: status,
		    preventCancel:false,
		    choices:[
	        {label: 'Done', value:true, type:'dismiss'}    
		    ]
		  	});	  
			}			
		this.controller.modelChanged(this.dataListModel, this);
	},
	
	slotQueryDone: function(success, payload) {
		if(!success)
			return;
		if(payload.slot)
			PoundData.slot = payload.slot;
		else
			PoundData.slot = 0;
		TelephonyCommands.pdpProfileQuery(PoundData.slot,this.dataQueryDone.bind(this));
		
	},
	
	listChangeHandler:function(event) {
			
		if(!event.model)
			return;
		
		var key;
		var value = event.value;
		//Get the key from the Hash Map
		this.fieldMap.each(function(pair){
			if (pair.value === event.model.FIELDNAME) {
				key = pair.key;
				return;
			}
		});
		
		TelephonyCommands.pdpProfileSet(PoundData.slot,key,value,null);
		
		//Hide the password values again.
		if((key == "aaapassword" || key == 'hapassword') ) { 
				if(key == "aaapassword")
					this.aaapassword = value;
				else
					this.hapassword = value;
				var temp = '';
				for(var i = 0;i<value.length;i++)
					temp += 'x';
				event.model.FIELDVALUE = temp;
				this.controller.modelChanged(this.dataListModel, this);					
		}
	},
	
	verifyMSL: function(event) {
		
		if(!event.item)
			return;
		
		if(PoundData.mslVerified)
			return;
			
		this.selectedRow = event.index;
		this.showMSLDialog();
		
	},
	
	verifiedMSL: function(success,msl) {
		
		PoundData.mslVerified = success;
		this.msl = msl;
		if(success) {
			PoundData.edited = true;
			
			for (var i = 0; i < PoundData.poundPdpProfileList.length; i++) {
				PoundData.poundPdpProfileList[i].DISABLED = false;
			}	
			
			this.controller.modelChanged(this.dataListModel, this);
			this.controller.get('datalist').mojo.focusItem(this.dataListModel.items[this.selectedRow]);
			
			if(this.showRestoreNow) {
				this.showRestoreNow = false;
				this.showRestoreDialog();
			}			
		}		
	},
	
	showMSLDialog: function() {				
		this.dialogBox = this.controller.showDialog({
			template: 'template/phone-msl-dialog',
			assistant: new MslAssistant(this),	
			preventCancel: true		
		});
	},
	
	showRestoreDialog: function() {
		this.dialogBox = this.controller.showDialog({
			template: 'poundRtn/rtn-reset-dialog',			
			assistant: new ResetAssistant(this, this.msl),		
			preventCancel: true	
		});
	},
	
	doneRestore: function() {
		//this.controller.stageController.popScene('poundData');
		Mojo.Controller.getAppController().assistant.closePhoneStage();
	},
	
	
	saveData: function() {
		//Bt tapping on the Save button causes the row to lose focus which will fire the propertyChange event.
		//In the list property change event the value is saved. Hence do nothing in this function.
		var elm = this.controller.get('datalist').querySelector('*:focus');
		if(elm)
			elm.blur();		
	},
	
	categoryMenuModel: { label: 'Category', items: [{label: 'Browser', command:'debug-Browser' },									                 
									                {label: 'MMSC URL', command:'debug-MMSCURL'},
													{label: 'Multimedia', command:'debug-Multimedia'},
													{label: 'Advanced', command:'debug-Advannced'},
													{label: 'Restore', command:'debug-Restore'}
								]},
	
	
});


var ResetAssistant = Class.create({
	
	initialize: function(sceneAssistant,mslVal) {
		this.sceneAssistant = sceneAssistant;
		this.mslVal = mslVal;		
	},
	
	setup : function(parent) {
		this.parent = parent;			
		this.sceneAssistant.controller.get('reset').addEventListener(Mojo.Event.tap, this.handleReset.bindAsEventListener(this));
		this.sceneAssistant.controller.get('cancel').addEventListener(Mojo.Event.tap, this.handleCancel.bindAsEventListener(this));
	},
	
	
	handleCancel: function() {
		this.parent.mojo.close();		
	},
	
	handleReset: function() {
		TelephonyCommands.radioDefaultsRestore('data',this.mslVal,this.sceneAssistant.doneRestore.bind(this.sceneAssistant));
		this.parent.mojo.close();	
	},		
	
	
});
