var map = null;
var geocoder = null;
var myPano;
var directions;
var directionsPanel;

function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}

function initialize() {
  if (GBrowserIsCompatible()) {
	document.getElementById('search-top').style.display='block';
	document.getElementById('map_canvas').style.display='block';
	map = new GMap2(document.getElementById("map_canvas"));
	map.setCenter(new GLatLng(54.3,-3.4), 5);

	map.removeMapType(G_HYBRID_MAP);
	var mapControl = new GMapTypeControl();
	map.addControl(mapControl);
	var mapControl2 = new GLargeMapControl();
	map.addControl(mapControl2);
	
	geocoder = new GClientGeocoder();
	directionsPanel = document.getElementById("route");
	directions = new GDirections(map, directionsPanel);
  }
}

function addBranches()
{
address = document.forms.searchBranchesForm.address.value;
if (address != '' && address != ' ')// added by MK
{
	// Creates a marker with info window containing htmlText
    function createMarker(point, htmlText) {
      var ybsIcon = new GIcon();
      ybsIcon.image = "http://www.ybs.co.uk/images/your_society/ybs_marker.png";
	  ybsIcon.iconSize = new GSize(39, 39);
	  ybsIcon.iconAnchor = new GPoint(17, 35);
	  ybsIcon.infoWindowAnchor = new GPoint(5, 1);

	// Set up our GMarkerOptions object
      markerOptions = { icon:ybsIcon };
      var marker = new GMarker(point, markerOptions);

      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(htmlText);
		document.getElementById("branchDetails").innerHTML = htmlText; //print only
		document.getElementById("pano").innerHTML = ''; //clears any previous street views
      });
      return marker;
    }
	//Add branches and agencies markers
	GDownloadUrl("./ybs-branches-agencies.xml", function(data) {
	var xml = GXml.parse(data);
	var markers = xml.documentElement.getElementsByTagName("marker");
	var infoText = '';
	for (var i = 0; i < markers.length; i++) {
	  var latlng = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
							  parseFloat(markers[i].getAttribute("lng")));
		//build info box (htmlText variable) - name, address, phone etc
		htmlText = '<h2 class=afterH1 style="margin-bottom: 6px; margin-left: 0px">' + markers[i].getAttribute("name") + ' ' + markers[i].getAttribute("type") + '</h2>';

		//add photo (street view)  //showStreetView(53.796179,-1.542502,103.62,-5.8,0)
		if (markers[i].getAttribute("streetViewLat") && markers[i].getAttribute("streetViewLng") && markers[i].getAttribute("streetViewYaw") && markers[i].getAttribute("streetViewPitch") && markers[i].getAttribute("streetViewZoom"))
		htmlText = htmlText + '<p><a href="#streetView" class="noprint" onclick="showStreetView(' + 
								markers[i].getAttribute("streetViewLat") + ',' +
								markers[i].getAttribute("streetViewLng") + ',' +
								markers[i].getAttribute("streetViewYaw") + ',' +
								markers[i].getAttribute("streetViewPitch") + ',' +
								markers[i].getAttribute("streetViewZoom") + '); return true">Show street view</a></p>';
		if (markers[i].getAttribute("photoBranch"))
		htmlText = htmlText + '<p><a href="#streetView" class="noprint" onclick="showBranchPhoto(\'' + 
								markers[i].getAttribute("photoBranch") + '\'); return true">Show <span style="text-transform: lowercase">' + markers[i].getAttribute("type") + '</span> photo</a></p>';
									
		//add address
		htmlText = htmlText + '<div class="htmlTextColumn1">' +
				  markers[i].getAttribute("address1") + '<br>' +
				  markers[i].getAttribute("address2") + '<br>';
		if (markers[i].getAttribute("address3") != "") htmlText = htmlText + markers[i].getAttribute("address3") + '<br>';
		if (markers[i].getAttribute("address4") != "") htmlText = htmlText + markers[i].getAttribute("address4") + '<br>';
		htmlText = htmlText + markers[i].getAttribute("pc") + '<br>'; 

		//add phone and fax
		if (markers[i].getAttribute("telephone") != "") htmlText = htmlText + '<br>Phone: ' + markers[i].getAttribute("telephone") + '<br>';
		else htmlText = htmlText + '<br>Phone: 0845 1 200 831<br>';
		if (markers[i].getAttribute("fax") != "") htmlText = htmlText + 'Fax: ' + markers[i].getAttribute("fax");
		htmlText = htmlText + '</div>';

		//add opening hours
		htmlText = htmlText + '<div class="htmlTextColumn2">';
		if (markers[i].getAttribute("open") != "") htmlText = htmlText + '<b>Opening times:</b><br>' + markers[i].getAttribute("open") + '<br>';
		if (markers[i].getAttribute("open2") != "") htmlText = htmlText + markers[i].getAttribute("open2") + '<br>';
		if (markers[i].getAttribute("open3") != "") htmlText = htmlText + markers[i].getAttribute("open3") + '<br>';

		//add ATM
		if (markers[i].getAttribute("atm") == "Available") htmlText = htmlText + '<br>ATM available';
		htmlText = htmlText + '</div>';

		//additional info
		if (markers[i].getAttribute("info") != "") htmlText = htmlText + '<br clear=all>' + markers[i].getAttribute("info");

		//directions
	    var toAddress = markers[i].getAttribute("pc");
		htmlText = htmlText + '<br clear=all><div class="directionsContainer"><a href="#" class="noprint" onclick="showDirectionsLayer(); return false">Get directions</a> ';
		var toBranchDetails = markers[i].getAttribute("name") + ' ' + markers[i].getAttribute("type");
		htmlText = htmlText + '<div id="directionsFormLayer">to this <span>' + markers[i].getAttribute("type") + '</span> from: <form id="directionsForm" name="directionsForm" method=get action="#" onsubmit="getDirections(\'' + toAddress + '\', \' ' + toBranchDetails + ' \'); return false"><input type="text" name="directionsTo" id="directionsTo" value="" class="directionsToField"> <input type="image" src="/images/branches/go.gif" value="Go!" class="directionsGoField"></form></div>' +
		'<div class="htmlTextNotes">If this <span style="text-transform: lowercase">' + markers[i].getAttribute("type") + '</span> is not convenient for you and you are ready to apply call <b>0845 1200 831</b></div></div>'; //this.closeInfoWindow(); 
		
	map.addOverlay(createMarker(latlng, htmlText));
	}
});
document.getElementById("pano").innerHTML = ''; //clears any previous street views
}
}


function showAddress(address) {
if (address == '' || address == ' ') alert(address + "Please enter town or postcode."); // added by MK
else {
  	if (address.indexOf("M") == 0 && address.indexOf("1") == 1 && address.indexOf(" ") == 2) // M1 with a space returns M1 motorway near Leicester - fix this
	 {
	  var manchesterBug = new Array();
	  manchesterBug = address.split('M1 ');
	  address = 'M1' + manchesterBug[1];
	 }
  	if (address.indexOf("m") == 0 && address.indexOf("1") == 1 && address.indexOf(" ") == 2)
	 {
	  var manchesterBug = new Array();
	  manchesterBug = address.split('m1 ');
	  address = 'm1' + manchesterBug[1];
	 }
 
if(checkPostCode(address) == false)
addressUK = address + ', UK';
else addressUK = address + ', postcode';

  if (geocoder) {
		  geocoder.getLatLng(
			addressUK,
			function(point) {
			  if (!point) {
				alert(address + " not found");
			  } else {
				map.setCenter(point, 12); 
					  GDownloadUrl("ybs-branches-agencies.xml", function(data) {
					  var xml = GXml.parse(data);
					  var markers = xml.documentElement.getElementsByTagName("marker");
					  var localBranch = 0; //localBranch = 1|0 on the visible map 
					  var sum = 0;
					  localBranches();
						function localBranches() {
						for (var i = 0; i < markers.length; i++) {
						latlng = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
												  parseFloat(markers[i].getAttribute("lng")));
						var bounds = map.getBounds();
						var southWest = bounds.getSouthWest();
						var northEast = bounds.getNorthEast();
						var lngDelta = (northEast.lng() - southWest.lng()) / 19;
						var latDelta = (northEast.lat() - southWest.lat()) / 19;
					
						if ((latlng.lng() > (southWest.lng() + lngDelta)) && 
							(latlng.lng() < (northEast.lng() - lngDelta)) &&
							(latlng.lat() > (southWest.lat() + latDelta)) && 
							(latlng.lat() < (northEast.lat() - latDelta))) {localBranch = 1;}
							else {localBranch = 0;}
							
						sum = sum + localBranch;
						if (sum > 0) i = markers.length; //one local branch found, stop looking
						}
						}
						var zoomNumber = 10;
						//check for branches and zoom out until at least one branch is found
						while (sum == 0) {
						  map.setCenter(point, zoomNumber); 
						  localBranches();
						  zoomNumber = zoomNumber - 1;
						}
				  });
			  }
			}
		  );
		}
	}
}

// Street View
var panoOpts = {
  features: {
    userPhotos: false
  }
};

function showStreetView(streetViewLat,streetViewLng,streetViewYaw,streetViewPitch,streetViewZoom)
{
  document.getElementById('pano').style.display = 'block';
  var myPano = new GStreetviewPanorama(document.getElementById("pano"), panoOpts);
  branchPhoto = new GLatLng(streetViewLat,streetViewLng);
  myPOV = {yaw:streetViewYaw,pitch:streetViewPitch,zoom:streetViewZoom};
  myPano.setLocationAndPOV(branchPhoto, myPOV);
  GEvent.addListener(myPano, "error", handleNoFlash);

/*
var myPano = new GStreetviewPanorama(document.getElementById("pano"), panoOpts);
  branchPhoto = new GLatLng(streetViewLat,streetViewLng);
  myPOV = {yaw:streetViewYaw,pitch:streetViewPitch,zoom:streetViewZoom};
  myPano.setLocationAndPOV(branchPhoto, myPOV);
  GEvent.addListener(myPano, "error", handleNoFlash);
*/
}

function showBranchPhoto(branchPhoto)
{	
  document.getElementById('pano').style.display = 'block';
  document.getElementById("pano").innerHTML = '<img src="../../images/branches/' + branchPhoto + '.jpg">'
}

function handleNoFlash(errorCode) {
  if (errorCode == 603) {
	alert("Error: Flash doesn't appear to be supported by your browser");
	return;
  }
}  
function zoomOut() {
  var bounds = map.getBounds();
  var southWest = bounds.getSouthWest();
  var northEast = bounds.getNorthEast();
  var lngSpan = northEast.lng() - southWest.lng();
  var latSpan = northEast.lat() - southWest.lat();
}

// Directions 
function showDirectionsLayer()
{	  
if (document.getElementById('directionsFormLayer').style.display == 'inline') 
	document.getElementById('directionsFormLayer').style.display='none'
else document.getElementById('directionsFormLayer').style.display='inline';
}
function getDirections(toAddress,toBranchDetails) { 
var fromAddress = document.getElementById('directionsTo').value + ', postcode';
directions.load("from: " + fromAddress + " to: " + toAddress);
	  map.clearOverlays();
	  document.getElementById('directionsHeader').innerHTML = '<h2>Directions to ' + toBranchDetails + '</h2>';

}
//Clear any previous results - street view and directions
function clearResults()
{
directions.clear(); 
map.clearOverlays();
document.getElementById("pano").innerHTML = '';
document.getElementById('directionsHeader').innerHTML = '';
}

