/**
 * @author rogerstringer
 */
var gpsfixAssistantClass = null;

// constants
var filenamePattern = /[^a-zA-Z0-9_#-]/;
var NEW_SERVICE_NAME    = "palm://com.palm.logctld";

////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The contolling class
var GpsfixAssistant = Class.create ({
	
	initialize: function() {
	/* this is the creator function for your scene assistant object. It will be passed all the 
	   additional parameters (after the scene name) that were passed to pushScene. The reference
	   to the scene controller (this.controller) has not be established yet, so any initialization
	   that needs the scene controller should be done in the setup function below. */
	  gpsfixAssistantClass = this;
	},

	setup: function() {
		
		this.controller.setupWidget('fixButton', this.mainRadioAttributes, this.mainRadioModel);
		$('fixButton').observe(Mojo.Event.propertyChange, this.handleFixButtonChange.bindAsEventListener(this));
		
		this.controller.setupWidget('typeButton', this.subRadioAttributes, this.subRadioModel);
		$('typeButton').observe(Mojo.Event.propertyChange, this.handleTypeButtonChange.bindAsEventListener(this));
		
		this.controller.setupWidget('gpsfix_name', this.textFieldAttributes, this.textFieldModel);
 
 		$('save_fixes_button').observe(Mojo.Event.tap, this.saveFixes.bindAsEventListener(this));
 		$('clear_fixes_button').observe(Mojo.Event.tap, this.clearFixes.bindAsEventListener(this));

 	},
	
	
	activate: function(event) {
		/* put in event handlers here that should only be in effect when this scene is active. For
		   example, key handlers that are observing the document */
	},
	
	cleanup: function(event) {
		/* this function should do any cleanup needed before the scene is destroyed as 
		   a result of being popped off the scene stack */
	},

	////////////////////////////////////////////////////////////////////////
	//   Handle command method, which currently just services the main menu
	////////////////////////////////////////////////////////////////////////

 	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			if (event.command == 'help') {
				Mojo.Log.info("------------------ help -------------------------");
				this.showDialogBox(null, "Select type of GPS Fix point");
			} else {
				Mojo.Log.info("------------ Command [" + event.command +  "] ignored! -------------------------");
			}
		}
	},
	
	////////////////////////////////////////////////////////////////////////
	//     Handle radio button changes
	////////////////////////////////////////////////////////////////////////
	
	handleFixButtonChange: function(event) {
		if (this.mainRadioModel.value === "tracking") {
			this.subRadioModel.value = "na";
			this.controller.modelChanged(this.subRadioModel);
		}
	},

	handleTypeButtonChange: function(event) {
		if (this.mainRadioModel.value === "tracking" &&	this.subRadioModel.value != "na") {
			this.subRadioModel.value = "na";
			this.controller.modelChanged(this.subRadioModel);
		}
	},


	////////////////////////////////////////////////////////////////////////
	//  handle save button
	////////////////////////////////////////////////////////////////////////

	saveFixes: function(event) {
		$('gpsfix_name').blur();
		
		if (this.mainRadioModel.value != "tracking" && this.subRadioModel.value === "na") {
			this.showDialogBox (null, "<b>You must select either [Cold], [Hot], or [Warm]!</b>");
			return;
		} 
		
		if (this.mainRadioModel.value === "tracking" &&	this.subRadioModel.value != "na") {
			this.subRadioModel.value = "na";
			this.controller.modelChanged(this.subRadioModel);
		}
		
		if (this.textFieldModel.textValue == "") {
			$('gpsfix_name').focus();
			this.showDialogBox (null, "<b>Information text is empty!</b><br><br>Please enter information.");
		}
		else {
			var isBadChars = filenamePattern.test(this.textFieldModel.textValue);
			if (false == isBadChars) {
				var that = this;
				this.controller.serviceRequest('palm://com.palm.systemservice/time', {
					method: 'getSystemTime',
					onSuccess: function(result)		{
						var date = new Date(result.localtime * 1000);
						var saveName = that.mainRadioModel.value + '_'
								+ that.subRadioModel.value + '_'
								+ that.textFieldModel.textValue + '_'
								+ date.getFullYear().toString() 
								+ ( (date.getMonth() >= 9)    ? "" : "0") + (date.getMonth()+1)
								+ ( (date.getDate() >= 10)    ? "" : "0") + date.getDate() 
								+ ( (date.getHours() >= 10)   ? "" : "0") + date.getHours() 
								+ ( (date.getMinutes() >= 10) ? "" : "0") + date.getMinutes();
						that.createFixesPoint(saveName);
					},
					onFailure: function(result) {
						console.log("failed");
					}
				});
			} else {
				this.showDialogBox ($L("Error"), "<b>Information text contains invalid characters!</b><br><br>Please just use alphabetic and numeric characters, plus hyphen, underscore and # characters.");
			}
		}
	},
	
	clearFixes: function () {
		var that = this;
		this.controller.showAlertDialog({
			onChoose: function(value){
			},
			title: $L("Are you sure?"),
			message: "<b>Do you want to clear the current GPS fixes file?</b><br><br>This can't be undone.",
			allowHTMLMessage: true,
			choices: [
				{label: $L('OK'), value: 'ok', type: 'affirmative'},
				{label: $L('Cancel'), value: 'cancel', type: 'negative'}
			],
			onChoose: function(value) {
				if (value === 'ok') {
					that.createFixesPoint ("discard");
				}
			}
		});	
	},

	createFixesPoint: function(saveName) {
		var that = this;
		//$('progress_label').innerHTML = saveName;

		var saveServiceRequest = this.controller.serviceRequest(NEW_SERVICE_NAME, {
			method: 'savegpslogs',
			parameters: {
				name: saveName
			},
			onSuccess: function(result) {
				that.controller.cancelServiceRequest(saveServiceRequest);
				//$('progress_label').innerHTML = "";
				that.showDialogBox($L("Success"), 
						(saveName != "discard" 
							? "GPS fixes point created in file named: <b>gpsfixes_" + saveName + ".csv</b>"
							: "GPS fixes file cleared") );					
			},
			onFailure: function(result) {
				that.controller.cancelServiceRequest(saveServiceRequest);
				//$('progress_label').innerHTML = "";
				that.showDialogBox ($L("Error"), "<b>" 
					+ (saveName != "discard" ? "Unable to establish GPS Fix point!" : "Can't clear GPS fixes file!")
					+ "</b><br><br>" + result.errorText);
			}
		});
		
	},

 	////////////////////////////////////////////////////////////////////////
	//   Utility methods
	////////////////////////////////////////////////////////////////////////
	
	// any parameter can be null or omitted, but very silly not to have 'message'
	showDialogBox: function (title, message, func) {
		this.controller.showAlertDialog({
			onChoose: function(value){
				if (func) func(value);
			},
			title: (title && title.length > 0 ? title : $L("Information")),
			message: (message ? message : ''),
			allowHTMLMessage: true,
			choices: [{label: $L('OK'),	value: 'ok', type: 'dismiss'}]
		});
	},

	////////////////////////////////////////////////////////////////////////
	//   class variables
	////////////////////////////////////////////////////////////////////////
	
	mainRadioModel: {
		value: "tracking" // establish a default value
	},
		
	mainRadioAttributes: {
		choices: [
			{label:"MSBased", value: "msbased"},
			{label:"StandAln", value: "standalone"},
			{label:"Tracking", value: "tracking"},
		]
	},	
	
	subRadioModel: {
		value: "na" // establish a default value
	},

	subRadioAttributes: {
		choices: [
			{label:" Cold ", value: "cold"},
			{label:" Hot ", value: "hot"},
			{label:" Warm ", value: "warm"},
			{label:"n/a", value: "na"},
		]
	},	

	textFieldModel: {
		'textValue' : ''
	},

	textFieldAttributes: {
		hintText: 'Text',
		focus: true,
		enterSubmits: true,
		multiline: false,
		modelProperty: 'textValue',
		modifierState: Mojo.Widget.sentenceCase,
		focusMode: Mojo.Widget.focusInsertMode,
		requiresEnterKey: true,
		label: 'Text'
	},


});
