﻿// JScript File

var gLocalSearch;
var map;

function load() {
    if (!invalidClue && GBrowserIsCompatible()) {
        var divMap = document.getElementById("map");
        if (divMap !== null) {
            map = new GMap2(divMap);
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            
            if (currentClueEggFound) {
                var point = new GLatLng(currentClueEggLat, currentClueEggLng);
                var marker = new GMarker(point);
                
                var balloonHtml = "<b>" + currentClueEggTitle + "</b><br/><br/>" + currentClueEggDescription;
                
                if (currentCluePetTag != "")
                    balloonHtml += "<br />" + currentCluePetTag;
                    
                balloonHtml += "<br/><a href=\"" + currentClueEggURL + "\" target=\"_blank\">" + currentClueEggURL + "</a>";
                
                GEvent.addListener(marker, "click", function() {
                    marker.openInfoWindowHtml(balloonHtml, {maxWidth:360});
                });

                map.setCenter(point, currentClueEggMinZoomLevel);
                map.addOverlay(marker);
                                
                marker.openInfoWindowHtml(balloonHtml, {maxWidth:360});
            }
            else {
                // Default to a zoomed out world view
                map.setCenter(new GLatLng(0, 0), 1);
            }
            
            if (defaultMapType === "Satellite")
                map.setMapType(G_SATELLITE_MAP);
            else if (defaultMapType === "Hybrid")
                map.setMapType(G_HYBRID_MAP);
                        
            // Setup a moveend handler
            GEvent.addListener(map, "moveend", function() {                 
                if (isFirstMapPan) {
                    isFirstMapPan = false;
                    displayScanMessage("To start looking, pan the map or use the search box on the left.");
                }       
                if (map.getZoom() >= currentClueEggMinZoomLevel) {
                    var btnFoundIt = document.getElementById("ctl00_ContentPlaceHolder1_btnFoundIt");
                    if (btnFoundIt !== null)
                        btnFoundIt.click();
                }
                else {
                    displayEggVisibilityZoomLevel();
                }
            });

            // Setup the local searcher            
            gLocalSearch = new GlocalSearch();
            gLocalSearch.setCenterPoint(map);
            gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);            
       }        
    }
}

function OnLocalSearch() {
    var txtSearch = document.getElementById("txtSearch");
    
    if (txtSearch === null) {
        alert("Programming error, txtSearch not found");
        return;
    }

    var address = txtSearch.value;        

    var invalidSearch = false;
    
    if (!gLocalSearch.results)
        invalidSearch = true;
    else if (gLocalSearch.results.length <= 0)
        invalidSearch = true;
    
    if (invalidSearch) {
        displayLocationNotFoundMessage(address);
    } 
    else {
        //alert("lat: " + point.lat() + ", " + "long: " + point.lng());

        var first = gLocalSearch.results[0];
        var point = new GLatLng(parseFloat(first.lat), parseFloat(first.lng));
        jumpToLocation(point);
    }
}

function btnSearch_onclick() {
    var txtSearch = document.getElementById("txtSearch");
    
    if (txtSearch === null) {
        alert("Programming error, txtSearch not found");
        return;
    }

    var address = txtSearch.value;        

    // For some reason, the GLocalSearch object was throwing an error
    // when users searched using latitude /longitude coordinates. It wasn't
    // happening somewhere we could catch the error. One idea was to parse
    // the coordinates and just set the map center using the coordinates. It's
    // a pretty tricky parsing algorithm though, so I decided to just use
    // Google's Geocoding service instead of local search whenever coordinates
    // are input.
    if (mightBeLatLng(address)) {
        var geocoder = new GClientGeocoder();
        
        geocoder.getLatLng(
            address,
            function(point) {
              if (!point) {
                displayLocationNotFoundMessage(address);
              } else {
                jumpToLocation(point);            
              }
            });            
    }
    else
        gLocalSearch.execute(address);
}

function jumpToLocation(point) {
    //Set zoom level for search to 14 or higher -> default to clue zoom level if less than 14
    if (currentClueEggMinZoomLevel < 11)
        map.setCenter(point,currentClueEggMinZoomLevel)
    else
        map.setCenter(point, 11);        
}

function displayLocationNotFoundMessage(address) {
    if (confirm("Google Maps does not recognize the text \"" + address + "\".  Try modifying the text or press OK to try a Google Search on this text."))
        btnSearchGoogle_onclick();
        
    displayScanMessage("Google Maps does not recognize the text \"" + address + "\".  Check your spelling or try clicking the Google Search button.");
}

function txtSearch_onkeydown(e) {
    if(window.event) // IE
    {
        keynum = e.keyCode
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which
    }
    //keychar = String.fromCharCode(keynum)

    //alert(keynum);
    if (keynum === 13) {
        btnSearch_onclick();
        e.returnValue = false; 
     }
}

function btnSearchGoogle_onclick() {
    var txtSearch = document.getElementById("txtSearch");
    var cof = document.getElementById("cof");
    
    
    if (txtSearch === null) {
        alert("Programming error, txtSearch not found");
        return;
    }

    var searchPhrase = txtSearch.value;        
    window.open("http://www.google.com/custom?q=" + searchPhrase + "&sa=Google+Search&client=pub-5702714577989293&forid=1&ie=ISO-8859-1&oe=ISO-8859-1&cof=GALT%3A%23008000%3BGL%3A1%3BDIV%3A%23336699%3BVLC%3A663399%3BAH%3Acenter%3BBGC%3AFFFFFF%3BLBGC%3A336699%3BALC%3A0000FF%3BLC%3A0000FF%3BT%3A000000%3BGFNT%3A0000FF%3BGIMP%3A0000FF%3BFORID%3A1&hl=en", "_blank");
}

function doEggCheckCallBack(result, context) {
    // Now that we redirect to a success page, we mostly only need this
    // code to display the "not found" message.
    if (window.ActiveXObject) {
        var xmlDoc=new ActiveXObject('Microsoft.XMLDOM');
        xmlDoc.async = 'false';
        xmlDoc.loadXML(result);        
    }
    else {
        // Firefox / Opera etc.
        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(result, "text/xml");
    }
                
    var root = xmlDoc.documentElement;
    var eggFound = xmlReadBoolean(root, "eggFound");
    var eggLat = xmlReadNullable(root, "eggLat");
    var eggLng = xmlReadNullable(root, "eggLng");
    var eggTitle = xmlReadNullable(root, "eggTitle");
    var eggDescription = xmlReadNullable(root, "eggDescription");
    var eggURL = xmlReadNullable(root, "eggURL");
    
    if (eggFound === 'true') {
        // Redirect to success URL stored in a hidden field
        var ctl00_ContentPlaceHolder1_hiddenSuccessURL = document.getElementById("ctl00_ContentPlaceHolder1_hiddenSuccessURL");
        if (ctl00_ContentPlaceHolder1_hiddenSuccessURL !== null) {
            var defaultMapType = "Normal";
            if (map.getCurrentMapType() == G_SATELLITE_MAP)
                defaultMapType = "Satellite";
            else if (map.getCurrentMapType() == G_HYBRID_MAP)
                defaultMapType = "Hybrid";
                
            window.location = ctl00_ContentPlaceHolder1_hiddenSuccessURL.value + "&DefaultMapType=" + defaultMapType + "#MapMessage";
        }    
    }
    else {
        var spanScanAlert;
        
        spanScanAlert = document.getElementById("spanScanAlert");
        if (spanScanAlert !== null)
            spanScanAlert.innerHTML = "Answer visible at zoom level " + currentClueEggMinZoomLevel + " or higher, currently at " + map.getZoom() + "<br/>Visible at this zoom level, but not found here. Keep looking.";
    }        
}

function getMapDivWidth() {
    var divMap;
    var result = "0px";
    
    divMap = document.getElementById("map");
    if (divMap !== null)
        result = divMap.style.width;
        
    return result;        
}

function getMapDivHeight() {
    var divMap;
    var result = "0px";
    
    divMap = document.getElementById("map");
    if (divMap !== null)
        result = divMap.style.height;
   
    return result;
}    

function displayEggVisibilityZoomLevel() {
    if (currentClueEggFound)
        displayScanMessage("");
    else
        displayScanMessage("Answer visible at zoom level " + currentClueEggMinZoomLevel + " or higher, currently at " + map.getZoom());
}

function startScanningAlert() {
    displayScanMessage("Scanning map...");
}

function displayScanMessage(message) {
    var spanScanAlert;
            
    spanScanAlert = document.getElementById("spanScanAlert");
    if (spanScanAlert !== null)
        spanScanAlert.innerHTML = message;
}
