//***************************
//    Global variables Start
//***************************

var showVars = [];
var map;                         // google map object
var icons = [];                  // array of icons
var markers = [];                // array of markers
var navbarHtml = [];             // array of html strings for the nav bar
var counts = [];
var subNames = [];               // array of subdivision names
var descriptions = [];           // array of subdivision descriptions

var resizingInterval = null;     // window sizing var
var resizingFlag = false;        // window sizing var
var bounds;								// bounds of results markers

//***************************
//    Global variables End
//***************************

function initVars()
{
   navbarHtml["sub"]= '<span class="listHead">Subdivisions</span><ol>';         // html for subdivision part of sidebar
//   navbarHtml["sf"]= '<span class="listHead">Single Family</span><ol>';         // html for subdivision part of sidebar
//   navbarHtml["mf"]= '<span class="listHead">Condo/Townhomes</span><ol>';         // html for subdivision part of sidebar
//   navbarHtml["vacant"]= '<span class="listHead">Vacant</span><ol>';         // html for subdivision part of sidebar
   navbarHtml["otherMarker"] = "";
   navbarHtml["results"] = "";
   navbarHtml["sideBar"] = "";

   markers["sub"] = [];         // array of listing markers
   markers["results"] = [];         // array of listing markers
//   markers["sf"] = [];         // array of listing markers
//   markers["mf"] = [];         // array of listing markers
//   markers["vacant"] = [];         // array of listing markers
   markers["otherMarker"] = [];
   markers["subCenters"] = [];         // array of listing markers

   showVars["sub"] = true;
//   showVars["sf"] = true;
//   showVars["mf"] = true;
//   showVars["vacant"] = true;
   showVars["results"] = true;
   showVars["otherMarker"] = true;

   counts["sub"] = 0;
//   counts["sf"] = 0;
//   counts["mf"] = 0;
//   counts["vacant"] = 0;
   counts["results"] = 0;
   counts["otherMarker"] = 0;

	bounds = new GLatLngBounds();
}

//
// Create all the icons for the different markers
//
function createIcons()
{
   // There is the capability to define very different icons for each 
   icons["vacant"] = new GIcon(G_DEFAULT_ICON);
//   icons["vacant"].iconSize = new GSize(32,32);
//   icons["vacant"].shadowSize = new GSize(56,32);
//   icons["vacant"].iconAnchor = new GPoint(16,16);
//   icons["vacant"].infoWindowAnchor = new GPoint(16,0);
//   icons["vacant"].image = "http://maps.grandcountyforsale.com/images/property.png";
//   icons["vacant"].shadow = "http://maps.google.com/mapfiles/kml/pal4/icon17s.png";

   icons["sf"] = new GIcon(G_DEFAULT_ICON);
   icons["mf"] = new GIcon(G_DEFAULT_ICON);
   icons["results"] = new GIcon(G_DEFAULT_ICON);
}

// A function to create the marker and set up the event window
function createMarker(point, zoom, name, html)
{
   var marker = new GMarker(point);

   GEvent.addListener(marker, "click", function() {
      map.setCenter(point, zoom);
      marker.openInfoWindowHtml(html);
   });

   // save the info we need to use later for the side_bar
   markers["otherMarker"][counts["otherMarker"]] = marker;
   // add a line to the side_bar html
   navbarHtml["otherMarker"] += '<a href="javascript:myclick(' + counts["otherMarker"] + ')">' + name + '</a><br>';
   counts["otherMarker"]++;
   return marker;
}

// A function to create the marker and set up the event window
function createSubMarker(point, zoom, name, html)
{
   var marker = new GMarker(point);

   GEvent.addListener(marker, "click", function() {
      map.setCenter(point, zoom);
      marker.openInfoWindowHtml(html);
   });

   // save the info we need to use later for the side_bar
   markers["subCenters"][counts["sub"]] = marker;
   // add a line to the side_bar html
   navbarHtml["sub"] += '<li><a href="javascript:clickSub(' + counts["sub"] + ')">' + name + '</a></li>';
   counts["sub"]++;
   return marker;
}

// A function to create the marker and set up the event window
function createListingMarker(point, ptype, name, html)
{
//   var marker = new GMarker(point, icons[ptype]);
   var marker = new GMarker(point);

   GEvent.addListener(marker, "click", function() {
      map.setCenter(point);
      marker.openInfoWindowHtml(html);
   });

   // save the info we need to use later for the side_bar
   markers[ptype][counts[ptype]] = marker;
   // add a line to the side_bar html
   navbarHtml[ptype] += '<li><a href="javascript:clickListing(' + "'" + ptype + "', " + counts[ptype] + ')">' + name + '</a></li>';
   counts[ptype]++;
   return marker;
}

function	addListingsToMap()
{
   if(isDefined(allListings))
   {
      for(var i = 0; i < allListings.length; i++)
         addListingToMap(allListings[i].lat, allListings[i].lng, allListings[i].mlsid, allListings[i].html);
   }
}

function	addListingToMap(lat, lng, mlsid, html)
{
	if( (lat > 0) && (lng < 0) )
	{
//		alert(mlsid + "\nLat: " + lat + "Lng: " + lng);
		var point = new GLatLng(lat, lng);
	   var marker = createListingMarker(point, "results", mlsid, html);
	   map.addOverlay(marker);
      // If there are currently no points in the bounds, create a new bounds with the new point,
      // otherwise extend the bounds
      if(bounds.isEmpty())
      	bounds = new GLatLngBounds(point);
      else
         bounds.extend(point);
	}
}

// This function picks up the click and opens the corresponding info window
function myclick(i) {
  GEvent.trigger(markers["otherMarker"][i], "click");
}

// This function picks up the click and opens the corresponding info window
function clickListing(what, i) {
  GEvent.trigger(markers[what][i], "click");
}

// This function picks up the click and opens the corresponding info window
function clickSub(i) {
  GEvent.trigger(markers["subCenters"][i], "click");
}

// === A method for testing if a point is inside a polygon
// === Returns true if poly contains point
// === Algorithm shamelessly stolen from http://alienryderflex.com/polygon/ 
GPolygon.prototype.Contains = function(point)
{
   var j=0;
   var oddNodes = false;
   var x = point.lng();
   var y = point.lat();
   for (var i=0; i < this.getVertexCount(); i++)
   {
      j++;
      if (j == this.getVertexCount()) {j = 0;}
      if (((this.getVertex(i).lat() < y) && (this.getVertex(j).lat() >= y))
      || ((this.getVertex(j).lat() < y) && (this.getVertex(i).lat() >= y))) {
        if ( this.getVertex(i).lng() + (y - this.getVertex(i).lat())
        /  (this.getVertex(j).lat()-this.getVertex(i).lat())
        *  (this.getVertex(j).lng() - this.getVertex(i).lng())<x ) {
          oddNodes = !oddNodes
        }
      }
   }
   return oddNodes;
}


function updateSidebarText()
{
   navbarHtml["sideBar"] = "";
//   if(showVars["sf"])
//      navbarHtml["sideBar"] += navbarHtml["sf"];
//   if(showVars["mf"])
//      navbarHtml["sideBar"] += navbarHtml["mf"];
//   if(showVars["vacant"])
//      navbarHtml["sideBar"] += navbarHtml["vacant"];
   if(showVars["results"])
      navbarHtml["sideBar"] += navbarHtml["results"];
   if(showVars["sub"])
      navbarHtml["sideBar"] += navbarHtml["sub"];

   document.getElementById("side_bar").innerHTML = navbarHtml["sideBar"];
}

//***************************************
// Read the subdivision data from subs.xml
//***************************************
function loadSubdivisions()
{
   asProcess("/data/subs.php", "", "Loading Subdivisions...", handleSubXML)
}

function handleSubXML()
{
	if(xmlHttp.readyState == 4)
	{
		var xmlDoc = xmlHttp.responseXML;
      var subs = xmlDoc.documentElement.getElementsByTagName("subdivision");

      // read each line
      for (var a = 0; a < subs.length; a++)
      {
         // get any state attributes
         var name  = subs[a].getAttribute("name");
         var description = subs[a].getAttribute("description");

         var subCenter = subs[a].getElementsByTagName("center");
         var point = new GLatLng(parseFloat(subCenter[0].getAttribute("lat")), parseFloat(subCenter[0].getAttribute("lng")));
         var zoomLevel = parseInt(subCenter[0].getAttribute("zoom"));
         var marker = createSubMarker(point, zoomLevel, name, description);

         // read each point on that line
         var points = subs[a].getElementsByTagName("point");
         var pts = [];
         for (var i = 0; i < points.length; i++) {
            pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")), parseFloat(points[i].getAttribute("lng")));
         }
         var poly = new GPolygon(pts,"#000000",1,1,"#ddfea0",0.5);
         markers["sub"].push(poly);
         subNames.push(name);
         descriptions.push(description);
         map.addOverlay(poly);
         map.addOverlay(marker);
         marker.hide();
      }
      //  Close html list
      navbarHtml["sub"] += '</ol>';
      // Added this refresh of the side bar text here, because this section seems to be asynchronous
      updateSidebarText();
		show_working("status", "");
   }
	else
		show_working("status", "Loading Subdivisions...");
}

function toggleHide(what)
{
   var headerText = "";

   if(what == "sf")
      headerText = "Single Family";
   else if(what == "mf")
      headerText = "Condo/Townhomes";
   else if(what == "vacant")
      headerText = "Vacant";
   else if(what == "sub")
      headerText = "Subdivisions";
   else if(what == "results")
      headerText = "Results";

//   headerText = '<a id="' + what + 'Header" onclick="javascript:toggleHide(' + "'" + what + "'" + ');">';
//   headerText = '<a onclick="javascript:toggleHide(' + "'" + what + "'" + ');">';
   if(showVars[what] == true)
   {
      showVars[what] = false;
      headerText = "Show " + headerText;
      for(var j = 0; j < markers[what].length; j++)
         map.removeOverlay(markers[what][j]);
   }
   else
   {
      showVars[what] = true;
      headerText = "Hide " + headerText;
      for(var j = 0; j < markers[what].length; j++)
         map.addOverlay(markers[what][j]);
   }
	document.getElementById(what + "Header").innerHTML = headerText;

	updateSidebarText();
}

function load_map()
{
   if(!isDefined(map))
   {
      // map is nt defined.  create it if we can
      if (GBrowserIsCompatible())
      {
         // Compatible browser, make map
         // Force window to draw correct size
         window.onresize();
         // create the map
         map = new GMap2(document.getElementById("map"));
         // Add the large map controls
   //      map.addControl(new GLargeMapControl());
         // Add the terrain map
         map.addMapType(G_PHYSICAL_MAP);
         map.addControl(new GMenuMapTypeControl());
         // Create the keyboard control   
         new GKeyboardHandler(map);
   
         // Center the map at the King's Foot office
         map.setCenter(new GLatLng(39.941429,-105.802073), 14);
   
         // Add a click listener to check if the click was in a subdivision
//         GEvent.addListener(map, "click", clickSubCheck)
         GEvent.addListener(map, "click", function(overlay,point)
         {
            if (point)
            {
               for(var i = 0; i < markers["sub"].length; i++)
               {
                  if (markers["sub"][i].Contains(point))
                  {
                     clickSub(i);
   //                  map.openInfoWindowHtml(point, '<b>' + subNames[i] + '</b><br>' + descriptions[i]);
                     i = 999; // Jump out of loop
                  }
               }
            }
         });
   
         initVars();
         createIcons();
   
         // add King's Foot office to the map    
         var point = new GLatLng(39.944424,-105.810442);
         var marker = createMarker(point, 13, "King's Foot Office","Next to Safeway in the Fraser Market Place")
         map.setCenter(point, 13);
         map.addOverlay(marker);
         document.getElementById("tabText").innerHTML = navbarHtml["otherMarker"];
   
         loadSubdivisions();
   
         // put the assembled side_bar_html contents into the side_bar div
         updateSidebarText();
      }
      else
         alert("Sorry, the Google Maps API is not compatible with this browser");
   }

   addListingsToMap();
}