﻿function DeviceManagerController()
{
    this.Devices = null;
    this.HistoryLocations = null;
    this.TrackingEvent = null; 
    this.SocialNetworkManager = new SocialNetworkManager();
}

//attributes
DeviceManagerController.prototype.Devices;
DeviceManagerController.prototype.HistoryLocations;
DeviceManagerController.prototype.TrackingEvent;
DeviceManagerController.prototype.SocialNetworkManager;
DeviceManagerController.prototype.CurrentPoint;
var eventStarted = new Boolean(false);
var pins = new Array();
var refreshTimer;
var eventTimer;
var singleParticipant = new Boolean(false);
var circuit = new Boolean(false);
var deviceMarkers = new Array("/images/map/deviceMarkers/Black.png",
                    "/images/map/deviceMarkers/Blue.png",
                    "/images/map/deviceMarkers/Gold.png",
                    "/images/map/deviceMarkers/Green.png",
                    "/images/map/deviceMarkers/Orange.png",
                    "/images/map/deviceMarkers/Purple.png",
                    "/images/map/deviceMarkers/Red.png",
                    "/images/map/deviceMarkers/Silver.png",
                    "/images/map/deviceMarkers/Turquoise.png");
                    

DeviceManagerController.prototype.LoadDevices = function(){
    EventEagle.EventEagleService.GetAllDevices(Function.createDelegate(this, this.OnGetAllDevices),Function.createDelegate(this,this.OnFailGetAllDevices));
    
}

DeviceManagerController.prototype.GetAllDeviceHistory = function()
{
    EventEagle.EventEagleService.GetAllDeviceLocations(Function.createDelegate(this, this.OnGetAllLocations),Function.createDelegate(this,this.OnFailGetAllLocations));
}

DeviceManagerController.prototype.OnGetAllDevices = function(result){
    //store then result
    this.Devices = result;
    var speed;
    if (singleParticipant == false){
    var counter = 0;
     for (device in this.Devices) {
            this.Devices[device].CurrentPinPointShape = this.MarkOnMap(this.Devices[device].LastValidLocation, this.Devices[device].LastValidLocation.SentDateDateTimeShort, "Speed " + this.Devices[device].LastValidLocation.Speed + "mph", '<img class ="current" width="26" height="26" style="margin:0px 0 -3px 5px; padding:0px;" src= "' + deviceMarkers[counter] + '" /><div class ="atclabel">' + this.Devices[device].DeviceHost.Name + '</div>');
            counter++;
        }
        //map.SetMapView(pins);
     }
     else{
        if (this.Devices.length != 0){
            speed = this.Devices[0].LastValidLocation.Speed;
            //this.Devices[0].CurrentPinPointShape = this.MarkOnMap(this.Devices[0].LastValidLocation, this.Devices[0].LastValidLocation.SentDateDateTimeShort, "Speed " + speed + "mph", '<img class ="current" width="26" height="26" style="margin:0px 0 -3px 5px; padding:0px;" src="/images/map/Current26x26.gif" />');
            this.CurrentPoint = this.MarkOnMap(this.Devices[0].LastValidLocation, this.Devices[0].LastValidLocation.SentDateDateTimeShort, "Speed " + speed + "mph", '<img class ="current" width="26" height="26" style="margin:0px 0 -3px 5px; padding:0px;" src="/images/map/Current26x26.gif" />');
            map.SetMapView(pins);
            this.GetAllDeviceHistory();
        }
     }
}

DeviceManagerController.prototype.OnFailGetAllDevices = function(result){
    if (result._message=='Premature')
    {//Event not started, so no devices will be loaded
    }
    else{
        //alert("Failed to load devices");
        showStatus("Failed to load devices", 8000, 'error');
    }
}

DeviceManagerController.prototype.OnGetAllLocations = function(result){
    //store then result
    this.HistoryLocations = result;
    var date;
    var speed;
    for(deviceLocation in this.HistoryLocations)
    {
        date = this.HistoryLocations[deviceLocation].SentDateDateTimeShort;
        speed = this.HistoryLocations[deviceLocation].Speed;
        this.MarkOnMap(this.HistoryLocations[deviceLocation],  date, "Speed " + speed + " mph", '<img class ="history" width="7" height="7" style="margin:0px 0 -3px 5px; top:5px; left:5px; padding:0px;" src="/images/map/History7x7.gif" />');
    }
     map.SetMapView(pins);
}

DeviceManagerController.prototype.OnFailGetAllLocations = function(result){
//alert("Failed to load locations");
showStatus("Failed to load locations", 8000, 'error'); 

}

DeviceManagerController.prototype.MarkOnMap = function(location, title, description, image){
      //alert(location.Latitude);
      var shape = new VEShape(VEShapeType.Pushpin, [new VELatLong(location.Latitude, location.Longitude)]);
      shape.SetCustomIcon(image);
      shape.SetTitle(title);
      shape.SetDescription('<div class="GenericInfoBox">'+description+'</div>');
      pins.push(shape);
      map.AddShape(shape); 
      return shape;
}


DeviceManagerController.prototype.LoadEventDetails = function(){
    //alert("Load Details");
    EventEagle.EventEagleService.GetTrackingEvent(Function.createDelegate(this, this.OnGetTrackingEvent),Function.createDelegate(this,this.OnFailGetTrackingEvent));
    
}

DeviceManagerController.prototype.OnGetTrackingEvent = function(result) {
    this.TrackingEvent = result;
    singleParticipant = this.TrackingEvent.SingleParticipant;
    circuit = this.TrackingEvent.Circuit;
    $(".dialog").html('<div id="dialog"><p>' + this.TrackingEvent.EventMessage + '</p></div>');
    $(".dialog").dialog({
        modal: true,
        resizable: false,
        title: this.TrackingEvent.Name,
        height: 250,
        width: 360,
        hide: 'fadeOut'
        /*buttons: {
        OK: function() {
        $(this).dialog('close');
        }
        }*/
    });
    this.SetEventDialog();
    //this.SetLogo();
    this.SetUpMap();
    this.SocialNetworkManager.LoadTwitter(this.TrackingEvent.TwitterAccount.AccountName);
    this.SocialNetworkManager.LoadFlickr(this.TrackingEvent.FlickrAccount.AccountName);
    this.SetParticipantEventMessage();
    this.SetTwitterMessage(this.TrackingEvent.TwitterAccount.AccountName);
    this.SetFlickrMessage(this.TrackingEvent.FlickrAccount.AccountName);
    this.AddEventName();
    //this.SetStyling();    
    //alert(this.TrackingEvent.EventMessage);
    //	$("#dialog").dialog({ autoOpen: false })
    if (this.TrackingEvent.EventState == 0) {
        //alert("The event has not been started yet.");
        //start the timer : timer waiting for hiddenfield set time and activate refresh timer
        EventCountDown();
    }
    else if (this.TrackingEvent.EventState == 2) {
        if (this.TrackingEvent.TweetHistory == null){
            this.ArchiveTweets();
        }
        //just call the history webmthod do not need to start the refresh timer
        if (singleParticipant == true){
            this.GetAllDeviceHistory();
        }
        //alert("The event has expired now.")
    }
    else {
        //start the refresh timer loading device latest location and call the history points
        this.LoadDevices();
        //this.GetAllDeviceHistory();
        timedCount();
    }
    map.SetMapView(pins);
}

DeviceManagerController.prototype.OnFailGetTrackingEvent = function(result){
    alert("Failed to load Event");
}
 
DeviceManagerController.prototype.SetUpMap = function(){
    if (circuit == false){
        this.MarkOnMap(new VELatLong(this.TrackingEvent.StartLocation.Latitude, this.TrackingEvent.StartLocation.Longitude), 'Event Starting Point', this.TrackingEvent.StartDate.format("dddd dd MMMM yyyy, HH:mm"), '<img class ="start" width="33" height="42" style="position:relative;padding:0px;left:12px;top:-17px;margin:0;width:33px; height:42px;" src="/images/map/StartMarker7.png" />');
        this.MarkOnMap(new VELatLong(this.TrackingEvent.EndLocation.Latitude, this.TrackingEvent.EndLocation.Longitude), 'Event End Point', this.TrackingEvent.EndDate.format("dddd dd MMMM yyyy, HH:mm"), '<img class ="end" width="42" height="33" style="position:relative;padding:0px;left:12px;top:-8px;margin:0;" src="/images/map/EndMarker7.png" />');
    //map.SetMapView(pins);
    }
    else{
    //Mark single start/end point
    }
}

DeviceManagerController.prototype.SetEventDialog = function() {
    var EventTimings = '';
    if (this.TrackingEvent.EventState == 2)
        EventTimings = '<p>The Event ended on <b>' + this.TrackingEvent.EndDate.format("dddd dd MMMM yyyy, HH:mm") + '</b>.</p>';
    else
        EventTimings = '<p>The Event runs from <b>' + this.TrackingEvent.StartDate.format("dddd dd MMMM yyyy, HH:mm") + '</b> until <b>' + this.TrackingEvent.EndDate.format("dddd dd MMMM yyyy, HH:mm") + '</b>.</p>';
    $('#dialog').append(EventTimings);
}

DeviceManagerController.prototype.SetParticipantEventMessage = function() {
    var EventTimings = '';
    var PartnerMessage = '';
    if (this.TrackingEvent.EventState == 1)
        EventTimings = '<p>The Event runs from ' + this.TrackingEvent.StartDate.format("dddd dd MMMM yyyy, HH:mm") + ' to ' + this.TrackingEvent.EndDate.format("dddd dd MMMM yyyy, HH:mm") + '.</p>';
    if (this.TrackingEvent.Style == 'biketrac.css')
        PartnerMessage = '<p>Tracking devices proudly produced by <a href="https://www.roadangelgroup.com/biketrac.aspx" target="_blank">Road Angel</a>.</p>';
    else
        PartnerMessage = '<p>Tracking devices and software proudly produced by <a href="http://www.alphamicro.net/" target="_blank">Alpha Micro Systems</a>.</p>';

    $('#participantEventMessage').html(this.TrackingEvent.EventMessage + EventTimings + PartnerMessage);
    $('#participantEventInfoHeader').html('<h1>' + this.TrackingEvent.Name + '</h1>');
}

DeviceManagerController.prototype.SetTwitterMessage = function(TwitAccount) {
    var twittermessage;
    if ((TwitAccount != null) && (TwitAccount != '')) {
        if ((this.TrackingEvent.EventState == 0) || (this.TrackingEvent.EventState == 1)) {
            twittermessage = '<p>Throughout this event I will be posting onto my <a href="http://twitter.com/' + TwitAccount + '" target="_blank">Twitter Event page</a>. All messages will also be shown on this page as soon as they are posted.</p>';
            twittermessage += '<p>If you have any message of encouragement you can post them against your own Twitter account.   To do this you simply need to include <b>@' + TwitAccount + '</b> in your message.  It will then immediately be shown on this page.</p>';
            twittermessage += '<p>If you do not already have one you will need to <a href="http://twitter.com/signup" target="_blank">Create a Twitter Account</a>.</p>';
        }
        else {
            twittermessage = '<p>Throughout the event well wishers and I posted messages against my <a href="http://twitter.com/' + TwitAccount + '" target="_blank">Twitter Event page</a>. The facility to post onto this site has now been frozen, but will be kept here for the sake of posterity.</p>';
            twittermessage += '<p>Many thanks to all who posted messages of encouragement throughout the event.</p>';            
        }
        $('#twitterContainerBody').html(twittermessage);
    }
}

DeviceManagerController.prototype.SetFlickrMessage = function(FlickrAccount) {
        if ((FlickrAccount != null) && (FlickrAccount != '')) {
            var FlickrGetUserName = 'http://api.flickr.com/services/rest/?format=json&jsoncallback=?&api_key=bb14c3a46a55bd099214ebdc854e6798&method=flickr.urls.getUserProfile&user_id=' + FlickrAccount;


        $.getJSON(FlickrGetUserName,
		    function(data) {
		        var flickrmessage;
		        flickrmessage = '<p>Throughout the event I will be posting photos up on my Flickr page.</p>';
		        flickrmessage += '<p>You will be able to view them on this page as well as on my <a href="'+data.user.url+'" target="_blank">Flickr Page</a>. You can see a larger version of any photo by clicking on the magnifying glass against it.</p>';

		        $('#flickrContainerBody').html(flickrmessage);
        });
    }
}

DeviceManagerController.prototype.SetLogo = function() {
    if (this.TrackingEvent.Logo != null)
        $('#nameContainer').css({ 'background': 'url("' + this.TrackingEvent.Logo + '")' });
}

DeviceManagerController.prototype.SetStyling = function() {
    $('.ui-dialog-content a, .hoverContainer a, .query .tweet_list li a ').css({ 'color': '#F17A2A' });
}

DeviceManagerController.prototype.AddEventName = function() {
$('#nameContainer').append('<div id="EventNameBar">'+ this.TrackingEvent.Name +'</div>');
}

DeviceManagerController.prototype.RefreshData = function(){
    this.SocialNetworkManager.LoadTwitter(this.TrackingEvent.TwitterAccount.AccountName);
    this.SocialNetworkManager.LoadFlickr(this.TrackingEvent.FlickrAccount.AccountName);
    EventEagle.EventEagleService.GetAllDevices(Function.createDelegate(this, this.OnRefreshTrackingEvent),Function.createDelegate(this,this.OnFailRefreshTrackingEvent));
}

    DeviceManagerController.prototype.OnRefreshTrackingEvent = function(result){
    //Update the map
    if (singleParticipant == true){
        outerloop:
        for(device in result)
        {
            for (oldDevice in this.Devices){
                if (result[device].ID == this.Devices[oldDevice].ID)
                    //alert('Found moving device');
                    result[device].CurrentPinPointShape = this.Devices[oldDevice].CurrentPinPointShape;
                    this.Devices[oldDevice]= result[device];
                    //this.Devices[oldDevice].CurrentPinPointShape.SetCustomIcon('<img class ="history" width="7" height="7" style="margin:0px 0 -3px 5px; padding:0px;" src="/images/map/History7x7.gif" />');
                    this.CurrentPoint.SetCustomIcon('<img class ="history" width="7" height="7" style="position:relative;padding:0px;left:4px;top:2px" src="/images/map/History7x7.gif" />');
                    //this.Devices[oldDevice].CurrentPinPointShape = this.MarkOnMap(this.Devices[device].LastValidLocation, this.Devices[device].LastValidLocation.SentDateDateTimeShort,"Speed " + this.Devices[device].LastValidLocation.Speed + " mph", '<img class ="current" width="26" height="26" style="margin:0px 0 -3px 5px; padding:0px;" src="/images/map/Current26x26.gif" />');
                    this.CurrentPoint = this.MarkOnMap(this.Devices[device].LastValidLocation, this.Devices[device].LastValidLocation.SentDateDateTimeShort, "Speed " + this.Devices[device].LastValidLocation.Speed + " mph", '<img class ="current" width="26" height="26" style="position:relative;padding:0px;left:2px;top:-5px;" src="/images/map/Current26x26.gif" />');
                    break outerloop;
                }
            }
        }
     else{
          this.Devices = result;
          map.DeleteAllShapes();
          pins = new Array();
            this.SetUpMap();
            var counter = 0;
            for (device in this.Devices) {
                this.Devices[device].CurrentPinPointShape = this.MarkOnMap(this.Devices[device].LastValidLocation, this.Devices[device].LastValidLocation.SentDateDateTimeShort, "Speed " + this.Devices[device].LastValidLocation.Speed + "mph", '<img class ="current" width="26" height="26" style="position:relative;padding:0px;left:2px;top:-5px;" src="' + deviceMarkers[counter] + '" /><div class ="atclabel">' + this.Devices[device].DeviceHost.Name + '</div>');
                counter++;
            }
            map.SetMapView(pins);
        }
    }

    DeviceManagerController.prototype.OnFailRefreshTrackingEvent = function(result){
    //alert("Failed to refresh location data");
    if (result._message=='Expired' || result._message == '2'){
        //Kill the timer
        clearTimeout(refreshTimer);
        //change live pinpoint to history pinpoint
        for (oldDevice in this.Devices){
            this.Devices[oldDevice].CurrentPinPointShape.SetCustomIcon('<img class ="history" width="7" height="7" style="position:relative;padding:0px;left:4px;top:2px" src="/images/map/History7x7.gif" />');
        }
    }
    }

    function timedCount() {
        $('#_statusbar').html('');
        showStatus("Checking for new locations, messages and photos", 6000, 'genericRefresh');    
        if (eventTimer != null){
            clearTimeout(eventTimer);
            eventTimer = null;
            deviceManagerController.LoadDevices();
        }
        else
            deviceManagerController.RefreshData();
        
        refreshTimer=setTimeout("timedCount()",60000);
        
        
    }

    function EventCountDown()
    {
        //alert("Counting down");
        var counterValue = document.getElementById("HiddenEventStartTimeCounter").value;
        //alert(counterValue);
        eventTimer = setTimeout("timedCount()", counterValue * 1000); 
    }
    
    DeviceManagerController.prototype.ArchiveTweets = function(){
        if (this.TrackingEvent.TwitterAccount.AccountName != null && this.TrackingEvent.TwitterAccount.AccountName != ''){
            $.getJSON('http://search.twitter.com/search.json?&q=' + this.TrackingEvent.TwitterAccount.AccountName + '&rpp=100&callback=?', function(data){
            EventEagle.EventEagleService.SaveTweets(Sys.Serialization.JavaScriptSerializer.serialize(data));  
            });      
        }
    }      



