/*******************************************************************************************************/
/*-------------------------------------------Globals---------------------------------------------------*/
/*******************************************************************************************************/
    var xmlLocation = Sarissa.getDomDocument();
    var xmlLocationDates = Sarissa.getDomDocument();
    var xmlSettings = Sarissa.getDomDocument();
    var xsltProcessor = new XSLTProcessor();
    var xsltProcessor2 = new XSLTProcessor();
 
    var xslLocationDoc;
    var xslLocationDatesDoc;
    var xslMessageDoc;
    var htmlResultDocument;
    var htmlResultString;    
    var highestLocationID=0;
    
    var start = false;
      
    function LoadXSL()
    {
        var xmlxslhttp = new XMLHttpRequest();
        var xslDoc = Sarissa.getDomDocument();
               
        xmlxslhttp.open("GET", "xsl/message.xslt", false);
        xmlxslhttp.send('');
        xslMessageDoc = (new DOMParser()).parseFromString(xmlxslhttp.responseText, "text/xml");
        
        
        
    }

/*******************************************************************************************************/
/*-------------------------------------------OBJECTS---------------------------------------------------*/
/*******************************************************************************************************/


  
 /*Location*/
 function xLocation()
 {
    this.id = null;
    this.Latitude = null;
    this.Longitude= null;
    this.DateTimeRecorded = null;
    this.Image = null;
    this.PushPin = null;
    
    //methods
    this.ChangeToHistoryImage = ChangeToHistoryImage;
 }
 
 function ChangeToHistoryImage()
 {
    this.Image = 'images/mapmarkers/channelMarkerHistory.gif';
 }
 
   /*Message*/
 function Message()
 {
    this.id = null;
    this.Message= null;
 }
 
 function DisplayMessageTable()
 {
        xsltProcessor2.importStylesheet(xslMessageDoc);
        htmlResultDocument = xsltProcessor2.transformToDocument(xmlMessage);
        htmlResultString =  (new XMLSerializer().serializeToString(htmlResultDocument));
        MessagesWindow.SetContent(htmlResultString);
        messagesTimer = setTimeout("LoadAllMessages()",60000);
 }
 
 function DisplayLocationDateTable()
 {
        htmlResultString ='';
        var xmlnode = xmlLocationDates.getElementsByTagName("location");
        var datex;
        var location;
        
        
                            
                            
        htmlResultString += '<div id="MapController"><div id="MapControlMapStyle"><a href="javascript:map.SetMapStyle(VEMapStyle.Road);">ROAD</a>' +
                            ' | <a href="javascript:map.SetMapStyle(VEMapStyle.Aerial)">AERIAL</a>' +                 
                            ' | <a href="javascript:map.SetMapStyle(VEMapStyle.Hybrid)">HYBRID</a>'+
                            ' </div><div id="MapControlZoom"><a alt="Zoom In" href="javascript:map.ZoomIn()">Z +</a>' +
                            ' | <a alt="Zoom Out" href="javascript:map.ZoomOut()">Z -</a>' +
                            '</div></div>';
                            
                                            

                                            
        htmlResultString += '<br/><br/><p><a class=journeyLink href="javascript:LoadLastLocation()">Show Last Location</a></p>';                          
        htmlResultString += '<p><a class=journeyLink href="javascript:LoadAllLocations()">Show All Locations</a></p>';                          
        
        for(j=0;j<xmlnode.length;j++)
        {
            location = new xLocation();
            location.DateTimeRecorded = xmlnode.item(j).getAttribute('DateTimeRecorded');
            htmlResultString += "<p><a class=journeyLink href=\"javascript:LoadLocationsByDate('"+ location.DateTimeRecorded.toString() +"')\">Show " + location.DateTimeRecorded + " Locations</a></p>";
        }
        
        htmlResultString += "<div id='journeyStatusImage'></div><div id='journeyStatusText'></div><p>&nbsp</p>"
        JourneyWindow.SetContent(htmlResultString);
 }
 
 /*Settings*/
 function Settings()
 {
    this.EventStarted = false;
    this.EventStartDateTime = null;
    this.Hours = 0;
    this.Minutes = 0;
    this.Seconds = 0;
 }
 
 
 
 
/*******************************************************************************************************/
/*-------------------------------------------LOGIC-*---------------------------------------------------*/
/*******************************************************************************************************/

function LoadAllLocations() 
{
    ShowLoadingMessage('Please wait loading map locations...');
    sleep(1);
    PageMethods.LoadAllLocations(OnSucceeded, OnFailed);
}

function LoadLocationsByDate(datex) 
{
    ShowLoadingMessage('Please wait loading map locations...');
    PageMethods.LoadLocationsByDate(datex, OnSucceeded, OnFailed);
    
}

function LoadLastLocation() 
{
    PageMethods.LoadLastLocation(OnSucceeded, OnFailed);
}

function LoadLocationDates() 
{
    PageMethods.LoadLocationDates(OnSucceeded, OnFailed);
}


function LoadAllMessages() 
{
    PageMethods.LoadAllMessages(OnSucceeded, OnFailed);
}

function LoadSettings() 
{
    PageMethods.LoadSettings(OnSucceeded, OnFailed);
}

// Callback function invoked on successful 
// completion of the page method.
function OnSucceeded(result, userContext, methodName) 
{
    if (methodName == "LoadLastLocation")
    {
         xmlLocation = (new DOMParser()).parseFromString(result, "text/xml");
         CreateLocationObject();
         PlotMarkers();
         ZoomToLastLocation();
    }
    else if (methodName == "LoadAllMessages")
    {
         xmlMessage= (new DOMParser()).parseFromString(result, "text/xml");
         DisplayMessageTable();
    }
    else if (methodName == "LoadSettings")
    {
         xmlSettings= (new DOMParser()).parseFromString(result, "text/xml");
         CreateSettingsObject();
         SetDisplay();
    }
    else if (methodName == "LoadLocationsByDate")
    {
         xmlLocation = (new DOMParser()).parseFromString(result, "text/xml");
         CreateLocationObject();
         PlotMarkers();
         HideLoadingMessage();
         ZoomToLastLocation();
    }
    else if (methodName == "LoadLocationDates")
    {
         xmlLocationDates = (new DOMParser()).parseFromString(result, "text/xml");
         DisplayLocationDateTable();
    }
    else if (methodName == "LoadAllLocations")
    {
         xmlLocation = (new DOMParser()).parseFromString(result, "text/xml");
         
         CreateLocationObject();
         ShowLoadingMessage('Please wait loading map locations...');
         PlotMarkers();
         HideLoadingMessage();
         ZoomToLastLocation();
    }
    
    
    //positionTimer = setTimeout("LoadLatestPositions()",120000);  
    
    
}

function CreateLocationObject()
{
        var xmlnode = xmlLocation.getElementsByTagName("location");
        var objectsCreated = 0;
        
        //empty the existing array
        LocationList = null;
        LocationList = new Array();
        
        if(xmlnode.length > 0)
            ReplaceLastLocationMarker();
            
        for(j=0;j<xmlnode.length;j++)
        {
            xlocation = new xLocation();    
            xlocation.id = xmlnode.item(j).getAttribute('LocationID');
            xlocation.Latitude = xmlnode.item(j).getAttribute('Latitude');
            xlocation.Longitude= xmlnode.item(j).getAttribute('Longitude');
            
            xlocation.DateTimeRecorded = xmlnode.item(j).getAttribute('DateTimeRecorded');
            if(j == xmlnode.length-1) //it the latest marker! 
                xlocation.Image = 'images/mapmarkers/Current26x26.gif';
            else
                xlocation.Image = 'images/mapmarkers/History7x7.gif';
                
            highestLocationID = xlocation.id;
            LocationList.push(xlocation);    
            objectsCreated++;
         }   
         return objectsCreated;
}


function CreateSettingsObject()
{
   
        var xmlnode = xmlSettings.getElementsByTagName("Global");
        objSettings = new Settings();  
        for(j=0;j<xmlnode.length;j++)
        {
            objSettings = new Settings();    
            objSettings.EventStartDateTime = xmlnode.item(j).getAttribute('StartEvent');
            
            if(xmlnode.item(j).getAttribute('EventStarted')==1)
                objSettings.EventStarted = true;
            else
                objSettings.EventStarted = false;
            


         }   
}

function SetDisplay()
{

    if (objSettings.EventStarted == false)
    {
        //objManager.ShowWindow('MiddleWindow'); 
        //MiddleWindow.SetContent("<div class='miniAMSLogo'><a href='http://www.alphamicro.net/' alt='Alpha Micro'><img  src='images/logos/amslogo.png' alt='Alpha Micro Systems'/></a></div><p style='margin:5% 5% 0 5%'><p>Africa...where man began. <br/><br/><br/><p style='text-align:center;'><a href=javascript:objManager.CloseWindow('" +MiddleWindow.id+ "')>Close Window</a></p>."); 
    }
    else
    {
        ZoomToLastLocation();
    }
    
    
   
    objManager.ShowWindow('LeftInfoWindow');           
      
    
    
}

function PlotMarkers()
{
        var latlongpoint; 
        var pin; 
       
        map.Clear();
                    
        for (x in LocationList)
        {
            if (LocationList[x].PushPin == null)
            {
                try
                {
                    latlongpoint = new VELatLong(LocationList[x].Latitude,LocationList[x].Longitude); 
                    pin = new VEPushpin(LocationList[x].id,latlongpoint,LocationList[x].Image,'Date and Time', LocationList[x].DateTimeRecorded ,'');            
                    map.AddPushpin(pin);     
                }
                catch(err) {  }

                LocationList[x].PushPin = pin;
            }
        }
        //change this FOR LIVE RELEASE
        //positionTimer = setTimeout("LoadLatestPositions()",120000 );      
}

function ShowLoadingMessage(message)
{
    WriteHTML("journeyStatusImage", "<img src='images/ajax-loader.gif' />");
    WriteHTML("journeyStatusText", message);
}

function HideLoadingMessage()
{
    WriteHTML("journeyStatusImage", "");
    WriteHTML("journeyStatusText","" );
}

function sleep(sleepinterval)
{
    sleepinterval = sleepinterval*1000;
    var sleeping=true;
    var startTime = new Date();
    var alarm;
    while(sleeping)
    {
        alarm= new Date();
        if(alarm.getTime() - startTime.getTime() > sleepinterval )
        {
            sleeping = false;
        }
    }
}

function pause( iMilliseconds )
{
    var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
    window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}


function ReplaceLastLocationMarker()
{
        //if we are only updating the markers we need to replace the last one with a history marker
 
          theLastLocation = LocationList.pop();
         
          if (theLastLocation!=null)
          {
            map.DeletePushpin(theLastLocation.id);
            theLastLocation.Image = 'images/mapmarkers/History7x7.gif';
            theLastLocation.PushPin = null;
            LocationList.push(theLastLocation);
          }
          
       
        
}

function PlotCrosshair()
{
    var latlongpoint = new VELatLong(13.379734, -16.753788); 
    pin = new VEPushpin(99999,latlongpoint,'images/mapmarkers/Crosshair35x35.gif','Brufut, Gambia', 'Final Destination' ,'');            
    map.AddPushpin(pin); 
}

function ZoomToLastLocation()
{
        var latlongpoint;
        for (x in LocationList)
        {
            latlongpoint = new VELatLong(LocationList[x].Latitude,LocationList[x].Longitude); 
        }
        if(latlongpoint!=null)
            map.SetCenterAndZoom(latlongpoint, 12);

}
// Callback function invoked on failure 
// of the page method.
function OnFailed(error, userContext, methodName) 
{
    if(error !== null) 
        alert(error.get_message());
}


function SetTimers()
{
  
}
    
function ClearTimer(objTimer)
{
    clearTimeout(objTimer);
}

