var map = null;

var directionsPanel;
var directions;


function initTabs()
{
	if (document.location.href.indexOf("/branches/") != -1)
	{
		//document.getElementById("show-on-map").style.display = "block";
	}

	var sets = document.getElementsByTagName("ul");
	for (var i = 0; i < sets.length; i++)
	{
		if (sets[i].className.indexOf("tabset") != -1)
		{
			var tabs = [];
			var links = sets[i].getElementsByTagName("a");

			for (var j = 0; j < links.length; j++)
			{
				if (links[j].className.indexOf("tab") != -1)
				{
					links[j].className = links[j].className.replace("hidden", "");
					tabs.push(links[j]);
					links[j].tabs = tabs;
					var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));

					//reset all tabs on start
					if (c) if (links[j].className.indexOf("active") != -1) c.style.display = "block";
					else c.style.display = "none";

					links[j].onclick = function ()
					{
						var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
						if (c)
						{
							//reset all tabs before change
							for (var i = 0; i < this.tabs.length; i++)
							{
								if (document.location.href.indexOf("/branches/") != -1)
								{
									if (this.id != "tabHead2")
									{
										document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1)).style.display = "none";
										//document.getElementById("directions").innerHTML = "";
									}
								}
								else
									document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1)).style.display = "none";
								this.tabs[i].className = this.tabs[i].className.replace("active", "");
							}
							this.className += " active";
							c.style.display = "block";
							if (document.location.href.indexOf("/branches/") != -1)
							{
								if (this.id == "tabHead2")
								{
									showMap('SMALL', 15, true);
								}
							}
							return false;
						}
					}
				}
			}
		}
	}
}


function changeTab(tab)
{
	return false;
	showMap('SMALL', 15, true);
	
	for (i = 1; i < 3; i++)
	{
		document.getElementById("tab"+i).style.display = "none";
		document.getElementById("tabHead"+i).className = "tab";
	}
	document.getElementById("tab"+tab).style.display = "block";
	document.getElementById("tabHead"+tab).className += " active";
	return false;
}

if (window.addEventListener) window.addEventListener("load", initTabs, false);
else if (window.attachEvent) window.attachEvent("onload", initTabs);


function resetServicePanel()
{
	for (var i = 1; i < 4; i++)
	{
		document.getElementById("slide-block-"+i).style.display="none";
	}
}

function showServicePanel(panelId)
{
	resetServicePanel();
	document.getElementById("slide-block-" + panelId).style.display="block";
}



function codeAddress(postcode, title, single, branch, id) {
	geocoder.geocode( { address: postcode, country:"GB"}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK && results.length)
		{
		// You should always check that a result was returned, as it is
		// possible to return an empty results object.
			if (status != google.maps.GeocoderStatus.ZERO_RESULTS)
			{
				var image = new google.maps.MarkerImage('http://elias.emdev.co.uk/static/images/pin' + id + '.png',
				  // This marker is 20 pixels wide by 32 pixels tall.
				  new google.maps.Size(54, 44),
				  // The origin for this image is 0,0.
				  new google.maps.Point(0,0),
				  // The anchor for this image is the base of the flagpole at 0,32.
				  new google.maps.Point(27, 44));

				var marker = new google.maps.Marker({
				  position: results[0].geometry.location,
				  map: map,
				  icon: image, //"http://elias.emdev.co.uk/static/images/pin" + id + ".png",
				  title: title,
				  clickable: !single
				});
				if (single == true)
				{
					map.set_center(results[0].geometry.location);
				}
				else
				{
					google.maps.event.addListener(marker, 'click', function() {
					  goToBranch(branch);
					});
				}
			}
		}
	});
}



function goToBranch(branch)
{
	parent.document.location.href=branch;
}



function showMap(nav, zoom, centre)
{
	if (document.getElementById("map").innerHTML != "")
		return;
	//geocoder = new google.maps.Geocoder();
	//var latlng = new google.maps.LatLng(54.971658,-1.612984); //High Bridge
	
	/* THIS IS FOR V3 */
	//var latlng = new google.maps.LatLng(51.535000,-0.169516);
    //var myOptions = {zoom: zoom, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: true, navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL}};
	
    //map = new google.maps.Map(document.getElementById("map"), myOptions);
	//showMapMarkersV3(map, centre);
	/* END V3 */
	
	//alert(1);
	map = new GMap2(document.getElementById("map"));
	//alert(2);
	showMapMarkersV2(map, centre);
}




function showMapMarkersV3(map, centre)
{
	geocoder = new google.maps.Geocoder();
	var markerSize = new google.maps.Size(54, 44);
	var markerOrigin = new google.maps.Point(0, 0);
	var markerAnchor = new google.maps.Point(27, 44);
	var popupSize = new google.maps.Size(200, 130, "px", "px");
		

	var l = Array(5);
	var m = Array(5);
	var w = Array(5);
	var c = Array(5);
	var content = '';
	
	for (var i=0; i < arrBranches.length; i++)
	{
		content = "<div id=\"MapPopup\"><span class=\"MapPopupTitle\">" + arrBranches[i].BranchName + "</span><br />";
		content += arrBranches[i].Address + ", " + arrBranches[i].Postcode + "<br />";
		content += "T: " + arrBranches[i].Tel;
		content += "<p><span class=\"MapPopupDirections\">Get directions:</span><span class=\"MapPopupDirections\">To here</span>From here</p>";
		content += "<p>Start address:<br /><input type=\"text\" name=\"DirectionsFrom\" class=\"MapPopupTextbox\" /> <input class=\"btn\" type=\"image\" src=\"/static/images/btn-go.gif\" alt=\"go\" /></p>";
		content += "</div>";
		c[i] = content;
		w[i] = new google.maps.InfoWindow({ content: c[i], disableAutoPan: false, size: popupSize });
		m[i] = new google.maps.Marker({position: arrBranches[i].Geocode, map: map, icon: new google.maps.MarkerImage('http://elias.emdev.co.uk/static/images/pin' + (i+1) + '.png', markerSize, markerOrigin, markerAnchor), clickable: !centre });

		//google.maps.event.addListener(m[i], 'click', function() {goToBranch('" . $branches[$i]["url"] . "');});
		google.maps.event.addListener(m[i], 'mouseover', function() { var x = parseInt(this["icon"]["Pc"].substr(this["icon"]["Pc"].length-5, 1))-1; w[x].open(map,m[x]); });
//		google.maps.event.addListener(m[i], 'mouseover', function() {showMapPopup(i);});

	}
	map.set_center(arrBranches[ActiveIndex-1].Geocode);

}



function showMapMarkersV2(map, centre)
{
	var markerSize = new GSize(54,44);
	var markerAnchor = new GPoint(27,44);
	var popupSize = new GSize(300,130);
	var infoAnchor = new GPoint(13,44);
	
	var m = Array(5);
	var c = Array(5);
	var icons = Array(5);
	var content = '';
	
	for (var i=0; i < arrBranches.length; i++)
	{
		content = "<div id=\"MapPopup\"><span class=\"MapPopupTitle\">";
		if (centre)
			content += arrBranches[i].BranchName;
		else
			content += "<a href=\"/" + arrBranches[i].Url + "\" title=\"View branch details\">" + arrBranches[i].BranchName + "</a>";
		content += "</span><br />";
		content += arrBranches[i].Address + ", " + arrBranches[i].Postcode + "<br />";
		content += "T: " + arrBranches[i].Tel;
		content += "<p><span class=\"MapPopupDirections\">Get directions:</span><span class=\"MapPopupDirections\">To here</span>From here</p>";
		content += "<p>Start address:<br /><input type=\"text\" id=\"DirectionsFrom\" class=\"MapPopupTextbox\" /> <input class=\"btn\" type=\"image\" src=\"/static/images/btn-go.gif\" alt=\"go\" onclick=\"mapDirections('" + arrBranches[i].GeocodeV2 + "');\" /></p>";
		// arrBranches[i].GeocodeV2 was arrBranches[i].Address.replace("'", "") + ", " + arrBranches[i].Post but this was causing probs as Google keep changing the addresses
		content += "</div>";
		c[i] = content;

		icons[i] = new GIcon();
		icons[i].image = 'http://elias.emdev.co.uk/static/images/pin' + (i+1) + '.png';
		icons[i].iconSize = markerSize;
		icons[i].iconAnchor = markerAnchor;
		icons[i].infoWindowAnchor = infoAnchor;
		
		m[i] = new GMarker(arrBranches[i].GeocodeV2, {icon:icons[i], title:arrBranches[i].BranchName});

		GEvent.addListener(m[i], "mouseover", function() { var x = parseInt(this.getIcon().image.substr(this.getIcon().image.length-5, 1))-1; m[x].openInfoWindowHtml(c[x]); });
		//GEvent.addListener(m[i], 'click', function() {alert('ok');});
		
		map.addOverlay(m[i]);

	}
	if (centre)
		map.setCenter(arrBranches[ActiveIndex-1].GeocodeV2, 15);
	map.setUIToDefault();
	
	directionsPanel = document.getElementById("directions");
	directions = new GDirections(map, directionsPanel);
	GEvent.addListener(directions, "error", handleErrors);
}





function mapDirections(dest) {
  if (document.getElementById('DirectionsFrom').value == "")
  	return;
  var start = document.getElementById('DirectionsFrom').value;
  //alert(dest);
  var geocoder = new GClientGeocoder();
  geocoder.getLatLng(start.replace("'", ""), function(point) {directions.load("from: " + point + " to: " + dest);});
  //alert(dest);
  //alert("from: " + start.replace("'", "") + ", England to: " + dest.replace("'", "") + ", England");
  //DURING TESTING, GOOGLE MAPS WAS DEFAULTING TO USA SO I NEEDED TO ADD 'ENGLAND' TO FORCE THE LOCATION
  //NOW IT IS THROWING AN ERROR WHEN I USE ENGLAND, SO REMOVING IT
  //directions.load("from: " + start.replace("'", "") + ", England to: " + dest.replace("'", "") + ", England");
  
  //alert("from: " + start + " to: " + dest.replace("'", ""));
  //directions.load("from: " + start + " to: " + dest.replace("'", ""));

}



function handleErrors()
{
	if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for the start addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");
	else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.");
	
	else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.");
	
	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	
	else if (directions.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given.");
	
	else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.");
	
	else alert("An unknown error occurred.");

}