//common vars for all
var page;	//page object holder
var lastNameVarText = '';
var lastStatus = new Array();
var checkedlength = 0;
var checkedcounter = 0;
var jsHistory = new Array();
var thispagename = '';




/* a handler to startup the js for the page we are on */
function runPage(pagename) {
	$(window).unload( function() {cleanup(pagename);});
	$(document).unload( function() { cleanup(pagename); });

	
	switch(pagename){
		case 'devices': 
			// MF: get the number of devices from the DOM so we can control refresh rate.
			var devicecount = dojo.attr('deviceslist','count');
			page = new devices(devicecount);
			break;
		case 'tracking': page = new tracking();break;
		case 'userheader': page = new userHeader();break;
		case 'sharing': page = new sharing();break;
		case 'schedule': page = new schedule();break;
		case 'preferences': page = new preferences();break;
		case 'account': page = new account();break;
		case 'help': page = new help();break;
	}
	thispagename = pagename;
	page.run();
}
function cleanup(pagename) {
	page=null;fo=null;document.fo=null;jQuery=null;lastStatus=null;lastNameVarText=null;lastStatus=null;checkedlength=null;checkedcounter=null;jsHistory=null;
	if(pagename == 'tracking'){map = null;GUnload();}
}

function refreshData(myfunc, interval) {return setInterval(myfunc, interval);}

function stopRefresh(timerid) {	clearInterval(timerid);}

function getDeviceMenuSelected() {return $("#devicemenu").children("option:selected").attr("value");}

function getDeviceMenuSelectedText() {return $("#devicemenu").children("option:selected").attr("text");}

function updateStatusWindow(json, deviceid, ajaxcomplete) {
	if(!ajaxcomplete){json=null;deviceid=null;ajaxcomplete=null;return;}

	var jsc = [];
	jsc.push(json.online);jsc.push(json.emergkey);jsc.push(json.nomotion);jsc.push(json.nocheckin);jsc.push(json.battery);
	jsc.push(json.gprs);jsc.push(json.mandown);jsc.push(json.charging);jsc.push(json.lastpositiontimestamp);
	var jsoncompare = jsc.join('');
	if(lastStatus[deviceid] != null){if(lastStatus[deviceid] == jsoncompare){return;}}
	lastStatus[deviceid] = jsoncompare;

	var onlinestatus = $('#status_'+deviceid+'_online');var onlineindicator = $('div.indicator', onlinestatus);
	var emergkeystatus = $('#status_'+deviceid+'_emerg');var emergindicator = $('div.indicator', emergkeystatus);
	var nocheckinstatus = $('#status_'+deviceid+'_nocheckin');var nocheckinindicator = $('div.indicator', nocheckinstatus);
	var nomotionstatus = $('#status_'+deviceid+'_motion');var nomotionindicator = $('div.indicator', nomotionstatus);
	var mandownstatus = $('#status_'+deviceid+'_mandown');var mandownindicator = $('div.indicator', mandownstatus);
	var signalstatus = $('#status_'+deviceid+'_signal');var signallevel = $('div.level', signalstatus);
	var batterystatus = $('#status_'+deviceid+'_battery');var batterylevel = $('div.level', batterystatus);
	if(thispagename=='tracking'){var onlineindicatorwindow = $('div.indicatorwindow .indicator', onlinestatus);
	var signallevelwindow = $('div.indicatorwindow .level', signalstatus);var batterylevelwindow = $('div.indicatorwindow .level', batterystatus);}

	var online = json.online;	//online/offline
	if(online == 0){
		//MF: dojo works better here (go figure!)
		dojo.query('#status_'+deviceid+'_online .indicator').addClass('indicator_offline');
		dojo.query('#status_'+deviceid+'_online .indicator').removeClass('indicator_online');
		dojo.query('#status_'+deviceid+'_motion .indicator').addClass('opaque');
		dojo.query('#status_'+deviceid+'_mandown .indicator').addClass('opaque');
		dojo.query('#status_'+deviceid+'_battery .level').addClass('opaque');
		dojo.query('#status_'+deviceid+'_signal .level').addClass('opaque');
		
		$('span.indtext', onlinestatus).text($('span.offlineindtext', onlinestatus).text());
	}else{	
		dojo.query('#status_'+deviceid+'_online .indicator').addClass('indicator_online');
		dojo.query('#status_'+deviceid+'_online .indicator').removeClass('indicator_offline');
		dojo.query('#status_'+deviceid+'_motion .indicator').removeClass('opaque');
		dojo.query('#status_'+deviceid+'_mandown .indicator').removeClass('opaque');
		dojo.query('#status_'+deviceid+'_battery .level').removeClass('opaque');
		dojo.query('#status_'+deviceid+'_signal .level').removeClass('opaque');
		
		$('span.indtext', onlinestatus).text($('span.onlineindtext', onlinestatus).text());
	}
	if(json.emergkey == 0){
		$('span.indtext', emergkeystatus).text($('span.emergoffindtext', emergkeystatus).text());
		dojo.query('#status_'+deviceid+'_emerg .indicator').addClass('indicator_emergoff');
		dojo.query('#status_'+deviceid+'_emerg .indicator').removeClass('indicator_emergon');
	}else{
		$('span.indtext',emergkeystatus).text($('span.emergonindtext',emergkeystatus).text());
		dojo.query('#status_'+deviceid+'_emerg .indicator').addClass('indicator_emergon');
		dojo.query('#status_'+deviceid+'_emerg .indicator').removeClass('indicator_emergoff');
	}

	if(json.nocheckin == 0){
		$('span.indtext',nocheckinstatus).text($('span.nocheckinoffindtext',nocheckinstatus).text());
		dojo.query('#status_'+deviceid+'_nocheckin .indicator').addClass('indicator_nocheckinoff');
		dojo.query('#status_'+deviceid+'_nocheckin .indicator').removeClass('indicator_nocheckinon');
    }else{  
    	$('span.indtext',nocheckinstatus).text($('span.nocheckinonindtext',nocheckinstatus).text());
    	dojo.query('#status_'+deviceid+'_nocheckin .indicator').addClass('indicator_nocheckinon');
		dojo.query('#status_'+deviceid+'_nocheckin .indicator').removeClass('indicator_nocheckinoff');
    }
	
	//motion / nomotion
	if(json.nomotion == 0){
		$('span.indtext',nomotionstatus).text($('span.motionindtext',nomotionstatus).text());	
		dojo.query('#status_'+deviceid+'_motion .indicator').addClass('indicator_motion');
		dojo.query('#status_'+deviceid+'_motion .indicator').removeClass('indicator_nomotion');
	}else{
		$('span.indtext',nomotionstatus).text($('span.nomotionindtext',nomotionstatus).text());
		dojo.query('#status_'+deviceid+'_motion .indicator').addClass('indicator_nomotion');
		dojo.query('#status_'+deviceid+'_motion .indicator').removeClass('indicator_motion');
	}
	if(json.mandown == 0){
		$('span.indtext',mandownstatus).text($('span.mandownoffindtext',mandownstatus).text());
		dojo.query('#status_'+deviceid+'_mandown .indicator').addClass('indicator_mandownoff');
		dojo.query('#status_'+deviceid+'_mandown .indicator').removeClass('indicator_mandownnon');
    }else{  
    	$('span.indtext',mandownstatus).text($('span.mandownonindtext',mandownstatus).text());
    	dojo.query('#status_'+deviceid+'_mandown .indicator').addClass('indicator_mandownon');
    	dojo.query('#status_'+deviceid+'_mandown .indicator').removeClass('indicator_mandownoff');
    }
	//gsm level
	if(online == 1){
		var mygsm = json.gprs;
		if(mygsm < 0){mygsm = Math.floor((100 - 80*(-40 - mygsm)/(80))/20);}
		var mygsmtext = (mygsm*20)+' %';
		$(signallevel).removeClass('level_gsm_0');$(signallevel).removeClass('level_gsm_1');
		$(signallevel).removeClass('level_gsm_2');$(signallevel).removeClass('level_gsm_3');
		$(signallevel).removeClass('level_gsm_4');$(signallevel).removeClass('level_gsm_5');
		$(signallevel).addClass('level_gsm_'+mygsm);
		$('span.indval', signalstatus).text(mygsmtext);
		if(thispagename == 'tracking'){
		$(signallevelwindow).removeClass('level_gsm_0');$(signallevelwindow).removeClass('level_gsm_1');
		$(signallevelwindow).removeClass('level_gsm_2');$(signallevelwindow).removeClass('level_gsm_3');
		$(signallevelwindow).removeClass('level_gsm_4');$(signallevelwindow).removeClass('level_gsm_5');
		$(signallevelwindow).addClass('level_gsm_'+mygsm);
		$('span.indicatorwindow .indval', signalstatus).text(mygsmtext);
		}
	//battery level
		var mybattery = json.battery;
		if(mybattery > 6){mybattery = Math.floor(mybattery/20);}
		var mybatterytext = (mybattery*20)+' %';
		$(batterylevel).removeClass('level_battery_0');	$(batterylevel).removeClass('level_battery_1');
		$(batterylevel).removeClass('level_battery_2');	$(batterylevel).removeClass('level_battery_3');
		$(batterylevel).removeClass('level_battery_4');	$(batterylevel).removeClass('level_battery_5');
		$(batterylevel).removeClass('level_battery_charging');
		if(thispagename == 'tracking'){
		$(batterylevelwindow).removeClass('level_battery_0');$(batterylevelwindow).removeClass('level_battery_1');
		$(batterylevelwindow).removeClass('level_battery_2');$(batterylevelwindow).removeClass('level_battery_3');
		$(batterylevelwindow).removeClass('level_battery_4');$(batterylevelwindow).removeClass('level_battery_5');
		$(batterylevelwindow).removeClass('level_battery_charging');
		}
		if(json.charging == 1){
			$(batterylevel).addClass('level_battery_charging');	
			$('span.chargetext',batterystatus).show();$('span.indval',batterystatus).hide();
			if(thispagename=='tracking'){$(batterylevelwindow).addClass('level_battery_charging');	
			$('span.indicatorwindow .indval',batterystatus).hide();$('span.indicatorwindow .chargetext',batterystatus).show();}
		}else{	$(batterylevel).addClass('level_battery_'+mybattery);
			$('span.indval',batterystatus).text(mybatterytext);
			$('span.indval',batterystatus).show();$('span.chargetext',batterystatus).hide();
			if(thispagename=='tracking'){$(batterylevelwindow).addClass('level_battery_'+mybattery);$('span.indicatorwindow .indval',batterystatus).text(mybatterytext);
			$('span.indicatorwindow .indval',batterystatus).show();$('span.indicatorwindow .chargetext',batterystatus).hide();}

		}
		//last position timestamp
		var mytimetext = json.lastpositiontimestamp;
		$('#status_'+deviceid+'_lasttime > span.indval').text(mytimetext);
	}
	json=null;mytimetext=null;mybattery=null;mybatterytext=null;mygsm=null;mygsmtext=null;online=null;deviceid=null;ajaxcomplete=null;
	onlinestatus=null;onlineindicator=null;onlineindicatorwindow=null;emergkeystatus=null;emergindicator=null;nocheckinstatus=null;
        nocheckinindicator=null;nomotionstatus=null;nomotionindicator=null;mandownstatus=null;mandownindicator=null;
        signalstatus=null;signallevel=null;signallevelwindow=null;batterystatus=null;batterylevel=null;batterylevelwindow=null;

}
/* the class and functions to handle the tracking page */
function tracking() {
	var timerid;
	var commandIDs = new Array();
	var counter = 0;
	var continuous = false;
	var commandwindowlog = new Array();

	function run() {
		this.timerid = refreshData(this.dataUpdate, 7000);
		bindCommandButtons();
	}
	this.run = run;

	function stop() {stopRefresh(this.timerid);}
	this.stop = stop;

	function getTimerID() {	return this.timerid;}
	this.getTimerID = getTimerID;

	function commandButtonAction(commandurl,mydeviceid) {

		$.ajax({
                       url:commandurl,
                       dataType:"xml",
                       success: function(xml) { commandResult(xml, true);},
 	               error: function(xml) {  updateCommandWindow('Unable to perform command, please try again');}
                   });
		commandurl = null; mydeviceid = null;xml=null;
	}
	
	function bindCommandButtons() {

		var tc = $('.track_control');

		$('.locate', tc).click( function(e) { 
				var mydeviceid = $(this).attr('id');
				commandButtonAction('/tracking/'+mydeviceid+'/locate+xml/',mydeviceid);
				mydeviceid=null;
				e.stopPropagation();
				return false;});
		
		$('.arm', tc).click( function(e) { 
				var mydeviceid = $(this).attr('id');
				commandButtonAction('/tracking/'+mydeviceid+'/arm+xml',mydeviceid);
				mydeviceid=null;
				e.stopPropagation();
				return false;});

		$('.disarm', tc).click( function(e) { 
				var mydeviceid = $(this).attr('id');
				commandButtonAction('/tracking/'+mydeviceid+'/disarm+xml',mydeviceid);
				mydeviceid=null;
                                e.stopPropagation();
                                return false;});

		$('.poweroff', tc).click( function(e) {
				var isokay = confirm('CAUTION - if you choose to turn this Loner GPS device off, it cannot be turned on remotely. Press Cancel if you do NOT wish to turn this device off');
				if(isokay){	var mydeviceid = $(this).attr('id');
        	                        	commandButtonAction('/tracking/'+mydeviceid+'/poweroff+xml',mydeviceid);
						mydeviceid=null;isokay=null;
					}
                                e.stopPropagation();
                                return false;});

		$('.reset', tc).click( function(e) {
				var mydeviceid = $(this).attr('id');
				commandButtonAction('/tracking/'+mydeviceid+'/reset+xml',mydeviceid);
				mydeviceid=null;
				e.stopPropagation();
				return false;});

		$('.continuous', tc).click( function(e) { 
				if(continuous == false){	alert('Starting Continuous Tracking, Press again to stop');
								continuous = true;
								var mydeviceid = $(this).attr('id');
								commandButtonAction('/tracking/'+mydeviceid+'/locate+xml/',mydeviceid);	
								mydeviceid=null;
								}
				else if(continuous == true){	alert('Stopping Continuous Tracking');
								continuous = false;}
				e.stopPropagation();
				return false;});
				
		$('.refresh_history').click( function(e) {
                                var startdate = $('#locations_date1').val();
                                var enddate = $('#locations_date2').val();
                                var historytype = $('#locations_filter').children('option:selected').attr('value');
                                var mydeviceid = $(this).attr('id');

                                $.ajax({
                                        url:'/tracking/'+mydeviceid+'/history+xml/',
                                        data:'startdate='+startdate+'&enddate='+enddate+'&historytype='+historytype,
                                        type:'POST',
                                        dataType:'html',
                                        success: function(html) { $('#history_table').html(html);html = null},
                                        error: function(html, textStatus, errorThrown) { html = null; }});
				startdate=null;enddate=null;historytype=null;mydeviceid=null;
                                e.stopPropagation();
                                return false;});
		

		$('#togglecheck').click( function(e) {
				$('.histitem > td > input').each(function() {
					var checktype = $('#togglecheck:checked').length;
					this.checked = checktype;
				});
		});

		$('.showchecked').click( function(e) {
				updateCommandWindow('Loading locations....');
				var checkeditems = $('.histitem > td > input:checked');
				checkedlength = checkeditems.length;
				checkedcounter = 0;
				var showhistory = new Array();
	                        checkeditems.each( function() {
					checkedcounter++;
					var id = this.id.replace('history_', '');
					showhistory.push(id);
					});
				if(showhistory.length > 0){
					showonmapids(showhistory);
				}
				updateCommandWindow('Displaying Locations');
				checkeditems=null;checkedlength=null;checkedcounter=null;showhistory=null;id=null;
                                e.stopPropagation();
                                return false;});
	}

	function commandResult(xml, returnstate) {

		var mystatus = $("status", xml).text();
		
		if(mystatus == 'FALSE'){	//the command did not take
			updateCommandWindow('Unable to perform command');
		}
		else if(mystatus == 'TRUE'){	//able to do
				var mycommandid = $('commandID', xml).text();
				var deviceid = $('deviceID', xml).text();
				var result = [deviceid, mycommandid];
				if(mycommandid != '1' && mycommandid != ''){
					commandIDs.push(result);
					updateCommandWindow('Sent Command to Device');
				}else{
					updateCommandWindow('Sent Command to Device');
				}
		}
		mystatus = mycommandid = result = null;deviceid=null;
	}
	this.commandResult = commandResult;
		
	function updateCommandWindow(msg) {

		commandwindowlog.push(Date()+' : '+msg);
		if(commandwindowlog.length > 3){
			commandwindowlog.shift();
		}
		var out = commandwindowlog.join('<br>');
		$('#commandlog').html(out);
		out = null;
	}
	this.updateCommandWindow = updateCommandWindow;
	
	function dataUpdate() {
		//process any open commands here
		counter++;
		var dateobj = new Date();
		var j = parseInt(dateobj.getTime() / 1000)
		if(commandIDs.length > 0){
			for(i in commandIDs){
				$.ajax({
					url:"/tracking/"+commandIDs[i][0]+"/checkcommand+xml/"+j,
					data:"commandid="+commandIDs[i][1],
					type:"POST",
					dataType:"xml", 
					success: function(xml) {processData(i, xml, true)}, 
					error: function(xml) {processData(i, xml, false)}});
			}
		}
		else{
			//$('.track_control *').fadeTo('slow',1);
		}
		
		$.ajax({
			url:"/devices//+json/"+j, 
			dataType:"json", 
			success: function(json) { updateTrackingStatusWindow(json, true)}, 
			error: function(json) { updateTrackingStatusWindow(json,false)}});
		dateobj=null;j=null;counter=null;
	}
	this.dataUpdate = dataUpdate;
	
	function updateTrackingStatusWindow(json, wasgood) {

		if(!wasgood){ return false; }

		var trackingdeviceid = getDeviceMenuSelected();

		$.each(json.devices, function(i,item){
			if(item.deviceid == trackingdeviceid){
	                        updateStatusWindow(item.devicestatus,item.deviceid, true);
				return false;
			}});
		updateAlarm(json);
		json = null;mystatus = null;mydeviceid = null;devicelist = null;xml=null;
	}

	function processData(i, xml, wasgood) {
		
		if(!wasgood){			//our ajax request failed.  
			updateCommandWindow('Server did not respond, try again');
			i=null;xml=null;wasgood=null;
			return false;}

		if( $("commandstatus",xml).text() == 'acked'){updateCommandWindow('Device Acknowledged, Waiting ....');}
		else if( $("commandstatus",xml).text() == 'nacked'){updateCommandWindow('Device Unavailable');commandIDs.splice(i, 1);}
		else if( $("commandstatus",xml).text() == 'complete'){//the command is done, delete this command
			commandIDs.splice(i, 1);
			if( $("datatype", xml).text() == 'location'){
				//we got something from history
				updateCommandWindow('Recieved Position, please see map');
				$(".refresh_history").click();
				var historyid = $("historyID",xml).text();
				var showhistory = new Array();
                                showhistory.push(historyid);
                                if(showhistory.length > 0){
                                        //showonmapids(showhistory);
                                }

				dataUpdate();

				//draw a point on the map
				if($("units",xml).text() == 'me'){var unitspeed = ' (km/h)';var unitalt = ' (meters)';}
				else{var unitspeed = ' (mph)';var unitalt = ' (feet)';}

				var hdev = getDeviceMenuSelectedText();
				var hlat = $("latitude",xml).text().substring(0,10);
				var hlon = $("longitude",xml).text().substring(0,10);
				var htime = $("timestamp",xml).text();
				var tz = $("tz",xml).text();
				var hdir = $("heading",xml).text();
				var hspeed = $("speed_km",xml).text();
				var halt = $("alt_m",xml).text();
				var heading = 'unknown';

				if(hspeed < 5){hspeed = 0;hdir = 'Unknown';}
				
				if(67 >= hdir && hdir >= 22){heading = 'North East';}
				else if(112 >= hdir && hdir >= 67){heading = 'East';}
				else if(157 >= hdir && hdir >= 112){heading = 'South East';}
				else if(202 >= hdir && hdir >= 157){heading = 'South';}
				else if(247 >= hdir && hdir >= 202){heading = 'South West';}
				else if(292 >= hdir && hdir >= 247){heading = 'West';}
				else if(337 >= hdir && hdir >= 292){heading = 'North West';}
				else if(hdir>=1 && 22 >= hdir || hdir>=337 && hdir <= 360){heading = 'North';}
				else if(hdir == 'Unknown'){heading = 'Unknown';}
				
				var popup = "<div popuponmap><b>Device:</b> "+hdev+"<br /><b>Time:</b> "+htime+
						"<br /><b>Speed</b>: "+hspeed+" "+unitspeed+
						" <br /><b>Alt:</b> "+halt+" "+unitalt+
						"<br /><b>Heading:</b> "+heading+" / "+hdir+
						" degrees<br /><b>Lat,Lon:</b> "+hlat+","+hlon+"</div>";

				var point = new GLatLng(hlat,hlon);
				map.setCenter(point,14);
				var marker = new GMarker(point);
			        map.addOverlay(marker);
			        marker.openInfoWindowHtml(popup);
				
			        GEvent.addListener(marker, "click", function(){marker.openInfoWindowHtml(popup);})
								
				if(continuous == true){
					var mydeviceid = $("deviceid",xml).text()
                                        commandButtonAction("/tracking/"+mydeviceid+"/locate+xml/",mydeviceid);
				}
			}else{updateCommandWindow('Command Complete');}
		}
		else if( $("status",xml).text() == 'FALSE'){
                        updateCommandWindow('Device Unavailable');
                        commandIDs.splice(i, 1);
                }else{	updateCommandWindow('Waiting For Device ....');	}
		xml = null;
		return true;
	}
	xml = null;	
}
/* ******************************************* */
/* the class and functions to handle the device page */
function devices(count) {
	
	var timerid;
	
	// MF: determine refresh rate bases on #of devices
	var refresh = Math.ceil(count/100)*10; // in seconds
	
	function run() {
		//refreshDeviceStatus();
		this.timerid = refreshData(this.refreshDeviceStatus, refresh*1000); // milliseconds
	}
	this.run = run;
	
	function refreshDeviceStatus() {
		
		var timeobj = new Date;
		var i = parseInt(timeobj.getTime() / 1000);
		$.ajax({
			url:"/devices//+json/"+i, 
			dataType:"json", 
			success: function(json) { updateEachDevice(json,true)}, 
			error: function(json) { updateEachDevice(json,false)}});
		timeobj=null;i=null;json=null;
	}
	this.refreshDeviceStatus = refreshDeviceStatus;
	
	function updateEachDevice(json, ajaxstate) {
		
		if(!ajaxstate){	json=null;return;}
		$.each(json.devices, function(i,item){
			var mydeviceid = item.deviceid;
			var mystatus = item.devicestatus;
			updateStatusWindow(item.devicestatus,item.deviceid, true);
		});
		updateAlarm(json);
		json = null;mydevice = null;mystatus = null;mydeviceid = null;devicelist = null;ajaxstate=null;
	}
	this.updateEachDevice = updateEachDevice;
}

function userHeader() {

	var timerid;
	var testcounter = 1;
	
	function run() {
		dataUpdate();
		this.timerid = refreshData(this.dataUpdate, 10000);
	}
	this.run = run;
	
	function stop() {stopRefresh(this.timerid);}
	this.stop = stop;
	
	function getTimerID() {	return this.timerid;}
	this.getTimerID = getTimerID;
	
	function dataUpdate() {
		$.ajax({
			url:"/data/header.html",
			dataType:"html", 
			success: function(html) { $("#userheader").html(html);}, 
			error: function(html) {  }
			});
	}
	this.dataUpdate = dataUpdate;
}

function preferences() {

	function run() {}
	this.run = run;
}
					
function sharing() {

	function run() {
		bindSharingButtons();
		$(".sharerow").hide();
		$(".shortmsg").fadeOut(2000);
	}
	this.run = run;
	
	function bindSharingButtons() {
	
		$(document).ready(function(){
		
			$(".friendrow").click(
				function() {
					var myid = $(this).attr('id');
					var friendid = myid.replace(/friend_/, '');
					//alert('pressed '+friendid);
					loadInner(friendid);
					});
		});
	}
	
	this.bindSharingButtons = bindSharingButtons;
	
	function loadInner(toload) {
		
		//alert(toload);
		$(document).ready(function(){
			$(".sharerow").hide();
			
			$("#sharerow_"+toload).fadeIn('slow');
		});
	}
	this.loadInner = loadInner;
}

function account() {

	function run() {

		bindButtons();

	}
	this.run = run;

	function ButtonAction(commandurl,postdata) {

                $.ajax(
                   {
                       url:commandurl,
                       dataType:"xml",
		       type:"POST",
		       data:postdata,
                       success: function(xml) { buttonResult(xml, true, '');},
                       error: function(xml) {  buttonResult(xml, false, 'unable to save');}
                   }
                );

                commandurl = postdata = null;xml=null;
        }
	this.ButtonAction = ButtonAction;

        function bindButtons() {

                $("#addlonermobile2submit").click(
                        function(e) {
				var deviceid = $("#lonermobileid").val();
				var deviceact = $("#lonermobileact").val();
                                ButtonAction("/account//checkactivation+xml/","deviceid="+deviceid+"&activationcode="+deviceact+"&devicetype=lonermobile");
                                e.stopPropagation();
                                return false;
                        }

                );

		$("#addlonergps2submit").click(
                        function(e) {
                                var deviceid = $("#lonergpsid").val();
                                var deviceact = $("#lonergpsact").val();
                                ButtonAction("/account//checkactivation+xml/","deviceid="+deviceid+"&activationcode="+deviceact+"&devicetype=loner");
                                e.stopPropagation();
                                return false;
                        }

                );

		$("#addlonermobile3submit").click(
			function(e) {
				var failed = false;
				$('#addlonermobile3 td input').each(function() {
					var val = $(this).val();
					if(val == ''){
						failed = true;
					}
				});
				if(failed == true){
					alert('Please Enter All Fields');
					e.stopPropagation();
					return false;
				}
			}
		);

		$("#addlonergps3submit").click(
                        function(e) {
                                var failed = false;
                                $('#addlonergps3 td input').each(function() {
                                        var val = $(this).val();
                                        if(val == ''){
                                                failed = true;
                                        }
                                });
                                if(failed == true){
                                        alert('Please Enter All Fields');
                                        e.stopPropagation();
                                        return false;
                                }
                        }
                );


		$("#checkcoupon").click(
			function(e) {
				var couponcode = $("#couponcode").val();
				var deviceid = $("#deviceid").val();
				ButtonAction("/account/"+deviceid+"/checkcoupon+xml/", "coupon="+couponcode+"&deviceid="+deviceid);
				e.stopPropagation();
				return false;
			}
		);

	}

	this.bindButtons = bindButtons;
	
	function buttonResult(xml, state, text) {

		var deviceid = $("deviceid",xml).text();
		var devicetype = $("devicetype",xml).text();
		var domain = document.domain;

		if( $("status",xml).text() == 'TRUE' && $("validactivation",xml).text() == '1'){

			if(devicetype == 'lonermobile'){
				window.location.href = "http://"+domain+"/account/"+deviceid+"/addlonermobile2/";

			}
			if(devicetype == 'loner'){
				window.location.href = "http://"+domain+"/account/"+deviceid+"/addlonergps2/";
			}
		}
		if( $("validactivation",xml).text() == '0' || $("active",xml).text() == '1'){
			//tell them
			$('#addlonererror').show();
		}

	}
	this.buttonResult = buttonResult;
	
	
}

function schedule() {

	var timerid;

        function run() {
                this.timerid = refreshData(this.refreshDeviceStatus, 10000);
        }
        this.run = run;

	function refreshDeviceStatus() {

	        var timeobj = new Date;
                var i = parseInt(timeobj.getTime() / 1000);

                $.ajax({
                        url:"/devices//+json/"+i,
                        dataType:"json",
                        success: function(json) { updateEachDevice(json, true)},
                        error: function(json) { updateEachDevice(json,false)}
                });
        }
        this.refreshDeviceStatus = refreshDeviceStatus;

        function updateEachDevice(json, ajaxstate) {

                if(!ajaxstate){ return false; }
		updateAlarm(json.devices);
                json = null; devicelist = null;
        }
        this.updateEachDevice = updateEachDevice;

	json = null, timerobj = null;
}

function help() {
	function run() { }
	this.run = run;
}

function updateAlarm(json) {

	var nameVar = new Array();
	var alarmVar = 0;

	$.each(json.devices, function(i,item){
		var mydevice = item.devicestatus;
		var myname = item.prefs.devicename;

		if( mydevice.mandown == 1) {
			nameVar.push(myname+' Emergency');
			alarmVar = 2;				//mandown beats nomotion for sound
		}
		if( mydevice.nomotion == 1 ) {
			nameVar.push(myname+' No Motion');
			if(alarmVar < 2){alarmVar = 1;}		
		}
		if( mydevice.nogps == 1 ) {
			nameVar.push(myname+' No GPS');
			if(alarmVar < 2){alarmVar = 1;}
		}
		if( mydevice.nocheckin == 1) {
			nameVar.push(myname+' No Checkin');
			if(alarmVar < 2){alarmVar = 1;}
		}
		if( mydevice.emergkey == 1 ) {
			nameVar.push(myname+' Emergency');
			alarmVar = 2;				//emergkey beats nocheckin for sound
		}
	});

	var nameVarText = nameVar.join(", ");
	if(nameVarText != lastNameVarText){
	        document.fo.addVariable('alarmVar', alarmVar);
                document.fo.addVariable('manVar', nameVarText);
                document.fo.write("flashcontent");
	}
	lastNameVarText = nameVarText;

	json = null; nameVar = null; alarmVar = null; nameVarText = null; devicelist = null;
}
