var map = null;
var mymarkers = null;
var categories = null;
var c_address = "60611";
var c_maxmiles = 9999;
var c_maxresults = 9999;
var c_q = "";
var mapBounds;
var strSearch = "";
var distance = []; 
var sortti = []; 
var km2mi=0.621369949495;
var mi2km=1.6093472186943065;
var iever = msieversion();
var pointer = new GMarker(new GLatLng(62,23));
var closer = "<a href='javascript:luokse();'>See closer</a>";
var kaikki = "<a href='javascript:fit();'>Show all</a>";

function msieversion() {
  var ua = window.navigator.userAgent ;
  var msie = ua.indexOf("MSIE") ;
  if(msie > 0) 	{
    return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
  }
  else  {     
    return 0 ;
  }
}

function setCookie(c_name,value,expiredays)  {
  var exdate = new Date() ;
  exdate.setDate(expiredays)
  document.cookie=c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate)
}

function getCookie(c_name)  {
  if(document.cookie.length > 0)  {
    c_start = document.cookie.indexOf(c_name + "=") ;
    if(c_start != -1)  { 
      c_start = c_start + c_name.length + 1 ; 
      c_end = document.cookie.indexOf(";",c_start) ;
      if(c_end == -1)  {
        c_end = document.cookie.length ;
        return unescape(document.cookie.substring(c_start,c_end)) ;
      }
    } 
  }
  return null
}

function checkCookies()  {
  var temp;
  temp = getCookie('c_address') ;
  if(temp != null && temp != "")  {
    c_address = temp ;
  }
  temp = getCookie('c_maxmiles') ;
  if(temp != null && temp != "")  {
    c_maxmiles = temp ;
  }
  temp = getCookie('c_maxresults') ;
  if(temp != null && temp != "")  {
    c_maxresults = temp ;
  }
  temp = getCookie('c_q') ;
  if(temp != null && temp != "")  { 
    c_q = temp ;
  }
  document.getElementById("addr").value = c_address ;
  document.getElementById("q").value = c_q ;
  document.getElementById("radius").value = c_maxmiles ;
}

function checklisting(id, i)  {
  var marker = mymarkers[id][i] ;
  var e = document.getElementById("chk" + i) ;
  if(e.checked == true)  {
    if(marker)  {
      marker.display(true) ;
    }
  }
  else  {
    if(marker)  {
      marker.display(false) ;
      map.closeInfoWindow() ;
    }
  }
}

function showprintview(id)  {
  var div_c = document.getElementById("content_map") ;
  var div_printview = document.getElementById("printview_map") ;
  var div_backtonormal = document.getElementById("normalview_map") ;
  var div_l = document.getElementById("listingforprint_map") ;
  var h = '<BR><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"mapTbl\">' ;
  var n = 0 ;
  div_backtonormal.innerHTML = '<tr valign="top"><a href=\"javascript:shownormalview(\''+id+'\')\">Back to Normal View</a></tr>' ;
  div_printview.style.display = 'none';
  div_backtonormal.style.display = 'block';
  div_c.style.display = 'none';
  div_l.innerHTML = 'Formatting Listings...';
  div_l.style.display = 'block';
  document.getElementById("map").style.width="700";
  for(var index = 0 ; index < mymarkers[id].length ; index++)  {
    var marker = mymarkers[id][index] ;
    if(marker)	{
    var e = document.getElementById("chk"+index);
      if (e.checked == true)  {
        n++ ; 
	if(index > 99)  {
          var iconnum = 'red' ;
	} 
        else  {
	  var iconnum = 'red_'+index;
	}
	var d = document.getElementById(id+"_listingtext"+index);
	if(n % 3 == 1)  {
	  h += '<tr><td valign=\"top\"><div id=\"'+id+'_'+'pin'+n+'\"><a href=\"#\">' ;
          h += '<img src=\"images/pushpins/marker_'+iconnum+'.png\" border=\"0\"></a></div></td><td width=\"150\" valign=\"top\">' ;
          h += '<div class=\"listings_map\">'+d.innerHTML+'</div></td>' ;
        }  
        else  {
	  if(n % 3 == 2)  {
	    h += '<td width=\"20\">&nbsp;</td><td valign=\"top\"><div id=\"'+id+'_'+'pin'+n+'\">' ;
            h += '<a href=\"#\"><img src=\"images/pushpins/marker_'+iconnum+'.png\" border=\"0\"></a></div></td><td width=\"150\" valign=\"top\">' ;
            h += '<div class=\"listings_map\">'+d.innerHTML+'</div></td>' ;
      	  }
          else  {
	    h += '<td width=\"20\">&nbsp;</td><td valign=\"top\"><div id=\"'+id+'_'+'pin'+n+'\"><a href=\"#\">' ;
            h += '<img src=\"images/pushpins/marker_'+iconnum+'.png\" border=\"0\"></a></div></td><td width=\"150\" valign=\"top\">' ;
            h += '<div class=\"listings_map\">'+d.innerHTML+'</div></td></tr>';
	  }
	} 
      }
    }
  }
  h += '</table>' ;
  div_l.innerHTML = h ;
  map.disableScrollWheelZoom();
}

function shownormalview(id)  {
  var div_c = document.getElementById("content_map");
  var div_printview = document.getElementById("printview_map");
  var div_backtonormal = document.getElementById("normalview_map");
  var div_l = document.getElementById("listingforprint_map");
  div_backtonormal.style.display = 'none';
  div_printview.style.display = 'block';
  div_l.style.display = 'none';
  div_c.style.display = 'block';
  document.getElementById("map").style.width="655px";
  map.enableScrollWheelZoom();
}

function CenterMapToMe()  {
  map.setCenter(pointer.getPoint());	//make user's location the center of map
} 

function reloadmap()  {
  c_address = document.getElementById("addr").value ;
  c_maxmiles = document.getElementById("radius").value ;
  c_q = document.getElementById("q").value ;
  setCookie('c_address',c_address,365) ;
  setCookie('c_maxmiles',c_maxmiles,365) ;
  setCookie('c_q',c_q,365) ;
  loadCategory('garagesales');
}

function adjustView() {
  map.setZoom(map.getBoundsZoomLevel(mapBounds));
  var clat = (mapBounds.getNorthEast().lat() + mapBounds.getSouthWest().lat()) /2;
  var clng = (mapBounds.getNorthEast().lng() + mapBounds.getSouthWest().lng()) /2;
  map.setCenter(new GLatLng(clat,clng));
}

function fit()  {
  map.zoomToMarkers(5,2);
}

function ReSortDistance(id, myXML)
{
    var status  = document.getElementById('status');
    //var status_hidden  = document.getElementById('status_hidden');
	try
	{
        	var channel  = myXML.getElementsByTagName('listings')[0];
        	var m_status = channel.getElementsByTagName('title')[0].firstChild.nodeValue;
        	var listings_id  = channel.getElementsByTagName('id')[0].firstChild.nodeValue;
        	var color    = channel.getElementsByTagName('color')[0].firstChild.nodeValue;
        	var items    = channel.getElementsByTagName('item');

		// TODO:  reuse markers to (possibly) avoid memory leak when I add refresh code
		categories[listings_id] = true;

		var content = document.getElementById('listingsContent_' + listings_id);
		content.innerHTML = '';
		//var contentimg = document.getElementById('listingsContentImg_' + listings_id);
		//contentimg.innerHTML = '';

		sortti.length = 0; 
		var listing_count = 0;
		for (var index = 0; index < items.length; index++)
		{
			var item = items[index];
			var title = item.getElementsByTagName('title')[0].firstChild.nodeValue;
			var link  = item.getElementsByTagName('link')[0].firstChild.nodeValue;
			var desc  = item.getElementsByTagName('description')[0].firstChild.nodeValue;
       		var loc   = item.getElementsByTagName('loc')[0].firstChild.nodeValue;
       		var adno   = item.getElementsByTagName('ad')[0].firstChild.nodeValue;
       		var lat   = item.getElementsByTagName('lat')[0].firstChild.nodeValue;
       		var lng   = item.getElementsByTagName('lng')[0].firstChild.nodeValue;
       		var point = new GLatLng(parseFloat(lat), parseFloat(lng));

			distance = point.distanceFrom(pointer.getPoint()); 
			sortti.push( { distance : distance, title : title, loc : loc, adno : adno, link : link, desc : desc, point : point} ); 
		}

		var howMany = c_maxresults;					//document.getElementById("maara").value*1;
		var radius = (c_maxmiles * 1000)*mi2km;		//(document.getElementById("radius").value * 1000)*mi2km;

		sortti = sortti.sort(function (a, b) { return (a.distance - b.distance)} ); 

		var strmatch = c_q.toLowerCase();

		var n = 0;
		for (var j = 0; j < sortti.length && j < howMany * 1; j++) {
			var gotamatch = 0;
			if (strmatch == '') {
				gotamatch = 1;
			} else {
				var d = sortti[j].desc.toLowerCase();
				if (d.indexOf(strmatch)>=0) {
					gotamatch = 1;
				} else {
					var d = sortti[j].loc.toLowerCase();
					if (d.indexOf(strmatch)>=0) {
						gotamatch = 1;
					} else {
						var d = sortti[j].title.toLowerCase();
						if (d.indexOf(strmatch)>=0) { gotamatch = 1;	}
					}
				}
			}
			if (sortti[j].distance < radius && gotamatch==1) {
				n++; 
			}
		}
		mymarkers[listings_id] = new Array(n);

		var n = 0;
		for (var j = 0; j < sortti.length && j < howMany * 1; j++) {
			var gotamatch = 0;
			if (strmatch == '') {
				gotamatch = 1;
			} else {
				var d = sortti[j].desc.toLowerCase();
				if (d.indexOf(strmatch)>=0) {
					gotamatch = 1;
				} else {
					var d = sortti[j].loc.toLowerCase();
					if (d.indexOf(strmatch)>=0) {
						gotamatch = 1;
					} else {
						var d = sortti[j].title.toLowerCase();
						if (d.indexOf(strmatch)>=0) { gotamatch = 1;	}
					}
				}
			}
			if (sortti[j].distance < radius && gotamatch==1) {
				//mapBounds.extend(pointer.getPoint()); 
				n++; 
				// -------------------------------------------------------------
				var marker = createMarker(sortti[j].point, n, sortti[j].link, '<small>' + ((sortti[j].distance / 1000)*km2mi).toFixed(1) + ' mi</small>&nbsp;-&nbsp;', sortti[j].title, sortti[j].loc, sortti[j].desc, sortti[j].adno);
				map.addOverlay(marker);
				mapBounds.extend(sortti[j].point);
				mymarkers[listings_id][n] = marker;

				var list_div = document.createElement("div");
				list_div.className = 'listings_map';

			//	if (mybrowser.isIE) {
					//addOnClick(list_div, listings_id, n);
					addOnMouseOver(list_div, listings_id, n);
					addOnMouseOut(list_div, listings_id, n);
			//	} else {
			//		title_link.setAttribute('onclick', "clickMarker('" + n + "'); return false;"); 
			//		title_link.setAttribute('onmouseover', "showToolTip('" + n + "'); return false;"); 
			//		title_link.setAttribute('onmouseout', "hideToolTip('" + n + "'); return false;"); 
			//	}

				if (n > 99) {
					var iconnum = 'red';
				} else {
					var iconnum = 'red_'+n;
				}
				list_div.innerHTML = '<table onMouseover=\"changeto(event, \'lightgreen\')\" onMouseout=\"changeback(event, \'white\')\" cellspacing=\"0\" cellpadding=\"0\"><tr><td valign=\"top\"><div id=\"'+listings_id+'_'+'pin'+n+'\"><a href=\"#\"><img src=\"images/pushpins/marker_'+iconnum+'.png\" border=\"0\"></a>&nbsp;</div><BR><input checked name=\"chk'+n+'\" type=\"checkbox\" id=\"chk'+n+'\" onclick=\"checklisting(\''+listings_id+'\','+n+')\" /></td><td><div id=\"'+listings_id+'_'+'listingtext'+n+'\"><div class=\"listings_map\" id=\"'+listings_id+'_'+'title'+n+'\"><b><a href=\"#\"><small>' + ((sortti[j].distance / 1000)*km2mi).toFixed(1) + ' mi</small>&nbsp;-&nbsp;'+sortti[j].title + '</a></b></div><div id=\"'+listings_id+'_'+'desc'+n+'\"><b>' + sortti[j].loc + '</b><BR>' + sortti[j].desc+'</div></div></td></tr></table>';

				content.appendChild(list_div);

				var linkpin = document.getElementById(listings_id + '_' + 'pin' + n);
				addOnClick(linkpin, listings_id, n);
				var linktitle = document.getElementById(listings_id + '_' + 'title' + n);
				addOnClick(linktitle, listings_id, n);
				var linkdesc = document.getElementById(listings_id + '_' + 'desc' + n);
				addOnClick(linkdesc, listings_id, n);

				listing_count++;
				// ----------------------------------------------------------
				}
			}
		//document.getElementById("status").innerHTML = n + " matches found within " + ((sortti[n - 1].distance / 1000)*km2mi).toFixed(1) + " miles of '<b>"+document.getElementById("addr").value+"</b>'.";
		if (c_maxmiles==9999) {
			document.getElementById("status").innerHTML = n + " matches found (no distance limit) - <a onclick=\"clickPointer();\" href=\"#\"><b>"+c_address+"</b></a> &nbsp;&nbsp;&bull;&nbsp;&nbsp; <a onclick=\"CenterMapToMe();\" href=\"#\">Center map on my location</a>  &nbsp;&nbsp;&bull;&nbsp;&nbsp;  <a onclick=\"fit();\" href=\"#\">Zoom map to fit results</a>";
		} else {
			document.getElementById("status").innerHTML = n + " matches found within "+c_maxmiles+" miles of <a onclick=\"clickPointer();\" href=\"#\"><b>"+c_address+"</b></a> &nbsp;&nbsp;&bull;&nbsp;&nbsp; <a onclick=\"CenterMapToMe();\" href=\"#\">Center map on my location</a>  &nbsp;&nbsp;&bull;&nbsp;&nbsp;  <a onclick=\"fit();\" href=\"#\">Zoom map to fit results</a>";
		}
		fit();
		//map.addOverlay(trafficInfo);

		//adjustView();
		//map.setCenter(pointer.getPoint());	//make user's location the center of map

		// parse the listings update time out of the xml
		at_pos = m_status.indexOf(" On ");
		if (at_pos > 0)
		{
			if (iever > 0) {
				var time = document.getElementById('listingsTime_' + listings_id);
				update_time = "updated on " + m_status.substring(at_pos+4);
				time.innerHTML = update_time;
			}
		}

		if (listing_count == 0)
		{
			showSectionStatus(listings_id, "No listings match.")
		}

		//status.innerHTML = m_status;

	} catch(e) { 
		status.innerHTML = e;
		//status.innerHTML = "Failed to retrieve listings!";
		//status_hidden.innerHTML = e;
		showSectionStatus(id, "Failed to retrieve listings!");
	}
}








function SetDefLocation(address)  {
  document.getElementById("addr").value = '60611';
  reloadmap();
}

function CenterOnAddress(address, id, myXML)  {
  if(address == "")  {
    document.getElementById("status").innerHTML = "Address is blank, defaulting to Orlando..."; 
  }
  else  {
    geocoder = new GClientGeocoder();
    geocoder.getLatLng(address, 
      function(point)  {
        if(!point)  {
	  var status_b = document.getElementById("status")
          status_b.innerHTML = address + ' could not be found. <a href=\"#\" onclick=\"SetDefLocation();\">Click here for Orlando.</a>';
	  showSectionStatus(id, 'Valid address required!');
	  address = "" ;
	} 
        else  {
	  map.clearOverlays();
	  bounds = new GLatLngBounds()
	  pointer = createMarker(point, 'house', '', '', 'My Location', address, '', '');

          map.addOverlay(pointer);
          mapBounds.extend(point);
	  map.setCenter(pointer.getPoint());

          ReSortDistance(id, myXML);
        }
      }); 
  }
}

function _xmlRequest(url, data, callback, id)  {
  return false ;
}
var m_id = "" ;
var m_callback = "" ;

function getXML(url, callback, id)  {
  m_id = id ;
  m_callback = callback ;
  http.open('GET', url) ;
  http.onreadystatechange = listingsResponse ;
  http.send(null) ;
  return true ;
}
function listingsResponse()  {
  if(http.readyState == 4 && http.status == 200)  {
  var response = http.responseXML ;
    eval(m_callback+'(m_id, response);') ;
  }
}

function displayResults(id, myXML)  {
  CenterOnAddress(c_address, id, myXML);
}

function addHideOnClick(obj, id)  {
  obj.onclick = 
    function() {
      hideListings(id);
      return false;
    }
  obj = null ; 
}

function addShowOnClick(obj, id)  {
  obj.onclick = 
    function() {
      showListings(id);
      return false;
    }
  obj = null ; 
}

function addOnClick(obj, id, index)  {
  obj.onclick = 
    function()  {
      clickMarker(id, index);
      return false;
    }
  obj = null ; 
}

function addOnMouseOver(obj, id, index)  {
  obj.onmouseover = 
    function() {
      if(index > -1 && index < mymarkers[id].length)  {
        mymarkers[id][index].setImage("images/pushpins/marker_green_"+(index)+".png");
      }
      return false;
    }
  obj = null ;
}

function addOnMouseOut(obj, id, index)  {
  obj.onmouseout = 
    function() {
      if(index > -1 && index < mymarkers[id].length)  {
        mymarkers[id][index].setImage("images/pushpins/marker_red_"+(index)+".png");
      }
      return false;
    }
	obj = null; // so we don't get mem leak
}

function showTTip(id, index)  {
  if(index > -1 && index < mymarkers[id].length)  {
    mymarkers[id][index].onMouseOver();
  }
}

function hideTTip(id, index)  {
  if(index > -1 && index < mymarkers[id].length)  {
    mymarkers[id][index].onMouseOut();
  }
}

function makeToolTip(text)  {
  return "<span style='background-color: #ccc; color: black; font-size: 12px; font-weight: bold; white-space: nowrap'>" + text + "</span>";
}

function createIcon(color)  {
  var icon = new GIcon();
  if(color == 'house')  {
    icon.image = "images/pushpins/house.png";
    icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    icon.iconSize = new GSize(21, 31);
    icon.shadowSize = new GSize(37, 34);
    icon.iconAnchor = new GPoint(9, 34);
    icon.infoWindowAnchor = new GPoint(9, 2);
    icon.infoShadowAnchor = new GPoint(18, 25);
  } 
  else  {
    if(parseInt(color) > 99)  {
      icon.image = "images/pushpins/marker_red.png";
    } 
    else  {
      icon.image = "images/pushpins/marker_red_"+color+".png";
    }
    icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    icon.iconSize = new GSize(20, 34);
    icon.shadowSize = new GSize(37, 34);
    icon.iconAnchor = new GPoint(9, 34);
    icon.infoWindowAnchor = new GPoint(9, 2);
    icon.infoShadowAnchor = new GPoint(18, 25);
  }
  return icon ;
}

function createMarker(point, color, link, dist, title, addr, desc, adno)  {
  var icon = createIcon(color);
  var marker = new PdMarker(point, icon, title + ' - ' + addr);
  if(color == 'house')  {
    var html = '<div id=\"bubble_map\"><div id=\"title_map\">' + dist + title + '</div><div id=\"location\"><b>' + addr ;
    html += '</b><BR><div id=\"description\">' + desc + '</div></div>';
  } 
  else  {
    var html = '<div id=\"bubble_map\"><div id=\"title_map\">' + dist + title + '</div><div id=\"location\"><b>' ;
    html += addr + '</b><BR><div id=\"description\">' + desc + '</div><div id=\"link\"><table width=\"100%\"><tr><td>' ;
    html += '<a href=\"http://maps.google.com/?saddr='+c_address+'&daddr='+addr+'\" target=\"_blank\">Get directions to here &#187;</a>' ;
    html += '</td><td align=\"right\">Ad id: '+adno+'</td></tr></table></div></div>';
  }
  GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); });
  GEvent.addListener(marker, "mouseover", function() { marker.setImage("images/pushpins/marker_green_"+color+".png"); });
  GEvent.addListener(marker, "mouseout", function() { marker.setImage("images/pushpins/marker_red_"+color+".png"); });
  return marker;
}

function clickMarker(id, index)  {
  var marker = mymarkers[id][index];
  var e = document.getElementById("chk"+index);
  if(e.checked == true)  {
    if(marker)  { 
      GEvent.trigger(marker, "click"); 
    }
  }
}

function clickPointer()  {
  map.removeOverlay(pointer);
  map.addOverlay(pointer);
  GEvent.trigger(pointer, "click");
}

function onLoad()  {
  mymarkers  = new Array();
  categories = new Array();
  if(document.getElementsByTagName && document.createElement)  {
    if(!GBrowserIsCompatible())  {
      var map_block = document.getElementById("map") ;
      map_block.innerHTML = "<p id=\"warning\">I'm sorry, your browser is not compatible with Google Maps.</p>" ;
      map_block.innerHTML += "<p id=\"warning\">Please visit <a href='http://local.google.com/support/bin/answer.py?answer=16532&topic=1499'" ;
      map_block.innerHTML += " target='_blank'>Google Maps</a> to view a list of compatible browsers.</p>" ;
      return ;
    }
    checkCookies();
    loadMap();
    shownormalview('garagesales');
    loadCategory('garagesales');
  } 
  else {
    alert("I'm sorry, your browser does not support the necessary JavaScript features used by this site.") ;
  }
}

function loadMap()  {
  map = new GMap2(document.getElementById("map"));
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  map.enableScrollWheelZoom();
  map.addControl(new GScaleControl(300));
  map.enableDoubleClickZoom();
	
  var centerLng = -87.613564;
  var centerLat = 41.895700;
  var zoomLevel = 12;
  map.setCenter(new GLatLng(centerLat, centerLng), zoomLevel);

  mapBounds = new GLatLngBounds();
}

function loadListings(id)  {
  loadCategory(id);
}

function showSectionStatus(id, status)  {
  var content = document.getElementById('listingsContent_' + id);
  content.innerHTML = '';
  var loading = document.createElement('div');
  loading.className = 'listings_map';
  loading.appendChild(document.createTextNode(status));	
  content.appendChild(loading);
}

function loadCategory(id)  {
  showSectionStatus(id, 'Loading...');
  //var url = 'xml/'+id+'.xml?q='+thetime;
  var url = 'xml/'+id+'.xml?q='+new Date().getTime() ;
  //if (!xmlRequest(url, '', 'displayResults', id))
  if(!getXML(url, 'displayResults', id))  { 
    showSectionStatus(id, 'Sorry, I failed to get the listings.');
  }
}

function showListings(id)  {
  Element.show('listingsContent_'+id, 'hideListings_'+id);
  Element.hide('showListings_'+id);
  if(categories)  {
    if(categories[id] != true)  {
      loadListings(id) ;
      return ;
    }
  }
  for(index = 0; index < mymarkers[id].length; index++)  {
    var marker = mymarkers[id][index] ;
    //map.addOverlay(marker); 
    if(marker)  {
      marker.display(true) ;
    }
  }
}

function hideListings(id)  {
  Element.hide('listingsContent_'+id, 'hideListings_'+id);
  Element.show('showListings_'+id);
  map.closeInfoWindow();
  for(var index = 0; index < mymarkers[id].length; index++)  {
    var marker = mymarkers[id][index];
    if(marker)  {
      marker.display(false);
    }
  }
}
