/*******************************************************************************************************/
/*-------------------------------------------Globals---------------------------------------------------*/
/*******************************************************************************************************/
    var xmlSwimmer = Sarissa.getDomDocument();
    var xmlLocation = Sarissa.getDomDocument();
    var xmlSettings = Sarissa.getDomDocument();
    var xsltProcessor = new XSLTProcessor();
    var xsltProcessor2 = new XSLTProcessor();
    var xslSwimmersDoc;
    var xslLocationDoc;
    var xslMessageDoc;
    var htmlResultDocument;
    var htmlResultString;    
    var highestLocationID=0;
    
    var start = false;
    var c=0;
    var secString="00"
    var t;    
    var hours=0;
    var hourString="00";
    var mins=0;
    var minString="00";
      
    function LoadXSL()
    {
        var xmlxslhttp = new XMLHttpRequest();
        var xslDoc = Sarissa.getDomDocument();
        
        xmlxslhttp.open("GET", "xsl/swimmer.xslt", false);
        xmlxslhttp.send('');
        xslSwimmersDoc = (new DOMParser()).parseFromString(xmlxslhttp.responseText, "text/xml");
        
        xmlxslhttp.open("GET", "xsl/message.xslt", false);
        xmlxslhttp.send('');
        xslMessageDoc = (new DOMParser()).parseFromString(xmlxslhttp.responseText, "text/xml");
    }

/*******************************************************************************************************/
/*-------------------------------------------OBJECTS---------------------------------------------------*/
/*******************************************************************************************************/

/*Swimmer*/
 function Swimmer() 
 {
    this.id= null;
    this.Name = '';
    this.IsSwimming = null;
    this.PhotoPath = null;
    this.xWindow = null;
 }
 
 function DisplaySwimmerContent()
 {
 
        xsltProcessor.importStylesheet(xslSwimmersDoc);
        for (objSwimmer in SwimmerList)
        {
            xsltProcessor.setParameter(null, "SwimmerID", SwimmerList[objSwimmer].id); 
            htmlResultDocument = xsltProcessor.transformToDocument(xmlSwimmer);
            htmlResultString =  (new XMLSerializer().serializeToString(htmlResultDocument));
            WriteHTML(SwimmerList[objSwimmer].xWindow.contentid, htmlResultString );      
        }
        
        
 }
 
 function GetSwimmerByID(id)
 {
    for(obj in SwimmerList)
    {
        
        if(SwimmerList[obj].id == id)
            return SwimmerList[obj];
    }
    return null;
 }
 
 /*Location*/
 function xLocation()
 {
    this.id = null;
    this.Latitude = null;
    this.Longitude= null;
    this.SwimmerID = 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);
 }
 
 /*Settings*/
 function Settings()
 {
    this.EventStarted = false;
    this.EventStartDateTime = null;
    this.Hours = 0;
    this.Minutes = 0;
    this.Seconds = 0;
 }
 
 
 
 
/*******************************************************************************************************/
/*-------------------------------------------LOGIC-*---------------------------------------------------*/
/*******************************************************************************************************/

// Gets the session state value.
function LoadAllSwimmers() 
{
    PageMethods.LoadAllSwimmers(OnSucceeded, OnFailed);
}

function LoadAllLocations() 
{
    PageMethods.LoadAllLocations(OnSucceeded, OnFailed);
}

function LoadLatestPositions() 
{
    
    PageMethods.LoadLatestLocations(highestLocationID, 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 == "LoadAllSwimmers")
    {
        
         xmlSwimmer = (new DOMParser()).parseFromString(result, "text/xml");
         CreateSwimmerObjects();
         DisplaySwimmerContent(); 
         LoadAllLocations();
         objManager.ShowWindow('LogoWindow'); 
    }
    else if (methodName == "LoadAllLocations")
    {
         
         xmlLocation = (new DOMParser()).parseFromString(result, "text/xml");
         CreateLocationObjects();
         PlotMarkers(false);
         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 == "LoadLatestLocations")
    {
         xmlLocation = (new DOMParser()).parseFromString(result, "text/xml");
         newLocations = CreateLocationObjects();
         
         
         
         if (newLocations > 0)
         {
            UpdateSwimmerStatus();
            PlotMarkers(true);
            ZoomToLastLocation();   
         }
         else
            positionTimer = setTimeout("LoadLatestPositions()",120000);  
    }
    
}

function CreateLocationObjects()
{
        var xmlnode = xmlLocation.getElementsByTagName("location");
        var objectsCreated = 0;
        
        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.SwimmerID = xmlnode.item(j).getAttribute('SwimmerID');
            
            xlocation.Swimmer = GetSwimmerByID(xlocation.SwimmerID);
            
            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 CreateSwimmerObjects()
{
        var xmlnode = xmlSwimmer.getElementsByTagName("swimmer");
        var swimmerName;

        
            for(j=0;j<xmlnode.length;j++)
            {
                    objSwimmer = new Swimmer();    
                    objSwimmer.id = xmlnode.item(j).getAttribute('SwimmerID');
                    objSwimmer.Name = xmlnode.item(j).getAttribute('Name');
                    objSwimmer.IsSwimming = xmlnode.item(j).getAttribute('IsSwimming');
                    objSwimmer.PhotoPath = xmlnode.item(j).getAttribute('Photo');
                    //create window for object
                    if(objSwimmer.IsSwimming==1)
                        swimmerName = objSwimmer.Name + ' <span class="isSwimming"> - Swimming</span>';           
                    else
                        swimmerName = objSwimmer.Name;          
                        
                    objSwimmer.xWindow = new xWindow('SwimmerWindow'+objSwimmer.id  ,swimmerName ,  "WindowLedge1",  "","");   
                    objSwimmer.xWindow.maxHeight = 270;
                    objSwimmer.xWindow.minimiseOnOpen = true;
                    objSwimmer.xWindow.hideCloseButton = true;
                    
                    objManager.AddWindow(objSwimmer.xWindow);
                    objManager.ShowWindow(objSwimmer.xWindow.id);  
                    
                    SwimmerList.push(objSwimmer);    
             }   
        
         
}

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;
             
             objSettings.Hours = xmlnode.item(j).getAttribute('Hours');
             objSettings.Minutes = xmlnode.item(j).getAttribute('Minutes');
             objSettings.Seconds = xmlnode.item(j).getAttribute('Seconds');
            hours = Number(objSettings.Hours);
            mins = Number(objSettings.Minutes); 
            c = Number(objSettings.Seconds);
            
            if(hours < 0)
                hours = Math.sqrt(hours * hours );
            if(mins < 0)
                mins = Math.sqrt(mins * mins);
            if(c < 0)
                c = Math.sqrt(c*c);                
                

         }   
}

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><strong>Congratulations to the Swim team!</strong></p><p>They landed in France at 15:37 on 16/09/2007  - a fantastic effort . It took 14 hours and 11 minutes to swim and you can see their route on the map behind this window.</p><p>Over <strong>12,000 pounds</strong> has been raised for the <a href='http://www.airambulancetvac.org/' alt='Thames Valley and Chiltern Air Ambulance Trust'>Thames Valley and Chiltern Air Ambulance Trust</a>. Brilliant! <br/><br/><br/><p style='text-align:center;'><a href=javascript:objManager.CloseWindow('" +MiddleWindow.id+ "')>Close Window</a></p>."); 
    }
    else
    {
        ZoomToLastLocation();
    }
    
    
    if(!objSettings.EventStarted)
    {
        ControlWindow.minimiseOnOpen = true;
        objManager.ShowWindow('ControlWindow');           
        
    }
    else
    {
        objManager.ShowWindow('ControlWindow');           
        //document.getElementById("startClockDesc").innerHTML = "Swimming Time&nbsp; ";
        stopwatch();
    }
    
    
}

function PlotMarkers(updates)
{
        
        var latlongpoint; 
        var pin; 
       
        for (x in LocationList)
        {
            if (LocationList[x].PushPin == null)
            {
                 latlongpoint = new VELatLong(LocationList[x].Latitude,LocationList[x].Longitude); 
                imageHTML = "<img class=imageCallout height=100 width=100 src=images/swimmers/" + LocationList[x].Swimmer.PhotoPath + " alt=" + LocationList[x].Swimmer.Name + " ></img>";
                pin = new VEPushpin(LocationList[x].id,latlongpoint,LocationList[x].Image,'Swimmer: '  + LocationList[x].Swimmer.Name,'Time: '+LocationList[x].DateTimeRecorded + imageHTML,'');            
                map.AddPushpin(pin);     
                LocationList[x].PushPin = pin;
            }
        }
        //change this FOR LIVE RELEASE
        positionTimer = setTimeout("LoadLatestPositions()",120000 );      
}

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 UpdateSwimmerStatus()
{
        lastLocation = LocationList.pop();
    
        for (x in SwimmerList)
        {
            name = SwimmerList[x].Name;
            if (SwimmerList[x].id == lastLocation.SwimmerID)
            {
                 SwimmerList[x].xWindow.SetTitle(name + '  <span class="isSwimming"> - swimming now</span>');               
            }
            else
                SwimmerList[x].xWindow.SetTitle(name); 
        } 
        
        LocationList.push(lastLocation);
}

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);
}

function stopwatch()
{
 
if(c>59)
{
    c=0;
    mins=mins+1;
}
if(mins>59)
{
    mins = 0;
    hours=hours+1;
}
//date.setSeconds(c);
    if(objSettings.EventStarted)
    {
    
        if(hours<10)
        {
            hourString="0"+hours;
        }
        else
        {
            hourString=hours;
        }
            
        if(mins < 10)
        {
            minString="0"+mins;
        }
        else
        {
            minString=mins;
        }
        
        
        if(c<10)
        {
            secString="0"+c;
        }
        else
        {
            secString=c;
        }
        
        
        //replace this line with where you want the clock string to go!
        //.. = hourString+":"+minString+":"+secString;
        try
        {
            document.getElementById("startClock").innerHTML = hourString+":"+minString+":"+secString;
        }
        catch(err)
        {
        
        }

        c=c+1;
        t=setTimeout("stopwatch()",1000);
    }
    else
    {
        mins=0;
        hours=0;
        c=0;
    }
}