﻿var ge;
var track;
var TrainingID;
var showtracks;

// Get a PageRequestManager reference.
var prm = Sys.WebForms.PageRequestManager.getInstance()
// Hook the _endRequest event and add our own handler.
// prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);

// var sysDefaultTimeout =
   //      Sys.Net.WebRequestManager.get_defaultTimeout();

// alert("Get default timeout: " + sysDefaultTimeout);

// Sys.Net.WebRequestManager.set_defaultTimeout(10000);
 
google.load("earth", "1");

QueryString.keys = new Array();
QueryString.values = new Array();
QueryString_Parse();

// get the value for event, if parameter available
ev = QueryString("event");
showtracks = QueryString("showtracks");

    

function button_clicked(args) 
{
    alert("Button " + args + " clicked!");

}


function QueryString(key) {
    var value = null;
    for (var i = 0; i < QueryString.keys.length; i++) {
        if (QueryString.keys[i].toLowerCase() == key) {
            value = QueryString.values[i];
            break;
        }
    }
    return value;
}


function QueryString_Parse() {
    var query = window.location.search.substring(1);
    var pairs = query.split("&");

    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        if (pos >= 0) {
            var argname = pairs[i].substring(0, pos);
            var value = pairs[i].substring(pos + 1);
            QueryString.keys[QueryString.keys.length] = argname;
            QueryString.values[QueryString.values.length] = value;
        }
    }
}






function EndRequest(sender, args)  {
// called when page changed in gridview
// Used to check the tracks witch are currently on the map

if (sender._postBackSettings.sourceElement.id == "ctl00_ContentPlaceHolder1_GridView2" || 
    sender._postBackSettings.sourceElement.id == "ctl00_ContentPlaceHolder1_GridView2_ctl01_ddCountry" ||
    sender._postBackSettings.sourceElement.id == "ctl00_ContentPlaceHolder1_Timer1" )
    {
        SetGridviewCheckboxes();  
    }
}

function SetGridviewCheckboxes() {
//Get the Rows
    var rows = document.getElementById("ctl00_ContentPlaceHolder1_GridView2").getElementsByTagName("tr");
    var tl = rows.length;
    if (tl > 11) {
        tl = 11;
    }
        
     
      // get number of all tracks currently there
    var  le = ge.getFeatures().getChildNodes().getLength();
    
    
    // loop throug the track container each track
    for (x=0;x<le;x++)
    {
        // loop throuh page grid view
        for (y=1;y<=tl-1;y++)
        {
            // Get Row Elements
            var elTableCells = rows[y].getElementsByTagName("td");
            // get the elment containing the TraininID
            
            if (showtracks == null) {
                TrainingID = elTableCells[2].innerHTML;
            }
            else {
                if (showtracks.toLowerCase() == "false")
                    TrainingID = elTableCells[1].innerHTML;
                else
                    TrainingID = elTableCells[2].innerHTML;
            }
           
            // if Name is the same TrackID, set the checkbox
            if (ge.getFeatures().getChildNodes().item(x).getName()  == TrainingID + " Position")
            {
                elTableCells[0].children[0].checked = true;
                
            }
            if (ge.getFeatures().getChildNodes().item(x).getName() == TrainingID +" Track") {
                elTableCells[1].children[0].checked = true;
                break;
            }

            if (ge.getFeatures().getChildNodes().item(x).getName() == TrainingID + " Position") {
                break;
            }
           
        }
    }

}

function initCallback(pluginInstance) {
  ge = pluginInstance;
  ge.getWindow().setVisibility(true);
 
  // add a navigation control
  ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);

  // Set options
  var options = ge.getOptions();
  options.setStatusBarVisibility(true);
  //options.setGridVisibility(form.grid.checked);
  // options.setOverviewMapVisibility(true);
  options.setScaleLegendVisibility(true);
  // options.setAtmosphereVisibility(form.atmosphere.checked);
  //options.setMouseNavigationEnabled(form.mouseNav.checked);
 
 
  // add some layers
  ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
  ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);

  // if event parametr found, load the track with the same name, if available
  if (ev > "") {
      
      var link = ge.createLink('');
      var href = 'http://www.athlosoft.com/live/LiveTracks/' + ev + '.kml'
      link.setHref(href);

      var networkLink = ge.createNetworkLink('');
      networkLink.set(link, true, true); // Sets the link, refreshVisibility, and flyToView 

      ge.getFeatures().appendChild(networkLink);

  }
  
 
}
 
 
// This function is called when someone clicks the checkbox on the GridView control
function get_track(CheckBoxObject){
 


    //Get the Row based on checkbox 
    var row = CheckBoxObject.parentNode.parentNode; 
    // Get Row Elements
    var elTableCells = row.getElementsByTagName("td");
    // get the elment containing the TraininID

    if (showtracks == null) {
        TrainingID = elTableCells[2].innerHTML;
    }
    else {
        if (showtracks.toLowerCase() == "false")
            TrainingID = elTableCells[1].innerHTML;
        else
            TrainingID = elTableCells[2].innerHTML;
    }
    if ( CheckBoxObject.checked)
    {
        // Add the track to the map
        // Call the webservice to get the track by TrainingID
        callback_done = false;
        // Athlosoft_Live_Portal.GPSTrackService.set_timeout(10000);

        xy = Athlosoft_Live_Portal.GPSTrackService.GetTrackByID(TrainingID, jsDrawAndFlyPosition, OnError, OnError);

     
        // when service is complete the track is added in the jsDrawTrack function           
        
    }
    else
    {
        // Call the webservice to get the track by TrainingID 
        jsRemoveTrack(TrainingID);
    }
 return (true);
}


// This function is called when someone clicks the checkbox on the GridView control
function get_position(CheckBoxObject){
 
    //Get the Row based on checkbox 
    var row = CheckBoxObject.parentNode.parentNode; 
    // Get Row Elements
    var elTableCells = row.getElementsByTagName("td");
    // get the elment containing the TraininID

    if (showtracks == null) {
        TrainingID = elTableCells[2].innerHTML;
    }
    else {
        if (showtracks.toLowerCase() == "false")
            TrainingID = elTableCells[1].innerHTML;
        else
            TrainingID = elTableCells[2].innerHTML;

    }

    if ( CheckBoxObject.checked)
    {
        // Add the track to the map
        // Call the webservice to get the track by TrainingID
        // xy = Athlosoft_Live_Portal.GPSTrackService.GetTrackByID(TrainingID, jsDrawTrack, OnTimeOut, OnError);
        xy = Athlosoft_Live_Portal.GPSTrackService.GetCurrentPositionByID(TrainingID, jsDrawAndFlyPosition, OnError, OnError);
    
        // when service is complete the track is added in the jsDrawTrack function           
    }
    else
    {
        
        // jsRemoveTrack(TrainingID);
        jsRemovePosition(TrainingID);
    }
 return (true);
}


function jsDrawAndFlyPosition(arg) {
    // if ge object available
    if (ge) {
        // parse the track
        track = ge.parseKml(arg);
        // if track is not null
        if (track) {
            ge.getFeatures().appendChild(track);
            // Fly to the LookAt view
            if (track.getAbstractView()) {
                ge.getView().setAbstractView(track.getAbstractView());
            }
        }
    }

}




// Draw KML passed to this function, without flying to the view
function jsDrawPosition(arg)  
{ 
// if ge object available
if (ge)
{
    // parse the track
    track = ge.parseKml(arg);
    // if track is not null
    if (track)
    {
        ge.getFeatures().appendChild(track); 
    }
}
} 

 
function jsRemoveTrack(TID)  
{ 
// get number of all tracks currently there
var  le = ge.getFeatures().getChildNodes().getLength();
// loop throug the track container each track
for (x=0;x<le;x++)
{
    // if Name is the same TrackID
    if (ge.getFeatures().getChildNodes().item(x).getName()  == TID + " Track")
    {
        // remove the one found
        ge.getFeatures().removeChild(ge.getFeatures().getChildNodes().item(x));  
        break;
    }
}
}

function jsRemovePosition(TID) {
    // get number of all tracks currently there
    var le = ge.getFeatures().getChildNodes().getLength();
    // loop throug the track container each track
    for (x = 0; x < le; x++) {
        // if Name is the same TrackID
        if (ge.getFeatures().getChildNodes().item(x).getName() == TID + " Position") {
            // remove the one found
            ge.getFeatures().removeChild(ge.getFeatures().getChildNodes().item(x));
            break;
        }
    }
}  
 
 
function jsExportKML(imageObj){
    //Get the Row based on checkbox 
    var row = imageObj.parentNode.parentNode; 
    // Get Row Elements
    var elTableCells = row.getElementsByTagName("td");
    // get the elment containing the TraininID
    
    if (showtracks == null) {
        TrainingID = elTableCells[2].innerHTML;
    }
    else {
        if (showtracks.toLowerCase() == "false")
            TrainingID = elTableCells[1].innerHTML;
        else
            TrainingID = elTableCells[2].innerHTML;

    }

    // Create an IFRAME.
    var iframe = document.createElement("iframe");
 
      // Point the IFRAME to GenerateFile, with the
      //   desired region as a querystring argument.
    iframe.src = "GetTrackbyID.aspx?TrainingID=" + TrainingID;
 
      // This makes the IFRAME invisible to the user.
      iframe.style.display = "none";
 
      // Add the IFRAME to the page.  This will trigger
      //   a request to GenerateFile now.
      document.body.appendChild(iframe); 
}


function OnTimeOut(arg) {
alert("timeout encountered.");
}

function OnError(arg) {
alert("error encountered.");
}

// failed to init GE Plugin 
function failureCallback(errorCode) {
   // alert("Google Earth initialisation failed.");
};
