/*****************************************
Creative imports Geocoded client locations
Will Cadell, 20 July 2008
willcadell at hotmail dot com 
*****************************************/

//Spreadsheet Feed:
//http://spreadsheets.google.com/feeds/list/o06046206416153487406.6743300975002742970/od6/public/basic

//variable definitions	

//map variables

var map
var centre = new GLatLng(55.5, 3.1);
var scale = 5;
var geocoder = null;
var siteIcon
var blueIcon

//spreadsheet connection variables
var param_wsId = "od6";
var param_ssKey = "o06046206416153487406.6743300975002742970";
var param_useSidebar = false;
var param_titleColumn = "name";
var param_geoRes = "response";
var param_A1 = "a1";
var param_A2 = "a2";
var param_A3 = "a3";
var param_A4 = "a4";
var param_A5 = "a5";
var param_Phone1 = "phone1";
var param_latColumn = "lat";
var param_lngColumn = "lng";

//functional variables
var mapPoints = [];
var mapHtmls =[];
var highlightCircle;
var currentMarker;
var nearest_point;
var directions = '';
var address = "1 Royal Mile, Edinburgh, UK";

function mapSetup() {

	map = new GMap2(document.getElementById("map"));
	//map setup
	map.setCenter(centre, scale);
	map.enableInfoWindow();	
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GOverviewMapControl(new GSize(200,150)));

	geocoder = new GClientGeocoder();
	
	//Icons
	
	//Client Site Icon (red, default)
	siteIcon = new GIcon(G_DEFAULT_ICON);
	
	//Geocoded Address Point Icon (blue)
	blueIcon = new GIcon(G_DEFAULT_ICON);
	blueIcon.shadowSize = new GSize(0,0);
	blueIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
	
	//function call	to set up the map	
	cm_getJSON();	

}


// Retrieve the JSON feed & call other functions
function cm_getJSON() {
	  var script = document.createElement('script');
	  script.setAttribute('src', 'http://spreadsheets.google.com/feeds/list'
	                         + '/' + param_ssKey + '/' + param_wsId + '/public/values' +
	                        '?alt=json-in-script&callback=cm_loadMapJSON');
	  script.setAttribute('id', 'jsonScript');
	  script.setAttribute('type', 'text/javascript');
	  document.documentElement.firstChild.appendChild(script);
}

//load the marker data from the spreadsheet	
function cm_loadMapJSON(json) {  
	for (var i = 0; i < json.feed.entry.length; i++) {
		var entry = json.feed.entry[i];
		if (entry["gsx$" + param_geoRes].$t==200){
	      	var lat = parseFloat(entry["gsx$" + param_latColumn].$t);
	      	var lng = parseFloat(entry["gsx$" + param_lngColumn].$t);
		  	var html = "<strong>" + entry["gsx$"+param_titleColumn].$t + "</strong><br/>";
			if (entry["gsx$"+param_A1].$t != ''){
				html += entry["gsx$"+param_A1].$t;
			}
			if (entry["gsx$"+param_A2].$t != ''){
				html += entry["gsx$"+param_A2].$t + "<br/>";
			}
			if (entry["gsx$"+param_A3].$t != ''){
				html += entry["gsx$"+param_A3].$t + "<br/>";
			}
			if (entry["gsx$"+param_A4].$t != ''){
				html += entry["gsx$"+param_A4].$t + "<br/>";
			}
			if (entry["gsx$"+param_A5].$t != ''){
				html += entry["gsx$"+param_A5].$t + "<br/>";
			}
			if (entry["gsx$"+param_Phone1].$t != ''){
				html += "Phone: " + entry["gsx$"+param_Phone1].$t + "<br/>";
			}
			
	      	var point = new GLatLng(lat,lng);
	      	var marker = createMarker(point, html, siteIcon);
			mapPoints.push(point);
			mapHtmls.push(html);
			map.addOverlay(marker);			
		}
	}			
	var new_address = check_entry();
	if (new_address != ""){
		address = new_address;
		showAddress(address);
		};
	document.getElementById("addressInput").address.value = address;
	return false;
}

//create the marker
function createMarker(point,html,icon){
 	var marker = new GMarker(point,icon);
 	GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(html);
	});
	return marker;	
}

function check_entry(){
	if (location.search.substr(1).split("?") != ''){
		var ck_address = location.search.substr(9);
		ck_address = ck_address.replace(/%2C/g,",");
		ck_address = ck_address.replace(/\+/g," ");
		return ck_address;
		}
	return '';
	}

//show results of geocoding
function showAddress(address) {
	if (directions != ''){directions.clear()}
	map.enableInfoWindow();	
  	if (geocoder) {
  		geocoder.getLatLng(address, function(point) {
        	if (!point) {
          		alert(address + " not found");
        	} else {
          		var marker = createMarker(point,address,blueIcon);
          		map.addOverlay(marker);
          		//GLog.write(mapPoints.length);
		  		html = getClosestSite(point);
				currentMarker = marker;
				highlightCurrentMarker();
		  		html = "<ul id='sidebar-list'><h1>Nearest Blue Witch Stockist:</h1><li><a>" + html + "</a></li>";
				html += "<li><a id='directions' onclick=getDirections()>Get Driving Directions</a></li></ul>"
		  		document.getElementById("sidebar_location").innerHTML = html;
        	}
      	});
	}
}

function getClosestSite(newPoint) {  
	var mBounds = new GLatLngBounds();
	mBounds.extend(newPoint);
	for (var i = 0; i < mapPoints.length; i++ ){
		if (i == 0){
			var shortest_distance = newPoint.distanceFrom(mapPoints[i]);
			nearest_point = mapPoints[i];
			nearest_html = mapHtmls[i];
			} 
		else if (shortest_distance > newPoint.distanceFrom(mapPoints[i])){
			shortest_distance = newPoint.distanceFrom(mapPoints[i]);
			nearest_point = mapPoints[i];
			nearest_html = mapHtmls[i];
		}
		
	}
	var intShortkm = Math.round(shortest_distance / 1000)
	mBounds.extend(nearest_point);
	zoomOut = map.getBoundsZoomLevel(mBounds) - 1;
	map.setZoom(zoomOut);
	map.panTo(mBounds.getCenter());		
	return nearest_html + '<br/>Search Result:<br/>Lat: ' + nearest_point.y + '  Long: ' + nearest_point.x + '<br/>Distance to Nearest Site: ' + intShortkm + 'km';
};
//function to hightlight marker

function highlightCurrentMarker(){
   var markerPoint = currentMarker.getPoint();
   var polyPoints = Array();

   if (highlightCircle) {
     map.removeOverlay(highlightCircle);
   }

   var mapNormalProj = G_NORMAL_MAP.getProjection();
   var mapZoom = map.getZoom();
   var clickedPixel = mapNormalProj.fromLatLngToPixel(markerPoint, mapZoom);
   var polySmallRadius = 20;
   var polyNumSides = 20;
   var polySideLength = 18;

   for (var a = 0; a<(polyNumSides+1); a++) {
	    var aRad = polySideLength*a*(Math.PI/180);
	    var polyRadius = polySmallRadius; 
    	    var pixelX = clickedPixel.x + polyRadius * Math.cos(aRad);
	    var pixelY = clickedPixel.y + polyRadius * Math.sin(aRad);
	    var polyPixel = new GPoint(pixelX,pixelY);
	    var polyPoint = mapNormalProj.fromPixelToLatLng(polyPixel,mapZoom);
	    polyPoints.push(polyPoint);
   }
   // Using GPolygon(points,  strokeColor?,  strokeWeight?,  strokeOpacity?,  fillColor?,  fillOpacity?)
   highlightCircle = new GPolygon(polyPoints,"#000000",2,0.0,"#FF0000",.5);
   map.addOverlay(highlightCircle);
}

function getDirections(){
 	directionsPanel = document.getElementById("sidebar_directions");
  	directions = new GDirections(map, directionsPanel);
	direction_string = currentMarker.getPoint().lat() + ", " + currentMarker.getPoint().lng() + " to " + nearest_point.y + ", " + nearest_point.x;
  	directions.load(direction_string);
}


