// Common variables
var page;
var lastStatus = new Array();
var jsHistory = new Array();
var thispagename = '';
var commandwindowlog = new Array();

// Sound Settings
window.soundManager.url = '/audio/';
window.soundManager.useFlashBlock = true;

var alertSound;
var alertSoundUrl = '/audio/alert.mp3';
var alertSoundId = 'alertNotificationSound';

/* Initialize the Google Map */
var map;
var iconSize;
var iconAnchor;
var infoWindowAnchor;
var geocoder;
var histdata;

// Don't cache any jQuery ajax requests
$.ajaxSetup({
    cache: false
});

google.load('maps','2');
$(document).ready(function () {
    soundManager.onready(function(){

        alertSound = soundManager.createSound({
            id: alertSoundId,
            url: alertSoundUrl
        });
    });

    if ($('#map_canvas').length > 0) {
        initialize();
    }
});

function initialize()
{
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(47.279229002570816, -93.427734375), 2);
        map.setUIToDefault();

        iconSize = new GSize(36,36);
        iconAnchor = new GPoint(18,18);
        infoWindowAnchor = new GPoint(18,18);

        geocoder = new GClientGeocoder(null, mapKey);
    }
}

function showLocations(ids)
{
    // Start with the most recent location
    ids.reverse();

    for (var i=0; i<ids.length; i++) {
        var details =  histdata[ids[i]][0];
        var lat = histdata[ids[i]][1];
        var lng = histdata[ids[i]][2];
        var offset = Math.abs(histdata[ids[i]][3]);

        var latlng = getLatLng(lat,lng);
        map.setCenter(latlng, 14);

        marker = createMarker(details, latlng, offset, true);
    }
}

/**
 * @desc creates a marker with info window displaying corresponding heading to offset
 * @param info, point, icon offset
 * @return marker object
 * @author mark <mfleet@blacklinegps.com>
 */
function createMarker(details,point,offset, autoOpenMarker)
{
    var address;
    var icon = new GIcon();
    icon.image = "/images/arrow_"+offset+".gif";
    icon.iconSize = iconSize;
    icon.iconAnchor = iconAnchor;
    icon.infoWindowAnchor = infoWindowAnchor;

    var marker = new GMarker(point, icon);
    geocoder.getLocations(point, function getAddress(response)
    {
        if (!response || response.Status.code != 200) {
            if (page.updateCommandWindow != undefined) {
                page.updateCommandWindow("Unable to locate address ["+response.Status.code+"]");
            }
        } else {
            place = response.Placemark[0];
            address = place.address;

            if (autoOpenMarker) {
                marker.openInfoWindowHtml(details+'<br/>'+address);
            }
        }
    });

    GEvent.addListener(marker,"click", function() {
        if (!address) address='';
        marker.openInfoWindowHtml(details+'<br/>'+address);
    });

    map.addOverlay(marker);
    return marker;
}

function getLatLng(lat,lng)
{
    return new GLatLng(lat,lng);
}

/* a handler to startup the js for the page we are on */
function runPage(pagename) {

    switch (pagename) {
        case 'devices':
            page = new devices();
            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;
        case 'maplast':
            page = new maplast();
            break;
    }
    thispagename = pagename;
    page.run();
}

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.emergkey);
    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 emergkeystatus = $('#status_'+deviceid+'_emergkey');
    var emergkeyindicator = $('div.indicator', emergkeystatus);
    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);
    }
    
    if (json.online == 0) {
        $('#status_'+deviceid+'_online .indicator').addClass('indicator_offline').removeClass('indicator_online');
        $('#status_'+deviceid+'_motion .indicator').addClass('opaque');
        $('#status_'+deviceid+'_emergkey .indicator').addClass('opaque');
        $('#status_'+deviceid+'_battery .level').addClass('opaque');
        $('#status_'+deviceid+'_signal .level').addClass('opaque');

        $('span.indtext', onlinestatus).text($('span.offlineindtext', onlinestatus).text());
    } else {
        $('#status_'+deviceid+'_online .indicator').addClass('indicator_online').removeClass('indicator_offline');
        $('#status_'+deviceid+'_motion .indicator').removeClass('opaque');
        $('#status_'+deviceid+'_emergkey .indicator').removeClass('opaque');
        $('#status_'+deviceid+'_battery .level').removeClass('opaque');
        $('#status_'+deviceid+'_signal .level').removeClass('opaque');

        $('span.indtext', onlinestatus).text($('span.onlineindtext', onlinestatus).text());
    }

    if (json.nocheckin == 0) {
        $('span.indtext',nocheckinstatus).text($('span.nocheckinoffindtext',nocheckinstatus).text());
        $('#status_'+deviceid+'_nocheckin .indicator').addClass('indicator_nocheckinoff').removeClass('indicator_nocheckinon');
    } else {
        $('span.indtext',nocheckinstatus).text($('span.nocheckinonindtext',nocheckinstatus).text());
        $('#status_'+deviceid+'_nocheckin .indicator').addClass('indicator_nocheckinon').removeClass('indicator_nocheckinoff');
    }

    if (json.nomotion == 0) {
        $('span.indtext',nomotionstatus).text($('span.motionindtext',nomotionstatus).text());
        $('#status_'+deviceid+'_motion .indicator').addClass('indicator_motion').removeClass('indicator_nomotion');
    } else {
        $('span.indtext',nomotionstatus).text($('span.nomotionindtext',nomotionstatus).text());
        $('#status_'+deviceid+'_motion .indicator').addClass('indicator_nomotion').removeClass('indicator_motion');
    }

    if (json.emergkey == 0) {
        $('span.indtext',emergkeystatus).text($('span.emergkeyoffindtext',emergkeystatus).text());
        $('#status_'+deviceid+'_emergkey .indicator').addClass('indicator_emergkeyoff').removeClass('indicator_emergkeyon');
    } else {
        $('span.indtext',emergkeystatus).text($('span.emergkeyonindtext',emergkeystatus).text());
        $('#status_'+deviceid+'_emergkey .indicator').addClass('indicator_emergkeyon').removeClass('indicator_emergkeyoff');
    }

    //gsm level
    if (json.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')
                      .removeClass('level_gsm_1')
                      .removeClass('level_gsm_2')
                      .removeClass('level_gsm_3')
                      .removeClass('level_gsm_4')
                      .removeClass('level_gsm_5')
                      .addClass('level_gsm_'+mygsm);
        $('span.indval', signalstatus).text(mygsmtext);

        if (thispagename == 'tracking') {
            $(signallevelwindow).removeClass('level_gsm_0')
                                .removeClass('level_gsm_1')
                                .removeClass('level_gsm_2')
                                .removeClass('level_gsm_3')
                                .removeClass('level_gsm_4')
                                .removeClass('level_gsm_5')
                                .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')
                       .removeClass('level_battery_1')
                       .removeClass('level_battery_2')
                       .removeClass('level_battery_3')
                       .removeClass('level_battery_4')
                       .removeClass('level_battery_5')
                       .removeClass('level_battery_charging');
        if (thispagename == 'tracking') {
            $(batterylevelwindow).removeClass('level_battery_0')
                                 .removeClass('level_battery_1')
                                 .removeClass('level_battery_2')
                                 .removeClass('level_battery_3')
                                 .removeClass('level_battery_4')
                                 .removeClass('level_battery_5')
                                 .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).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;
    emergkeystatus=null;
    emergkeyindicator=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;

    function run() {

        // Show the most recent location by default
        this.showMostRecentLocation();

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

    function showMostRecentLocation () {
        // The histdata variable is loaded at the bottom of tracking.html
        for (i in histdata) {
            if (histdata.hasOwnProperty(i)) {
                showLocations([i]);
                break;
            }
        }
    }
    this.showMostRecentLocation = showMostRecentLocation;

    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');

            // Start the spinner
            toggleSpinner('history_loader');

            $.ajax({
                url:'/tracking/'+mydeviceid+'/history+xml/',
                data:'startdate='+startdate+'&enddate='+enddate+'&historytype='+historytype,
                type:'POST',
                dataType:'html',
                success: function(html) {
                    $('#history_table').html(html);
                    toggleSpinner('history_loader');

                    // Trigger any events bound to the history table
                    $('#history_table').trigger('refresh').unbind('refresh');

                },
                error: function(html, textStatus, errorThrown) {
                    toggleSpinner('history_loader');
                    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').unbind().click( function(e) {
            updateCommandWindow('Loading locations....');

            var showHistoryEvents = new Array();
            $('#history_table input.history_event:checked').each( function() {
                var id = this.id.replace('history_', '');
                showHistoryEvents.push(id);
            });

            if (showHistoryEvents.length > 0) {
                showLocations(showHistoryEvents);
                updateCommandWindow('Displaying Locations');
            } else {
                updateCommandWindow('No locations selected')
            }
        });
        
    }

    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++;
        if (commandIDs.length > 0) {
            for (i in commandIDs) {
                $.ajax({
                    url:"/tracking/"+commandIDs[i][0]+"/checkcommand+xml/",
                    data:"commandid="+commandIDs[i][1],
                    type:"POST",
                    dataType:"xml",
                    success: function(xml) {
                        processData(i, xml, true)
                    },
                    error: function(xml) {
                        processData(i, xml, false)
                    }
                });
            }
        }

        $.ajax({
            url:"/devices//+json/",
            dataType:"json",
            success: function(json) {
                updateTrackingStatusWindow(json)
            }
        });
        dateobj=null;
        j=null;
        counter=null;
    }
    this.dataUpdate = dataUpdate;

    function updateTrackingStatusWindow(json) {
        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' || $('datatype', xml).text() == 'last_known_gps_location') {
                // Refresh the history table
                $('.refresh_history').click();

                // When the history table has finished updating, show the most recent location
                $('#history_table').unbind('refresh').bind('refresh', function () {
                    updateCommandWindow('Recieved Position, please see map');
                    showMostRecentLocation();
                });

                dataUpdate();

                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() {
	
    var timerid;
	
    function run() {
        // How often to refresh the devices?
        var numDevices = $('#deviceslist').attr('count');
        var refreshRate = Math.ceil(numDevices/100)*10; 

        this.timerid = refreshData(this.refreshDeviceStatus, refreshRate * 1000); // milliseconds
        refreshDeviceStatus();
    }
    this.run = run;
	
    function refreshDeviceStatus() {
        $.ajax({
            url:"/devices//+json/",
            dataType:"json",
            success: function(json) {
                updateEachDevice(json)
            }
        });
    }
    this.refreshDeviceStatus = refreshDeviceStatus;
	
    function updateEachDevice(json) {
        $.each(json.devices, function(i,item) {
            var mydeviceid = item.deviceid;
            var mystatus = item.devicestatus;
            updateStatusWindow(item.devicestatus,item.deviceid, true);
        });

        updateAlarm(json);
    }
    this.updateEachDevice = updateEachDevice;
}

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

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

function account() {

    function run() {
        bindButtons();
        getDevicesAndUpdateAlarm();
    }
    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();
                var devicetype = $("#lonermobiledevicetype").val();
                ButtonAction("/account//checkactivation+xml/","deviceid="+deviceid+"&activationcode="+deviceact+"&devicetype="+devicetype);
                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;
            });
                   

        $('#export_history').click( function(e) {
        	window.open($(this).attr('href'), '_self');
        	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' || devicetype == 'winlonermobile') {
                window.location.href = "http://"+domain+"/account/"+deviceid+"/addlonermobile2/?devicetype="+devicetype;
            }

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

    }
    this.buttonResult = buttonResult;
    
    var nextContactIndices = 1;
    function addContact(element) {
    	
        var template = $("#template > .contact").clone();
        
        // Since we can have multiple contacts on a form, we need to uniquely identify each                                    
        $(template).find('[name*=contacts\\[contact_0\\]]').each(function() {
            this.name = this.name.replace('contacts[contact_0]', 'contacts[contact_'+nextContactIndices+']');
        });
        element.append(template);
        nextContactIndices++;
        return false;
    }
    this.addContact = addContact;
}

function schedule() {
    function run() {
        getDevicesAndUpdateAlarm();
    }
    this.run = run;
}

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

function maplast() {
    function run() {
        this.showMapLast();
        getDevicesAndUpdateAlarm();
    }
    this.run = run;

    function showMapLast() {
        for (j in histdata) {
            var details = histdata[j][0];
            var lat = histdata[j][1];
            var lng = histdata[j][2];
            var offset = Math.abs(histdata[j][3]);
            var point = getLatLng(lat,lng);

            map.addOverlay(createMarker(details,point,offset, false))
        }
        
        // Show the marker for the last point in the list
        if (point != undefined) {
            map.setCenter(point, 14);
            map.openInfoWindowHtml(point, details);
        }
    }
    this.showMapLast = showMapLast;
}

/**
 * Retrieve the list of devices for this account and
 * call the updateAlarm() function with the results
 *
 * @return void
 */
function getDevicesAndUpdateAlarm() {
    // Update every X seconds
    var updateSeconds = 10;

    $.ajax({
        url:"/devices//+json/",
        dataType:"json",
        success: function(json) {
            updateAlarm(json);
        }
    });

    // Run this function once every X seconds
    setTimeout(getDevicesAndUpdateAlarm, updateSeconds * 1000);
}

var isFirstAlert = true;
var isInAlertState = false;
var previousAlertNotificationMessage = '';
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.emergkey == 1) {
            nameVar.push(myname+' Emergency');
            alarmVar = 2;				//emergkey beats nomotion for sound
        }
        if ( mydevice.nomotion == 1 ) {
            nameVar.push(myname+' No Motion');
            if (alarmVar < 2) {
                alarmVar = 1;
            }
        }
        if ( mydevice.nocheckin == 1) {
            nameVar.push(myname+' No Checkin');
            if (alarmVar < 2) {
                alarmVar = 1;
            }
        }
    });

    var alertNotificationMessage = nameVar.join(", ");

    if (alertNotificationMessage == '') {
        // Clear the alert notification
        if (isInAlertState) {
            isFirstAlert = true;

            // Stop the sound and marquee animation
            isInAlertState = false;

            // Clear the message
            $('#alert .alert_message').empty().hide();
        }
    } else if (alertNotificationMessage != previousAlertNotificationMessage) {
		// Add the audio element and marquee message
        if (isFirstAlert) {
            isFirstAlert = false;
            isInAlertState = true;

            // Add the marquee and text
            $('#alert .alert_message').html('<marquee behavior="scroll" scrollamount="3" direction="left" width="900">' + alertNotificationMessage + '</marquee>').show();

            // Setup the scrolling marquee
            $('#alert marquee').marquee('marquee').mouseover(function () {
                $(this).trigger('stop');
            }).mouseout(function () {
                $(this).trigger('start');
            }).mousemove(function (event) {
                if ($(this).data('drag') == true) {
                    this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
                }
            }).mousedown(function (event) {
                $(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
            }).mouseup(function () {
                $(this).data('drag', false);
            });

            soundManager.onready(function(){
                soundManager.play(alertSoundId, {onfinish: loopAlertSound});
            });

            // Loop the background animation effect
            loopAlertStyle();
        } else {
            // Already in the Alert state, so just update the message
            $('#alert .alert_message .marquee div').html(alertNotificationMessage);
        }
    }

    previousAlertNotificationMessage = alertNotificationMessage;

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

function loopAlertSound() {
    if (isInAlertState) {
        this.play({onfinish:loopAlertSound});
    }
}
// Loop the alert background color change
function loopAlertStyle() {
    if (isInAlertState) {
        $('#alert .alert_message').animate({
            backgroundColor: '#ffffff'
        }, 2000, function () {
            $('#alert .alert_message').animate({
                backgroundColor: '#ff0000'
            }, 2000, function () {
                loopAlertStyle();
            });
        });
    }
}

function SetCookie(c_name,value,expiredays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value) + (expiredays==null ? "" : ";expires="+exdate.toGMTString());
}

function toggleSpinner(spinnerElementId) {
    $('#' + spinnerElementId).toggleClass('active');
}

