var map;
var localSearch = new GlocalSearch();
var gmarkers = new Array();
var mapzoom;
var postcodeSearchedLat = 0;
var postcodeSearchedLong = 0;
var postcodeSearched;
var hassearched = false;

// vars that will need to be translated or update per country //


var centlat             = 54.41892996865827;
var centlng             = -2.10;
var noStores            = 'Sorry there are no stores in this town or area';
var noPostcodeEntered   = 'Please enter a postcode or town';    
var noOptionsEntered    = 'Please enter a town or postcode and select a search option:\n\n - Spectacles & contact lenses\n - Laser eye surgery\n - Intraocular lenses';
var retrievingData      = 'retrieving data'
var laserDirectoryName  = 'laser-eye-surgery/clinic-';
var tnName              = 'Location';
var tnPostcode          = 'Postcode';
var tnDistance          = 'Distance';
var townUnmatched       = 'Town not found';
var laserDirectory      = '/laser-eye-surgery/';
var directoryName       = 'clinics/';
var moreInfo            = 'Find out more';
var stores              = ' stores ';
var showing             = ' showing ';
var countryName         = ' UK';
var storelistHeader     = 'Nearest stores to:';
var unit                = ' miles';
var townName;

function isLaserPage() {
	return document.getElementById('isLaserPage');
}	


function addEvent(oTarget, sType, fpDest) {
  sType = 'on'+sType;
  var oOldEvent = oTarget[sType];
  if (typeof oOldEvent != "function") {
    oTarget[sType] = fpDest;
  } else {
    oTarget[sType] = function(e) {
      oOldEvent(e);
      fpDest(e);
    }
  }
}

function showStoreInfo(id)
{
 	// pops up the infor window
 	map.addOverlay( gmarkers[id]);
    GEvent.trigger(gmarkers[id], "click");
}

function writelist (content)
{
	  var xml = GXml.parse(content);
	  eDIV = document.createElement("div");
	  eDIV.setAttribute("id","list");
	  
	  // lets get the markers out of that into an array 		 	
	  var markers = xml.documentElement.getElementsByTagName("marker"); 
	  if(markers.length != 0)
	  {
		  
	  	var header	= document.createElement('h2');
	  	var headtext= document.createTextNode(storelistHeader);
	  	header.appendChild(headtext);
	  	eDIV.appendChild(header);
	  	
	  	var storedetails = document.createElement('h2');
	  	var storetext= document.createTextNode(townName);
	  	storedetails.appendChild(storetext);
	  	eDIV.appendChild(storedetails);
	  	 	
	  	//use the setAttribute method to assign it an id
 	  	var tbl     = document.createElement("table");
 	  	tbl.setAttribute("id","storeLocator-storelist");
	 
	   
	  	var tblHead = document.createElement("thead");
	  	var row 	= document.createElement("tr");
	  
	  	// table header for name
	  	var cell0 = document.createElement("th");	
        var cellText = document.createTextNode(tnName);
      	cell0.appendChild(cellText);
      	row.appendChild(cell0);
	  
	   // table header for town
        var cell0 = document.createElement("th");   
        var cellText = document.createTextNode('');
        cell0.appendChild(cellText);
        row.appendChild(cell0);
      
	  	// table header for distance if required
	  	if(postcodeSearchedLat != 0 && postcodeSearchedLong != 0)
	  	{
	  		var cell0 = document.createElement("th");	
      		var cellText = document.createTextNode(tnDistance);
      		cell0.appendChild(cellText);
      		row.appendChild(cell0);
	  	}
	  
	  	tblHead.appendChild(row);
	  	tbl.appendChild(tblHead);
	    
      	var tblBody = document.createElement("tbody");
	  }
      
	  for (var $i = 0; $i < markers.length; $i++) 
      {  
	        var row = document.createElement("tr");
	    	// we want to get the distance of these markers from a postode if one was entered.

            var link = document.createElement( 'A' );       
            link.href = '/' + directoryName + markers[$i].getAttribute("fname").replace(' ','-') + "-" + markers[$i].getAttribute("id") + ".html";
            link.setAttribute('onclick','saveCurrentPosition();');
            
            //link.href = 'javascript:showStoreInfo(' + markers[$i].getAttribute("id") +  ')';
            
            var textname = markers[$i].getAttribute("town") + ', ' + markers[$i].getAttribute("name");
            var name = document.createTextNode(markers[$i].getAttribute("name"));
            
            link.title = textname;
            
			var town = document.createTextNode(markers[$i].getAttribute("town"));
            link.appendChild(town);
            

			// add entries for town and name
			var cell = document.createElement("td");
			cell.className = 'town';
            cell.appendChild(link);
            row.appendChild(cell);

			var cell = document.createElement("td");
            cell.className = 'name';
            cell.appendChild(name);
            row.appendChild(cell);

			// add entry for distance if user has entered a postcode or town
			if(postcodeSearchedLat != 0 && postcodeSearchedLong != 0)
			{
				var cell2 = document.createElement("td");
	            cell2.className = 'distance';
				var distance = markers[$i].getAttribute("distance");	
            	var cellText = document.createTextNode(distance + unit);
            	cell2.appendChild(cellText);
            	row.appendChild(cell2);
			}
			
			tblBody.appendChild(row);
		
	  }
	  
	  // if we had markers to create a table from lets add them to the div to display
	  if(markers.length != 0)
	  {
	  	tbl.appendChild(tblBody);
	  	eDIV.appendChild(tbl);
	  }
   
      // if we already have html in the div lets replace it
      var old = document.getElementById("list");
	  if(old)
	  {
		if(document.getElementById("ajaxstorelist"))
		{
	   	  	document.getElementById("ajaxstorelist").replaceChild(eDIV, old);
		}
	  }
	  else
	  {
		if(document.getElementById("ajaxstorelist"))
		{
			var storelist = document.getElementById("ajaxstorelist");
	
			if ( storelist.hasChildNodes() )
			{
			    while ( storelist.childNodes.length >= 1 )
			    {
			        storelist.removeChild( storelist.firstChild );       
			    } 
			}
			storelist.appendChild(eDIV);	  
		}
	  }
}


function usePointFromPostcodeTown(town) {
// this function takes a town and zooms and center on the map based on this

	town += ',' + countryName;

  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);
        townName = localSearch.results[0].title;
		postcodeSearchedLat = resultLat;
		postcodeSearchedLong = resultLng;
		postcodeSearched = town;
		if(!isLaserPage()) {
			map.clearOverlays();
		}
	    var zoom = 11;
        map.setCenter(point, zoom, G_PHYSICAL_MAP);
		putResultsOnMap();
      }else{
        alert(townUnmatched);
		map.setCenter(new GLatLng(centlat,centlng), 5, G_PHYSICAL_MAP);
      }
    });

  localSearch.execute(town);
}


function putResultsOnMap(fromZoom, fromLaser)
{
	//Don't populate the markers if they haven't done a search yet on main Store Locator
	if(!isLaserPage() && !hassearched) {
		return false;
	}

   	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();
    
    // Adjust for the big hidden square search
    if(!isLaserPage()) {
        
        var adjustment = ((((max_long - min_long) / 2) - (max_lat - min_lat)) / 2);         
        max_lat = max_lat + adjustment;
        min_lat = min_lat - adjustment;                   
                    
    }  
      
    
    // based on the current map bounds send off a request to get what stores are in this.
	var url = "/inc/storeLocator-xml.inc.php?min_lat=" + min_lat + '&max_lat=' +  max_lat + '&min_long='  + min_long + '&max_long=' + max_long + '&zoom=' + map.getZoom();
	// if we have a post send the long and lat of this so that we can return ordered results
	if(postcodeSearchedLat && postcodeSearchedLong )
	{
      url +=  '&postcodeLat=' + postcodeSearchedLat + '&postcodeLong=' + postcodeSearchedLong;
	}
	
	
	
	GDownloadUrl(url, function(data, responseCode) 
    {  
	  // if the script doesnt die on us process the results
      if(responseCode == 200) 
	  {
	  	if(!fromLaser && !fromZoom)
		{
		 writelist(data);
		}
		
		// we get returned an xml document 
	     var xml = GXml.parse(data);
         // lets get the markers out of that into an array
		 if(xml)
		 {
			 var markers = xml.documentElement.getElementsByTagName("marker"); 
			 var markertotal = markers.length;
			 
			 // if we have no markers returned and they didnt just zoom then we know they came from a search
			 // so tell them the search returned no results
			 
			 if(markertotal < 3 && !fromZoom) 
			 { 
			   map.zoomOut();
			   putResultsOnMap(fromZoom, fromLaser);
			   return;
			 } 
			 var lattotal = 0;
			 var lngtotal = 0;
			
			var Icon = new GIcon();
			Icon.image = "/img/markerSign.png";
			Icon.iconSize = new GSize(45, 45);
			Icon.shadow = "/img/markerSignShadow.png";
			Icon.shadowSize = new GSize(78, 47);
			Icon.iconAnchor = new GPoint(10, 45);
			Icon.infoWindowAnchor = new GPoint(21, 0);

		 	// lets loop through the xml list
		 	for (var i = 0; i < markers.length; i++) { 
				var title = '';
				// lets plot the location
				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"));	 
				
				// make individual markers
				title = markers[i].getAttribute("town") + ', ' + markers[i].getAttribute("name");	  
				
				var marker = new GMarker(point, {title: title, icon:Icon}); 
				lowerCaseTownForUrl = markers[i].getAttribute("town").toLowerCase();
				name = markers[i].getAttribute("name");
				postcode = markers[i].getAttribute("postcode");
				phone = markers[i].getAttribute("phone");
				marker.name = title; // add some info that we can access later for linking
				marker.myhtml = "<img src=\"/img/storeLocator-logo.gif\" alt=\"The Dental Clinic\"><br /><strong> " + markers[i].getAttribute("town") + "</strong><br />" + name + "<br />" + postcode + "<br />" + phone + "<br /><br /><a onClick=\"saveCurrentPosition();\" href=\"/" + directoryName +  markers[i].getAttribute("fname") + '-'  +  markers[i].getAttribute("id") +  ".html \">" + moreInfo + "</a>";	
				 
				marker.id =  markers[i].getAttribute("id");
				// add marker to the map - if it isn't already there!
				if(!gmarkers[markers[i].getAttribute("id")]) {
					gmarkers[markers[i].getAttribute("id")] = marker;
					map.addOverlay(marker);
				}
			}
		  	
		  }
	   }
    }   
  );  
}


function createMap()
{
  	// basic  function just to create the google map
  	map = new GMap2(document.getElementById("storeMap"));
	// add the new terrain map type
  	map.addMapType(G_PHYSICAL_MAP); 
	// add the large zoom bar
  	map.addControl(new GLargeMapControl());
	// add the maps types eg. satellite, hybrid, street
  	map.addControl(new GMapTypeControl());
	// allow users to double on the map to zoom
  	map.enableDoubleClickZoom();
  	//Enable mouse wheel zooming
	map.enableScrollWheelZoom();
	  	 
	// set min/max map scale
	var minmapscale = 5;
	var maxmapscale = 15;
	// get array of map types
	var mapTypes = map.getMapTypes();
	// overwrite the getMinimumResolution() and getMaximumResolution() methods for each map type
	for (var i=0; i<mapTypes.length; i++) {
		mapTypes[i].getMinimumResolution = function() {return minmapscale;}
		mapTypes[i].getMaximumResolution = function() {return maxmapscale;}
  	}
}



function addMapListeners()
{
	GEvent.addListener(map, "moveend", function() {
		checkZoom(); 
	} );

	// lets add some listeners for clikc and zoom events
	GEvent.addListener(map, "click", function(overlay, point) {
		if (overlay) { 
			if (overlay.openInfoWindowHtml) {
				overlay.openInfoWindowHtml(overlay.myhtml);
			} 
		} 
	} );
}


function searchFormSubmitted()
{
	// lets first save the search values	
	// if we have postcode or town search by this 
	targ = document.getElementById('postcodeTown');
	
	//We're going to rebuild the list of markers
	gmarkers = new Array();
	
	// lets validate first
	isSpecsContacts = document.getElementById('isSpecsContacts');
	isLaser = document.getElementById('isLaser');
	isIOL = document.getElementById('isIOL');
 
 	//If it's the laser page and they're trying to submit the form with no postcode, do an error
	if(isLaserPage() && targ.value == '')
	{
		alert(noPostcodeEntered);
      	return false;   
	}
  	
  	//Otherwise we need to check they've selected something from the radio buttons
  	if(!isLaserPage()) {
	   	if(targ.value == '' || (isSpecsContacts.checked == false && isLaser.checked == false && isIOL.checked == false))
		{
		  	alert(noOptionsEntered);
	      	return false;
		}
	}
	
	hassearched = true;
	
	// go get the results if the user gave us something to search for 
  	if(targ.value != '')
  	{
   		 usePointFromPostcodeTown(targ.value);	
  	}
  	else
  	{
		// get rid of all current markers and replot for these search params
		map.clearOverlays();  
		putResultsOnMap(); 
  	}
  	
  	return false;

}

function mapLoad( ) 
{
  // unless we are setting the zoom to be something else default it to 4 veiw of europe
  if (GBrowserIsCompatible()) 
  {
		  createMap(); 
		  // if they hit back from a store info page then they will have their last pos saved so return them to it
		  returnToSavedPosition();  
		  if(!mapzoom) { 
		      if(isLaserPage()) {
		          mapzoom = 6;
		      } else {
		          mapzoom = 5;
		      }   
		  }
		  map.setCenter(new GLatLng(centlat,centlng), mapzoom, G_PHYSICAL_MAP);
		  if(isLaserPage())
		  {
			// if we are coming from laser we don't want to use the ajax list   
			checkZoom(1);
			//Check if we have posted something
			var isformposted = document.getElementById('from_storelist');
			if(isformposted && isformposted.value == '1') {
		  		searchFormSubmitted();
		  	}  	
		  } else {
		  	checkZoom();
			
		  }
		 
		  addMapListeners(); 	  
		 
  }
}

function checkZoom(fromLaser)
{
	putResultsOnMap(1, fromLaser); 
}

function clinicSelected()
{
  var targ = document.getElementById('clinics');
  if(targ)
  {
	var name = targ.options[targ.options.selectedIndex].value;
    location.href= laserDirectory + name + '.html';	
  }
}

function saveCurrentPosition()
{
	// get the map position
	expires = 1000 * 60 * 5;
	cent = map.getCenter();
	var zoom = map.getZoom();
	//save this to cookies so that when the user hits back they 
	//get returned to where they were on the map
	if(!isLaserPage()) {
		var latCookie = 'opEx_centlat';		
		var longCookie = 'opEx_centlng';		
		var zoomCookie = 'opEx_zoom';		
	} else {
		var latCookie = 'opEx_laser_centlat';		
		var longCookie = 'opEx_laser_centlng';		
		var zoomCookie = 'opEx_laser_zoom';		
	}
	
	setCookie(latCookie, cent.lat(), expires);
	setCookie(longCookie, cent.lng(), expires);
	setCookie(zoomCookie,zoom, expires);
	
}

function returnToSavedPosition()
{
	if(!isLaserPage()) {
		var latCookie = 'opEx_centlat';		
		var longCookie = 'opEx_centlng';		
		var zoomCookie = 'opEx_zoom';		
	} else {
		var latCookie = 'opEx_laser_centlat';		
		var longCookie = 'opEx_laser_centlng';		
		var zoomCookie = 'opEx_laser_zoom';		
	}

  //if cookie get the previous map position and zoom
  if(getCookie(zoomCookie))
  {
  	mapzoom = Number(getCookie(zoomCookie));
  }
  
  if(getCookie(latCookie) && getCookie(longCookie))
  {
  	centlat = Number(getCookie(latCookie));
  	centlng = Number(getCookie(longCookie));
  	hassearched = true;
  }
}

function getCookie(sName)
{
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) return unescape(aCrumb[1]);
  }
  return 0;
}

function setCookie(sName, sValue, sExpires)
{
  // create a cookie
  var today = new Date();
  today.setTime( today.getTime() );
  var expires = 1000 * 60 * 4;
  var expires_date = new Date( today.getTime() + (expires) );	
  document.cookie = sName + "=" + escape(sValue) + "; path=/; " + "expires=" +  expires_date.toGMTString();
}

function getElementsByClass(searchClass,node,tag)
{
	// provide a class name and it returns and array of all elements belonging to this class
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

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

function addUnLoadEvent(func) {
// we need this to avoid memory leaks
var oldonunload = window.onunload;
if (typeof window.onunload != 'function') {
  window.onunload = func;
  } else {
    window.onunload = function() {
        oldonunload();
            func();
              }
              }
}

// when the page loads load the map
addEvent( window, 'load',mapLoad);
addUnLoadEvent(GUnload);
