/**
 *	Global Logic for Google Maps API, Boydgroup Website
 *  Copyright 2011, Adnet Communications, unless otherwise noted
 *	Author: James Clarke
 *	
 *	Rev 1.1
 * 
 *	Requires:
 *	Locations.js
 *	_"companyname"_Params.js
 *	Utils.js
 *	
 */


	
// GMapLarge() METHODS:
// .init <-- handles set up of search map and locaton maps,  plots locations and calls setup of event handlers for html elements 	!!! location map should move to stand-along function
// .showPanel <-- shows search map on address search
// .closePanel <-- hides search map
// .showAddress <-- geocodes addresss
// .findNearest <-- calculates bounding box for address to show locations nearby
// .drawMap <-- draws search map on return of geolocation
// .dim <-- obscures map while looking up address
// .locationData < -- unused by this function? 
// .locationListing <-- unused by this function?
// .plotLocations <-- plots all locations


var locMap;
var sm_map;
var sm_myPoint = new GLatLng(47.9020004272,-100.2119979858);
var sm_myCenterPoint = sm_myPoint;
var sm_zoom = 8;







function GMapSmall(){
	return this;
}


GMapSmall.prototype.init = function() {
		
		//check if this is a Location page, if it is, add an interactive map to it
		if(document.getElementById(smallMapEl) != undefined){
				
			var locMapEl = document.getElementById(smallMapEl);
			
			locMap = new GMap2( locMapEl );
			locMap.setMapType(G_NORMAL_MAP);
			locMap.enableScrollWheelZoom();
			locMap.addControl(new GLargeMapControl3D());
			locMap.addControl (new GScaleControl());
			
			
			var locAddress = locMapEl.title;
			var locObj;
			
			for(i=0;i<locations.length;i++){
				if (locAddress == locations[i].GAddress){
					locObj = locations[i];
					break;
				}
			}
			if(locObj){

				var locPoint = new GLatLng(locObj.Lat,locObj.Long); 
				var locMarker;
				
				if(locObj.Name.match("Anvil")){
					locMarker = new GMarker(locPoint,{icon:anvilIcon});
				}else if(locObj.Name.match("Gerber")) {
					locMarker = new GMarker(locPoint,{icon:gerberIcon});
				}else if(locObj.Name.match("True")) {
					locMarker = new GMarker(locPoint,{icon:true2Icon});
				}else if(locObj.Name.match("Cars")) {
					locMarker = new GMarker(locPoint,{icon:carsIcon});
				}else if(locObj.Name.match("Master")) {
					locMarker = new GMarker(locPoint,{icon:masterIcon});
				}else {
					locMarker = new GMarker(locPoint,{icon:boydIcon});
				}
				
				if(locObj.Name.match("Cars")) {
					locMap.openInfoWindowHtml(locPoint,'<div align="center"><img src="/i/photos/locations/'+locObj.RID+'.jpg" width="138" height="91"></div>');			
				}else {
					locMap.openInfoWindowHtml(locPoint,'<img src="/i/photos/locations/'+locObj.RID+'.jpg" width="200" height="133">');			
				}
				
					
				GEvent.addListener(locMarker, "click", function() {
					this.openInfoWindowHtml('<img src="/i/photos/locations/'+locObj.RID+'.jpg" width="200" height="133">');
				});
	
				
				locMap.addOverlay(locMarker);
				locMap.setCenter(locPoint,loc_zoom);
			
			}else{
				alert('not found, address=' + locAddress);
				locMap.setCenter(sm_myPoint,zoom);
			}
			
			
			
		}
		
		
		if(document.getElementById(searchAddress) != undefined){
			document.getElementById(searchAddress).onfocus = function(){
					if(this.value == "Enter your address"){
						this.value = "";
					}
				}
			document.getElementById(searchAddress).onkeypress = function(e){
				if(window.event){
					keyPressed = window.event.keyCode; // IE
				}else{
					keyPressed = e.which; // Firefox
				}
				if(keyPressed == 13){ // on enter, submit address
					address = document.getElementById(searchAddress).value;
					GMapSmall.showPanel();
					GMapSmall.showAddress();
				
				}
			}
			document.getElementById(searchButton).onclick = function(){
				address = document.getElementById(searchAddress).value;	
				GMapSmall.showPanel();
				GMapSmall.showAddress();
					
			}
		}
		
		if(document.getElementById(searchMap) != undefined){
			sm_map = new GMap2(document.getElementById(searchMap));
			sm_map.setMapType(G_NORMAL_MAP);
			sm_map.enableScrollWheelZoom();
			sm_map.addControl(new GLargeMapControl3D());
			sm_map.addControl (new GScaleControl());
			//draw locations to map	
			GMapSmall.plotLocations(sm_map,GMapSmall);
		}


    }
	
	GMapSmall.prototype.drawMap = function(){
		
		sm_map = new GMap2(document.getElementById(searchMap));
		sm_map.setMapType(G_NORMAL_MAP);
		sm_map.enableScrollWheelZoom();
		sm_map.addControl(new GLargeMapControl3D());
		sm_map.addControl (new GScaleControl());
		//draw locations to map	
		GMapSmall.plotLocations(sm_map,GMapSmall);
	
		var sm_myMarker = new GMarker(sm_myPoint, markerOptions);
		GEvent.addListener(sm_myMarker, "click", function() {
			this.openInfoWindowHtml('You Are Here<br>'+ myPoint);
		});
		sm_map.addOverlay(sm_myMarker);
		
		//center map on calculated location
		sm_map.setCenter(sm_myCenterPoint, sm_zoom);
		
		
		
	}
	
				
	GMapSmall.prototype.showPanel = function(){
		var panel = document.getElementById( mapContainerEl);
			panel.style.display = 'block';
	}
	
	//bootstrap
	function closePanel(){
			GMapSmall.closePanel();
	}
	
	GMapSmall.prototype.closePanel = function(){
		var panel = document.getElementById( mapContainerEl);
			panel.style.display = 'none';
	}

	GMapSmall.prototype.dim = function(opacity){
		var dimmer = document.getElementById(searchMapDim);
		if(opacity){
			dimmer.style.display = 'block';
		}else{
			dimmer.style.display = 'none';
		}
	}

	GMapSmall.prototype.showAddress = function() {
	
		GMapSmall.dim(1);	//blocking
		
		geocoder = new GClientGeocoder();
		if (geocoder) {
		  geocoder.getLatLng(address,function(point){
			if (!point) {
			  alert("Could not find address: " + address);
			  GMapSmall.dim(0); // remove blocking
			  GMapSmall.drawMap();
			} else {
			  sm_myPoint = point;
			  GMapSmall.findNearest(point);
			}
			});
		}
	
	}

	GMapSmall.prototype.findNearest = function(point){
		//loop through locations, calculate hypoteneus(^2), determine closest
				 
		var py, px, lt, lng, nearest, hypSq;
		
			py = point.y;
			px = point.x;
			
		var shuffledLocations = locations.slice();	
		//loop and calculate hypoteneus(^2) for each. no Math.sqrt for speed
		for (i=0;i<shuffledLocations.length; i++){
			
			lt = py-shuffledLocations[i].Lat;
			lng = px-shuffledLocations[i].Long;
			hypSq = (lt*lt + lng*lng);
			shuffledLocations[i].hypSq = hypSq; 
									
		}
		
		//sort based on hypotenus
		shuffledLocations.sort(UTILS.sortMe);

		var bounds = new GLatLngBounds; 
			bounds.extend(new GLatLng(py, px)); 
			bounds.extend(new GLatLng(shuffledLocations[0].Lat, shuffledLocations[0].Long)); 		
			bounds.extend(new GLatLng(shuffledLocations[0].Lat, shuffledLocations[0].Long)); 		
			sm_map.setCenter(bounds.getCenter(),  GMapSmall.setZoomLevel( sm_map.getBoundsZoomLevel(bounds)-1 )); 
			sm_myCenterPoint = bounds.getCenter();
			//remove blocking
			GMapSmall.dim(0);		
	
			GMapSmall.drawMap();

		
	
	}
	
	GMapSmall.prototype.setZoomLevel = function(num){
		if(num){
			sm_zoom = num;
		}else{
			sm_zoom = 8;
		}
	}
	
	/** RETURNS HTML FOR NEAREST LOCATIONS LIST **/ 	
	GMapSmall.prototype.locationListing = function(obj){
	
		var	html = '<div class="location">';
		   html += '<div class="inner">';
		   html += '<div class="address">';
		   html += '<h2>'+obj.Name+'</h2>';
		   html += '<p>'+obj.FullAddress+'</p>';
		   html += '<a href="#">Go to this location</a>'; // need link
		   html += '</div>';
		   html += '<div class="phone">';
		   html += '<h3>Phone:</h3>';
		   html += '<h2>'+obj.Phone+'</h2>';
		   html += '<a href="#">Book Appointment</a>';
		   html += '</div>';
		   html += '<div class="clear"></div>';
		   html += '</div>';       
		   html += '</div>';
		   
		   return html;
	}

	/** RETURNS HTML FOR INFO BALLOON**/ 
	GMapSmall.prototype.locationData = function(obj){
			
		var html = '<div class="balloon">';
			html += '<h2>'+obj.Name+'</h2>';
			html += '<div class="logo">'
			
			if(obj.Name.toLowerCase().match('boyd')){
				html += '<img src="/i/common/boyd-logo.gif" /></div>';
			}else if(obj.Name.toLowerCase().match('gerber')){
				html += '<img src="/i/common/gerber-logo.gif" /></div>';
			}else if(obj.Name.toLowerCase().match('true')){
				html += '<img src="/i/common/true2form-logo.gif" /></div>';
			}else if(obj.Name.toLowerCase().match('master')){
				html += '<img src="/i/common/master-logo.gif" /></div>';
			}else if(obj.Name.toLowerCase().match('anvil')){
				html += '<img src="/i/common/anvil-logo.gif" /></div>';
			}
			
			html += '<p>'+obj.FullAddress+'<br /><br />';
		
			html += 'Hours of Operation:<br />';
			html += obj.Hours+'<br /><br />';
		
			html += 'Phone:'+obj.Phone+'<br />';
			html += 'Fax:'+obj.Fax+'<br />';
			html += 'Email: <a href="mailto:'+obj.Email+'">'+obj.Email+'</a></p>';
			html += '</div>';

		return html;

	}
	
	
	GMapSmall.prototype.plotLocations = function(targetMapEl,caller){
		geocoder = new GClientGeocoder();
		for(i=0; i<locations.length; i++){
		//for(i in locations){
			with({i:i}){
			if(locations[i].Lat){
				
				//Check if sorting has be activatd and what to sort for.
				if(sortLoc){
					if(sortLoc.by == 'province'){
						if(locations[i].State.toLowerCase() == sortLoc.val){
							//nothing, proceed
						}else{
							continue;
						}
					}else if(sortLoc.by == 'city'){
						if(locations[i].City.toLowerCase() == sortLoc.val){
							//nothing, proceed
						}else{
						   continue;	
						}
					}
				}
				
				
				//Check business name and assign appropriate icon 
				
				if(locations[i].Name.match('Anvil Glass')){
					var mrk = new GMarker( 
							new GLatLng(locations[i].Lat,locations[i].Long),anvilMarkerOptions
						);
						GEvent.addListener(mrk, "click", function() {
							window.location = locationPageURL+"?ReportID="+locations[i].RID;
						});
					targetMapEl.addOverlay(	mrk );
 
				}else if(locations[i].Name.match('True2Form Collision')){
					var mrk = new GMarker( 
							new GLatLng(locations[i].Lat,locations[i].Long),true2MarkerOptions
						);
						GEvent.addListener(mrk, "click", function() {
							window.location = locationPageURL+"?ReportID="+locations[i].RID;
						});
						
				    targetMapEl.addOverlay(	mrk );
					
				}else if(locations[i].Name.match('Gerber Collision & Glass')){
					var mrk = new GMarker( 
							new GLatLng(locations[i].Lat,locations[i].Long),gerberMarkerOptions
						);
						GEvent.addListener(mrk, "click", function() {
							window.location = locationPageURL+"?ReportID="+locations[i].RID;
						});
						
				    targetMapEl.addOverlay(	mrk );
					
				}else if(locations[i].Name.match('Cars Collision Center')){
					var mrk = new GMarker( 
							new GLatLng(locations[i].Lat,locations[i].Long),carsMarkerOptions
						);
						GEvent.addListener(mrk, "click", function() {
							window.location = locationPageURL+"?ReportID="+locations[i].RID;
						});
						
				    targetMapEl.addOverlay(	mrk );
					
				}else if(locations[i].Name.match('Master Collision Repair')){
					var mrk = new GMarker( 
							new GLatLng(locations[i].Lat,locations[i].Long),masterMarkerOptions
						);
						GEvent.addListener(mrk, "click", function() {
							window.location = locationPageURL+"?ReportID="+locations[i].RID;
						});
						
				    targetMapEl.addOverlay(	mrk );
						
					
				}else{
					var mrk = new GMarker( 
							new GLatLng(locations[i].Lat,locations[i].Long),boydMarkerOptions
						);
						GEvent.addListener(mrk, "click", function() {
							window.location = locationPageURL+"?ReportID="+locations[i].RID;
						});

					targetMapEl.addOverlay(	mrk );
					
				}
			}else if (geocoder) {
				
				  //If no lat/long available, geocode locations (not ideal as google only allows a small number at a time)
				  geocoder.getLatLng(locations[i].GAddress,	function(point) {
							if (!point) {
							//  alert(locations[i].gAddress + " not found")
							} else {
							  el.addOverlay(	new GMarker(point));
							  locations[i]['Lat'] = point.y;
							  locations[i]['Long'] = point.x;
							}
					  });
			}
			}
		}
	}
		
		
		
		
	var GMapSmall = new GMapSmall();
		
	
