var xmlHttpParks = GetXmlHttpObject();
var xmlHttpInfo = GetXmlHttpObject();
var xmlHttpImages = GetXmlHttpObject();
var map;
var gdir;
var centre_point;
var got_point;
var execution_time;
var html;
var current_marker;
var num_markers;
var finished_loading = false;
var start_location_required = false;
var loaded_point = false;
var timeout = 0;
var start_location = "";
var continue_execution = false;

function GetXmlHttpObject()
{
    var xmlObj;

    try
    {    // Firefox, Opera 8.0+, Safari
        xmlObj = new XMLHttpRequest();
    }
    catch (e)
    {    // Internet Explorer
        try
        {
            xmlObj = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    return xmlObj;
}

function getParks(pid, radius, location)
{
    map.clearOverlays();
    setDynamoHeadquarters();
    if(pid != "")
    {
        if(location != "")
        {
            var re = new RegExp("[0-9]{1,2}\.?[0-9]*?,\-?[0-9]{1,2}\.?[0-9]*");
            var geocoder = new GClientGeocoder();
            got_point = false;
            if(location.match(re))
            {
                var lat_lng_coords = location.split(",");
                centre_point = new GLatLng(lat_lng_coords[0], lat_lng_coords[1]);
                got_point = true;
            }
            else
            {
                geocoder.getLocations(location, addToMap);
            }
            document.getElementById("loading").style.display = 'block';
            document.getElementById("go").style.display = 'none';
            setTimeout("sendLoadDataCommand('" + pid + "', '" + radius + "', '" + location + "')", 500);
        }
        else
        {
            got_point = true;
            centre_point = new GLatLng(45.491886,-75.481975);
            sendLoadDataCommand(pid, radius, location);
        }
    }    
}

function sendLoadDataCommand(pid, radius, location)
{
    execution_time += 500;
    if(execution_time > 10000)
    {
        execution_time = 0;
        document.getElementById("loading").style.display = 'none';
        document.getElementById("go").style.display = 'block';
        alert("Google doesn't seem to be responding to the search request, this could be the result of a bad connection, or bad input. Please re-enter your search parameters and try again.");
        return;
    }
    if(got_point)
    {
        execution_time = 0;
        document.getElementById("loading").style.display = 'none';
        document.getElementById("go").style.display = 'block';
        // Center the map on this point
        if(radius != "")
        {
            map.setCenter(centre_point, Math.floor(16 - Math.log(radius) / Math.log(2)) - 2);
        }
        else
        {
            map.setCenter(centre_point, (location == "0,0" ? 1 : 4));
        }
    
        var url = "http://www.dynamoplaygrounds.com/loadData.php?prod=" + pid + (radius == "" ? "" : "&radius=" + radius) + "&lat=" + centre_point.lat() + "&long=" + centre_point.lng() + special_case + "&uniqueId=" + rand_id;
        xmlHttpParks.open('GET', url, true);
        xmlHttpParks.onreadystatechange = function() { parkDataStateChanged(); };
        xmlHttpParks.send(null);
        if(radius != "")
        {
            map.addOverlay(GPolyline.Circle(centre_point, radius * 1000));
        }
    }
    else
    {
        setTimeout("sendLoadDataCommand('" + pid + "', '" + radius + "', '" + location + "')", 500);
    }
}

function addToMap(data)
{
    var place = data.Placemark[0];
    
    // Retrieve the latitude and longitude
    centre_point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

    // Create a marker
    marker = new GMarker(centre_point);

    // Add the marker to map
    map.addOverlay(marker);

    // Add address information to marker
    marker.openInfoWindowHtml(place.address);

    got_point = true;
}

function createMarker(id, point, options, html)
{
    var marker = new GMarker(point, options);
    GEvent.addListener(marker, "click", 
        function(){
            marker.openInfoWindowHtml(html);
            var url = 'http://www.dynamoplaygrounds.com/get_images.php?id=' + id + '&uniqueId=<?php echo mt_rand(); ?>';
            xmlHttpImages.open('GET', url, true);
            xmlHttpImages.onreadystatechange = function() { imagesStateChanged(); };
            xmlHttpImages.send(null);
            document.getElementById("map").style.width = "710px";
            document.getElementById("directions").style.width = "0px";
            map.checkResize();
            document.getElementById("directions").innerHTML = "";
            map.panTo(point);
        }
    );
    return marker;
}

function imagesStateChanged()
{
    if (xmlHttpImages.readyState == 4 && xmlHttpImages.status == 200)
    {
        var data = xmlHttpImages.responseText;
        if(data)
        {
            document.getElementById("images").innerHTML = data;
        }
    }
}

function parkDataStateChanged()
{
    if (xmlHttpParks.readyState == 4 && xmlHttpParks.status == 200)
    {
        var data = xmlHttpParks.responseText;
        if(data)
        {
            var arch_icon = new GIcon();
            arch_icon.image = "http://www.dynamoplaygrounds.com/images/arch_vector.png";
            arch_icon.shadow = "http://www.dynamoplaygrounds.com/images/arch_shadow.png";
            arch_icon.iconSize = new GSize(30,24);
            arch_icon.shadowSize = new GSize(44,25);
            arch_icon.iconAnchor = new GPoint(20,24);
            arch_icon.infoWindowAnchor = new GPoint(9,2);
    
            var markerOptions = { icon:arch_icon };

            var currentParksContent = data.evalJSON();
            var park_data = "";

            document.getElementById("message").innerHTML = "Found " + currentParksContent.items.length + " location(s) that matched your criteria.";
            num_markers = currentParksContent.items.length;
            
            for(var i = 0; i < currentParksContent.items.length; i++)
            {
                var temp_item = currentParksContent.items[i];
                if(temp_item.lat != '')
                {
                    var latlng = new GLatLng(temp_item.lat, temp_item.long);
                    var equipment = temp_item.equip.split(",");
                    var product_urls = "";
                    for(var j = 0; j < equipment.length; j++)
                    {
                        product_urls += "<a href='http://www.dynamoplaygrounds.com/products/display_product_info.php?pid=" + equipment[j] + "' target='_blank'>" + equipment[j] + "</a>";
                        if((j + 1) != equipment.length)
                        {
                            product_urls += ", ";
                        }
                    }
                    //" + (directed_search != "" ? "(show_prompt() == -1 ? \"break;\" : \"\");" : "") + "
                    //console.log((directed_search != "" ? "alert(\"ID\"); " : "alert(\"NO ID\"); "));
                    //console.log("<div class='map'><b>" + temp_item.name + "</b><br/>" + temp_item.street + "<br/>" + temp_item.city + ", " + temp_item.prov + "<br/>" + temp_item.country + "<br/><a href='javascript:" + (directed_search != "" ? "alert(\"ID\"); " : "alert(\"NO ID\"); ") + "setDirections(\"" + centre_point.lat() + ", " + centre_point.lng() + "\", \"" + temp_item.lat + ", " + temp_item.long + "\", \"en_US\");'>Get Directions</a><br/><br/><b>Installed Since:</b> " + (temp_item.install_date == "0000-00-00" ? "Unknown" : temp_item.install_date) + "<br/><b>Products:</b> " + product_urls + (temp_item.images > 0 ? "<br/><br/><table cellpadding=0 cellspacing=0 style=\"height:" + temp_item.image_height + "px;\"><tr><td><a href=\"#images\"><img src=\"http://www.dynamoplaygrounds.com/install/images/" + temp_item.install_id + "_1_t.jpg\"/></a></td><td style=\"padding-left: 6px; vertical-align: middle\">" + (temp_item.images > 1 ? (temp_item.images - 1) + " more images below..." : "") + "</td></tr></table>" : "") + "</div>");
                    var marker = createMarker(temp_item.install_id, latlng, markerOptions, "<div class='map'><b>" + temp_item.name + "</b><br/>" + temp_item.street + "<br/>" + temp_item.city + ", " + temp_item.prov + "<br/>" + temp_item.country + "<br/><a href='javascript:setDirections(\"" + centre_point.lat() + ", " + centre_point.lng() + "\", \"" + temp_item.lat + ", " + temp_item.long + "\", \"en_US\");'>Get Directions</a><br/><a href='javascript:prepareDialog(\"" + temp_item.install_id + "\", \"" + temp_item.name + "\");'>Link to this Playground</a><br/><br/><b>Installed Since:</b> " + (temp_item.install_date == "0000-00-00" ? "Unknown" : temp_item.install_date) + "<br/><b>Products:</b> " + product_urls + (temp_item.images > 0 ? "<br/><br/><table cellpadding=0 cellspacing=0 style=\"height:" + temp_item.image_height + "px;\"><tr><td><a href=\"#images\"><img src=\"http://www.dynamoplaygrounds.com/install/images/" + temp_item.install_id + "_1_t.jpg\"/></a></td><td style=\"padding-left: 6px; vertical-align: middle\">" + (temp_item.images > 1 ? (temp_item.images - 1) + " more images below..." : "") + "</td></tr></table>" : "") + "</div>");
                    map.addOverlay(marker);
                    current_marker = marker;
                }
                park_data += temp_item.install_id + ", " + temp_item.name + ", " + temp_item.street + ", " + temp_item.city + ", " + temp_item.prov + ", " + temp_item.country + ", " + temp_item.install_date + ", " + temp_item.lat + ", " + temp_item.long + temp_item.equip + "<br/>";
            }
            if(num_markers >= 1)
            {
                document.getElementById("notice").style.display = 'block';
                document.getElementById("notice").innerHTML = num_markers + ' result(s) found. Click on the blue playground arches to get detailed park information.'
            }
            else
            {
                document.getElementById("notice").style.display = 'none';
            }
            finished_loading = true;
        }
    }
}

function prepareDialog(install_id, park_name)
{
    document.getElementById("email").value="http://www.dynamoplaygrounds.com/pg_locator.php?id=" + install_id;
    document.getElementById("web").value="<a href='http://www.dynamoplaygrounds.com/pg_locator.php?id=" + install_id + "'>" + park_name + "</a>";
    $("#dialog").dialog("open");
}
//<![CDATA[

function setDynamoHeadquarters()
{
    var dynamo_korea_icon = new GIcon();
    dynamo_korea_icon.image = "http://www.dynamoplaygrounds.com/images/dynamo_korea.png";
    dynamo_korea_icon.shadow = "http://www.dynamoplaygrounds.com/images/dynamo_korea_shadow.png";
    dynamo_korea_icon.iconSize = new GSize(116,30);
    dynamo_korea_icon.shadowSize = new GSize(116,30);
    dynamo_korea_icon.iconAnchor = new GPoint(43,16);

    var dynamo_icon = new GIcon();
    dynamo_icon.image = "http://www.dynamoplaygrounds.com/images/dynamo.png";
    dynamo_icon.shadow = "http://www.dynamoplaygrounds.com/images/dynamo_shadow.png";
    dynamo_icon.iconSize = new GSize(116,30);
    dynamo_icon.shadowSize = new GSize(116,30);
    dynamo_icon.iconAnchor = new GPoint(43,16);

    markerOptions = { icon:dynamo_icon };
    var latlng = new GLatLng(45.491954,-75.482828);

    markerOptionsKorea = { icon:dynamo_korea_icon };
    var latlng1 = new GLatLng(35.316777,129.200489);

    var marker = new GMarker(latlng, markerOptions);
    GEvent.addListener(marker, "click",
        function() {
            var myHtml = "<div class='map'><b>Dynamo Industries</b><br/>880 Taylor Creek Dr.<br/>Orleans, ON  K1C 1T1</div>";
            map.openInfoWindowHtml(latlng, myHtml);
        });

    var marker1 = new GMarker(latlng1, markerOptionsKorea);
    GEvent.addListener(marker1, "click",
        function() {
            var myHtml = "<div class='map'><b>Dynamo Korea</b><br/>1113-6 Dalsan-Ri<br/>Jungkwan-Myun<br/>Gijang-Kun<br/>Busan 619-961</div>";
            map.openInfoWindowHtml(latlng1, myHtml);
        });

    map.addOverlay(marker);
    map.addOverlay(marker1);		
}

function doSearch(which_button)
{
    if(which_button == "go_1")
    {
        var pid = document.getElementById("products_1").value;
        var radius = "";
        var location = "";
    }
    else
    {
        var pid = document.getElementById("products").value;
        var radius = document.getElementById("radius").value;
        var location = document.getElementById("location").value;
    }   
    
    //if the user doesn't select any product, then we'll default to "all" products.
    if(pid == "")
    {
        pid = "all";
        //Index 1 has the value "All Products"
        document.getElementById("products").selectedIndex = 1;
    }
    
    if(radius == "" && location == "")
    {
        location = '0,0';
        start_location_required = true;
    }
    else if(radius != "" && location == "")
    {
        alert("You've entered a radius of '" + radius + " km', but you haven't specified a location to start from, please specify your start location before continuing.");
        start_location_required = false;
        return;
    }
    
    getParks(pid, radius, location);
}

function setDirections(fromAddress, toAddress, locale) {
    if(fromAddress == "")
    {
        alert("Please specify a starting location by entering an address in the textbox below and click the \"GO\" button.");
        return;
    }
    if(start_location_required)
    {
        show_prompt();
        fromAddress = start_location;
    }
    document.getElementById("map").style.width = "433px";
    document.getElementById("directions").style.width = "265px";
    map.checkResize();
    gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
}

function handleErrors(){           
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS)
        alert("The GDirections object could not compute directions between the points mentioned in the query. This is usually because there is no route available between the two points, or because we do not have data for routing in that region.\n Error code: " + gdir.getStatus().code)                
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
        alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
        alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
        alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
        alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_UNAVAILABLE_ADDRESS)
        alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code)
    else alert("An unknown error occurred.");
    document.getElementById("map").style.width = "710px";
    document.getElementById("directions").style.width = "0px";
    document.getElementById("directions").innerHTML = "";
}

function check_for_enter_key(e)
{
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    if(keynum == 13)
    {
        doSearch();
    }
}

function wait_for_point()
{
    if(!got_point && timeout == 5000)
    {
        timeout = 0;
        alert("Timeout waiting for coordinates");
        return;
    }
    if(!got_point)
    {
        timeout += 500;
        setTimeout(wait_for_point, 500);
    }
}

function show_prompt(){
     if(start_location != "")
    {
        if(!confirm("Do you want to continue to use " + start_location + " as your starting location?\nOk => Yes\nCancel => No"))
        {
            start_location = "";
        }
    }
    if(start_location == "")
    {
        address = prompt("Please provide your starting location by typing in an Address, City and State/Province separated by commas.","");
    }
    else
    {
        address = start_location;
    }

    if (address != null && address != "")
    {
        var geocoder = new GClientGeocoder();
        geocoder.getLocations(address, addToMap);
        wait_for_point();
        start_location = address;
    }
    else if(address == null)
    {
        return -1;
    }
    else if(address == "")
    {
        show_prompt();
    }
}

function onGDirectionsLoad(){ 
    // Use this function to access information about the latest load()
    // results.
   
    map.setCenter(gdir.getBounds().getCenter(), map.getBoundsZoomLevel(gdir.getBounds()));
}

function HtmlControl(html) { this.html = html }

function load(directed_search) {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        
        var dynamo_headquarters = new GLatLng(45.491886,-75.481975);
        map.setCenter(dynamo_headquarters, 5);
    
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.enableScrollWheelZoom();
        
        HtmlControl.prototype = new GControl();
        
        HtmlControl.prototype.getDefaultPosition = function() {
            return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 30));
        } 
    
        HtmlControl.prototype.initialize = function(map) {
            var container = document.createElement("div");
            var extra = document.createElement("div");
            extra.className = "legend";
            extra.innerHTML = this.html;
            container.appendChild(extra);
            map.getContainer().appendChild(container);
            return container;
        }
    
        map.addControl(new HtmlControl("<table><th colspan=2>Legend</th><tr><td style='text-align: right'><img src='/images/dynamo_legend.png' /></td><td style='font-size: 12px'>Dynamo Headquarters</td><tr><td style='text-align: right'><img src='/images/arch_vector_legend.png' /></td><td style='font-size: 12px'>Playground</td>")); 
        
        getParks("", "", "");
        if(directed_search != "")
        {
            start_location_required = true;
            getParks("all", "0.1", directed_search);
        }
        else
        {
            start_location_required = false;
        }
    }
}
//]]>