var map, localSearch;
var icoBranch;
var xmlRegions, xmlBranches; 
var xmlHttp, XMLdoc;
var RegionCount = new Array; 
var RootURL =  window.location.protocol + '//' + window.location.hostname + '/Google_Maps/' //added GH 09-01-08, no hardcoded domain needed
var XMLurl = RootURL + "Points.xml";  // change to point to wherever the XML is generated

//##################################################################//
// ************************* Start of Load() function *************************************** //
//##################################################################//
function load() {
	if (GBrowserIsCompatible()) {
		try {
			if(document.implementation.hasFeature(
				"http://www.w3.org/TR/SVG11/feature#SVG","1.1")){ 
				_mSvgEnabled = true;
				_mSvgForced  = true;
			}
						
			// Capture map container object and set it to be a GMap2 object
			map = new GMap2(document.getElementById("map"));
			// add a function to be run on zoom, resize or move of map
			
			GEvent.addListener(map, "dragend", function() {	handleZoom(); });
			GEvent.addListener(map, "zoomend", function() {	handleZoom(); });
			
			// Add the controls and set up the map
			map.enableScrollWheelZoom();
			map.addControl(new GSmallZoomControl()); // the + and - zoom control
			map.addControl(new GHierarchicalMapTypeControl());
			map.addControl(new GScaleControl()); // displays the map scale
			
			// icons will need to be setup.. not sure what icons will be used, but here is where they are defined... 
			icoBranch = new GIcon();
			icoBranch.image = RootURL + "images/pin.png";
			icoBranch.shadow = RootURL + "images/shad.png";
			icoBranch.iconSize = new GSize(27, 25);
			icoBranch.shadowSize = new GSize(27, 25);
			icoBranch.iconAnchor = new GPoint(12, 35); // what is the distance (width, height) from the top left of the image to the pointer part of the image
			icoBranch.infoWindowAnchor = new GPoint(12, 35);
			
			// set the start point for the map to zoom to, this needs to change for every Region!!

			map.setCenter(new GLatLng(52.947100, -1.573510), 10);
			
			// create our search object
			localSearch = new GlocalSearch();
			localSearch.setAddressLookupMode( GlocalSearch.ADDRESS_LOOKUP_ENABLED );
			
			// load up the points for the map
				document.getElementById('MapOverlay').style.visibility="visible";
				document.getElementById('map').style.visibility="hidden";
			Load_XML();
			
		
// we used a try statement, so here's an error catcher!
		} catch( e ) {
			alert("An error was caught: " + e );
}	}	}

// ************************* End of Load() function *************************************** //

function Reset_View () {
				document.getElementById('MapOverlay').style.visibility="visible";
				document.getElementById('map').style.visibility="hidden";
				map.setCenter(new GLatLng(52.947100, -1.573510), 10);
}

function Load_XML() {
		xmlHttp = GetXmlHttpObject();
		// check our XMLhttp object was created
		if (xmlHttp==null) {	alert ("Browser does not support HTTP Request, points cannot be loaded");	return;	}
		
		// actually make the request

		xmlHttp.onreadystatechange=fnSearchSKUCallback;	// set the callback function (the function called when the status changes, ie the page loads)
		xmlHttp.open("GET",XMLurl,true);		
		xmlHttp.send(null);
}

// XML load helper functions
function GetXmlHttpObject(handler) {  // creates the XMLHTTP object
	var objXMLHttp = null;
	if (window.XMLHttpRequest) { objXMLHttp = new XMLHttpRequest();	} // firefox & Mozilla based browsers
	else if (window.ActiveXObject) {	objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");	} // Internet Explorer based browsers
	return objXMLHttp;
}
function fnSearchSKUCallback()  { // XMLhttp callback function
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
		Load_Pins(xmlHttp.responseText);
	}
}

  //#####################################################################//
 // ************************* Start of makepoint() function ************************************** //
//  ####################################################################//
function makepoint( inLat, inLon, strHeader, strAddress, strOpeninghours ) { 
	
	// take the header, address, and opening hours and create our HTML for the tabs 
	
	strHeader = "<div style='font-weight:bold;padding:10px 20px;margin-top: 5px;width:215px;background-color:#0047BE;background-image: url(\"images/tabheader.jpg\"); background-position:top left;background-repeat: no-repeat; color: #FFFFFF;'>"  + strHeader + "</div>"
	strAddress = strHeader + "<div style='font-size:90%;padding:10px 20px;width:215px;background-color:#D9E4F5;background-image: url(\"images/tabfooter.jpg\"); background-position:bottom left;background-repeat: no-repeat; color: #000000;'>"  + strAddress + "</div>"
	strOpeninghours = strHeader + "<div style='font-size:90%;padding:10px 20px;width:215px;background-color:#D9E4F5;background-image: url(\"images/tabfooter.jpg\"); background-position:bottom left;background-repeat: no-repeat; color: #000000;'>"  + strOpeninghours + "</div>"
	map.addOverlay( makeTooltipMarker(new GLatLng( inLat, inLon ), icoBranch, strAddress, strOpeninghours) ); 

}
// ************************* End of makepoint() function *************************************** //

  //#####################################################################//
 // ************************* Start of makeTooltipMarker() function ******************************** //
//  ####################################################################//
function makeTooltipMarker( inPoint, inIcon, tab1HTML, tab2HTML ) {
	// create the marker object
	var newMarker = new GMarker( inPoint, inIcon);
	// attatch a listener for clicks on the marker object
	GEvent.addListener(newMarker, "click", function() { 
		// this attatches the tabs to the marker... 
		
		var tempDiv;
		tempDiv = document.createElement("div");
		tempDiv.className = "bubble";
		tempDiv.style.height = "200px";
		tempDiv.style.width = "230px";
		tempDiv.innerHTML = tab1HTML
		var tab1 = new GInfoWindowTab("Contact", tempDiv ); // create a tab object from the parameters above
		
		tempDiv = document.createElement("div");
		tempDiv.className = "bubble";
		tempDiv.style.height = "200px";
		tempDiv.style.width = "230px";
		tempDiv.innerHTML = tab2HTML
		var tab2 = new GInfoWindowTab("Hours", tempDiv ); // create a tab object from the parameters above

		tempDiv = document.createElement("div");
		tempDiv.id = "detailmap";
		tempDiv.style.height = "200px";
		tempDiv.style.width = "250px";
		var tab3 = new GInfoWindowTab("Map", tempDiv ); // create another tab object
		var infoTabs = [tab3,tab2,tab1]; // a tab collection
		map.closeInfoWindow();
		infoWindowObject = infoTabs;
		infoWindowMarker = newMarker;
		
		infoWindowMarker.openInfoWindowTabs(infoWindowObject);
		
		detailMap = new GMap2(tempDiv)
		detailMap.enableScrollWheelZoom();
		detailMap.addControl(new GSmallZoomControl());
		detailMap.addControl(new GMapTypeControl(1));
		detailMap.checkResize();
		// right that should have created the mini map in one tab, and the tabHTML content on another tab

		// Hide the copyright on the small map
		// It will still be displayed on the large map, which should be OK 
		detailMap.getContainer().firstChild.nextSibling.style.display = "none";
		detailMap.getContainer().firstChild.nextSibling.nextSibling.style.display = "none";
		detailMap.checkResize();
		detailMap.setCenter(inPoint , 14);
		detailMap.addOverlay(new GMarker(inPoint, inIcon)); 
	});
	return newMarker; // return the marker object for display

}
// ************************* End of makeTooltipMarker() function *************************************** //

function handleZoom() {
	try { 
		if( map.getZoom() <= 7 ) { // check if the current soom level is below threshold, if it is then re-set it to prevent zooming outside of our limits
			map.setZoom(7);
	}	} catch( e ) {
		alert("An error was caught: " + e );
	}
}

function doPostCodeSearch() {
	if (document.getElementById("gmapSearch").value.replace(/^\s+|\s+$/g, '') != "") { // we have a search query
		usePointFromPostcode(document.getElementById("gmapSearch").value.replace(/^\s+|\s+$/g, '') , ZoomToPoint);
	}
	return false;
}

//#######################################################################################
// Google AJAX Search API - takes an address, calculates name, lat and lng, returns results in array
// filter matches outside the screen, then zoom screen to position.. 
// there are filters to ensure results are uk based only.... 
//#######################################################################################
function usePointFromPostcode(postcode, callbackFunction) {

	// Set up the callback function that will be executed once the GLocalSearch object finishes
	localSearch.setSearchCompleteCallback( null, function() {
		// Remove anything with lat/longs that are not in the UK
		// (mostly bad results will be in San Francisco - the default centre for the
		// GLocalSearch object)
		for( i = 0; i < localSearch.results.length; i++ ) {
			
			if( localSearch.results[i].lat > 55.838 || localSearch.results[i].lat < 49.923 ||
				localSearch.results[i].lng > 1.845 || localSearch.results[i].lng < -5.77 ) {
				
				// Remove an object from the array, and decrement the counter by one.
				// It will be re-incremented by the for loop, and the element in the same position
				// will be tested again.  Otherwise we would jump over the element
				localSearch.results.splice( i, 1 );
				i--;
			}
		}
		
		// If there is at least one result remaining, then we will invoke the callback function,
		// passing it the array of results.  Otherwise we just display an error.
		if ( localSearch.results[0] ) {     
			document.getElementById('MapOverlay').style.visibility="hidden";
			document.getElementById('map').style.visibility="visible";
			document.getElementById("txtlabel").innerHTML = "";
			callbackFunction(localSearch.results, 11);
		} else {
			alert("Your search for '" + postcode + "' returned no results");
		}
	});  
	
	// Invoke the search and wait for it to pass the result to our callback function
	localSearch.execute(postcode + ", United Kingdom");
	return false;
}

function ZoomToPoint( inObject, inZoom ) {
	var resultLat = inObject[0].lat;
	var resultLng = inObject[0].lng;
	var inPoint = new GLatLng(parseFloat(resultLat),parseFloat(resultLng));	
	map.setZoom( inZoom );
	map.panTo( inPoint );
	return false;
}

function placeMarkerAtPoint( inObject ) {

	var resultLat = inObject[0].lat;
	var resultLng = inObject[0].lng;
	var inPoint = new GLatLng(resultLat,resultLng);	
	map.setZoom( 11 );
	map.panTo( inPoint );
}

// ******************************************************************************
// ******************************************************************************
// The above functions should require little modifacation, the below functions are used 
// to setup the pins and custom data for the maps
// ******************************************************************************
// ******************************************************************************

function Load_Pins(XMLstring) {
	var intLoop, intSubLoop, intLoopIncrement; //intLoopIncrement added GH 09-01-08 1 for IE, 2 for FF
	var intSubLoopVal;// added GH 24-01-08 to fix Monday opening hours not appearing in IE, 0 for IE, 1 for FF
	XMLstring = XMLstring.toString();
	// load the XML Parser
	if (window.ActiveXObject)	{	XMLdoc=new ActiveXObject("Microsoft.XMLDOM");XMLdoc.async="false";	XMLdoc.loadXML(XMLstring); intLoopIncrement=1; intSubLoopVal=0;} // IE XMLdom 
	else { var parser=new DOMParser(); XMLdoc=parser.parseFromString(XMLstring,"text/xml"); intLoopIncrement=2;	intSubLoopVal=1;} // FF & Mozilla XMLdom
	XMLdoc=XMLdoc.documentElement;
	
	// grab the regions and branches
	xmlRegions = XMLdoc.getElementsByTagName("region");
	xmlBranches = XMLdoc.getElementsByTagName("branch");

	// populate the RegionCount array
	for (intLoop=0;intLoop<xmlRegions.length;intLoop++) {
		RegionCount[xmlRegions[intLoop].getAttribute("id")] = xmlRegions[intLoop].getAttribute("cbranches")
	}
	
	// lets create our points, loop through the branches and create our pin objects
	for (intLoop=0;intLoop<xmlBranches.length;intLoop++) {
		var xmlBranch = xmlBranches[intLoop];
		var tmpObjTest;
		var hoursHTML = "";
		var addressHTML =""; // addressHTML is also used to create alternating styles on the hours table before re-using for the address HTML
		
		// create our hours table
		 		
		for (intSubLoop=intSubLoopVal;intSubLoop<xmlBranch.getElementsByTagName("hours")[0].childNodes.length;intSubLoop=intSubLoop+intLoopIncrement) { //intLoopIncrement added GH 09-01-08, intSubLoopVal added GH 24-01-08
			// loop through the hours branches, ignore first element as it is the text element, as is every second element
			hoursHTML += "<tr " + addressHTML + "><td>" + xmlBranch.getElementsByTagName("hours")[0].childNodes[intSubLoop].nodeName + "</td>" +
														"<td>" + xmlBranch.getElementsByTagName("hours")[0].childNodes[intSubLoop].getAttribute("open") + "</td>" + 
														"<td>-</td><td>" + xmlBranch.getElementsByTagName("hours")[0].childNodes[intSubLoop].getAttribute("close")  + "</td></tr>";
			
			if (addressHTML=="") {	addressHTML="style='background-color:#A5C5EA;'"} else {addressHTML="";	} // alternating row style
		}
		
		
		hoursHTML = "<table cellspacing='0' callpadding='3'>" +  hoursHTML + "</table>"
		
		// create our address HTML
		addressHTML = ""
		tmpObjTest = xmlBranch.getElementsByTagName("contact")[0].getElementsByTagName("address")[0];
		if (tmpObjTest) { addressHTML += tmpObjTest.childNodes[0].nodeValue; }
		tmpObjTest = xmlBranch.getElementsByTagName("contact")[0].getElementsByTagName("postcode")[0];
		if (tmpObjTest) { addressHTML += tmpObjTest.childNodes[0].nodeValue + "<br /><br />"; }
		tmpObjTest = xmlBranch.getElementsByTagName("contact")[0].getElementsByTagName("tel")[0];
		if (tmpObjTest) { addressHTML += "<strong>Tel:</strong> " + tmpObjTest.childNodes[0].nodeValue + "<br />"; }
		tmpObjTest = xmlBranch.getElementsByTagName("contact")[0].getElementsByTagName("fax")[0];
		if (tmpObjTest) { addressHTML += "<strong>Fax:</strong> " + tmpObjTest.childNodes[0].nodeValue + "<br />"; }
		tmpObjTest = xmlBranch.getElementsByTagName("contact")[0].getElementsByTagName("email")[0];
		if (tmpObjTest) { addressHTML += "<br /><strong>Email:</strong> <a href='mailto:" + tmpObjTest.childNodes[0].nodeValue + "'>" + tmpObjTest.childNodes[0].nodeValue + "</a><br />"; }
		
		// create the pin!! 
		makepoint (
											xmlBranch.getElementsByTagName("lat")[0].childNodes[0].nodeValue,
											xmlBranch.getElementsByTagName("long")[0].childNodes[0].nodeValue,
											xmlBranch.getElementsByTagName("name")[0].childNodes[0].nodeValue,
											addressHTML,
											hoursHTML
							);
	}
}

function Zoom_To_Region(LocationID) { // this function is called from the links, and welcome overlay to zoom to regions
	document.getElementById('MapOverlay').style.visibility="hidden";
	document.getElementById('map').style.visibility="visible";
	document.getElementById("txtlabel").innerHTML = "";
    // need to zoom to the relevant area
	if (LocationID == 1) {map.setCenter(new GLatLng(52.705296, -1.264122), 10);} // Leicestershire
	if (LocationID == 2) {map.setCenter(new GLatLng(53.037600, -1.071081), 10);} // Nottinghamshire
	if (LocationID == 4) {map.setCenter(new GLatLng(52.950292, -2.120853), 9);}  // Staffordshire
	if (LocationID == 5) {map.setCenter(new GLatLng(52.925730, -1.492860), 10);} // Derbyshire
}


function Do_Place_mouseover (LocationID) { // displays summary information over the welcome overlay when mouse over of links / overlay regions occurs
	// need to get the number of branches in an area, there is no automatic calculation, so we need to do this manually :
	if (document.getElementById('MapOverlay').style.visibility=="visible") {
		var intBranchCount
		if (LocationID == 1) {intBranchCount = RegionCount[1];} // Leicestershire
		if (LocationID == 2) {intBranchCount = RegionCount[2];} // Nottinghamshire
		if (LocationID == 4) {intBranchCount = RegionCount[4];} // Staffordshire
		if (LocationID == 5) {intBranchCount = RegionCount[5];} // Derbyshire
		var PanelBg = RootURL + "images/paneltop.png";
		tHTML = 
		tHTML = "<div style=\"background-image:url('"  + PanelBg + "');background-repeat:no-repeat;height:61px;width:121px;\">" ;
		tHTML += "<div style=\"padding: 5px;font-size:83%;\">" +  document.getElementById("lab_" + LocationID).innerHTML + "</div>";
		if (intBranchCount >= 2) {
			tHTML += "<div style=\"padding: 5px;font-size:83%;\">  " + intBranchCount + " Branches </div>";
		} else {
			tHTML += "<div style=\"padding: 5px;font-size:83%;\">  " + intBranchCount + " Branch </div>";
		}
		tHTML += "</div>"
		document.getElementById("txtlabel").innerHTML = tHTML
	}
}
function ZoomToBranch( inObject, inZoom ) {
    var resultLat = inObject[0].lat;
    var resultLng = inObject[0].lng;
    var inPoint = new GLatLng(parseFloat(resultLat),parseFloat(resultLng));    
    map.setZoom( 15 );
    map.panTo( inPoint );
    return false;
}
