var map;
var geocoder;
var lat;
var lng;
var selectedStore;
var gdir;
var forceOverride;
var the_address;
var homePoint;
var destinationLatLong = ''; //Added by Paul 3/9/2008 as the destination when showing directions
var destinationStoreId = '0'; //Added by Paul 5/9/2008 as the destination store ID number when showing directions
var askForPostCode = true; //Whether or not to ask the user for a post code (when from branch locator or town search), added by Paul 3/9/2008
var uri;
var GLaddress;
var is_local = 0;  //stores locally found lng/lat results

//var mgr;
var inputLoc;
var number=1;


function asciivals(s)
{
    var r = '';
    for (var i = 0; i < s.length; i++) {
        r += "&#" + s.charCodeAt(i) + ";";
    }
    return r;
} 


function load()
	{
	//alert("load");//MS:
	if (GBrowserIsCompatible())
		{
		geocoder = new GClientGeocoder();
		geocoder.setBaseCountryCode("UK");
		
		map = new GMap2(document.getElementById('google_map'));
		map.setCenter(new GLatLng(51.7, -2), 7);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		
		gdir = new GDirections(map, $('directions_panel'));
		GEvent.addListener(gdir, "error", handleErrors);
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		mgr = new GMarkerManager(map);
		
		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
		baseIcon = new GIcon();
		baseIcon.shadow = "/images/store_finder/Storeflagshadow.png";
		baseIcon.iconSize = new GSize(100, 64);
		baseIcon.shadowSize = new GSize(100, 64);
		baseIcon.iconAnchor = new GPoint(0, 64);
		baseIcon.infoWindowAnchor = new GPoint(50,0);
		baseIcon.infoShadowAnchor = new GPoint(50,0);
		}
	}


function searchClean(address)
	{
	//alert("searchClean");//MS:
	clearUri();
	if(address)
		{
		searchLocations(address);
		}
	}


latTo=''
firstSearch=true;
lngTo=''
directionsChecked=false;


//There seem to be three ways of calling this function:
//1) by clicking on a store branch in the Flash map (calls the map page with latitude and longitude)
//2) by filling in the search form in the top right, or on top of the map (ends up calling checkLocally below)
//3) from the contact us section, by clicking on a branch name when it already knows your post code (calls load_store below - DISABLED 10/9/2008 - uses method 1 instead)
//4) From the "get directions" link in the contact section, which passes in #lat and #lon and runs checkLocally below
//5) from a "head office" link in the bottom right of the contact us page (calls laod_store below - DISABLED 15/9/2008)
//The load_store method doesn't work as store_finder_google.php does not call searchLocations in that instance. I'm not sure why so I haven't reenabled it.
function searchLocations(address)
	{
	//alert("searchLocations");//MS:
	hide_directions()
	showLoading();
	//var address = document.getElementById('addressInput').value;
	GLaddress=address;
	
	the_address = address;
	startZoom = '';//MS: Added to provide a non Flash search case
	headoffice = false;//MS: 2008.10.03: Added to help filter Head Office
	showspraystoreonly = false;//MS: 2008.10.14: Added to help filter Spraystore only branches
	
	$('searchQuery').innerHTML=address;
	//alert(is_local);
	var loc = document.location.toString();
	var hash = loc.indexOf('#');
     
	if(hash > 0 && !forceOverride && firstSearch)
		{
		var hashdirections = loc.indexOf('#lat');
		if(hashdirections > 0)
			{
			latTo=(loc.substr(loc.indexOf('#lat=')+5,(loc.length-loc.indexOf('lng'))-6));
			lngTo=(loc.substr(loc.indexOf('lng')+4));
			the_address='';
			checkLocally(address);
			}
     	else
     		{ //This is run when it comes from Flash, passing in startlat
			var hashdstart = loc.indexOf('#startlat');
			if(hashdstart > 0)
				{
				//alert("hashdstart");//MS
				the_address = '';
				querystring = (loc.substr(loc.indexOf('#startlat=')+10));
				startLat = querystring.substr(0,querystring.indexOf('&startlng='));
				querystring = (querystring.substr(querystring.indexOf('&startlng=')+10));
				startLng = querystring.substr(0,querystring.indexOf('&start'));
				
				if ((querystring.indexOf('&ho') == -1) && ((querystring.indexOf('&ss') == -1)))//MS: 2008.10.03: Added to filter out Head Office & Spraystore only
					{
					startZoom = (querystring.substr(querystring.indexOf('&startzoom=')+11));//MS: original startZoom code for non HO & Spraystore links
					}
				else
					{
					if (querystring.indexOf('&ho') != -1)
						{
						//MS: Adapted code to allow for extra HO link string
						querystring = (querystring.substr(querystring.indexOf('&startzoom=')+11));
						startZoom = querystring.substr(0,querystring.indexOf('&ho'));
						headoffice = true;
						}
					if (querystring.indexOf('&ss') != -1)
						{
						//MS: Adapted code to allow for extra Spraystore only link string
						querystring = (querystring.substr(querystring.indexOf('&startzoom=')+11));
						startZoom = querystring.substr(0,querystring.indexOf('&ss'));
						showspraystoreonly = true;
						}
					}			
				
				map.setCenter(new GLatLng(startLat,startLng), parseFloat(startZoom));
				//setTimeout('searchLocationsNear(map.getCenter());',5000);//MS: Not sure why this should be a timeout
				searchLocationsNear(map.getCenter(), true); //Pass in true so that it knows that it has come from Flash, Palu 5/9/2008
				}
			else
				{
				//alert("calling load_store");//MS
				var store = loc.substr(hash + 1);
				load_store(store); //This is run when a branch is passed in after the # directly (currently on the head office link on the contact us page) //MS 2008.10.03: NOT TRUE! Doesn't get used by head office link anymore
     			}
			}
     	}
     else
     	{
     	checkLocally(address);
     	}
	}


function checkGoogle()
	{
	//alert("checkGoogle");//MS:
	address=document.getElementById('search').value;
	//geocoder.getLatLng(the_address+'', function(latlng)// MS: original code
	geocoder.getLatLng(the_address+''+' UK', function(latlng)// MS: added to bias non postcode searches to UK
		{
		if (!latlng)
			{
			alert('The location \''+address + '\' was not found \n please try another search');
			document.getElementById('searchHeader').style.display='none';
			hideLoading();
			}
		else
			{
			lat=0;
			lng=0;
			document.getElementById('searchHeader').style.display='block';
			searchLocationsNear(latlng);
			}
		});
 
     document.getElementById('searchQuery').innerHTML=address;
	  
	if(address==savedLocation)
    	{
     	document.getElementById('remember').checked=true;
    	}
    else
    	{
		document.getElementById('remember').checked=false;
		}
	}


function checkLocally(postcode)
	{
	//alert("checkLocally");//MS:
	response = 0;
	var uri = '/postcode_search/?q=' + postcode;

	//The code below seems to look in the database for the post code and then zoom to that point on the Google map
	//or call checkGoogle above passing in a location (not a post code).
	GDownloadUrl(uri,function(data) {
		if(data != '0')
			{
			var xml = GXml.parse(data);
			var results = xml.documentElement.getElementsByTagName('result');
			var point = new GLatLng(parseFloat(results[0].getAttribute('lng')),parseFloat(results[0].getAttribute('lat')));
			askForPostCode = false; //We do not need to ask for a post code as we already know it (Paul 3/9/2008)
			searchLocationsNear(point);
			$('searchHeader').style.display='block';
			}
		else checkGoogle();
		});
	}

//This method is now only used by the head office link on the contact us page, by Paul 15/9/2008
function load_store (store) {
	//alert("load_store");// MS
	var searchUrl = '/get_store_data/?store=' + store;
	GDownloadUrl(searchUrl, function(data) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName('marker');
		map.clearOverlays();
		var sidebar = document.getElementById('store_list_ul');
		sidebar.innerHTML = '';

		if (markers.length == 0)
			{
			sidebar.innerHTML = "<p>That store couldn't be found</p>";
			map.setCenter(new GLatLng(51.7, -2), 7);
			
			hideLoading()
			return;
			}
		var bounds = new GLatLngBounds();
		
		var name = markers[0].getAttribute('name');
		var address = markers[0].getAttribute('address');
		var distance = 0;
		var point = new GLatLng(parseFloat(markers[0].getAttribute('lng')), parseFloat(markers[0].getAttribute('lat')));
		var notes = markers[0].getAttribute('notes');
		
		var marker = createMarker(point, name, address,distance,notes,markers[0]);
		mgr.addMarker(marker,9,17);
		
		var sidebarEntry = createSideBarEntry(marker, name, address, distance,markers[0]);
		sidebar.appendChild(sidebarEntry);
		bounds.extend(point);
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
		//GEvent.trigger(marker, 'click');
		});
	}

//fromflash argument added by Paul 5/9/2008 so it knows it has come from Flash
function searchLocationsNear(center, fromflash)
	{
	//alert("searchLocationsNear");//MS:
	number=1;
	lat=center.lat();
	lng=center.lng();
	homePoint = center;
	sidebarLimit = 5;
   	   
	var searchUrl = '/get_stores/?lat=' + center.lat() + '&lng=' + center.lng();
	GDownloadUrl(searchUrl, function(data) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName('marker');
		map.clearOverlays();

		var sidebar = document.getElementById('store_list_ul');
		sidebar.innerHTML = '';

		if (markers.length == 0)
			{
			map.setCenter(new GLatLng(51.7, -2), 7);
			return;
			}

		setLocation(address);
		
		var bounds = new GLatLngBounds();		
		for (var i = 0; i < markers.length; i++)
			{
			
			//MS: 2008.10.03: Added to skip Head Office in general searches.
			if (!headoffice && markers[i].getAttribute('code') == 'HOF')
				{
				i++;//Skip to next marker
				sidebarLimit++;//Adjusts sidebarLimit if Head Office is in the sidebar results
				}
				
			//MS: 2008.10.14: Added to skip Spraystore only branches unless clicked directly from the Flash map
			if (markers[i].getAttribute('spraystore') == '1' && !showspraystoreonly)
				{
				i++;//Skip to next marker
				sidebarLimit++;//Adjusts sidebarLimit if any Spraystore the sidebar results
				}
			
			var name = markers[i].getAttribute('name');
			var address = markers[i].getAttribute('address');
			var distance = parseFloat(markers[i].getAttribute('distance'));
			var point = new GLatLng(parseFloat(markers[i].getAttribute('lng')), parseFloat(markers[i].getAttribute('lat')));
			var notes = markers[i].getAttribute('notes');
			var marker = createMarker(point, name, address,distance,notes,markers[i]);
			mgr.addMarker(marker,9,17);
			//if (fromflash && i==0 && marker.contenthtml) marker.openInfoWindowHtml (marker.contenthtml); //Added by Paul 5/9/2008 to open up the first one automatically if from Flash
			if (fromflash && i==0)
				{
				GEvent.trigger (marker, 'click'); //Changed to this by Paul 12/9/2008 as it seems to be the preferred way of doing things
				}
			if(i < sidebarLimit)
				{
				var sidebarEntry = createSideBarEntry(marker, name, address, distance,markers[i], fromflash && i==0); //Last argument added by Paul 12/9/2008
				sidebar.appendChild(sidebarEntry);
				//bounds.extend(point);
				}
			number++;
			
			//MS: 2008.10.03: Added to create Head Office only Google map
			if (headoffice)
				{
				break;
				}
			}
		
		//if (startZoom == '')//MS: Stops pointer being added from Flash map
		if (!fromflash)//MS: Stops pointer being added from Flash map MS: 2008.10.03: Adapted to use Pauls fromflash argument
			{
			var homeMarker = createStartMarker(center,inputLoc);
			//map.addOverlay(homeMarker);
			mgr.addMarker(homeMarker,9,17);
			}
		bounds.extend(center);
       
		//alert(bounds.getCenter());
		//if (startZoom != '')
		if (fromflash)// MS: 2008.10.03: Adapted to use Pauls fromflash argument
			{
			map.setCenter(bounds.getCenter(), startZoom);//MS: Sets map to startZoom when searching from Flash map
			startZoom = '';
			}
		else
			{
			map.setCenter(bounds.getCenter(), 15);//MS: this one resets the map center/size after each search, zoom level increased by Paul 12/9/2008
			}
       
		//setTimeout('hideLoading()',3500);//MS: Not sure why this is on a timeout but it's faster and more reliable without
		hideLoading();
		});
     
	Effect.BlindDown('store_list',{duration:.3});
	}
   
function createStartMarker(point,name)
	{
	//alert("createStartMarker");//MS:
   	if(!name)
		{
		name=the_address;
		}
   	
	var marker = new GMarker(point);
	var html = '<b>' + name + '</b>';
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
		});
	return marker;
	}


//This is called each time a marker should be displayed on the map. 
function createMarker(point, name, address,distance,notes,fullMarker)
	{
	//alert("number = "+number+"\npoint = "+point+"\nname = "+name+"\naddress = "+address+"\ndistance = "+distance+"\nnotes = "+notes+"\nfullMarker = "+fullMarker);
	//alert("createMarker");//MS:
    var brewers_icon = new GIcon(baseIcon);
    	
	//Next line added by Paul 3/9/2008 to show Brewers logo when the spraystore parameter is 2. This image can be changed.
	if(fullMarker.getAttribute('spraystore')=='2') {brewers_icon.image = "/images/Storeflag.png";}
	else if(fullMarker.getAttribute('spraystore')=='1') {brewers_icon.image = "/images/spraystoreflag.png";}
	else {brewers_icon.image = "/images/Storeflag.png";}
    	
	var markerOptions  = { icon:brewers_icon }; 
	var marker = new GMarker(point,markerOptions);
	//var html = '<h4>' + fullMarker.getAttribute('name') + ' ' + fullMarker.getAttribute('city') +  '</h4><p><small>' + address+'</small></p><p style="padding-bottom:15px;padding-top:5px;"><a href="http://maps.google.co.uk/maps?saddr='+savedLocation+',UK&daddr='+fullMarker.getAttribute('postcode')+',UK" target="_blank">Get directions</a></p>';
	//var html = '<h4>' + fullMarker.getAttribute('name') + ' ' + fullMarker.getAttribute('city') +  '</h4><p><small>' + address+'</small></p><p style="padding-bottom:15px;padding-top:5px;"><a href="javascript:;" onclick="get_directions(\''+fullMarker.getAttribute('lng')+','+fullMarker.getAttribute('lat')+'\',\''+fullMarker.getAttribute('id')+'\');">Get directions</a></p>';
      
	var html = '<div class="address" style="height:19em;">';
	html += '<h4 style="font-size:1.2em;font-weight:bold;">'+fullMarker.getAttribute('name')+' '+fullMarker.getAttribute('city')+'</h4>';
	//html += '</p><div id="more'+(number-1)+'" style="padding-top:3px;margin-top:3px;border-top:10px solid #CCC">';
	html += '<div id="more'+(number-1)+'" style="padding-top:3px;margin-top:3px;border-top:1px solid #CCC;"></div>';

	if(fullMarker.getAttribute('parking') == 1) html +=' <div class="parking"><img src="images/icons/parking.png" alt="Parking available" /></div>';
	html += '<p style="font-size:1em;">'+ address +'</p>';
	//needed for when we ask for post code below, added by Paul 3/9/2008
	var branchlatlon = fullMarker.getAttribute('lng')+','+fullMarker.getAttribute('lat');
	html += '<form method="get" action="#" onsubmit="get_directions_between(\''+branchlatlon+'\',this.pc.value,\''+fullMarker.getAttribute('id')+'\');return false;" style="display:inline;margin:0;padding:0;">'; 
	html += '<p style="padding-top:6px;margin-top:3px;border-top:1px solid #CCC;font-size:1em;">';
	if (askForPostCode) { //When a post code was put in then output the Show Directions stuff or else ask for a post code
		html += '<strong>To get directions</strong> please enter your postcode:</p><p style="padding:6px 0px;"><input name="pc" type="text" size="10" maxlength="10" class="text_input" /> ';
		html += '<input type="submit" value="Go" /></span>';
	} else {
		html += '<a href="javascript:;" onclick="get_directions(\''+branchlatlon+'\',\''+fullMarker.getAttribute('id')+'\');">Show directions</a>';
		html += ' | <a href="javascript:;" onclick="print_directions(\''+branchlatlon+'\',\''+fullMarker.getAttribute('id')+'\');">Print directions</a>';
	}
	html += '</p></form></div>'; //form closing tag needed for asking for post code above, added by Paul 3/9/2008
	marker.contenthtml = html; //Added by Paul 5/9/2008 to store the HTML
	
	GEvent.addListener(marker, 'click', function() {
		//alert('opening window');
		marker_temp = marker;//MS 2008.10.07: Added to temp store marker for use with setTimout
		html_temp = html;//MS 2008.10.07: Added to temp store html for use with setTimout
		
		setTimeout("marker_temp.openInfoWindowHtml(html_temp)", 2);//MS 2008.10.07: Added to allow map to render before opening info window
		//marker.openInfoWindowHtml(html);
      	});
	return marker;
    }
    

//Last argument added by Paul 5/9/2008 to say whether it should be open by default
function createSideBarEntry(marker,name,address,distance,fullMarker,openit)
	{
	//alert("createSideBarEntry");//MS:
	var li = document.createElement('li');
	var current=number;
	if(distance) distance = '(' + distance.toFixed(1) + ' miles)';
	else distance = '';
	var html =  '<div class="address">';
	html += '<h4 class="title"><span class="small">'+number+'.</span> ';
	html += '<a href="javascript:;"><b>'+fullMarker.getAttribute('city')+'</b></a> <span class="small" style="font-size:11px;">' + distance + '</span></h4>';
	html +='<h4 style="font-size:1.2em;"><strong>Tel:</strong> '+fullMarker.getAttribute('phone')+'</h4>';
	if (fullMarker.getAttribute ('fax')) html += '<h4 style="font-size:1.2em;"><strong>Fax:</strong> '+fullMarker.getAttribute('fax')+'</h4>';
	if (fullMarker.getAttribute('code') == 'PNY') { // MS: temporary fix for Putney opening times
	   html += '<div class="hr"></div><p><b>Open</b><br /><small>Mon - Thu ' + fullMarker.getAttribute('hoursweek');
	   html += '<br />Fri 7.30am &mdash; 4.00pm';
    } else {
	   html += '<div class="hr"></div><p><b>Open</b><br /><small>Mon - Fri ' + fullMarker.getAttribute('hoursweek');
    }
  		
	if(fullMarker.getAttribute('hourssaturday').substr(0,1)!='.') {html=html+'<br/>Saturday '+ fullMarker.getAttribute('hourssaturday');}
	if(fullMarker.getAttribute('hourssunday').substr(0,1)!='.') {html=html+'<br/>Sunday '+ fullMarker.getAttribute('hourssunday');}
	if (fullMarker.getAttribute('notes')) html += '<br /><span class="branch_notes">' + fullMarker.getAttribute ('notes') + '</span>'; //Notes added by Paul 3/9/2008 //MS 2008.10.01: Added span and class so they can be styled
	html += '</small>';
	//html=html+'</p><div id="more'+(number-1)+'" style="display:none"><div class="hr"></div>';
	html=html+'</p><div id="more'+(number-1)+'"' + (openit ? '' : ' style="display:none"') + '><div class="hr"></div>'; //openit argument added by Paul 5/9/2008 to open up first one
	if(fullMarker.getAttribute('parking') == 1) html +=' <div class="parking"><img src="images/icons/parking.png" alt="Parking available" /></div>';
	html += '<p>'+ address +'</p><div class="hr"></div>';
		
	if (fullMarker.getAttribute('managervisible')) {
		if (fullMarker.getAttribute('contact')!='') {
			html=html+'<p><small>Branch Manager: </small><b>'+ fullMarker.getAttribute('contact') +'</b></p><div class="hr"></div>';
        }
    }
			
	//html=html+'<p>';

	if (fullMarker.getAttribute('retail_cat')!='') {
        html += '<p>' + fullMarker.getAttribute('retail_cat') + '</p>';
    }
	
	//fullMarker.getAttribute('notes') +'</p></div>'; //This statement was here but didn't do anything so I commented it 8/10/2008
	//html += '</p>';
	
	// email addresses for Brewers intranet users only
	if (bi) { // if we've come via Brewers intranet

        // check if any emails exist
    	var email_exists   = false;
    	var rep_count      = 0;
    	if (fullMarker.getAttribute('branch_email') != undefined)  { email_exists = true; var branch_email = fullMarker.getAttribute('branch_email'); }
    	if (fullMarker.getAttribute('admin_email') != undefined)   { email_exists = true; var admin_email = fullMarker.getAttribute('admin_email'); }
    	if (fullMarker.getAttribute('m2_email') != undefined)      { email_exists = true; var m2_email = fullMarker.getAttribute('m2_email'); }
    	if (fullMarker.getAttribute('rep1_email') != undefined)    { email_exists = true; var rep1_email = fullMarker.getAttribute('rep1_email'); rep_count++; }
    	if (fullMarker.getAttribute('rep2_email') != undefined)    { email_exists = true; var rep2_email = fullMarker.getAttribute('rep2_email'); rep_count++; }
    	if (fullMarker.getAttribute('rep3_email') != undefined)    { email_exists = true; var rep3_email = fullMarker.getAttribute('rep3_email'); rep_count++; }
    	if (fullMarker.getAttribute('rep4_email') != undefined)    { email_exists = true; var rep4_email = fullMarker.getAttribute('rep4_email'); rep_count++; }
	
	
    	if (email_exists) { // if at least one email exists
            //html += '<p><strong>Branch email</strong></p>';
            
            if (branch_email != undefined) { // if the branch email exists
                html += '<p><small>Branch:<br />';
                html += '<a href="' + asciivals('mailto:' + branch_email) + '"><strong>' + asciivals(branch_email) + '</strong></a></small></p>';
            }
            
            if (admin_email != undefined) { // if the admin email exists
                html += '<p><small>' + fullMarker.getAttribute('city') + ' admin:<br />';
                html += '<a href="' + asciivals('mailto:' + admin_email) + '"><strong>' + asciivals(admin_email) + '</strong></a></small></p>';
            }
            
            if (m2_email != undefined) { // if the M2 branch manager email exists
                html += '<p><small>M2 Branch Manager:<br />';
                html += '<a href="' + asciivals('mailto:' + m2_email) + '">';
                html += (fullMarker.getAttribute('m2_name') != undefined) ? '<strong>' + fullMarker.getAttribute('m2_name') + '</strong>' : asciivals(m2_email);
                html += '</a></small></p>';
            }
            
            if (rep_count) { // if one of the rep emails exists
                html += '<p><small>Rep' + ((rep_count > 1) ? 's' : '') + ':</small>';
                
                if (rep1_email != undefined) { // if the rep1 email exists
                    html += '<br /><small>';
                    html += '<a href="' + asciivals('mailto:' + rep1_email) + '">';
                    html += (fullMarker.getAttribute('rep1_email') != undefined) ? '<strong>' + fullMarker.getAttribute('rep1_name') + '</strong>' : asciivals(rep1_email);
                    html += '</a></small>';
                }
                
                if (rep2_email != undefined) { // if the rep2 email exists
                    html += '<br /><small>';
                    html += '<a href="' + asciivals('mailto:' + rep2_email) + '">';
                    html += (fullMarker.getAttribute('rep2_email') != undefined) ? '<strong>' + fullMarker.getAttribute('rep2_name') + '</strong>' : asciivals(rep2_email);
                    html += '</a></small>';
                }
                
                if (rep3_email != undefined) { // if the rep3 email exists
                    html += '<br /><small>';
                    html += '<a href="' + asciivals('mailto:' + rep3_email) + '">';
                    html += (fullMarker.getAttribute('rep3_email') != undefined) ? '<strong>' + fullMarker.getAttribute('rep3_name') + '</strong>' : asciivals(rep3_email);
                    html += '</a></small>';
                }
                
                if (rep4_email != undefined) { // if the rep4 email exists
                    html += '<br /><small>';
                    html += '<a href="' + asciivals('mailto:' + rep4_email) + '">';
                    html += (fullMarker.getAttribute('rep4_email') != undefined) ? '<strong>' + fullMarker.getAttribute('rep4_name') + '</strong>' : asciivals(rep4_email);
                    html += '</a></small>';
                }
            }
            
            html += '</p><div class="hr"></div>'; // close the email section
        }
	}
	
	//Added by Paul 8/10/2008 to show the print details link
	html += '<p><small><a href="javascript:;" onclick="print_details(' + fullMarker.getAttribute('id') + ');">Print details of this branch</a></small></p></div>';
	li.innerHTML = html;
	li.id='list'+(number-1);

	li.style.cursor = 'pointer';
	li.style.marginBottom = '5px';
	if (openit) {li.style.backgroundColor = '#e6eff7';selectedStore = 1;}//MS 2008.10.06: Added to colour initial box when clicking through from Flash
					
	GEvent.addListener(marker,'click',function() {
		//alert('marker click - showing details');
		showDetails(current,fullMarker);
		});
	GEvent.addDomListener(li, 'click', function() {
		//showDetails(current,marker);
		
		if(current != selectedStore)
			{
			//alert("DOM clicked");
			currentCenter=map.getCenter();
			newCenter=marker.getLatLng();
			differenceX=Math.max(currentCenter.lat(),newCenter.lat())-Math.min(currentCenter.lat(),newCenter.lat());    // 
			differenceY=Math.max(currentCenter.lng(),newCenter.lng())-Math.min(currentCenter.lng(),newCenter.lng());
			distance=(Math.sqrt( differenceX*differenceX)+(differenceY*differenceY));
			
			//alert(distance);
			//if(distance>0.5)
			//if(distance>0.2)//MS: made it more sensitive
			//	{
				map.panTo(newCenter);// MS: Centres map regardless of movement distance
			//	}
			GEvent.trigger(marker, 'click');
			//alert("firing");
			//showDetails(current,marker);
			}
		});
	GEvent.addDomListener(li, 'mouseover', function() {
		if(current != selectedStore) li.style.backgroundColor = '#eee';
		});
	GEvent.addDomListener(li, 'mouseout', function() {
		if(selectedStore != current) li.style.backgroundColor = '#fff';
		});
		
	return li;
	}
    

function showDetails(show,fromMarker)
	{
	//alert("showDetails");//MS:
	//alert("show = " + show + "\nfromMarker = " + fromMarker);
	selectedStore = show;
	set_uri(fromMarker);
    	
	for(i=0;i<5;i++)
		{
		id=('more'+i)
		
		if(show!=(i+1))
			{
			new Effect.BlindUp(id,{duration:.3});
			$('list'+i).className = 'norm';
			$('list'+i).style.backgroundColor = '#FFF';
    		}
		else
    		{
			new Effect.BlindDown(id,{duration:.3});
			$('list'+i).className = 'selectedStore';
			//$('list'+i).style.backgroundColor = '#f4f8fc';/*MS 2008.10.01: Original colour */
			$('list'+i).style.backgroundColor = '#e6eff7';/*MS 2008.10.01: New colour changed at Simon Brewer's request*/
    		}
    	}
    	
	//if(fromMarker)
	//	{
		//alert(fromMarker);
		//GEvent.trigger(fromMarker, 'click');
	//	}
	}
    

function set_uri(fromMarker)
	{
	//if(fromMarker) alert(fromMarker.getAttribute('name') + '+' + fromMarker.getAttribute('city'));
	//if(uri.charAt(uri.length - 1) != '/') uri += '/';
	//document.location = uri + '#' + fromMarker.getAttribute('name') + '+' + fromMarker.getAttribute('city');
    }
    

function clearUri()
	{
	//What does this do? - Robin
	document.location = uri;
	forceOverride = 1;
	selectedStore = '';
	}
    



//This function was added by Paul 3/9/2008 to get directions from a place rather than lat/lng. First it runs the local
//version and then the Google code. It is a copy and paste of the checkLocally and checkGoogle functions above. It 
//could have been done better, but I wanted to get it working quickly.
function get_directions_between (branch, postcode, storeid) {
	var uri = '/postcode_search/?q=' + postcode;
	GDownloadUrl(uri,function(data) {
		if(data != '0') {
			var xml = GXml.parse(data);
			var results = xml.documentElement.getElementsByTagName('result');
			homePoint = new GLatLng(parseFloat(results[0].getAttribute('lng')),parseFloat(results[0].getAttribute('lat')));
			get_directions (branch, storeid);
		} else {
			geocoder.getLatLng (postcode+''+' UK', function(latlng) {
				if (!latlng) alert('The location \''+address + '\' was not found.\nPlease enter another post code.');
				else {homePoint = latlng; get_directions (branch, storeid);}
			});
		}
	});
}

function get_directions (from, storeid)
	{
	askForPostCode = false; //We do not need to ask for a post code the next time as now we know it - doesn't work as createMarker is not called again! (Paul 3/9/2008)
	destinationLatLong = from; //this is the destination for the directions, used to show the "Print Directions" link, added by Paul 3/9/2008
	destinationStoreId = storeid; //this is the destination store ID number, used to show the "Print Directions" link, added by Paul 3/9/2008
	//alert("get_directions");//MS:
	//MS: 'from' is a string: 'longitude,latitude'
	gdir.load("from: " + homePoint.lat() + "," + homePoint.lng() + " to: " + from);
    }


function print_directions(from, storeid)
	{
	//alert("print_directions");//MS:
	if (!from) from = destinationLatLong; //if it has not been set (when the click the link on the left), then retrieve from the variable set above, added by Paul 3/9/2008
	if (!storeid) storeid = destinationStoreId; //if it has not been set (when the click the link on the left), then retrieve from the variable set above, added by Paul 5/9/2008
	window.open('/branch-locator/print-directions/?to='+homePoint.lat()+","+homePoint.lng()+"&from="+from+"&store="+(storeid?storeid:0));
	}
	

//Added by Paul 8/10/2008 to print details of this branch
function print_details(storeid)
	{
	if (storeid > 0) window.open('/branch-locator/print-details/?store='+storeid);
	}
	

function hide_directions()
	{
	//alert("hide_directions");//MS:
	$('store_list').style.display="block";
	$('directions_panel').style.display="none";
	$('directions_title').style.display="none";
	}
    

function setLocation(newLocation)
	{
	//alert("setLocation");//MS:
	new Ajax.Request('/set_location/',{parameters:'location='+the_address+'&lat='+lat+'&lng='+lng,method:'get'});
	savedLocation=newLocation;
    }
    

function onGDirectionsLoad()
	{
	//alert("onGDirectionsLoad");//MS:
	$('store_list').style.display="none";
	$('directions_panel').style.display="block";
	$('directions_title').style.display="block";
    }
    

function handleErrors()
	{
	//alert("handleErrors");//MS:
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	
	else if (gdir.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.\n Error code: " + gdir.getStatus().code);
	
	else if (gdir.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.\n Error code: " + gdir.getStatus().code);

	//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 (gdir.getStatus().code == G_GEO_BAD_KEY)
	alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	else alert("An unknown error occurred.");
	}
    
    
    
function showLoading()
	{
	//alert("showLoading");//MS:
	document.getElementById('searchBoxGoogle').style.display='none';
	new Effect.Appear('smallLoadingSymbol', {'duration':0.3});
	HideSideBar();
	//document.getElementById('smallLoadingSymbol').style.display='block';
	}
    
    
function hideLoading()
	{
	//alert("hideLoading");//MS:
	firstSearch=false;
	document.getElementById('smallLoadingSymbol').style.display='none';
	new Effect.Appear('searchBoxGoogle', {'duration':0.3});
	//document.getElementById('searchBoxGoogle').style.display='block';
	 
	showSideBar();
		
	if(latTo!='' && directionsChecked==false)
		{
		get_directions(latTo+','+lngTo);
		directionsChecked=true;
		}
	else
		{
		map.setCenter(lat,lng,6);//MS: Why?
		}
	map.setZoom(3);//MS: Why?
	}

    
function showSideBar()
	{
	//alert("showSideBar");//MS:
	new Effect.BlindDown('store_list_ul', {'duration':0.4});
	new Effect.Appear('store_list_ul', {'duration':0.3});
	//document.getElementById('store_list_ul').style.display='block';
	}


function HideSideBar()
	{
	//alert("HideSideBar");//MS:
	new Effect.BlindUp('store_list_ul', {'duration':0.4});
	new Effect.Fade('store_list_ul', {'duration':0.3});
	//document.getElementById('store_list_ul').style.display='none';
	}
