//
//	AJAX - addEvent - Cookie - Error Handling
//

/* dependencies:
		sf.asp?Lat='+Lng+'&Lng='+Lat+'&Rad='+fRadius+'&storeType='+storeType
		getCentreFromBranchID.asp?branchID=
		directDesk.asp?branchID=
		busPDF.aspx?branchID=
		christmas.asp?branchID= - removed

		get.store.info.asp?bID=

		hours.open.pharmacy.asp?bID=
		hours.open.optician.asp?bID=
		hours.open.cafe.asp?bID=
		hours.open.directdesk.asp?bID=
		hours.open.telecoms.asp?bID=

		hours.open.easter.asp?bID=
		hours.open.bh.mayday.asp?bID=
		hours.open.bh.may.asp?bID=
		hours.open.bh.aug.asp?bID=
		hours.open.christmas.asp?bID=
*/


function addEvent( obj, type, fn ){
	if (obj.addEventListener){
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent){
		obj["e"+type+fn]=fn;
		obj[type+fn]=function(){ obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type]=obj["e"+type+fn];
	}
}

var EventCache=function(){
	var listEvents=[];
	return {
		listEvents:listEvents,
		add:function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush:function(){
			var i, item;
			for(i=listEvents.length - 1; i >= 0; i=i - 1){
				item=listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				}
				if(item[1].substring(0, 2) != "on"){
					item[1]="on" + item[1];
				}
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				}
				item[0][item[1]]=null;
			}
		}
	};
}();


var AJAX={
	http:Object,
	httpCookie:Object,
	httpStore:Object,
	httpChristmas:Object,
	httpChristmas2:Object,
	httpDirectDesk:Object,
	httpBusPDF:Object,
	ro:Object,
	createRequestObject:function(){
		var browser=navigator.appName;
		if(browser=="Microsoft Internet Explorer"){
			AJAX.ro=new ActiveXObject("Microsoft.XMLHTTP");
		}else{
			AJAX.ro=new XMLHttpRequest();
		}
		return AJAX.ro;
	},
	sndReq:function(Lng,Lat,fRadius,storeType){
		try{
			AJAX.http=AJAX.createRequestObject();
//			alert(storeType)
			AJAX.http.open('get','sf.asp?Lat='+Lng+'&Lng='+Lat+'&Rad='+fRadius+'&storeType='+storeType,true);
			AJAX.http.onreadystatechange=AJAX.handleResponse;
			AJAX.http.send(null);
		}catch (error){ }
	},
	handleResponse:function(){
		try{
			if(AJAX.http.readyState==4){
				var response=AJAX.http.responseText;
				storeFinder.json=response;
				storeFinder.handleResults();
			}
		}catch (error){ }
	},

	sndReqCoord:function(Lng,Lat,fRadius,storeType){
		try{
			AJAX.httpCoord=AJAX.createRequestObject();
			AJAX.httpCoord.open('get','sf.asp?Lat='+Lng+'&Lng='+Lat+'&Rad='+fRadius+'&storeType='+storeType,true);
			AJAX.httpCoord.onreadystatechange=AJAX.handleCoord;
			AJAX.httpCoord.send(null);
		}catch (error){ }
	},
	handleCoord:function(){
		try{
			if(AJAX.httpCoord.readyState==4){
				var response=AJAX.httpCoord.responseText;
				storeFinder.json=response;
				storeFinder.handleResultsCoord();
			}
		}catch (error){ }
	},

/* I don't think this is used (couldn't find a reference to: getCookieCentre)*/
	getCookieCentre:function(branchID){
		try{
			AJAX.httpCookie=AJAX.createRequestObject();
			AJAX.httpCookie.open('get','getCentreFromBranchID.asp?BranchID='+branchID,true);
			AJAX.httpCookie.onreadystatechange=AJAX.handleCookieCentre;
			AJAX.httpCookie.send(null);		
		}catch (error){ }
	},
	handleCookieCentre:function(){
		try{
			if(AJAX.httpCookie.readyState==4){
				var response=AJAX.httpCookie.responseText;
				
				var aSplit=response.split('|');					
				if (aSplit){
					storeFinder.map.setCenter(new GLatLng(aSplit[0], aSplit[1]), 12);
				}
				storeFinder.handleResults();
			}
		}catch(error){ }
	},


	getMoreStoreInfo:function(branchID){
		try{			
			AJAX.httpStore=null;
			AJAX.httpStore=AJAX.createRequestObject();
			AJAX.httpStore.open('get','get.store.info.asp?bID='+branchID,true);
			AJAX.httpStore.onreadystatechange=AJAX.handleMoreStoreInfo;
			AJAX.httpStore.send(null);		
		}catch (error){ }
	},
	handleMoreStoreInfo:function(){
		try{
			if(AJAX.httpStore.readyState==4){
				var response=AJAX.httpStore.responseText;
//				alert(response)
				results.jsonStore=response;
				results.showDetailedStoreInformation();
			}
		}catch(error){ }
	},


// bus times
	getBus:function(branchID){
		try{			
			AJAX.httpBus=null;
			AJAX.httpBus=AJAX.createRequestObject();
			AJAX.httpBus.open('get','bus.aspx?bID='+branchID,true);
			AJAX.httpBus.onreadystatechange=AJAX.handleBus;
			AJAX.httpBus.send(null);		
		}catch (error){}
	},
	handleBus:function(){
		try{
			if(AJAX.httpBus.readyState==4){
				replaceContent('rBus','<div>\n'+$id('rBus').innerHTML+AJAX.httpBus.responseText+'\n</div>\n');
				externalLinks('rBus');
			}
		}catch(error){}
	},

// Instore timetables
	getPharmacy:function(branchID){
		try{			
			AJAX.httpPharmacy=null;
			AJAX.httpPharmacy=AJAX.createRequestObject();
			AJAX.httpPharmacy.open('get','hours.open.pharmacy.asp?bID='+branchID,true);
			AJAX.httpPharmacy.onreadystatechange=AJAX.handlePharmacy;
			AJAX.httpPharmacy.send(null);
		}catch (error){}
	},
	handlePharmacy:function(){
		try{
			if(AJAX.httpPharmacy.readyState==4){
				replaceContent('rPharmacy',AJAX.httpPharmacy.responseText);
				addLeadZeroToTableHoursLessThan1000('pharmacy_times');
				$('#rPharmacy').addClass('showIt');
				$('#times').empty().append($('.current table').html());
			}
		}catch(error){}
	},
	getOptician:function(branchID){
		try{			
			AJAX.httpOptician=null;
			AJAX.httpOptician=AJAX.createRequestObject();
			AJAX.httpOptician.open('get','hours.open.optician.asp?bID='+branchID,true);
			AJAX.httpOptician.onreadystatechange=AJAX.handleOptician;
			AJAX.httpOptician.send(null);
		}catch (error){}
	},
	handleOptician:function(){
		try{
			if(AJAX.httpOptician.readyState==4){
				replaceContent('rOptician',AJAX.httpOptician.responseText);
				addLeadZeroToTableHoursLessThan1000('optician_times');
				$('#rOptician').addClass('showIt');
				$('#times').empty().append($('.current table').html());
			}
		}catch(error){}
	},

	getCafe:function(branchID){
		try{			
			AJAX.httpCafe=null;
			AJAX.httpCafe=AJAX.createRequestObject();
			AJAX.httpCafe.open('get','hours.open.cafe.asp?bID='+branchID,true);
			AJAX.httpCafe.onreadystatechange=AJAX.handleCafe;
			AJAX.httpCafe.send(null);
		}catch (error){}
	},
	handleCafe:function(){
		try{
			if(AJAX.httpCafe.readyState==4){
				replaceContent('rCafe',AJAX.httpCafe.responseText);
				addLeadZeroToTableHoursLessThan1000('cafe_times');
				$('#rCafe').addClass('showIt');
				$('#times').empty().append($('.current table').html());
			}
		}catch(error){ }
	},

	getDirectDesk:function(branchID){
		try{			
			AJAX.httpDirectDesk=null;
			AJAX.httpDirectDesk=AJAX.createRequestObject();
			AJAX.httpDirectDesk.open('get','hours.open.directdesk.asp?bID='+branchID,true);
			AJAX.httpDirectDesk.onreadystatechange=AJAX.handleDirectDesk;
			AJAX.httpDirectDesk.send(null);
		}catch (error){ }
	},
	handleDirectDesk:function(){
		try{
			if(AJAX.httpDirectDesk.readyState==4){
				replaceContent('rDirectDesk',AJAX.httpDirectDesk.responseText);
				addLeadZeroToTableHoursLessThan1000('directdesk_times');
				$('#rDirectDesk').addClass('showIt');
				$('#times').empty().append($('.current table').html());
			}
		}catch(error){ }
	},

	getTelecoms:function(branchID){
		try{			
			AJAX.httpTelecoms=null;
			AJAX.httpTelecoms=AJAX.createRequestObject();
			AJAX.httpTelecoms.open('get','hours.open.telecoms.asp?bID='+branchID,true);
			AJAX.httpTelecoms.onreadystatechange=AJAX.handleTelecoms;
			AJAX.httpTelecoms.send(null);
		}catch (error){ }
	},
	handleTelecoms:function(){
		try{
			if(AJAX.httpTelecoms.readyState==4){
				replaceContent('rTelecoms',AJAX.httpTelecoms.responseText);
				addLeadZeroToTableHoursLessThan1000('telecoms_times');
				$('#rTelecoms').addClass('showIt');
				$('#times').empty().append($('.current table').html());
			}
		}catch(error){ }
	},


// Bank holidays
	getEaster:function(branchID){
		try{			
			AJAX.httpEaster=null;
			AJAX.httpEaster=AJAX.createRequestObject();
			AJAX.httpEaster.open('get','hours.open.easter.asp?bID='+branchID,true);
			AJAX.httpEaster.onreadystatechange=AJAX.handleEaster;
			AJAX.httpEaster.send(null);
		}catch (error){ }
	},
	handleEaster:function(){
		try{
			if(AJAX.httpEaster.readyState==4){
				replaceContent('rEaster',AJAX.httpEaster.responseText);
				addLeadZeroToTableHoursLessThan1000('easter_times');
				$('#rEaster').addClass('showIt');
				$('#times').empty().append($('.current table').html());
			}
		}catch(error){ }
	},

	getBankHolMayDay:function(branchID){
		try{			
			AJAX.httpBankHolMayDay=null;
			AJAX.httpBankHolMayDay=AJAX.createRequestObject();
			AJAX.httpBankHolMayDay.open('get','hours.open.bh.mayday.asp?bID='+branchID,true);
			AJAX.httpBankHolMayDay.onreadystatechange=AJAX.handleBankHolMayDay;
			AJAX.httpBankHolMayDay.send(null);
		}catch (error){ }
	},
	handleBankHolMayDay:function(){
		try{
			if(AJAX.httpBankHolMayDay.readyState==4){
				replaceContent('rBankHolMayDay',AJAX.httpBankHolMayDay.responseText);
				addLeadZeroToTableHoursLessThan1000('rBankHolMayDay');
				$('#rBankHolMayDay').addClass('showIt');
				$('#times').empty().append($('.current table').html());
			}
		}catch(error){ }
	},

	getBankHolMay:function(branchID){
		try{			
			AJAX.httpBankHolMay=null;
			AJAX.httpBankHolMay=AJAX.createRequestObject();
			AJAX.httpBankHolMay.open('get','hours.open.bh.may.asp?bID='+branchID,true);
			AJAX.httpBankHolMay.onreadystatechange=AJAX.handleBankHolMay;
			AJAX.httpBankHolMay.send(null);
		}catch (error){ }
	},
	handleBankHolMay:function(){
		try{
			if(AJAX.httpBankHolMay.readyState==4){
				replaceContent('rBankHolMay',AJAX.httpBankHolMay.responseText);
				addLeadZeroToTableHoursLessThan1000('rBankHolMay');
				$('#rBankHolMay').addClass('showIt');
				$('#times').empty().append($('.current table').html());
			}
		}catch(error){ }
	},

	getBankHolAug:function(branchID){
		try{			
			AJAX.httpBankHolAug=null;
			AJAX.httpBankHolAug=AJAX.createRequestObject();
			AJAX.httpBankHolAug.open('get','hours.open.bh.aug.asp?bID='+branchID,true);
			AJAX.httpBankHolAug.onreadystatechange=AJAX.handleBankHolAug;
			AJAX.httpBankHolAug.send(null);
		}catch(error){}
	},
	handleBankHolAug:function(){
		try{
			if(AJAX.httpBankHolAug.readyState==4){
				replaceContent('rBankHolAug',AJAX.httpBankHolAug.responseText);
				if ($("#rBankHolAug").innerHTML!=""){
					addLeadZeroToTableHoursLessThan1000('rBankHolAug');
					$("#rBankHolAug").addClass('showIt');
				}else{$("#rBankHolAug").removeClass('showIt')}
				$('#times').empty().append($('.current table').html());
			}
		}catch(error){}
	},

// New version of Christmas. Presenting the new and much improved Christmas2
	getChristmas2:function(branchID){
		try{			
			AJAX.httpChristmas2=null;
			AJAX.httpChristmas2=AJAX.createRequestObject();
			AJAX.httpChristmas2.open('get','hours.open.christmas.asp?bID='+branchID,true);
			AJAX.httpChristmas2.onreadystatechange=AJAX.handleChristmas2;
			AJAX.httpChristmas2.send(null);		
		}catch(error){}
	},
	handleChristmas2:function(){
		try{
			if(AJAX.httpChristmas2.readyState==4){
				replaceContent('rChristmas',AJAX.httpChristmas2.responseText);
				if ($("#rChristmas").innerHTML!=""){
					addLeadZeroToTableHoursLessThan1000('rrChristmas');
					$("#rChristmas").addClass('showIt');
				}else{
					$("#rChristmas").removeClass('showIt')
				}
				$('#times').empty().append($('.current table').html());
			}
		}catch(error){}
	},


// Original code and data set please replace prior to christmas
	getChristmas:function(branchID){
		try{			
			AJAX.httpChristmas=null;
			AJAX.httpChristmas=AJAX.createRequestObject();
			AJAX.httpChristmas.open('get','hours.open.christmas.asp?bID='+branchID,true);
			AJAX.httpChristmas.onreadystatechange=AJAX.handleChristmas;
			AJAX.httpChristmas.send(null);		
		}catch (error){ }
	},
	handleChristmas:function(){
		try{
			if(AJAX.httpChristmas.readyState==4){
				var response=AJAX.httpChristmas.responseText;
				results.jsonChristmas=response;
				results.showChristmasHours();
			}
		}catch(error){ }
	}


};

//Error Handling
var mapError={
	notCompatible:function(){
		//Clear map pane
		//write error message
	},
	ajaxBadReturn:function(){
		//attempt retry
		//display meesage
	},
	writeErrorMessage:function(errorMessage){
		//display errorMessage param
	}
};

var cookies={
	oStoreFinderCookie:Object,
	sName:'BranchNumber',
	iCookieValue:'1111',
	sDefaultExpiry:'',
	getIt:function(){
		cookie.iCookieValue=readCookie(cookies.sName);
		if (cookies.oStoreFinderCookie){
			return cookies.oStoreFinderCookie;
		}
	},
	createIt:function(cookieValue){
		document.cookie= cookise.sName + "=" + cookieValue + ";expires=" + cookies.sDefaultExpiry;
	},
	readIt:function(){
		if (document.cookie.length > 0){
			sName=document.cookie.indexOf(cookie.sName + "=");
			if (sName != -1){ 
				iValueStart=sName + cookies.sName.length + 1;
				iValueEnd=document.cookie.indexOf(";",iValueStart);
				if (iValueEnd==-1){
					iValueEnd=document.cookie.length;
				}
				return document.cookie.substring(iValueStart,iValueEnd);
			} 
		  }
		return "";
	},
	updateIt:function(){
		//DO
	}
};

var uti={
	fFig:function(v){
		var s=v+"";
		if (s.length==3){
			x="0"+s;
		}else{
			x=s;
		}
		return x;
	}
}

var admin={
	myEventTester:function(e){
		var events ="<p>LatLong: " + e.view.LatLong + "</p>";
		document.getElementById('adminMode').innerHTML=events;
	}
};


function jsCSS(action,obj,class1,class2){
// swap, add, remove or check for className
// author: Christian Heilmann - http://onlinetools.org
  switch (action){
	case 'swap':obj.className=!jsCSS('check',obj,class1)?obj.className.replace(class2,class1): obj.className.replace(class1,class2);break;
	case 'add':if(!jsCSS('check',obj,class1)){obj.className+=obj.className?' '+class1:class1};break;
	case 'remove':var rep=obj.className.match(' '+class1)?' '+class1:class1;obj.className=obj.className.replace(rep,'');break;
	case 'check':return new RegExp('\\b'+class1+'\\b').test(obj.className);break;
  }
  return false;
}

// author: mike foskett - http://webSemantics.co.uk/
function $id(id){return(document.getElementById(id)?document.getElementById(id):false)}
function idExists(id){return($id(id)?true:false)}
function replaceContent(id,content){if(idExists(id))$id(id).innerHTML=content}

// open or close a timetable
function openClose(obj){
	if(idExists('accessible')){
		return false;
	}else{
		if($.browser.msie){ // slide fails in IE
			$('#times').fadeOut('slow',function(){
				$(this).empty().append(obj.parent().next().html());
			}).fadeIn('slow'); // fade out table, change content, fade in table
		}else{
			$('#times').slideUp('slow',function(){
				$(this).empty().append(obj.parent().next().html());
			}).slideDown('slow'); // slide up table, change content, slide down table
		}

		// change .current
		$("#instoreTimes li").removeClass('current'); // remove .current from all li's
		obj.parent().parent().addClass('current'); // add .current to this li

		// change show / hide in title
		var t=obj.attr("title");
		$('#instoreTimes a').attr("title",function(){
			return this.title.replace("Hide","Show");
		});
		obj.attr("title",t.replace("Show","Hide")); // replace title
	}
	return false;
}



/* Validation of search form */
if(idExists('searchForm')){
	$id('searchForm').onsubmit=function(){
		var o=$id('searchTextBox')
		if(o.value < 1 || o.value.length<3){
			o.className="inpError "+o.className;
			alert('Please enter your town, or post code, to locate a store near you. (Minimum three characters)');
			o.focus();
		}else{			
			o.className.replace(/inpError /,"");
			searchBox.showAddress(this.address.value);

			// Exception advertising:
			// Activated here by entered postcode (first 3 chars).
			// Also activated by store location in msA.js
			var PCN=parseInt(o.value.toUpperCase().substring(2,3));
			if (PCN>0 && PCN<=9){
				var PC=o.value.toUpperCase().substring(0,2);
				switch (PC){
					case "NG": if(idExists('nottingham')){jsCSS('remove',$id('nottingham'),'hideIt')}; break;
					case "EH": if(idExists('edinburgh')){jsCSS('remove',$id('edinburgh'),'hideIt')}; break;
					case "GL": if(idExists('gloucestershire')){jsCSS('remove',$id('gloucestershire'),'hideIt')}; break;
					case "RM":;
					case "CO":;
					case "CM":;
					case "SS":; if(idExists('essex')){jsCSS('remove',$id('essex'),'hideIt')}; break;
				
					default :	if(idExists('nottingham')){jsCSS('add',$id('nottingham'),'hideIt')};
								if(idExists('edinburgh')){jsCSS('add',$id('edinburgh'),'hideIt')};
								if(idExists('essex')){jsCSS('add',$id('essex'),'hideIt')};
								if(idExists('gloucestershire')){jsCSS('add',$id('gloucestershire'),'hideIt')};
								if(idExists('liverpool')){jsCSS('add',$id('liverpool'),'hideIt')};
								if(idExists('hertfordshire')){jsCSS('add',$id('hertfordshire'),'hideIt')};
								if(idExists('hampshireshire')){jsCSS('add',$id('hampshireshire'),'hideIt')};
				}
			}
			// Liverpool - 
			if (o.value.toUpperCase()=="LIVERPOOL"){if(idExists('liverpool')){jsCSS('remove',$id('liverpool'),'hideIt')}}
			var liverpool=(o.value.toUpperCase().substring(0,1))=="L" && ((parseInt(o.value.toUpperCase().substring(1,2))>=0)&&(parseInt(o.value.toUpperCase().substring(1,2))<=9));
			if (liverpool){
				if(idExists('liverpool')){jsCSS('remove',$id('liverpool'),'hideIt')}
			}
			// Hampshire - inserted by county field only
			// Hertfordshire - inserted by county field only
		}
		return false;
}	}


/* Links with rel="external" get launched into new window */
function externalLinks(id){
if (document.getElementsByTagName){
	var anchors=(idExists(id))?$id(id).getElementsByTagName("a"):document.getElementsByTagName("a");
	for (var i=0;i<anchors.length;i++){
		var anchor=anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel")=="external"){
			anchor.target="_blank";
			anchor.title="Launches in new window";
}	}	}	}
externalLinks();


// repair Excel mishaps with leading zeros on opening / closing times
// this function would be better in the xsl if possible?
function addLeadZeroToTableHoursLessThan1000(id){
	if(idExists(id)){
		var tds=$id(id).getElementsByTagName('td')
		for (var i=0;i<tds.length;i++){
			// if 3 digits add a lead 0
			tds[i].innerHTML=(tds[i].innerHTML.search(/^\d{3}$/)!=-1)?"0"+tds[i].innerHTML:tds[i].innerHTML;
}	}	}
/* run when ajax updates like so: 
	addLeadZeroToTableHoursLessThan1000('store_times');
*/

// onLoad remove "loading" graphic from search box
if(idExists('searchTextBox')){$id('searchTextBox').style.background="#fff"};
