﻿
var cityLatitudeCenter  =  40.700722;
var cityLongitudeCenter = -111.885452;
var cityZoomLevel = 11;

var _upDating=true;//set to true so can't use toggle switches until data is loaded.

function StartAJAXRequest() {
    _upDating = true;
    StopPageTimer();
    ShowLoader(1, "");
}

function EndAJAXResponse() {

    InitiatePageTimer();
    HideLoader();
}


/*
Updates the main page by sending a request to ajax manager component.
*/
function UpdatePage(PageLoading)
{
    try {
        
        StartAJAXRequest();
        googleMap.clearOverlays();

        // Add the custom tiling back to the map. If this
        // has been called as a result of a refresh then
        // the tiles will be refreshed.
        setupMapForCustomTiling();
        
        MakeAjaxCallToTheWebService(PageLoading);
        
    }
    catch(e)
    {
        alert(e.name + "\n" + e.message + " - UpdatePage");
    }
}

/*
This method only gets called from the default page..so no need to worry about any virtual directory mis-haps.
*/
function ErrorMsg(errorMessage) {

    if (_sendEmailToDevelopers == "true")
        window.location.href = "ErrorPage.aspx?ErrorCode=101";
    else
        alert(errorMessage.responseText);
}
/* This method provides a short cut to get the given element from the current document.
*/
function GetElementByID(obj)
{
    return document.getElementById(obj);
}

function GetElementByClientId(obj)
{
    return document.getElementById('<%=' + obj + '.ClientID%>');
}
/* Sends a request to the server side which in return parses all the XML files in App_Code directory, and
creates javascripts on the server side, after the request is rendered, client side comes in and 
executes these newly generated javascripts.
*/
function CreateMarkerGroups(input) {

    UpdatePage(true); //Make an ajax call to the web 	    
}

/*
Create a multidimensional array in javascript. This multidimensional function is used by AppCode/Internal classes 
when each entity gets created(camera, sign..etc)
*/
function MultiDimensionalArray(iRows,iCols)
{
	try
	{
		var i; 
		var j; 
		var a = new Array(iRows);
		for (i=0; i < iRows; i++)
		{
			a[i] = new Array(iCols);
			for (j=0; j < iCols; j++)
			{
				a[i][j] = "";
			}
		}
		return(a);
	}
	catch(e)
	{
		var sErr=e.message;
	}
} 


function DisplayCameraOnDashBoard(id,direction,title, selectedIndexMapArea, selectedIndexCamera, url)
{
    try {

        //Set the source to the underlying Url and set the selected tab, text will be set by an Ajax call..
        //I couldnt see the text for some unknown reason
        GetElementByID('cameraImg').src = url;
        SetSelectedTab('ds_one');

        var input = "Camera" + " , " + id + " , " + direction + " , " + title.replace(",", " ") + " , " + selectedIndexMapArea + " , " + selectedIndexCamera;
        AsyncCallServerSide(input);
	 }
     catch(e)
     {
         alert(e.message + " - DisplayCameraOnDashBoard");
     }            
}

function DisplaySignOnDashBoard(id, direction, title, selectedIndexMapArea, selectedIndexCamera)
{
    try {
    
        //Javascript does not like " ' " characters. When populating the google marker object, we replace those characters
        //with single comma, and do the vice-versa, when looking for the sign image..
        //Set the source to the underlying gif and set the selected tab, text will be set by an Ajax call..
        //I couldnt see the text for some unknown reason
         GetElementByID('signImage').src = _tisAnimatedFolder + id + '-' + title.replace("`", "'") + ".gif";
         SetSelectedTab('ds_two');

         var input = "Sign" + " , " + id + " , " + direction + " , " + title.replace(",", " ").replace("`", "'") + " , " + selectedIndexMapArea + " , " + selectedIndexCamera; ;
         AsyncCallServerSide(input);
	 }
     catch(e)
     {
         alert(e.message + " - DisplaySignOnDashBoard");
     }
 }


  function SetSelectedTab(tabindex)
{
    SetTabButton(tabindex);

}

/*
Changes the inner text of a RadToggleControlButton as user clickage is fired from the client side.
I should have done something extraordinary to change the text, but for the time being lets go with this version, since
we also need to fire events that would hide and display the icons as well.

DO NOT TOUCH ANYTHING IN THIS METHOD IF AND UNLESS YOU ARE REALLY SURE WHAT YOU ARE DOING. --Mobby
*/
function RadToolBarButtonClicked(commandName, IsChecked)
{    
    if(_upDating)
    {
        alert('Map data is currently updating. Please try again when it is finished.');
        /* Pick up previous states from the cookie...*/
        return;
    }
    
    try
    {
        switch (commandName) {

            case "Cameras":

                ShowLoader(IsChecked ? 2 : 3, "Cameras");
                setCookie("ToolBarItemCamera", IsChecked ? 1 : 0);
                _toolBar.get_items().getItem(0).set_text(IsChecked ? "Hide Cameras" : "Show Cameras");

                TgCCTV();
                break;

            case "Signs":
            
                ShowLoader(IsChecked ? 2 : 3, "Signs");
                setCookie("ToolBarItemSign", IsChecked ? 1 : 0);
                _toolBar.get_items().getItem(2).set_text(IsChecked ? "Hide Signs" : "Show Signs");

                TgDMS();
                break;

            case "Incidents":

                ShowLoader(IsChecked ? 2 : 3, "Incidents");
                setCookie("ToolBarItemIncident", IsChecked ? 1 : 0);
                _toolBar.get_items().getItem(4).set_text(IsChecked ? "Hide Incidents" : "Show Incidents");


                TgEvent();
                TgPlannedEvent();
                break;

            case "Construction":

                ShowLoader(IsChecked ? 2 : 3, "Construction");
                setCookie("ToolBarItemConsruction", IsChecked ? 1 : 0);
                _toolBar.get_items().getItem(6).set_text(IsChecked ? "Hide Construction" : "Show Construction");
                
                
                TgConstruction();
                break;

            case "Weather":
            
                ShowLoader(IsChecked ? 2 : 3, "Weather");
                setCookie("ToolBarItemWeather", IsChecked ? 1 : 0);
                _toolBar.get_items().getItem(8).set_text(IsChecked ? "Hide Weather" : "Show Weather");

                TgTATS();
                
                break;
        }

        self.setTimeout('HideLoader()',1000);  
    }
    catch(e){ alert("ToolBarClick -- "  + e.message);}
    

}

function ToggleToolBarFromServerSide(ToggleButtonIndex) {

    _toolBar.get_items().getItem(ToggleButtonIndex).check();
    
    //Pass the command name and the check flag..
    RadToolBarButtonClicked(_toolBar.get_items().getItem(ToggleButtonIndex).get_commandName(),
            _toolBar.get_items().getItem(ToggleButtonIndex).get_checked());
       
}

function ZoomGoogleMapToParticularCoordinates(LatitudeNorth, LongitudeWest, selectedTrafficMapIndex, zoomLevel) {

    googleMap.setCenter(new GLatLng(LatitudeNorth, LongitudeWest), zoomLevel);
    FillMapAreasList(selectedTrafficMapIndex, 0);
}

/*
* Sets coordinates of google maps when a certain are needs to be viewed but google map has not been loaded
before this call. Sets global coordinates to the desired ones and let google map handles the rest.
*/
function SetCoordinatesGoogleMap(LatitudeNorth, LongitudeWest, selectedTrafficMapIndex, zoomLevel) {

    cityLatitudeCenter  = LatitudeNorth;
    cityLongitudeCenter = LongitudeWest;
    cityZoomLevel       = zoomLevel;

    FillMapAreasList(selectedTrafficMapIndex, 0);
}


function CheckZoom(oldZ,newZ) {

    setCookie('ZoomLevel', newZ / 1); //dividing by 1 converts string to number
        
    //variable to see if zoom level is exceeding allowable value.
    var maxZoomLevelReached = false;

    if (newZ > _maxZoomLevel || newZ < _minZoomLevel) {
        maxZoomLevelReached = true; //set it true to prevent repainting of GPolylines
        googleMap.setZoom(oldZ);
    }
}

function SetTextByElement(element, text) {    
    //For IE 6.0 and above
    if (document.all) {
        GetElementByID(element).innerText = text;
    } else { //for FireFox..
        GetElementByID(element).textContent = text;
    }
}

/*
* Sets the current coordinates from google map and save them in the document.cookie object. 
*/
function SetDefaultMap(showMessage) {
    
    var bounds    = googleMap.getCenter();
    var latitude  = bounds.lat();
    var longitude = bounds.lng();
    var zoomLevel = googleMap.getZoom();

    setCookie("DefaultLatitude",  latitude,  30);
    setCookie("DefaultLongitude", longitude, 30);
    setCookie("DefaultZoomLevel", zoomLevel, 30);

    if (showMessage) {
        alert('Your desired coordinates have been successfully saved.');
    }

}
/*
* Gets the previously set google map coordinates if they exist. If not, then google map
* is set to our default coordinates.
*/
function SetMapCenterFromCookies(){

    var latitude  = parseFloat(getCookie("DefaultLatitude"));
    var longitude = parseFloat(getCookie("DefaultLongitude"));
    var zoomLevel = parseFloat(getCookie("DefaultZoomLevel"));

    //verify if the desired coordinates and zoom level is of type Number and only set the center is there is not query string present in the url..
    if (!isNaN(latitude) && !isNaN(longitude) && !isNaN(zoomLevel) && window.location.search.substring(1).split('&') == ""  ) {
    
        var properlyFormattedlatitude = (Math.round(latitude * 1000000) / 1000000);
        var properlyFormattedlongitude = (Math.round(longitude * 1000000) / 1000000);
        googleMap.setCenter(new GLatLng(properlyFormattedlatitude, properlyFormattedlongitude), zoomLevel);
    
    } else {
        googleMap.setCenter(new GLatLng(cityLatitudeCenter, cityLongitudeCenter), cityZoomLevel);
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Follow methods Must be used in conjunction with Ajax call to webservice using JQuery.
/////////////////////////////////////////////////////////////////////////////////////////////////////////
function MakeAjaxCallToTheWebService(PageLoading) {

    $.ajax({
        type: "POST",
        url: "DataProvider.asmx/LoadEntities",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: ErrorMsg,
        success: LoadData,
        timeout: 120000
    });
}

/*
* The parameter data is populated by the calling service and it contains returned data from the method call.
*/
function LoadData(data) {
    
    var entities = data.d;

    AddCameraEntities(entities['Camera']);
    AddSignEntities(entities['Sign']);
    AddIncidentEntities(entities['Incident']);
    AddConstructionEntities(entities['Construction']);
    AddPlannedEventEntities(entities['PlannedEvent']);
    AddTatsEntities(entities["TATS"]);
    
    LoadIncidentViewerPage();
    DisplayViewerType('Inc');

    LoadWeatherViewerPage();
    DisplayViewerType('Wtr');

    SetImages();

    Dispose(data);

}

/*
* Dispose the data object and does some grunt work to set toolbar states based on the saved cookies.
*/
function Dispose(data) {

    data.d.length = 0; data.d = null; data = null;

    SetToolBarState();

    EndAJAXResponse();

    if (BrowserDetect.browser == "Explorer")
        CollectGarbage();
}

/*
* Sets toolBar's button state to the corresponding saved cookie. Everytimg a user clicks on the toolbar
a corresponding cookie is saved so that the selection can be made if user goes to a different page other than
Default.aspx. 

Indices are assigned keeping toolbar separators in mind.
*/
function SetToolBarState() {


    _upDating = false; //we have received the data from server side...set the flag to false;
       
    //Camera will always be selected by Default..so if the cookie does not exist, we will enable the
    if (isNaN(getCookie("ToolBarItemCamera")) || getCookie("ToolBarItemCamera") == null) {
        ToggleToolBarFromServerSide(0);
    } else {
    if (parseInt(getCookie("ToolBarItemCamera")) == 1) {
            ToggleToolBarFromServerSide(0);
        }
    }

    if (!isNaN(getCookie("ToolBarItemSign"))) {
        if (parseInt(getCookie("ToolBarItemSign")) == 1) {
            ToggleToolBarFromServerSide(2);
        }
    }

    if (!isNaN(getCookie("ToolBarItemIncident"))) {
        if (parseInt(getCookie("ToolBarItemIncident")) == 1) {
            ToggleToolBarFromServerSide(4);
        }
    }

    if (!isNaN(getCookie("ToolBarItemConsruction"))) {
        if (parseInt(getCookie("ToolBarItemConsruction")) == 1) {
            ToggleToolBarFromServerSide(6);
        }
    }

    if (!isNaN(getCookie("ToolBarItemWeather"))) {
        if (parseInt(getCookie("ToolBarItemWeather")) == 1) {
            ToggleToolBarFromServerSide(8);
        }
    }
}


function RemoveEscapeChars(str)
{
    str = str.replace("'", "").replace("\"", "").replace("`", "").replace("-", "").replace("\\", "").replace("/", "");
    str = str.replace("<", "&lt;").replace("\n", "").replace("\r", "");
    str = str.replace(">", "&gt;").replace("{", "&lt;").replace("}", "&gt;").replace("&amp;amp;", "&").replace("&amp;", "").replace("amp;","").replace(",", " ");

    return str;
}

/* Traffic Dashboard related routines */

button_one = new Image();
button_two = new Image();

button_one.src = "/images/camera_tab.JPG";
button_two.src = "/images/sign_tab.JPG";

function SetTabButton(x) {
    if (document.getElementById('ds_one'))
        document.getElementById('ds_one').style.display = 'none';
        
    if (document.getElementById('ds_two')) {
        document.getElementById('ds_two').style.height  = "220px";
        document.getElementById('ds_two').style.display = 'none';
    }
        
    document.getElementById(x).style.display = 'block';
    document.getElementById('tabs_Ds').className = 'tabs_' + x;
}

/*
We need to get the latest camera snapshot and sign animated image with each page refresh. 
Each image is concatenated by a random number, which is sent as a query string, following by a refresh on the
html image holder. We are tricking browser to get the latest image with each page refresh, instead of relying on
native cache support that caches the image for an unchanged url.
*/
function SetImages() {

    try {

        //First time the url will not contain any random query string, but with the subsequent page refresh, the exisiting url
        //will contain query string. In order to avoid this, we need to check if url contains any query string, if so, read only the 
        //given url and delete the rest, and then carry on with our query string addition.
        if (GetElementByID('cameraImg').src.split('?').length > 1) {
            GetElementByID('cameraImg').src = GetElementByID('cameraImg').src.split('?')[0] + '?rand=' + Math.random().toString();
        } else {
            GetElementByID('cameraImg').src = GetElementByID('cameraImg').src + '?rand=' + Math.random().toString();
        }

        if (GetElementByID('signImage').src.split('?').length > 1) {
            GetElementByID('signImage').src = GetElementByID('signImage').src.split('?')[0] + '?rand=' + Math.random().toString();
        } else {
            GetElementByID('signImage').src = GetElementByID('signImage').src + '?rand=' + Math.random().toString();
        }

    } catch (e) { } /* Gracefully, exit out from the block and let the compiler proceed further */
}
