var map;
var localSearch = new GlocalSearch();
var shortlist = new Array();
var gmarkers = new Array();
var scotland_lat =  55.037939134593;
var scotland_long = -2.399894114594;

function isShortlisted (propid)
{
  for(var i = 0; i < shortlist.length; i++)
  {
     if(shortlist[i] == propid )
     {
       return (i+1);
     }	 
  }
  return 0;
}

function delCookie (NameOfCookie) 
{
    // The function simply checks to see if the cookie is set.
    // If so, the expiration date is set to Jan. 1st 1970.
    if (Get_Cookie(NameOfCookie)) 
	{  
	    var cookie_date = new Date ( );  // current date & time
	    cookie_date.setTime ( cookie_date.getTime() - 1 );
	    document.cookie = NameOfCookie += "=; expires=" + cookie_date.toGMTString();
	}
}

function clearShortlist()
{
    shortlist = new Array();
    delCookie('shortlist');   
    writeShortlist(0);
}

function writeShortlist(startIndex)
{

    createShortlistCookie();
   // ajax magic
     if ( window.ActiveXObject ) // if it's ie
    {
       var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // xmlhttp is global
       xmlhttp.onreadystatechange = function ()
       {	
          if(xmlhttp.readyState == 4) writeShorlistContent(xmlhttp.responseText);
       };
    }
    else 
    {
       if (window.XMLHttpRequest) // if it's firefox etc.
       {
         var xmlhttp        = new XMLHttpRequest() // xmlhttp is global
         xmlhttp.onload = function () { writeShorlistContent(xmlhttp.responseText) };
       }
       else return; // 
    }   

     if(!startIndex)
     {
	     startIndex = 0;
     }
    
     
   
     if(Get_Cookie('shortlist'))
     {	   
			var url = "http://" + document.location.hostname  + "/property-for-sale/write_shortlist.cgi?startindex=" + startIndex + "&uniq=" + new Date().getTime() + "&maps=1";
			xmlhttp.open("GET", url , true);
			xmlhttp.send(null);
			document.getElementById('shortlistContent').style.display = 'block';	
     }
     else
	 {
	     document.getElementById('shortlistContent').style.display = 'none';
	 }

}

function writeShorlistContent(html)
{
  var targ = document.getElementById('shortlistContent');
  if(targ) { targ.innerHTML = html; } 
}  

function storeToShortList(propid)
{
  // we can only store a max of six
  if(shortlist && shortlist.length >= 6)
  {
    alert('Sorry the maximum you can shortlist is 6.');
  }
  else //add to the end of the list
  {
      // if we have this already stored alert 
	  for(var i = 0; i < shortlist.length; i++)
      {
        if(shortlist[i] == propid)
        {
          alert("You have already stored this property.");
		  return;
        }		
      }		  
      shortlist[shortlist.length]  = propid;
  }
  // lets call ajax now to write the html and leave it at this index so they can see it has been added
  var index = 0;
  if(shortlist.length > 3 ) { index = 3; } 
  writeShortlist(index);
  putResultsOnMap();
}

function createShorlistArrayFromCookie()
{ 
  
  shortlist = new Array();
  var cookiestring = Get_Cookie('shortlist');
  if(cookiestring)
  {
	  var separatedValues = cookiestring.split("/");
	  for( var i = 0; i < separatedValues.length; i++)
	  {
		var tmp = separatedValues[i].split("-");
		shortlist[tmp[0]] = tmp[1]; 
	  }
  }
}

function Get_Cookie( name )
 {	
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

// let stick the shortlist in a cookie so it hangs around for a while
function createShortlistCookie() 
 {
  var ExpireDate = new Date ();
  var tmp = new Date();
  ExpireDate.setTime(ExpireDate.getTime() + 100000000);
  var valuestring = '';
  if(shortlist)
      {
	  for(var i = 0; i < shortlist.length; i++)
	      {
		  valuestring = valuestring + '/' + i + '-' + shortlist[i];
	      }    
	  var curCookie = 'shortlist=' + valuestring + "; expires=" + ExpireDate.toGMTString() + "; path=/";
	  document.cookie = curCookie;
      }
 }

function removeFromShortlist(startIndex, propid)
{
  var tmplist = new Array();
  var count = 0;
  for(var i = 0; i < shortlist.length; i++)
  {
    if(shortlist[i] != propid)
	{
	  tmplist[count] = shortlist[i];
	  count++;
	}
  }
  shortlist = new Array();
  for(var i = 0; i < tmplist.length; i++)
      {
	  shortlist[i] = tmplist[i];  
      }
  writeShortlist(0);
  putResultsOnMap();
}


function usePointFromPostcode(postcode) {

  localSearch.setSearchCompleteCallback(null,
    function() {

      if (localSearch.results[0]) {
        var resultLat = localSearch.results[0].lat;
        var resultLng = localSearch.results[0].lng;
        var point = new GLatLng(resultLat,resultLng);
	var zoom = 14;
        map.setCenter(point, zoom, G_NORMAL_MAP);
      }else{
        alert("Postcode not found!");
      }
    });

  localSearch.execute(postcode + ", UK");
}

function TextualZoomInControl() {}
TextualZoomInControl.prototype = new GControl();
TextualZoomInControl.prototype.initialize = function(map) 
{
  var container = document.createElement("div");
  container.id = "mainControl";
  container.style.width = '600px';

  // *****************************************************************

  var normalDiv = document.createElement("span");
  normalDiv.id = "prop_count";
  container.appendChild(normalDiv);
  
  
  // *****************************************************************
  
  var normalDiv = document.createElement("div");
  normalDiv.id = "streetControl";
  normalDiv.style.cursor = "pointer";
  container.appendChild(normalDiv);
  
  normalDiv.appendChild(document.createTextNode(" Street "));
  GEvent.addDomListener(normalDiv, "click", function() {
  map.setMapType(G_NORMAL_MAP);
  });
  
    // *****************************************************************
  
  var satteliteDiv = document.createElement("div");
  satteliteDiv.id = "satteliteControl";
  satteliteDiv.style.cursor = "pointer";
  container.appendChild(satteliteDiv);
  
  satteliteDiv.appendChild(document.createTextNode(" Satellite "));
  GEvent.addDomListener(satteliteDiv, "click", function() {
  map.setMapType(G_SATELLITE_MAP);
  });
   
    // *****************************************************************
  
  var hybridDiv = document.createElement("div");
  hybridDiv.id = "hybridControl";
  hybridDiv.style.cursor = "pointer";
  container.appendChild(hybridDiv);
  
  hybridDiv.appendChild(document.createTextNode(" Hybrid "));
  GEvent.addDomListener(hybridDiv, "click", function() {
  map.setMapType(G_HYBRID_MAP);
  });
  
    // *****************************************************************
  
  var zoomToRegionDiv = document.createElement("div");
  zoomToRegionDiv.id = "regionControl";
  zoomToRegionDiv.style.cursor = "pointer";
  zoomToRegionDiv.style.textDecoration = "underline";
  container.appendChild(zoomToRegionDiv);
  
  zoomToRegionDiv.appendChild(document.createTextNode(" Region "));
  GEvent.addDomListener(zoomToRegionDiv, "click", function() {
  map.setZoom(9);
  });
  
    // *****************************************************************
  
  var zoomToCityDiv = document.createElement("div");
  zoomToCityDiv.id = "cityControl";
  zoomToCityDiv.style.cursor = "pointer";
  zoomToCityDiv.style.textDecoration = "underline";
  container.appendChild(zoomToCityDiv);
  
  zoomToCityDiv.appendChild(document.createTextNode(" City "));
  GEvent.addDomListener(zoomToCityDiv, "click", function() {
  map.setZoom(13);
  });
  
    // *****************************************************************
  
   var zoomToStreetDiv = document.createElement("div");
  zoomToStreetDiv.id = "localControl";
  zoomToStreetDiv.style.cursor = "pointer";
  zoomToStreetDiv.style.textDecoration = "underline";
  container.appendChild(zoomToStreetDiv);
  
  zoomToStreetDiv.appendChild(document.createTextNode(" Local "));
  GEvent.addDomListener(zoomToStreetDiv, "click", function() {
  map.setZoom(15);
  });
  
  map.getContainer().appendChild(container);
  return container;
}

TextualZoomInControl.prototype.getDefaultPosition = function() 
{ 
  return new GControlPosition( 0, new GSize(-20, -20));
}





function placeMarkerAtPoint(point, html)
{
 var icon = new GIcon(G_DEFAULT_ICON, "/ui/images/icons/house.png", true );
 icon.shadow = "images/shadow.png";
 icon.iconSize = new GSize(20, 21);
 icon.shadowSize = new GSize(22,25);
 var marker = new GMarker(point,icon);
 GEvent.addListener(marker, "click", function() {    marker.openInfoWindowHtml(html);  });
 map.addOverlay(marker);
}

function putResultsOnMap()
{
	document.getElementById('prop_count').innerHTML = "<strong>Retrieving properties...</strong>";
        bounds = map.getBounds();
        leftBottomCorner = bounds.getSouthWest();
	rightTopCorner = bounds.getNorthEast();
	min_lat =  leftBottomCorner.lat();
	max_lat =  rightTopCorner.lat();
	min_long = leftBottomCorner.lng();
	max_long = rightTopCorner.lng();
   
	var url = "/property-for-sale/forsale_search_results_onmap.cgi?min_lat=" + min_lat + '&max_lat=' +  max_lat + '&min_long='  + min_long + '&max_long=' + max_long + '&zoom=' + map.getZoom();

	if (window.force_prop_id)
	{
		url = url + '&force_prop_id=' + window.force_prop_id;
	}

	GDownloadUrl(url, function(data, responseCode) 

   {  
     if(responseCode == 200) 
	 {
		 document.getElementById('prop_count').innerHTML = "<strong>Plotting properties...</strong>";
		 var xml = GXml.parse(data); 		 
		 var markers = xml.documentElement.getElementsByTagName("marker"); 
		 var markertotal = markers.length; 
		 var lattotal = 0;
		 var lngtotal = 0; 
		 var infowindow = map.getInfoWindow();

		 if (infowindow.isHidden() == true)
		 {
		 	map.clearOverlays();
		 }
	
		 for (var i = 0; i < markers.length; i++) 
		 { 

                     var html = '';
                     var title = '';
				



		     if(markers[i].getAttribute("cluster"))
		     {
		     	
		     		var zoomIn = 1;
			 switch(map.getZoom()) // variable zoom for clustering
			 {
				// 17 -
				case 5: // 12
					zoomIn = 6; // to 7
					break;
				case 6: // 11
					zoomIn = 5; // to 7
					break;
				case 7: // 10
					zoomIn = 4; // to 7
					break;
				case 8: // 9
					zoomIn = 3; // to 6
					break;
				case 9: // 8
					zoomIn = 2; // to 6
					break;
				case 10: // 7
					zoomIn = 2; // to 5
					break;
			 }
		     	
			 
			 var clusterType = markers[i].getAttribute("clustertype");
			 var clusterTypeText = clusterType;
			 if (clusterType == "combined") { clusterTypeText = 'houses & flat'; }
			 html = "<p><strong>" + markers[i].getAttribute("count") + "</strong> " + clusterTypeText + "s in this area"  + "</p><a href=\"javascript:;\" onClick=\"map.setZoom(map.getZoom()+" + zoomIn + "); map.clearOverlays();\" >zoom into properties<a\>";
			 point = new GLatLng(markers[i].getAttribute("lat"), markers[i].getAttribute("lng"));
			 lattotal = lattotal + Number(markers[i].getAttribute("lat")); 
			 lngtotal = lngtotal + Number(markers[i].getAttribute("lng"));	 
			 var icon = new GIcon(); 
			 var shortlisted = isShortlisted(markers[i].getAttribute("prop_id"));
       //removed as there is bug which have funny way icon change color 
      // if(markers[i].getAttribute("icon_selected")== 1)
       //{
       	icon.image = "http://" + document.location.hostname + "/ui/images/flatgifs/b-" + clusterType + "-cluster.gif";
      /* }
      // else
       {
         icon.image = markers[i].getAttribute("surl")+"/ui/images/flatgifs/g-" + clusterType + "-cluster.gif";
       }*/
       
       
       if (clusterType == "combined") 
       { 
       	 icon.iconSize = new GSize(40, 48); 
       } 
       else 
       	{ 
       	  if( clusterType == "flat")
       		{
       		 icon.iconSize = new GSize(24, 40); 
       		}
       		else
       		{
       		icon.iconSize = new GSize(34, 33); 
       	  }
       	}
			 icon.iconAnchor = new GPoint(6, 20);
			 icon.infoWindowAnchor = new GPoint(5, 1);
         title = markers[i].getAttribute("count") + " " + clusterTypeText + "s in this area";
           }
         else 
		       {
		     	var zoomIn = 1;
			 switch(map.getZoom()) // variable zoom for clustering
			 {
				// 17 -
				case 5: // 12
					zoomIn = 9; // to 5
					break;
				case 6: // 11
					zoomIn = 8; // to 5
					break;
				case 7: // 10
					zoomIn = 7; // to 5
					break;
				case 8: // 9
					zoomIn = 6; // to 5
					break;
				case 9: // 8
					zoomIn = 5; // to 5
					break;
				case 10: // 7
					zoomIn = 4; // to 5
					break;
				case 11: // 7
					zoomIn = 3; // to 5
					break;
				case 12: // 7
					zoomIn = 2; // to 5
					break;
				case 13: // 7
					zoomIn = 1; // to 5
					break;
			 }
		     	
		     	
			html =  "<div style=\"width:300px; height: 200px;\"> <div id=\"Layer1\"><img src=\"" + markers[i].getAttribute("thumb") + "\" style=\"width:140; height:105; float:right; padding-right: 14px;\" ></div> <span style=\" font-size: 12px; font-family:Arial, Helvetica, sans-serif; color:#00145D; \"><a href=\"" + markers[i].getAttribute("url") +  "\" style=\"color:#00125C;\">" + markers[i].getAttribute("street") + " , " + markers[i].getAttribute("area") + "</a><br><br> <strong>£" + markers[i].getAttribute("price") + "</strong><br>" + markers[i].getAttribute("typeandbed") + "<br><br>" + markers[i].getAttribute("minidesc") + "</span>  <div style=\"float:left;\"><img src=\"" + markers[i].getAttribute("logo") + "\" alt=\"" + markers[i].getAttribute("agent_name") + "\"></div> <br> <div style=\"float:right; \"><br>"+"<a href=\"javascript:;\" onClick=\" map.setZoom(map.getZoom()+" + zoomIn + "); map.clearOverlays(); map.setCenter(new GLatLng("+markers[i].getAttribute("lat")+","+markers[i].getAttribute("lng")+" )); \" style=\"color:#00125C;\" > zoom </a>&nbsp;&nbsp;<a href=\"" + markers[i].getAttribute("url") + "\" style=\"color:#00125C;\" >details</a>&nbsp;&nbsp; <a href=\"javascript:;\"  style=\"color:#00125C;\" onClick=\"storeToShortList(" + markers[i].getAttribute("prop_id") + ")\" >shortlist</a>&nbsp;&nbsp; <a href=\"store-property.cgi?prop_id=" + markers[i].getAttribute("prop_id") + "&back_to_search=/property-for-sale/forsale_search_results_onmap.cgi?" + markers[i].getAttribute("backtosearch") + "\"  style=\"color:#00125C;\">store</a></div> </div>" + "</p>";
	
			 point = new GLatLng(markers[i].getAttribute("lat"), markers[i].getAttribute("lng"));
			 lattotal = lattotal + Number(markers[i].getAttribute("lat")); 
			 lngtotal = lngtotal + Number(markers[i].getAttribute("lng"));	 
			 var icon = new GIcon(); 
			 var shortlisted = isShortlisted(markers[i].getAttribute("prop_id"));
			 if(shortlisted > 0)
			 {
			    if(markers[i].getAttribute("typeandbed").match(/Flat/))
				  {
			      //icon.image = "http://" + document.location.hostname + "/ui/images/icons/icon-flat-" + shortlisted + ".png";
				  icon.image = "http://www.s1homes.com/ui/images/icons/icon-flat-" + shortlisted + ".png";
			    }
          else
          {
         	  //icon.image = "http://" + document.location.hostname + "/ui/images/icons/icon-house-" + shortlisted + ".png";
			  icon.image = "http://www.s1homes.com/ui/images/icons/icon-house-" + shortlisted + ".png";
          }
       }
			 else if(markers[i].getAttribute("typeandbed").match(/Flat/) )
			 {
			 	 // if(markers[i].getAttribute("icon_selected")== 1)
         // {
          	icon.image = "http://" + document.location.hostname + "/ui/images/flatgifs/b-small-flats.gif";
         /* }
			 		else	
			 	  {
			     icon.image = markers[i].getAttribute("surl")+"/ui/images/flatgifs/g-small-flats.gif";
			    }*/
			     icon.iconSize = new GSize(16, 28);
       }
       else
			 {
                     //       if(markers[i].getAttribute("icon_selected")== 1)
                     //       {
                            	icon.image = "http://" + document.location.hostname + "/ui/images/flatgifs/b-small-house.gif";
                       /*     }
                            else
                            {
                              icon.image = markers[i].getAttribute("surl")+"/ui/images/flatgifs/g-small-house.gif";
                            }*/
                              icon.iconSize = new GSize(21, 22);
			 }
			 //icon.shadow = "http://" + document.location.hostname + "/ui/images/shadow.png";
			 //icon.shadowSize = new GSize(21,22);
			 
			 icon.iconAnchor = new GPoint(6, 20);
			 icon.infoWindowAnchor = new GPoint(5, 1);
                         		 title = markers[i].getAttribute("street") +', '+markers[i].getAttribute("typeandbed")+", " + markers[i].getAttribute("rprice");
		     }	

                     var marker = new GMarker(point, {icon: icon, title: title});  
                     marker.myhtml = html;
                     
    
         if(markers[i].getAttribute("display").match(/1/)) 
		     {
                       map.addOverlay(marker);
         }
		     gmarkers[markers[i].getAttribute("prop_id")] = marker;
		     
		 }	 
	   var centlat = lattotal/markertotal;
	   var centlng = lngtotal/markertotal;
	  
           if(document.getElementById('mapviewprop') && document.getElementById('mapviewprop').value != '')
           {
	     showPropInfo(document.getElementById('mapviewprop').value);
             document.getElementById('mapviewprop').value = '';
           }

	   if(window.force_prop_id)
	   {
		map.addOverlay(gmarkers[force_prop_id]);
		GEvent.trigger(gmarkers[force_prop_id], "click");
		window.force_prop_id = null;
	   }

	   if(markertotal == 0) 
	   {
	     document.getElementById('prop_count').innerHTML = "<strong>no properties found</strong>";  
	   }
	   else
	   {
	     document.getElementById('prop_count').innerHTML = "&nbsp;";
	   }
   }
  }  
  ); 
  
  
  
}

function showPropInfo(propid)
{
	if (!gmarkers[propid])
	{
		window.force_prop_id = propid;
		putResultsOnMap();
	}
	else
	{
		map.addOverlay(gmarkers[propid]);
		GEvent.trigger(gmarkers[propid], "click");
	}
}

function createMap()
{
  map = new GMap2(document.getElementById("map"));
  map.addControl(new GLargeMapControl());
  map.addControl(new TextualZoomInControl());
  map.enableDoubleClickZoom();
}


function addMapListeners()
{
  GEvent.addListener(map, "click", function(overlay, point) {
  if (overlay) { if (!!overlay.openInfoWindowHtml) {overlay.openInfoWindowHtml(overlay.myhtml); } } } ); 
  GEvent.addListener(map, "moveend", function() { checkZoom(); });
  GEvent.addListener(map, "zoom", function() { checkZoom(); });
  
}

function mapLoad() {
	if (GBrowserIsCompatible()) 
	{
		createMap();   
		map.setCenter(new GLatLng(centlat,centlng), zoom_level, G_NORMAL_MAP);
		checkZoom();
		addMapListeners(); 	  
	}
}


function checkZoom()
{
          var zoom = map.getZoom();
          
          if(zoom == 6) 
               {
		  map.clearOverlays();
                  addScotlandMarker(); 
               }
          else if (zoom < 6) 
               {
                   map.setZoom(6);
		   alert('Sorry you cannot zoom out any futher');  
               }
          else 
               {
                  putResultsOnMap(); 
               } 

}


function addScotlandMarker()
{
    var icon = new GIcon();
    icon.image = "http://" + document.location.hostname + "/ui/images/icons/icon-house.png";
    icon.iconSize = new GSize(22, 25);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);
    point = new GLatLng(centlat+0.5, centlng);
    var marker = new GMarker(point,icon);
    var count = document.mainform.property_count.value;
    marker.myhtml = "<strong>Scotland</strong><a href=\"javascript:;\" onClick=\"map.setZoom(map.getZoom()+1);\" ><p>zoom in to see properties<a>";
    map.addOverlay(marker);
}


function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function addUnLoadEvent(func) {
var oldonunload = window.onunload;
if (typeof window.onunload != 'function') {
  window.onunload = func;
  } else {
    window.onunload = function() {
        oldonunload();
            func();
              }
              }
}




function loadfuncs()
{
 mapLoad();
 createShorlistArrayFromCookie();
 writeShortlist(0);

}

addLoadEvent(loadfuncs);


addUnLoadEvent(GUnload);
