/*	Google Maps API HtmlControl v1.1.2
	based on code posted on Google Maps API discussion group
	last updated/modified by Martin Pearman 20th August 2008
	
	http://googlemapsapi.martinpearman.co.uk/htmlcontrol
	
	This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

	You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
function HtmlControl(html, options){
	this.html=html;
	this.isVisible=true;
	this.isPrintable=false;	
	this.isSelectable=false;
	if(options){
		this.isVisible=(options.visible===false)?false:true;
		this.isPrintable=(options.printable===true)?true:false;
		this.isSelectable=(options.selectable===true)?true:false;
	}
}

HtmlControl.prototype=new GControl();

HtmlControl.prototype.initialize=function(map){
	this.div=document.createElement('div');
	this.div.innerHTML=this.html;
	this.setVisible(this.isVisible);
	map.getContainer().appendChild(this.div);
	return this.div;
};

HtmlControl.prototype.getDefaultPosition=function(){
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7));
};

HtmlControl.prototype.selectable=function(){
	return this.isSelectable;
};

HtmlControl.prototype.printable=function(){
	return this.isPrintable;
};

HtmlControl.prototype.setVisible=function(bool){
	this.div.style.display=bool ? '':'none';
	this.isVisible=bool;
};

HtmlControl.prototype.visible=function(){
	return this.isVisible;
}

// Class to structure contents in a GMap box
// Created by Large 200808
function GMapBox(hdrText,longHdrText,address,url,GLat,GLng,divHeight) {
	this.h2 = hdrText;
	this.h3 = longHdrText;
	this.adr = address;
	this.url = url;
	this.glat = GLat;
	this.glong = GLng;
	this.hght = divHeight!=null?divHeight:200;
	this.render = function() {
		var output = "<div style='height:"+this.hght+"px; width: 217px'><div class='gbox hdr1'>Search results</div>";
		output += "<div class='gbox hdr2'>"+this.h2+"</div>";
		output += "<div class='gbox hdr1'>"+this.h3+"</div>";
		output += "<div class='gbox addr'>"+this.adr+"</div>";
		//output += "<div class='gbox link'><a href='"+this.url+"'>Store details</a></div></div>";
		return output;
	};
	this.getGLat = function() {
		return this.glat;
	};
	this.getGLng = function() {
		return this.glong;
	};
}

// Object to setup the GMap
// Created by Large 200808
function GMapSetup(GLat,GLng,startZoom,mapName,showControls) {
	this.glat = GLat;
	this.glong = GLng;		
	this.zoom = startZoom;
	this.usemap = mapName;
	this.controls = showControls;
	this.markers = Array();
	
	this.getGLat = function() {
		return parseFloat(this.glat);
	};
	this.getGLng = function() {
		return parseFloat(this.glong);
	};
	this.getMarkers = function() {
		return this.markers;
	};
	this.getMarker = function(n) {
		return this.markers[n];
	};
	this.setMarker = function(obj) {
		this.markers.push(obj);
	};
	this.getZoom = function() {
		return this.zoom;
	};
	this.getMapName = function() {
		return this.usemap;
	};
	this.showControls = function() {
		return this.controls;
	};
}



function load(setup) {
      if (GBrowserIsCompatible()) {

		// A TextualZoomControl is a GControl that displays textual "Zoom In"
		// and "Zoom Out" buttons (as opposed to the iconic buttons used in
		// Google Maps).
		
		// ---- 		
		// Zoom Control
		function TextualZoomControl() {
		}
		
		// To "subclass" the GControl, we set the prototype object to
		// an instance of the GControl object
		TextualZoomControl.prototype = new GControl();
		
		// Creates a one DIV for each of the buttons and places them in a container
		// DIV which is returned as our control element. We add the control to
		// to the map container and return the element for the map class to
		// position properly.
		TextualZoomControl.prototype.initialize = function(map) {
		  var container = document.createElement("div");
		
		  var zoomInDiv = document.createElement("div");
		  this.setButtonStyle_(zoomInDiv);
		  container.appendChild(zoomInDiv);
		  zoomInDiv.appendChild(document.createTextNode("Zoom In"));
		  GEvent.addDomListener(zoomInDiv, "click", function() {
		    map.zoomIn();
		  });
		
		  var zoomOutDiv = document.createElement("div");
		  this.setButtonStyle2_(zoomOutDiv);
		  container.appendChild(zoomOutDiv);
		  zoomOutDiv.appendChild(document.createTextNode("Zoom Out"));
		  GEvent.addDomListener(zoomOutDiv, "click", function() {
		    map.zoomOut();
		  });

		  map.getContainer().appendChild(container);
		  return container;
		}
		
		// By default, the control will appear in the top left corner of the
		// map with 7 pixels of padding.
		TextualZoomControl.prototype.getDefaultPosition = function() {
		  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(15, 35));
		}
		
		// Sets the proper CSS for the given button element.
		TextualZoomControl.prototype.setButtonStyle_ = function(button) {
		  button.style.textDecoration = "none";
		  button.style.textTransform = "uppercase";
		  button.style.fontWeight = "bold";
		  button.style.color = "#fc9400";
		  button.style.backgroundColor = "white";
		  button.style.background = "url(/images/icon_zoomin.jpg) no-repeat 3px 3px #ffffff";
		  button.style.font = "1em Arial";
		  button.style.border = "1px solid #706c6b";
		  button.style.padding = "3px 3px 3px 25px";
		  button.style.marginBottom = "3px";
		  button.style.textAlign = "left";
		  button.style.width = "8em";
		  button.style.cursor = "pointer";
		}
		
		TextualZoomControl.prototype.setButtonStyle2_ = function(button) {
		  button.style.textDecoration = "none";
		  button.style.textTransform = "uppercase";
		  button.style.fontWeight = "bold";
		  button.style.color = "#fc9400";
		  button.style.backgroundColor = "white";
		  button.style.background = "url(/images/icon_zoomout.jpg) no-repeat 3px 3px #ffffff";
		  button.style.font = "1em Arial";
		  button.style.border = "1px solid #706c6b";
		  button.style.padding = "3px 3px 3px 25px";
		  button.style.marginBottom = "3px";
		  button.style.textAlign = "left";
		  button.style.width = "8em";
		  button.style.cursor = "pointer";
		}
		

		// ---- 		
		// Map Controls	
		function TextualMapControl() {
		}
		
		// To "subclass" the GControl, we set the prototype object to
		// an instance of the GControl object
		TextualMapControl.prototype = new GControl();
		
		// Creates a one DIV for each of the buttons and places them in a container
		// DIV which is returned as our control element. We add the control to
		// to the map container and return the element for the map class to
		// position properly.
		TextualMapControl.prototype.initialize = function(map) {
		  var container = document.createElement("div");
		
		  var zoomMapDiv = document.createElement("div");
		  this.setButtonStyle_(zoomMapDiv);
		  container.appendChild(zoomMapDiv);
		  zoomMapDiv.appendChild(document.createTextNode("Map"));
		  GEvent.addDomListener(zoomMapDiv, "click", function() {
		    map.setMapType(G_NORMAL_MAP);
		  });
		
		  map.getContainer().appendChild(container);
		  return container;
		}

		// By default, the control will appear in the top left corner of the
		// map with 7 pixels of padding.
		TextualMapControl.prototype.getDefaultPosition = function() {
		  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(95, 35));
		}
		
		// Sets the proper CSS for the given button element.
		TextualMapControl.prototype.setButtonStyle_ = function(button) {
		  button.style.textDecoration = "none";
		  button.style.textTransform = "uppercase";
		  button.style.color = "#706c6b";
		  button.style.backgroundColor = "white";
		  button.style.font = "1em Arial";
		  button.style.border = "1px solid #706c6b";
		  button.style.padding = "3px";
		  button.style.marginBottom = "3px";
		  button.style.textAlign = "center";
		  button.style.width = "6em";
		  button.style.cursor = "pointer";
		}		
		
		// ---- 		
		// Sat Controls	
		function TextualSatControl() {
		}
		
		// To "subclass" the GControl, we set the prototype object to
		// an instance of the GControl object
		TextualSatControl.prototype = new GControl();
		
		// Creates a one DIV for each of the buttons and places them in a container
		// DIV which is returned as our control element. We add the control to
		// to the map container and return the element for the map class to
		// position properly.
		TextualSatControl.prototype.initialize = function(map) {
		  var container = document.createElement("div");
		
		  var zoomSatDiv = document.createElement("div");
		  this.setButtonStyle_(zoomSatDiv);
		  container.appendChild(zoomSatDiv);
		  zoomSatDiv.appendChild(document.createTextNode("Sat"));
		  GEvent.addDomListener(zoomSatDiv, "click", function() {
		    map.setMapType(G_SATELLITE_MAP);
		  });
	  		  		
		  map.getContainer().appendChild(container);
		  return container;
		}		
		
		// By default, the control will appear in the top left corner of the
		// map with 7 pixels of padding.
		TextualSatControl.prototype.getDefaultPosition = function() {
		  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(15, 35));
		}
		
		// Sets the proper CSS for the given button element.
		TextualSatControl.prototype.setButtonStyle_ = function(button) {
		  button.style.textDecoration = "none";
		  button.style.textTransform = "uppercase";
		  button.style.color = "#706c6b";
		  button.style.backgroundColor = "white";
		  button.style.font = "1em Arial";
		  button.style.border = "1px solid #706c6b";
		  button.style.padding = "3px";
		  button.style.marginBottom = "3px";
		  button.style.textAlign = "center";
		  button.style.width = "6em";
		  button.style.cursor = "pointer";
		}		
				
	// Create Marker Class
      function createMarker(point,name,html,icon) {
        var marker = new GMarker(point, {icon:icon});
               
        if (setup.showControls()) {
	        GEvent.addListener(marker, "click", function() {
	          marker.openInfoWindowHtml(html);
	        });
        };
      	gMarkers.push(marker);
      }

	  gMarkers = [];   
	  var cntrpnt = new GLatLng(setup.getGLat(),setup.getGLng());
	  var mapBounds = new GLatLngBounds();
	  mapBounds.extend(cntrpnt)
	  
    var icon = new GIcon();
    icon.image = "/images/clinique_pin.png";
    icon.shadow = "/images/clinique_shadow.png";
    icon.iconSize = new GSize(50, 50);
    icon.shadowSize = new GSize(50, 50);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);      

	  G_SATELLITE_MAP.getName=function($short){
	    return 'Sat';
	  };

      var map = new GMap2(document.getElementById(setup.getMapName()), {mapTypes:[G_NORMAL_MAP, G_SATELLITE_MAP ]});

	  // Create the Google Map
	  if (setup.showControls()) {
	      loadingMessage = new HtmlControl('<div style="height:32px; width:32px;"><img src="/images/ajax-loader_trans.gif" width="32" height="32" alt="Map loading..." /></div>')
	      map.addControl(loadingMessage, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(309, 234)));
	  };
	        
    // Add Google markers to the map: short name, full name, address (with html breaks), url to detail page
    //Download the xml file that holds the store data.
    
    //var storesFileName = 'stores_test.xml?noCache='+new Date().getTime(); 
    var storesFileName = 'stores_test.xml?noCache=20081112';

		GDownloadUrl(storesFileName, function(this_xml, responseCode) 
		{
			if(responseCode == 200)
			{
			    var pointer = new GMarker(cntrpnt, {draggable:false});//pointer
    			var resultstoshow = 5;
    			var leftnav = '';
    			var strlst = [];
    			var xml = GXml.parse(this_xml);

    			//Loop through each store and work out the distance 
    			var n = 0;
    			$jq(xml).find("store").each(function() {
    			  n++;
    				var store 		= $jq(this);
    				var point 		= new GLatLng($jq("xloc", store).text(),$jq("yloc", store).text() );
    				var distance 	= point.distanceFrom(pointer.getPoint());
    				var content 	= store;
    				strlst.push({
    					distance:distance, 
    					content:content, 
    					point:point
    				});
    			});

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

    			for (var j=0; j<strlst.length && j<resultstoshow; j++){
    				var store = strlst[j]['content'];
    
    				setup.setMarker(
    					new GMapBox(
    						$jq("storename", store).text(),
    						$jq("storename", store).text(),
    						$jq("storedetails", store).text(),
    						"/stores/directorydetail.tmpl?store_id=" + $jq("internalid", store).text(),
    						$jq("xloc", store).text(),
    						$jq("yloc", store).text(),
    						200
    					)
    				);
    
    				leftnav = leftnav + '<dt>' + $jq("storename", store).text() + '<br />' + $jq("street", store).text() + '<br />' + $jq("city", store).text() + '</dt>\n';
    				//leftnav = leftnav + '<dd><a href="/stores/directorydetail.tmpl?store_id=' + $jq("internalid", store).text() + '">View store details</a></dd>\n';
    				leftnav = leftnav + '<dd></dd>\n';
    			}

    			$jq('#stores_leftnav_holder').html(leftnav);
    			
    			// Create Marker Manager.
    	    var mm = new GMarkerManager(map, {borderPadding:1});
    	          
    	    // This will be run multiple times to create an array of markers .. 
    	    // Only those in the viewport are shown on the maps .. i.e. bounded.

    	    for (i in setup.getMarkers()) {
    	    	var point = new GLatLng(setup.getMarker(i).getGLat(),setup.getMarker(i).getGLng())
    	    	mapBounds.extend(point);
    	    	createMarker(point,"pin_"+i,setup.getMarker(i).render(),icon);
    	    };
    	
    	  	// Finally add the markers array .. viewable from zoom 0 to 17 (Maximum view)
    	  	//map.setZoom(map.getBoundsZoomLevel(mapBounds));

    	    mm.addMarkers(gMarkers,0,17);
    	  	mm.refresh();     
    	  	map.setCenter(cntrpnt, map.getBoundsZoomLevel(mapBounds) -1);
    	  	if(map.isLoaded()){
    	  	    map.removeControl(loadingMessage);  
    	  	    map.addControl(new TextualZoomControl());
        	    map.addControl(new TextualMapControl());
        	    map.addControl(new TextualSatControl());      
    	  	}
    	  }
    });//GDownloadURL end
    }
  }
