// Title: VE

// Version: 1.0 

// Date: 

// Note: Script consists of virtual earth load methods

// Last post back variable declaration
var lastPostBackElement = null;

// Map variable declaration
var map = null;

// Culture object declaration
var cultureObject = null;

// Culture name declaration
var cultureName = null;

// Date object declaration
var dtfObject = null;

// Current date declaration
var currentDate = null;



// Variable for Radio button post back
var URL = null;

//PURPOSE: Will be called on getting the xml http
function GetXmlHttp() {
    var x = null;
    //alert(x);
    try {
        x = new ActiveXObject("Msxml2.XMLHTTP");
        //alert(x);
    }
    catch (e) {
        try {
            x = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) {
            x = null;
        }
    }
    if (!x && typeof XMLHttpRequest != "undefined") {
        x = new XMLHttpRequest();
    }
    return x;
}

//PURPOSE: Parse the response from FindNearby.aspx.cs and evaluate
function MWSRequest(url) {
    var xmlhttp = GetXmlHttp();
    //alert(xmlhttp);
    if (xmlhttp) {
        xmlhttp.open("GET", url, true);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                var html = xmlhttp.responseText;
                eval(html);
            }
        }
        xmlhttp.send(null);
    }
}

//PURPOSE: Create a URL string that will hit LoadMap.aspx
function LoadMap() {
    // Check if map is null
    if (map != null) {
        map.Clear();
    }

    var url = "LoadMap.aspx?";
    var m =
    document.getElementById('hiddenMap');
    if (m.value == 'ContainerTrainingSearch'
        || m.value == '') {
        var l =
        document.getElementById('Container_Result_hiddenLocation');
        url += "location=" + l.value;
        var p =
        document.getElementById('Container_Result_hiddenPinPointLocation');
        url += "&pinpointlocation=" + p.value;
        url += "&map=" + m.value;
        //alert(url);
        MWSRequest(url);
    }
    else
    { return; }
}

//PURPOSE: show the pin point mouse over from result pane
//USAGE: onmouseout="resultpinpoint();"
function resultpinpoint(id, index, identifier) {
    var shape = null;

    shape = map.GetShapeByID(eval("pin" + index).GetID());

    if (identifier == 'over') {
        if (document.getElementById(id) != null) {
            document.getElementById(id).style.background =
             'URL("Common/Images/mappoi_active.gif")';
            document.getElementById(id).style.backgroundRepeat
            = "no-repeat";
        }
        if (document.getElementById(index) != null) {
            // Maximum z-index for the selected icon
            shape.SetZIndex(1500);

            document.getElementById(index).src =
            'Common/Images/mappoi_active.gif';
        }
    }
    else {
        if (document.getElementById(id) != null) {
            document.getElementById(id).style.background =
            'URL("Common/Images/poi_search.gif")';
            document.getElementById(id).style.backgroundRepeat
            = "no-repeat";
        }
        if (document.getElementById(index) != null) {
            shape.SetZIndex(999 + index);

            document.getElementById(index).src =
            'Common/Images/poi_search.gif';
        }
        hideddrivetip();
    }
}

//PURPOSE: show the pin point info from result pane
//USAGE: onclick="resultpinpointclick();"
function resultpinpointclick(id, index) {
    var prefix = null;
    var display = null;
    var hiddenMap = null;
    var addressLine1 = null;
    var addressLine2 = null;
    var addressLine3 = null;
    var phoneNumber = null;
    var shape = null;
    var latLong = null;

    hiddenMap
        = document.getElementById('hiddenMap');

    if (hiddenMap.value == 'ContainerTrainingSearch'
        || hiddenMap.value == '') {
        prefix = "Container_Result_";
    }
    else {
        prefix = "Preferences_";
    }

    addressLine1
        = document.getElementById(prefix + 'hiddenTrainingCenterAddressLine1' + index).value;
    addressLine2
        = document.getElementById(prefix + 'hiddenTrainingCenterAddressLine2' + index).value;
    addressLine3
        = document.getElementById(prefix + 'hiddenTrainingCenterAddressLine3' + index).value;
    phoneNumber
        = document.getElementById(prefix + 'hiddenTrainingCenterPhoneNumber' + index).value;

    display = addressLine1
              + '<br>' + addressLine2
              + '<br>' + addressLine3
              + '<br>' + phoneNumber;

    ddrivetip(display, 180);

    shape = map.GetShapeByID(eval("pin" + index).GetID());

    if (shape != null) {
        latLong = shape.GetIconAnchor();

        if (latLong != null) {
            map.IncludePointInView(latLong);
        }
    }

    if (document.getElementById(index) != null) {
        // Maximum z-index for the selected icon
        shape.SetZIndex(1500);

        document.getElementById(index).src =
            'Common/Images/mappoi_active.gif';
    }
}

//PURPOSE: show the pin point mouse over from map control
//USAGE: onmouseover="mappinpointover();"
function mappinpointover(id, index) {
    if (document.getElementById('Container_Result_RepeaterNavigationTrainingCentersProximity_ctl0' + index
            + '_buttonPinPoint' + id) != null) {
        document.getElementById('Container_Result_RepeaterNavigationTrainingCentersProximity_ctl0' + index
            + '_buttonPinPoint' + id).style.background =
                'URL("Common/Images/mappoi_active.gif")';
        document.getElementById('Container_Result_RepeaterNavigationTrainingCentersProximity_ctl0' + index
            + '_buttonPinPoint' + id).style.backgroundRepeat = "no-repeat";
    }
    else if (document.getElementById('Container_Result_RepeaterNavigationTrainingCenters_ctl0' + index
            + '_buttonPinPoint' + id) != null) {
        document.getElementById('Container_Result_RepeaterNavigationTrainingCenters_ctl0' + index
            + '_buttonPinPoint' + id).style.background =
                'URL("Common/Images/mappoi_active.gif")';
        document.getElementById('Container_Result_RepeaterNavigationTrainingCenters_ctl0' + index
            + '_buttonPinPoint' + id).style.backgroundRepeat = "no-repeat";
    }
    if (document.getElementById(id) != null) {
        document.getElementById(id).src = 'Common/Images/mappoi_active.gif';
    }
}

//PURPOSE: show the pin point mouse out from map control
//USAGE: onmouseover="mappinpointout();"
function mappinpointout(id, index) {
    if (document.getElementById('Container_Result_RepeaterNavigationTrainingCentersProximity_ctl0' + index
            + '_buttonPinPoint' + id) != null) {
        document.getElementById('Container_Result_RepeaterNavigationTrainingCentersProximity_ctl0' + index
            + '_buttonPinPoint' + id).style.background =
                'URL("Common/Images/poi_search.gif")';
        document.getElementById('Container_Result_RepeaterNavigationTrainingCentersProximity_ctl0' + index
            + '_buttonPinPoint' + id).style.backgroundRepeat = "no-repeat";
    }
    else if (document.getElementById('Container_Result_RepeaterNavigationTrainingCenters_ctl0' + index
            + '_buttonPinPoint' + id) != null) {
        document.getElementById('Container_Result_RepeaterNavigationTrainingCenters_ctl0' + index
            + '_buttonPinPoint' + id).style.background =
                'URL("Common/Images/poi_search.gif")';
        document.getElementById('Container_Result_RepeaterNavigationTrainingCenters_ctl0' + index
            + '_buttonPinPoint' + id).style.backgroundRepeat = "no-repeat";
    }
    if (document.getElementById(id) != null) {
        document.getElementById(id).src = 'Common/Images/poi_search.gif';
    }
}

//PURPOSE: Will be called for creating the map control
function formmapcontrol() {
    // Check if map is null
    if (map != null) {
        map.Clear();
    }
    // Form the map control
    map = new VEMap('mapControl');
}

//PURPOSE: Will be called for loading the empty map control
function loademptymap() {

    // Load the empty map 
    map.LoadMap();
    //TODO : Need to check on configuring the events for endpan and endzoom 
    // Attach the event for map pan end
    //map.AttachEvent("onendpan", endpan);
    // Attach the event for mouse wheel
    //map.AttachEvent("onmousewheel", endzoom);
}

//PURPOSE: Will be called to set the map style
function setmapstyle() {
    // Set the map style
    map.SetMapStyle(VEMapStyle.Road);
    // Set failed shape request
    map.SetFailedShapeRequest(VEFailedShapeRequest.DoNotDraw);
    // Set shape accuracy
    map.SetShapesAccuracy(VEShapeAccuracy.Pushpin);
    // Set shape accuracy request limit
    map.SetShapesAccuracyRequestLimit(25);
}

//PURPOSE: Will be called on end pan
//USAGE: onendpan="endpan();"
function endpan(e) {
    // Get the mapx and mapy
    var mapx = e.mapX;
    var mapy = e.mapY;
    // Check the element position  
    if (!isNaN(mapx)
        && !isNaN(mapy)) {
        var pixel = new VEPixel(mapx, mapy);
        var url = "Default.aspx";
        document.getElementById('hiddenLatLongDetails').innerText
            = map.PixelToLatLong(pixel);
        document.frmHome.action = url;
        document.frmHome.submit();
    }
}

//PURPOSE: Will be called on end zoom
//USAGE: onendzoom="endzoom();"
function endzoom(e) {
    var center = map.GetCenter();
    var url = "Default.aspx";
    document.getElementById('hiddenLatLongDetails').innerText
        = center;
    document.frmHome.action = url;
    document.frmHome.submit();
}

//PURPOSE: Will be called on start request
//USAGE: onload="StartRequestHandler();"
function StartRequestHandler(sender, args) {
    
    // Get the last postback element
    if (args.get_postBackElement() != null
       || args.get_postBackElement() != "undefined") {
        // Set the last post back element id
        lastPostBackElement
                = args.get_postBackElement().id;
    }
    else {
        // Clear the last post back element as null
        lastPostBackElement = null;
    }
    window.scroll(0, 0);
}

//PURPOSE: Will be called on end request
//USAGE: onload="EndRequestHandler();"
function EndRequestHandler(sender, args) {

    if (URL == null) {
        URL = window.location.href; 
    }

        
            var webTrends = document.getElementById('Container_Result_hiddenWebTrendsValues');
            var stringArray = new Array();
            if (webTrends != null) {
                var webTrendsValues = document.getElementById('Container_Result_hiddenWebTrendsValues').value;
                stringArray = webTrendsValues.split("#");
                webTrendsValues = null;
            }
            // Check if the string array is not null
            if (stringArray != null) {

                // Check the value of the array in the first position
                // and pass the parameters to the function accordingly
                if (webTrends != null) {

                    wtReportEvent();

                    if (stringArray[0] == "GO") {
                        dcsMultiTrack('DCS.dcsuri', '/learning/classlocator/search', 'WT.ti', stringArray[1], 'WT.oss', stringArray[2], 'WT.oss_r', stringArray[3],
                    'DCSext.cpls_satv', stringArray[4], 'DCSext.cpls_location', stringArray[5], 'DCSext.cpls_searchtype', 'basic',
                    'DCSext.cpls_coursetrain', stringArray[6], 'DCSext.cpls_deliveryformat', stringArray[7], 'DCSext.cpls_proximity', stringArray[8],
                    'DCSext.cpls_searchopt', '1', 'DCSext.cpls_sortby', 'Best Matches', 'WT.dl', '2');

                    }
                    else if (stringArray[0] == "ADVAN") {
                        dcsMultiTrack('DCS.dcsuri', '/learning/classlocator/search/advanced', 'WT.ti', stringArray[1], 'WT.oss', stringArray[2], 'WT.oss_r', stringArray[3],
                'DCSext.cpls_satv', stringArray[4], 'DCSext.cpls_location', stringArray[5], 'DCSext.cpls_searchtype', 'advanced',
                'DCSext.cpls_coursetrain', stringArray[6], 'DCSext.cpls_fromdate', stringArray[11], 'DCSext.cpls_todate', stringArray[12],
                'DCSext.cpls_deliveryformat', stringArray[7], 'DCSext.cpls_language', stringArray[10], 'DCSext.cpls_proximity', stringArray[8],
                'DCSext.cpls_msprodtechnology1', stringArray[15],
                'DCSext.cpls_msprodtechnology2', stringArray[16],
                'DCSext.cpls_msprodtechnology3', stringArray[17],
                'DCSext.cpls_gold', stringArray[13],
                'DCSext.cpls_coursenum', stringArray[14], 'DCSext.cpls_searchopt', '1', 'DCSext.cpls_sortby', 'Best Matches', 'WT.dl', '2');
                    }
                    else if (stringArray[0] == "PROX") {
                        dcsMultiTrack('DCS.dcsuri', '/learning/classlocator/search/proxsearch', 'WT.ti', 'Class locator search (Proximity)', 'WT.oss', stringArray[2], 'WT.oss_r', stringArray[3],
                'DCSext.cpls_satv', stringArray[4], 'DCSext.cpls_location', stringArray[5], 'DCSext.cpls_searchtype', 'proximity',
                'DCSext.cpls_coursetrain', stringArray[6], 'DCSext.cpls_fromdate', stringArray[11], 'DCSext.cpls_todate', stringArray[12],
                'DCSext.cpls_deliveryformat', stringArray[7], 'DCSext.cpls_language', stringArray[10], 'DCSext.cpls_proximity', stringArray[8],
                'DCSext.cpls_msprodtechnology1', stringArray[15],
                'DCSext.cpls_msprodtechnology2', stringArray[16],
                'DCSext.cpls_msprodtechnology3', stringArray[17],
                'DCSext.cpls_gold', stringArray[13],
                'DCSext.cpls_coursenum', stringArray[14], 'DCSext.cpls_searchopt', '1', 'DCSext.cpls_sortby', 'Best Matches', 'WT.dl', '2');
                    }

                    // Fetch the parameters for query string
                    var queryParameters = document.getElementById('Container_Result_hiddenUrlQueryParameters');
                    if (queryParameters != null) {
                        var queryParametersValues = document.getElementById('Container_Result_hiddenUrlQueryParameters').value;
                        var url = URL + '#&&' + queryParametersValues;
                        AtlasRequest(url);
                    }                    
                    
                }
            }
    
    
       
    
    
    // Check the error 
    if (args.get_error() != null
        && args.get_error() != "undefined") {
        // Clear the last post back element as null
        lastPostBackElement = null;
        // Set the indication of error handled
        args.set_errorHandled(true);

        // Set the error messages
        if (document.getElementById('ErrorMessageDiv') != null) {
            document.getElementById('ErrorMessageDiv').style.display = 'block';
            document.getElementById('ErrorMessageDiv').style.background = 'URL("Common/Images/Legal_Disclaimer_Panel.png")';
            document.getElementById('ErrorMessageDiv').style.backgroundRepeat = "no-repeat";
            document.getElementById('ErrorMessageDiv').style.height = '81px';
        }

        if (document.getElementById('LocationListDiv') != null)
            document.getElementById('LocationListDiv').style.display = 'none';

        if (document.getElementById('NoResultsDiv') != null)
            document.getElementById('NoResultsDiv').style.display = 'none';

        document.getElementById('labelDisplayMessages').innerText = document.getElementById('hiddenTimeoutMessage').value;
    }

    window.scroll(0, 0);
}

//PURPOSE: Will be called on page loaded
//USAGE: onload="PageLoadedHandler();"
function PageLoadedHandler(sender, args) {
    var postBack = true;

    if (lastPostBackElement != null
        && lastPostBackElement.toLowerCase().indexOf("dropdownlistarrangeby") != -1) {
        postBack = false;
    }

    // Check the post back        
    if (postBack) {
        // Load the map       
        LoadMap();
    }
    window.scroll(0, 0);
}

//PURPOSE: Will be called on end request
//USAGE: onload="loadMyMap();"
function loadMyMap() {

    // Check whether the sys object is loaded
    if (typeof (Sys) != "undefined") {
        // Get the current date
        currentDate = new Date();
        // Create the CurrentCulture object
        cultureObject = Sys.CultureInfo.CurrentCulture;
        // Get the name field of the CurrentCulture object
        cultureName = cultureObject.name;
        // Get the dateTimeFormat object from the CurrentCulture object
        dtfObject = cultureObject.dateTimeFormat;
        // Set the hidden value
        document.getElementById('hiddenClientCurrentDate').value
            = currentDate.localeFormat(dtfObject.ShortDatePattern);
        // Call the method to initialize the start request handler
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(StartRequestHandler);
        // Call the method to initialize the end request handler
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
        // Call the method to initialize the page loaded handler
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(PageLoadedHandler);
    }

}

//PURPOSE: Delegate declaration in case of amubigious input
function FindLoc(locationName) {
    var url = "Default.aspx";
    document.getElementById('hiddenAmbiguousLocation').innerText
        = locationName;
    document.frmHome.action = url;
    document.frmHome.submit();
}

//PURPOSE: Delegate declaration in case of amubigious input
function MoreResults(layer, resultsArray, places, hasMore, veErrorMessage) {
    var showError = false;
    var resultIndex = 0;

    if (places != null) {
        // Set zoom level
        map.SetZoomLevel(13);

        if (places.length == 1) 
        {
            if (places[places.length - 1].MatchCode == 0) 
            {
                var url = "Default.aspx";
                document.getElementById('hiddenAmbiguousLocation').innerText = places[places.length - 1].Name;
                document.frmHome.action = url;
                document.frmHome.submit();
            }
        }
    }
}

//PURPOSE: Delegate declaration in case of ambigious input
function SuggestLocations(layer, resultsArray, findResults, hasMore, veErrorMessage) 
{    
    var results = "<table border='0' width='90%'>";    

    if (findResults != null) 
    {
        var resultsCount = findResults.length;

        if (resultsCount > 0) 
        {   
            if (findResults[0].Name != null && (findResults[0].MatchCode == 0 || findResults[0].MatchCode == 1))
                results += "<tr><td><p class='BlackColorSmallSubHeading'>Select a Location:</p></td></tr>";            
            
            for (r = 0; r < resultsCount; r++)
            {
                if (findResults[r].Name != null) 
                {
                    if (findResults[r].MatchCode == 0 || findResults[r].MatchCode == 1)  //&& (findResults[r].MatchConfidence == 0 || findResults[r].MatchConfidence == 1)
                    {
                        results += "<tr><td>"
                        results += "<a id='a" + r + "' onclick='javascript:SubmitSelectedLocation(this.id);' class='BlueColorMedContents' Title='";
                        results += findResults[r].Name;
                        results += "'>";
                        results += findResults[r].Name;
                        results += "</a></td></tr>";
                    }
                }
            }
        }
    }
    results += "</table>";
    //document.getElementById('ErrorMessageDiv').style.display = 'block';

    if (document.getElementById('LocationListDiv') != null) 
    {
        document.getElementById('LocationListDiv').style.display = 'block';
        var resultPane = document.getElementById('LocationListDiv');
        resultPane.innerHTML = results;
    }
}

function SubmitSelectedLocation(objSelLocation) 
{
    var selLocation = document.getElementById(objSelLocation).title;
    var url = "Default.aspx";
    document.getElementById('hiddenAmbiguousLocation').innerText = selLocation;
    document.frmHome.action = url;
    document.frmHome.submit();
}



//function dcsMultiTrack(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26,
//s27, s28, s29, s30, s31, s32, s33, s34, s35, s36, s37, s38, s39, s40, s41, s42) {
//    alert(s1); alert(s2); alert(s3); alert(s4); alert(s5); alert(s6); alert(s7); alert(s8); alert(s9); alert(s10);
//    alert(s11); alert(s12); alert(s13); alert(s14); alert(s15); alert(s16); alert(s17); alert(s18); alert(s19); alert(s20);
//    alert(s21); alert(s22); alert(s23); alert(s24); alert(s25); alert(s26);
//    if (s27 != null) {
//        alert(s27); alert(s28); alert(s29); alert(s30);
//        alert(s31); alert(s32); alert(s33); alert(s34);
//        alert(s35); alert(s36); alert(s37); alert(s38);
//        alert(s39); alert(s40); alert(s41); alert(s42);
//    }
//}

/*******************************************************************************************
**************Code Added today for clearing parameters**************************************
*******************************************************************************************/
// code added for clearing 
function wtReportEvent() {
//    DCS.dcsuri = 
     WT.ti = WT.oss = WT.oss_r = DCSext.cpls_satv = DCSext.cpls_location = DCSext.cpls_searchtype = DCSext.cpls_coursetrain = DCSext.cpls_fromdate = DCSext.cpls_todate = DCSext.cpls_deliveryformat = DCSext.cpls_language = DCSext.cpls_proximity = DCSext.cpls_msprodtechnology1 = DCSext.cpls_msprodtechnology2 = DCSext.cpls_msprodtechnology3 = DCSext.cpls_goldcert = DCSext.cpls_searchcoursenum = DCSext.cpls_searchopt = DCSext.cpls_sortby = DCSext.cpls_proximitychange = DCSext.cpls_partner_id = DCSext.cpls_linktype = DCSext.cpls_courseid = DCSext.cpls_startdate = DCSext.cpls_lang = DCSext.cpls_audience = '';
    //DCSext = new Object(); //not sure what this does exactly.
    //dcsMultiTrack(arguments); //we might want to remove this part from the function. Then, we could call wtReportEvent() when a link is clicked (just to clear params) then immediately fire the multiTrack as we do now.
}

/*******************************************************************************************
**************Code Added today for clearing parameters**************************************
*******************************************************************************************/

function AtlasRequest(url) {

    var xmlhttp = GetXmlHttp();

    if (xmlhttp) {
        var results = "<table><tr><td>";

        if (url.toString().toUpperCase().indexOf('&ID=GOCLICK') > 0) {
            url = 'http://view.atdmt.com/action/ukmuit_FY09MSLearningInfoPageLearningSolutions_1?href=' + url;            
        }
        else if (url.toString().toUpperCase().indexOf('&ID=CNM') > 0) {
            url = 'http://view.atdmt.com/action/ukmuit_FY09MSLearningInfoPageClassesButton_1?href=' + url;            
        }
        else if (url.toString().toUpperCase().indexOf('&ID=TCN') > 0) {
            url = 'http://view.atdmt.com/action/ukmuit_FY09MSLearningInfoPageTrainingCentersBu_1?href=' + url;            
        }

        results += "<img height='1' width='1' src='" + url + "'/>";
        results += "</td></tr></table>";
        if (document.getElementById('Container_Result_divAtlas') != null) {
            document.getElementById('Container_Result_divAtlas').style.display = 'none';
            var resultPane = document.getElementById('Container_Result_divAtlas');
            resultPane.innerHTML = results;
        }
    }
}


