﻿/**
 * Performs an AJAX call
 *
 * @param url - AJAX handler/servlet URL
 * @param callback - Callback function to receive response text
 */
function AjaxRequest(Url, Callback)
{
    var xmlHttp = null;
    var callback = null;
    
    if(Callback != null)
    {
        callback = Callback;
    }
    
    /**
     * Creates an xmlHttp request
     */
    function CreateRequest() {
        //determine type of xmlHttp object to use
        try
        {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            // Try to use different activex object
            try
            {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (E) {
                xmlHttp = false;
            }
        }

        // If not initialized, create XMLHttpRequest object
        if(!xmlHttp && typeof XMLHttpRequest!='undefined')
        {
            xmlHttp = new XMLHttpRequest();
        }
    }

    /**
     * Perform the AJAX call
     */
    function StartRequest()
    {
        CreateRequest();
        xmlHttp.onreadystatechange = OnStateChange;
        xmlHttp.open("GET", Url, true);
        xmlHttp.setRequestHeader('Pragma', 'no-cache');
        xmlHttp.send(null);
    }

    /**
     * Issues the callback with the appropriate xmlHttp response
     */
    function OnStateChange() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200 && callback != null) {
            callback(xmlHttp.responseText);
        }
    }
    
    /**
     * Public method to execute an AJAX call
     */
    this.Execute = StartRequest;
}

/**
 * Called at page reload to restore page status
 *
 */
function RestoreState()
{
    var searchType = getQueryVariable("stype");
    var searchHistory = new Array();
    
    /* MOVE SEARCH HISTORY FROM GET VARIABLES TO CLIENT CACHE */    
    
    // if url conatins a search (i.e. url is a link for a specific search)
    if(searchType != null){
        // save map style and zoom level to Client Cache variables from get variables
        ClientCache.Save('style',getQueryVariable("style"));
        ClientCache.Save('zoom',getQueryVariable("zoom"));
        ClientCache.Save('traffic',getQueryVariable("traffic"));
        // save active poi list to Client Cache from get variable
        var activePois = getQueryVariable("pois");
        if(activePois != null){
            // split-up pois get variable into actived pois' id
            var activePoisArray = activePois.split('|');
            for(var i=0; i<activePoisArray.length; i++){
                ClientCache.Save('poi_'+activePois[i],'active');
            }
        }
        // Move search from url get variables to Client Cache
        ClientCache.Save('pane_0_type',searchType);
        switch(searchType)
        {
            // find on a map search
            case 'fm':
                ClientCache.Save('pane_0_FindInput',decodeURI(getQueryVariable("FindInput")));
                break;
            // find on a business search
            case 'bus':
                ClientCache.Save('pane_0_location',decodeURI(getQueryVariable("location")));
                ClientCache.Save('pane_0_keyword',decodeURI(getQueryVariable("keyword")));
                break;
            // find on a person search
            case 'per':
                ClientCache.Save('pane_0_location',decodeURI(getQueryVariable("location")));
                ClientCache.Save('pane_0_keyword',decodeURI(getQueryVariable("keyword")));
                break;
            // driving directions search
            case 'dd':
                var locationArray = decodeURI(getQueryVariable("waypoints")).split("|");
                // from location
                var from = locationArray[0].split(';')[0]+'@'+eval(decodeURI(locationArray[0].split(';')[1]));
                //var from = ((eval(decodeURI(locationArray[0].split(';')[0])))+'@'+(eval(decodeURI(locationArray[0].split(';')[1]))));
                //alert('RestoreState - searchType:dd, from:'+from);
                ClientCache.Save(('pane_0_FromInput'),from);
                searchHistory.push(from);
                // to location
                var to = locationArray[1].split(';')[0]+'@'+eval(decodeURI(locationArray[1].split(';')[1]));
                //var to = ((eval(decodeURI(locationArray[1].split(';')[1])))+'@'+(eval(decodeURI(locationArray[1].split(';')[1]))));
                //alert('RestoreState - searchType:dd, to:'+to);
                ClientCache.Save(('pane_0_ToInput'),to);
                break;
        }    
        // update url to remove get variables
        var url = document.location.href;
        document.location.href = url.split('?')[0];
        
        return;
    }
    
    /* RETRIEVE SEARCH HISOTRY FROM CLIENT CACHE */
    
    // if url does not conatin a search (i.e. url is not a link for a specific search)
    else{
        // Move search history from client cache to searchHistory array
        // only get search inputs from client cache for most recent searches
        var paneNumber = (ClientCache.Retrieve('firstPaneNumber') != undefined ? ClientCache.Retrieve('firstPaneNumber') : 0);
        var numPanes = -1;
        searchType = ClientCache.Retrieve('pane_' + paneNumber + '_type');
        // loop through search history stored in client cache
        while (searchType != null) {
            numPanes++;
            searchHistory.push(searchType);
            switch(searchType)
            {
                // find on a map search
                case 'fm':
                    searchHistory.push(ClientCache.Retrieve('pane_'+paneNumber+'_FindInput'));
                    searchHistory.push(ClientCache.Retrieve('pane_'+paneNumber+'_Find'));
                    break;
                // find on a business search
                case 'bus':
                    searchHistory.push(ClientCache.Retrieve('pane_'+paneNumber+'_location'));
                    searchHistory.push(ClientCache.Retrieve('pane_' + paneNumber + '_keyword'));
                    //alert(ClientCache.Retrieve('pane_' + paneNumber + '_location') + ' | ' + ClientCache.Retrieve('pane_' + paneNumber + '_keyword'));
                    break;
                // find on a person search
                case 'per':
                    searchHistory.push(ClientCache.Retrieve('pane_'+paneNumber+'_location'));
                    searchHistory.push(ClientCache.Retrieve('pane_'+paneNumber+'_keyword'));
                    break;
                // get driving directions search
                case 'dd':
                    // get from and to locations
                    searchHistory.push(ClientCache.Retrieve('pane_' + paneNumber + '_FromInput'));
                    searchHistory.push(ClientCache.Retrieve('pane_' + paneNumber + '_ToInput'));
                    searchHistory.push(ClientCache.Retrieve('pane_' + paneNumber + '_From'));
                    searchHistory.push(ClientCache.Retrieve('pane_' + paneNumber + '_To'));
                    // get additional waypoints
                    var numWaypoints = ClientCache.Retrieve('pane_' + paneNumber + '_NumWaypoints');
                    searchHistory.push(numWaypoints);
                    for (var j = 0; j < numWaypoints; j++) {
                        searchHistory.push(ClientCache.Retrieve('pane_' + paneNumber + '_WaypointInput' + j));
                        searchHistory.push(ClientCache.Retrieve('pane_' + paneNumber + '_Waypoint' + (j+2)));
                    }
                    break;
            }
            // get the next search stored in client cache
            paneNumber++;
            searchType = ClientCache.Retrieve('pane_'+paneNumber+'_type');
        }
        // set style, zoom level, and toggle traffic based on Client Cache variables        
        if(ClientCache.Retrieve("style") != null)
            mapManager.Map.SetMapStyle(ClientCache.Retrieve("style"));
        var mapZoom = ClientCache.Retrieve("zoom");
        if(mapZoom != null) {
            if (mapManager.Map.GetZoomLevel() != mapZoom)
                mapManager.Map.SetZoomLevel(mapZoom);
        }
        // toggle traffic as per traffic client cache variable
        if(ClientCache.Retrieve("traffic") == 'true')
            ToggleTraffic();

        ClientCache.Save('firstPaneNumber', 0);
    }
    
    /* PERFORM SEARCHES */
    
    // Re-perform all searches in searchHistory array
    var i = 0;
    var paneNumber = 0;
    var lastSearch = false;
    while (i < searchHistory.length) {
        lastSearch = (numPanes == paneNumber);
        searchType = searchHistory[i];
        i++;
        switch(searchType)
        {
            // find on a map search
            case 'fm':
                // restore search field
                document.getElementById('txtFind').value = searchHistory[i];
                ClientCache.Save('pane_' + paneNumber + '_FindInput', searchHistory[i]);
                ClientCache.Save('pane_' + paneNumber + '_Find', searchHistory[i + 1]);
                //setTimeout("mapManager.NewFindLookup('" + searchHistory[i] + "')", (i * 500));

                // if this is the last search
                if (lastSearch) {
                    if(ClientCache.Retrieve('lastSearchFailed') != 'true')
                        // perform search
                        mapManager.NewFindLookup(searchHistory[i]);
                }
                // if this is not the last search
                else{
                    // add search to side pannel
                    mapManager.PrepareForNewFindLookup(searchHistory[i]);
                }

                i = i + 2;
                break;
            // find on a business search
            case 'bus':
                // restore search fields
                document.getElementById('txtBusLocation').value = searchHistory[i];
                document.getElementById('txtBusName').value = searchHistory[i + 1];
                // perform search
                //setTimeout("mapManager.NewFindBusiness('false','false','"+searchHistory[i+1]+"','"+searchHistory[i]+"')",(i*500));

                // if this is the last search
                if (lastSearch) {
                    if (ClientCache.Retrieve('lastSearchFailed') != 'true')
                        // perform search
                        mapManager.NewFindBusiness('false', 'false', searchHistory[i + 1], searchHistory[i]);
                }
                // if this is not the last search
                else {
                    // add search to side pannel
                    mapManager.PrepareForNewFindBusiness(searchHistory[i], searchHistory[i + 1]);
                }

                i = i + 2;
                break;
            // find on a person search
            case 'per':
                // restore search fields
                document.getElementById('txtPersonLocation').value = searchHistory[i];
                document.getElementById('txtPersonName').value = searchHistory[i + 1];
                // perform search
                //setTimeout("mapManager.NewFindPerson('false','false','"+searchHistory[i+1]+"','"+searchHistory[i]+"')",(i*500));

                // if this is the last search
                if (lastSearch) {
                    if (ClientCache.Retrieve('lastSearchFailed') != 'true')
                        // perform search
                        mapManager.NewFindPerson('false', 'false', searchHistory[i + 1], searchHistory[i]);
                }
                // if this is not the last search
                else {
                    // add search to side pannel
                    mapManager.PrepareForNewFindPerson(searchHistory[i], searchHistory[i + 1]);
                }

                i = i + 2;
                break;
            // get driving directions search
            case 'dd':
                // restore search fields
                document.getElementById('txtFrom').value = searchHistory[i];
                document.getElementById('txtTo').value = searchHistory[i + 1];
                // restore client cache
                ClientCache.Save('pane_' + paneNumber + '_FromInput', searchHistory[i]);
                ClientCache.Save('pane_' + paneNumber + '_ToInput', searchHistory[i + 1]);
                ClientCache.Save('pane_' + paneNumber + '_From', searchHistory[i + 2]);
                ClientCache.Save('pane_' + paneNumber + '_To', searchHistory[i + 3]);
                var numWaypoints = searchHistory[i + 4];
                ClientCache.Save('pane_' + paneNumber + '_NumWaypoints', numWaypoints);
                var j = 0;
                while (j < numWaypoints) {
                    ClientCache.Save('pane_' + paneNumber + '_WaypointInput' + j, searchHistory[i + 5 + j]);
                    j++;
                    ClientCache.Save('pane_' + paneNumber + '_Waypoint' + (j + 2), searchHistory[i + 5 + j]);
                    j++;
                }
                // perform search
                //setTimeout("mapManager.GetNewDirections()", (i * 500));

                // if this is the last search
                if (lastSearch) {
                    if (ClientCache.Retrieve('lastSearchFailed') != 'true')
                       // perform search
                        mapManager.GetNewDirections();
                }
                // if this is not the last search
                else {
                    // add search to side pannel
                    mapManager.PrepareForGetNewDirections(searchHistory[i], searchHistory[i + 1]);
                }

                //setTimeout("mapManager.GetNewDirections('" + searchHistory[i] + "','" + searchHistory[i + 1] + "')", (i * 500));
                i = i + 5 + numWaypoints;
                break;
        }
        paneNumber++;
    }
    
    // reset failed search logic param
    ClientCache.Save('lastSearchFailed', 'false');
    
    // set top navigation tab to type of most recent search performed
    switch(searchType)
    {
        case 'fm':
            TopNav('FindMap');
            break;
        case 'bus':
            TopNav('FindBusiness');
            break;
        case 'per':
            TopNav('FindPerson');
            break;
        case 'dd':
            TopNav('DrivingDirections');
            break;
    }

    //mapManager.NewFindBusiness(false, true, 'gas', '65 Harbour Sq, Toronto, ON  M5J2L4');
    //mapManager.PrepareForNewFindBusiness('65 Harbour Sq, Toronto, ON  M5J2L4', 'gas');
    //mapManager.PrepareForNewFindBusiness('65 Harbour Sq, Toronto, ON  M5J2L4', 'gas');
    /*mapManager.PrepareForNewFindBusiness('65 Harbour Sq, Toronto, ON  M5J2L4', 'gas');
    mapManager.PrepareForNewFindBusiness('65 Harbour Sq, Toronto, ON  M5J2L4', 'gas');*/
    //mapManager.NewFindPerson(false, true, 'Lok', 'Toronto');
    //mapManager.NewFindPerson(false, true, 'McCarthy');
    //mapManager.NewFindBusiness(false, true, 'chipotle');
    //mapManager.NewFindLookup('toronto');
    //mapManager.PrepareForGetNewDirections('markham', 'l6e');
    //mapManager.AddWaypoint('gcasdfasdf');
    //mapManager.GetNewDirections('markham', 'l6e');
    //mapManager.GetNewDirections('42.77327,-79.37007', '43.89926,-78.94254');
    
    // Restore POI Toggle Map
    //POIManager.Restore();
}
