var map;
var geocoder;
var selected_state;
var no_results = false;
var can_be_updated = false;

var micon2 = new GIcon();
            
micon2.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
micon2.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
micon2.iconSize = new GSize(12, 20);
micon2.shadowSize = new GSize(22, 20);
micon2.iconAnchor = new GPoint(6, 20);
micon2.infoWindowAnchor = new GPoint(5, 1);
            
var icon = new GIcon();

icon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
icon.iconSize = new GSize(12, 20);
icon.shadowSize = new GSize(22, 20);
icon.iconAnchor = new GPoint(6, 20);
icon.infoWindowAnchor = new GPoint(5, 1);

var dealericon = new GIcon();

dealericon.image = "icons/skystream_dealer.gif";
dealericon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
dealericon.iconSize = new GSize(20, 20);
dealericon.shadowSize = new GSize(22, 20);
dealericon.iconAnchor = new GPoint(6, 20);
dealericon.infoWindowAnchor = new GPoint(5, 1);

// On body load, load the Google Maps interface and load event handlers
function load()
{
    document.forms[0].q.focus();
    
    if (GBrowserIsCompatible())
    {
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(38, 0), 1);
        geocoder = new GClientGeocoder();

        var address = "US";
        var width = 1;
        
        var i = document.getElementById('windmap');
        
        i.onclick = function() { window.alert("You must enter search criteria to view a wind map."); document.forms[0].q.focus(); return false; };

        //displayStart(address,width);
    }

    // Capture event for when a user drags the map around and update the map
    // with a new result set based on the map boundaries
    GEvent.addListener(map, "dragend",
        function() { updateMap('drag'); });

    // Capture event for when a user zooms in or out on the map and update the map
    // with a new result set based on the map boundaries
    GEvent.addListener(map, "zoomend",
        function() { updateMap('zoom'); });
}

// Called by onclick event handler, which seems to be most friendly with IE7 and Opera browsers
function browserLoad1()
{
    var b = navigator.appName;
    
    if ( b == "Microsoft Internet Explorer" || b == "Opera" ) { return updateSearch(); }
}

// Called by onchange event handler, which seems to be most friendly with Firefox and Safari browsers
function browserLoad2()
{
    var b = navigator.appName;
    
    if ( b != "Microsoft Internet Explorer" && b != "Opera" ) { return updateSearch(); }
}

// Create a map marker consisting of dealer or owner information
function createMarker(point, icon, company, firstname, lastname, address1, address2, city, state, zip, country, phone1, phone2, email, website, notes, rid)
{
    var loc = document.forms[0].q.value;
    var c = document.forms[0].country.value;
    
    var marker = new GMarker(point, icon);

    GEvent.addListener(marker, "click", function() 
    {
        var s = searchType();
        
        if (s == "showdealers")
        {
            marker.openInfoWindowHtml("<span class=\"markerstitle\">" + company + "</span>" + "<br />" + address1 + "<br />" + address2 + "<br />" + city + ", " + state + " " + zip + "<br />" + phone1 + "<br />" + phone2  + "<br />" + "<a href=\"mailto:" + email + "\">" + email + "</a>" + "<br />" + "<a href=\"http://" + website + "\">" + website + "</a>" + "<br />" + "<a href=\"\" onclick=\"openwin('directions.php?id=" + rid + "&country=" + c + "&zip=" + loc + "','Directions'); return false;\">directions</a>" + "<br />" + notes);
        }
        else if (s == "showowners")
        {
            marker.openInfoWindowHtml("<span class=\"markerstitle\">" + firstname + " " + lastname + "</span>" + "<br />" + address1 + "<br />" + city + ", " + state + " " + zip + "<br />" + "<a href=\"mailto:" + email + "\">" + email + "</a>" + "<br />" + "<a href=\"http://" + website + "\">" + website + "</a>" + "<br />" + notes);            
        }
    });
    
    return marker;
}

function createMarkerCenter(plat, plng, icon)
{
    var point = new GPoint(plng, plat);
    var marker = new GMarker(point, icon);
    
    GEvent.addListener(marker, "click", function()
    {
        marker.openInfoWindowHtml(point + "<br>Search Location");
    });

    return marker;
}

function createMarkerPoint(point, icon)
{
    var marker = new GMarker(point, icon);

    GEvent.addListener(marker, "click", function()
    {
        marker.openInfoWindowHtml("<b>" + point + "<br />Search Location");
    });
    
    return marker;
}

function displayStart(address, width)
{
    geocoder.getLatLng( address, function(point)
    {
        map.setCenter(point, width);
        map.addOverlay(createMarkerPoint(point, micon2, address));
    });
}

// When a user clicks on expand, this function will zoom out the map and update the results accordingly
function expand()
{
    var width = map.getZoom();
    
    width--;
    
    map.setZoom(width);
    
    //updateMap('zoom');
}

// Tied to input text box to ignore the enter key stroke
// In the future, on enter key press will result in a map update
function onenter(e)
{
    var evt = e || window.event;
    var keyPressed = evt.which || evt.keyCode;
    
    if (keyPressed == 13)
    {
        updateSearch();
        return false;
    }
}

// Open new window of a limited size using Javascript
function openwin(url, title)
{
    window.open(url,title,'width=575,height=750,directories=no,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no');
}

// Open generic new window via Javascript
function gopenwin(url)
{
    window.open(url,'','');
}

// Return the selected radio button
function searchType()
{
    var searchoption = 0;
    
    for ( var i = 0; i < document.forms[0].searchgroup.length; i++ )
    {
        if ( document.forms[0].searchgroup[i].checked == true )
        {
            searchoption = document.forms[0].searchgroup[i].value;
            break;
        }
    }
    
    return searchoption;
}

// This function is called by updateSearch
function showAddress(address,width)
{
    geocoder.getLatLng(address, function(point)
    {
        if (!point)
        {
            window.alert(address + " not found");
        }
        else
        {
            map.clearOverlays();
            
            map.setCenter(point, width);
            map.addOverlay(createMarkerPoint(point, micon2));

            // Calculate bounds of map in order to update map with new result set
            var bounds = map.getBounds();
            var southWest = bounds.getSouthWest();
            var northEast = bounds.getNorthEast();
            var lngSpan = northEast.lng() - southWest.lng();
            var latSpan = northEast.lat() - southWest.lat();
            
            // Call the function that updates the results
            updateResults(northEast.lng(),northEast.lat(),southWest.lng(),southWest.lat(),searchType(),true);
            
            // allow google to update
            can_be_updated = true;
        }
    });
}

// This function is used to load the incentives content and windmap URL based on state and country
function showIncentives(loc)
{
    GDownloadUrl("loc_toxml.php?loc=" + document.forms[0].q.value + '&country=' + document.forms[0].country.value, function(data)
    {
        if ( data )
        {
            var xml = GXml.parse(data);
            var root = xml.documentElement.getElementsByTagName("loc");

            var state = root[0].getAttribute("state");

            if ( ! state )
            {
                document.forms[0].searchgroup[0].checked = true;
                window.alert("This search tool currently displays results for the United States only. If you live outside the United States, please contact your local dealer to find out what incentives are available.");
            }
            else
            {
                var m = document.getElementById('map');
                m.className = 'hidemap';
                var mr = document.getElementById('mapfooter');
                mr.className = "hidemapfooter";
                
                var r = document.getElementById('results');
                removeNodes(r);
                
                updateAjax('incentives', 'incentives.php?state=' + state);
            }
        }
        else
        {
            window.alert(document.searchform.q.value + " not found");
        }
    });
}

function showWindmap(loc)
{
    GDownloadUrl("loc_toxml.php?loc=" + document.forms[0].q.value + '&country=' + document.forms[0].country.value, function(data)
    {
        if ( data )
        {
            var xml = GXml.parse(data);
            var root = xml.documentElement.getElementsByTagName("loc");

            var windurl = root[0].getAttribute("windurl");
            
            var i = document.getElementById('windmap');
            if ( windurl == 'none' )
            {
                i.onclick = function() { window.alert("You must enter search criteria to view a wind map."); return false; };
            }
            else
            {
                i.onclick = function() { gopenwin(windurl); return false; };
                //i.setAttribute("href", windurl);
            }
        }
        else
        {
            window.alert(document.searchform.q.value + " not found");
        }
    });
}

// This function is called by the Google Maps event handler when an event occurs (drag or zoom)
function updateMap(eventtype)
{
    if ( document.forms[0].q.value )    
    {
        map.clearOverlays();
        wait(500);
    
        var clat = map.getCenter().lat();
        var clng = map.getCenter().lng();
        
        map.addOverlay(createMarkerCenter(clat, clng, micon2));
        
        // Calculate bounds of map in order to update map with new result set
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        var lngSpan = northEast.lng() - southWest.lng();
        var latSpan = northEast.lat() - southWest.lat();
        
        // Display URL to access XML marker list directly for debug purposes
        //var d = document.getElementById('debug');
        //d.innerHTML = "markers_toxml.php?nelng=" + northEast.lng() + "&nelat=" + northEast.lat() + "&swlng=" + southWest.lng() + "&swlat=" + southWest.lat() + "&searchoption=" + searchType();

        // Call the function that updates the results
        if (can_be_updated) {
        	if (eventtype == 'zoom') {
        		updateResults(northEast.lng(),northEast.lat(),southWest.lng(),southWest.lat(),searchType(),true);
        	}
        	else {
        		// turn off auto-expand after drag
          	updateResults(northEast.lng(),northEast.lat(),southWest.lng(),southWest.lat(),searchType(),false);
          }
        }
    }
}

// This code actually updates the map markers and results on the site
function updateResults(nelng,nelat,swlng,swlat,searchoption,autoexpand)
{    
    // reverse geocode center point to determine which state/country it belongs to
    geocoder.getLocations(map.getCenter(), function(response) {
      // parse responses
      if (!response || response.Status.code != 200) {
        selected_state = '';
      } else {
        place = response.Placemark[0];
        if (place.AddressDetails.Country.AdministrativeArea == undefined) {
          selected_state = '';
        }
        else {
          selected_state = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
        }
      }
      
      // allow google to update
      can_be_updated = true;
    
      // Update the map markers
      GDownloadUrl("markers_toxml.php?nelng=" + nelng + "&nelat=" + nelat + "&swlng=" + swlng + "&swlat=" + swlat + "&searchoption=" + searchoption + '&country=' + document.forms[0].country.value + '&state=' + selected_state, function(data) 
      {
          if (data)
          {
              var active = 1;
              var xml = GXml.parse(data);
              var markers = xml.documentElement.getElementsByTagName("marker");
              
              // set no results
              no_results = markers.length == 0;
              
              // load result list only if there are results
              if (no_results) {
                document.getElementById('results').innerHTML = '';
                if (autoexpand) {
                	expand();
                }
              }
              else {
                // Update the search result list
                updateAjax('results', 'results.php?nelng=' + nelng + '&nelat=' + nelat + '&swlng=' + swlng + '&swlat=' + swlat + '&searchoption=' + searchoption + '&loc=' + document.forms[0].q.value + '&country=' + document.forms[0].country.value + '&state=' + selected_state);
              }
  
              for (var i = 0; i < markers.length; i++)
              {
                  var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                              parseFloat(markers[i].getAttribute("lng")));
                  var type = markers[i].getAttribute("type");
                  var company = markers[i].getAttribute("company");
                  var firstname = markers[i].getAttribute("firstname");
                  var lastname = markers[i].getAttribute("lastname");
                  var address1 = markers[i].getAttribute("address1");
                  var address2 = markers[i].getAttribute("address2");
                  var city = markers[i].getAttribute("city");
                  var state = markers[i].getAttribute("state");
                  var zip = markers[i].getAttribute("zip");
                  var country = markers[i].getAttribute("country");
                  var phone1 = markers[i].getAttribute("phone1");
                  var phone2 = markers[i].getAttribute("phone2");
                  var email = markers[i].getAttribute("email");
                  var website = markers[i].getAttribute("website");
                  var notes = markers[i].getAttribute("notes");
                  var dealerid = markers[i].getAttribute("dealerid");
                  var sdealer = 0;
  
                  if ( type == "dealer" )
                  {
                      active = markers[i].getAttribute("active");
                      sdealer = markers[i].getAttribute("sdealer");
                  }
  
                  var marker;
  
                  if ( sdealer == '1' && active == '1' )
                  { 
                      marker = createMarker(point, dealericon, company, firstname, lastname, address1, address2, city, state, zip, country, phone1, phone2, email, website, notes, dealerid);
                  }
                  else if ( active == '1' )
                  {
                      marker = createMarker(point, icon, company, firstname, lastname, address1, address2, city, state, zip, country, phone1, phone2, email, website, notes, dealerid);
                  }
  
                  if ( active == '1' )
                  {
                      map.addOverlay(marker);
                  }
              }
          }
      });
    });
}

// This function is the starting point to updating the map when a user clicks on a radio button or clicks Go
function updateSearch()
{
    var loc = document.forms[0].q.value;
    var c = document.forms[0].country.value;
    var s = searchType();
    
    // prevent google from call update results before we do our job
    can_be_updated = false;
    
    // Check if a user entered a state in the search field instead of a city or zip code
    // IE
    try
    {
        xml = new ActiveXObject("MSXML2.DOMDocument");
    }
    catch(e)
    {
        try
        {
            // Firefox, Opera
            xml = document.implementation.createDocument("","",null);
        }
        catch(e)
        {
            alert(e.message);
            return;
        }
    }

    // Safari does not support the XML load function
    // Working on alternative
    try
    {
        xml.async=false;
        xml.load("input_toxml.php?input=" + document.forms[0].q.value);
        var root = xml.getElementsByTagName("input")
        var result = root[0].getAttribute("result");

        if ( result != '0' )
        {
            window.alert("You have entered a state in the search field. Please enter a valid city or zip code.");
            return ;
        }
    }
    catch(e) { }
    
    if ( ! document.forms[0].q.value )
    {
        window.alert("Please enter a zip code or city.");
        document.forms[0].q.focus();
    }
    else
    {
        var m = document.getElementById('map');
        m.className = "showmap";
        var mr = document.getElementById('mapfooter');
        mr.className = "showmapfooter";
        
        var i = document.getElementById('incentives');
        removeNodes(i);
        
        showWindmap(loc);
        
        if (s == "showincentives") { showIncentives(loc); }
        else if (c == "US" && s == "showdealers") { showAddress(loc + ' ' + c,8); }
        else { showAddress(loc + ' ' + c,8); }
    }
}

// Sleep function in ms
function wait(delay)
{
    d = new Date();
    while ( 1 )
    {
        ms = new Date();
        diff = ms - d;
        if( diff > delay ) { break; }
    }
}
