
// On page load
window.onload = function() {
	branchLocator.init();
	carousel.init();
	externalLinks();
}

// Homepage Carousel
var carousel = {

	carouselName:	'#carousel',
	carouselPos:	0,	
	numPanels:		0,
	panelWidth:		148,
	viewablePanels:	6,
	scrollRate:		800,

	init:function() {
	
		if($(this.carouselName).length < 1) return;
		this.numPanels = $(this.carouselName + ' div.panel').length;
		
		this.attachControls();
		this.addEvents();
		
		// set width of slider based on number of panels
		$(this.carouselName + ' #slider').css('width',this.numPanels * this.panelWidth);
		
	},
	attachControls:function(){
	
		$(this.carouselName + ' #carouselPrev').html('<a id="prev" href="" class="prevInactive"></a>');
		$(this.carouselName + ' #carouselNext').html('<a id="next" href=""></a>');
	
	},
	addEvents:function() {
	
		var obj = this;
	
		$(this.carouselName + ' #prev').click(function(){
			obj.scroll('left');
			$(this).blur();
			return false;
		});
		
		$(this.carouselName + ' #next').click(function(){
			obj.scroll('right');
			$(this).blur();
			return false;
		});
	
	},
	scroll:function(direction) {
	
		// remove inactive classes
		$(this.carouselName + ' #prev').removeClass('prevInactive');
		$(this.carouselName + ' #next').removeClass('nextInactive');
	
		if(direction == 'right'){

			if(this.carouselPos > 0 - ((this.numPanels - this.viewablePanels) * this.panelWidth)) {
			
				this.carouselPos = parseInt(this.carouselPos - this.panelWidth,10);
			
				$(this.carouselName + ' #slider').animate({
					left: this.carouselPos
				},this.scrollRate);
			
			}
		}
		else {
			
			if(this.carouselPos != 0) {
			
				this.carouselPos = parseInt(this.carouselPos + this.panelWidth,10);
				
				$(this.carouselName + ' #slider').animate({
					left: this.carouselPos
				},this.scrollRate);

			}
		}

		// check if inactive classes need to be added on
		if(this.carouselPos == 0)	
			$(this.carouselName + ' #prev').addClass('prevInactive');
	
		if(this.carouselPos == 0 - ((this.numPanels - this.viewablePanels) * this.panelWidth))
			$(this.carouselName + ' #next').addClass('nextInactive');
			
	}

}

// NCA Branch locator
var branchLocator = {

	map:			null,
	localSearch:	null,
	defaultZoom:	6,
	closeZoom:		15,
	markers:		[],
	mapIcon:		null,
	markerOptions:	null,
	lat:			53.107217,
	lng:			-1.417236,
	userLat:		null,		
	userLng:		null,
	geocodes:		[],
	distances:		[],
	address:		[],

	init:function() {
	
		if(!document.getElementById("branchLocationsMap")) return;
		if(!GBrowserIsCompatible() || !document.getElementById) return;

		this.buildMapHTML();
		this.mapLoad();
		this.setData();
		this.addBranchEvents();
		this.localSearch = new GlocalSearch();
		this.setBranchMarkers();

	},
	buildMapHTML:function() {
	
		var mapHTML;
		mapHTML 	= 	'<div id="mapCanvas"></div><div id="postcodeFormContainer"><form id="postcodeForm" action="" onsubmit="branchLocator.checkPostcode(); return false;"><div>' +
						'<label for="postcode">Postcode Search</label><input type="text" id="postcode" size="9" /><input id="postcodeSubmitBtn" type="submit" value="" />' +
						'</div></form></div><div id="postcodeMsg"></div>';
		
		var mapHook = document.getElementById("branchLocationsMap");
		mapHook.innerHTML = mapHTML;
		
	},
	setData:function() {
	
		// Set branch geocodes
		this.geocodes[0] 	= '50.85853,0.465737';			// Bexhill	
		this.geocodes[1] 	= '51.994603,-0.729481';		// Bletchley		
		this.geocodes[2] 	= '52.335503,-2.060421';		// Bromsgrove			
		this.geocodes[3] 	= '52.480332,-1.739249';		// Chelmsley Wood		
		this.geocodes[4] 	= '53.479992,-2.146227';		// Droylsden
		this.geocodes[5]    = '51.451578,0.052405';			// Eltham				
		this.geocodes[6]	= '51.657668,-0.046949';		// Enfield				
		this.geocodes[7] 	= '53.025083,-2.176124';		// Hanley				
		this.geocodes[8]	= '51.784285,0.123844';			// Harlow				
		this.geocodes[9]	= '51.519683,-0.412557';		// Hayes				
		this.geocodes[10]	= '51.582985,-0.227664';		// Hendon				
		this.geocodes[11]	= '51.549573,-0.108671';		// Holloway			
		this.geocodes[12]	= '53.643771,-1.77402';			// Huddersfield			
		this.geocodes[13]	= '52.63315,-1.15893';			// Leicester			
		this.geocodes[14]	= '52.452904,-1.784292';		// Sheldon				
		this.geocodes[15]	= '51.528503,-0.616269';		// Slough				
		this.geocodes[16]	= '52.502086,-1.99013';			// Smethwick		
		this.geocodes[17]	= '51.540338,0.714791';			// Southend-on-sea		
		this.geocodes[18]	= '53.411183,-2.162222';		// Stockport			
		this.geocodes[19]	= '53.54448,-2.632773';			// Wigan				
		this.geocodes[20]	= '53.381183,-2.248744';		// Wythenshawe
		
		// Set branch addresses
		this.address[0]		= "<h3>Bexhill</h3>Near to Sidley Post Office,<br />54 Ninfield Road,<br /> Sidley,<br /> Bexhill on Sea, <br />TN39 5BD";
		this.address[1]		= "<h3>Bletchley</h3>Near the Main Post Office,<br /> Unit 4, Agora Shopping Centre,<br />Milton Keynes,<br />Bletchley,<br />MK2 2AA";
		this.address[2] 	= "<h3>Bromsgrove</h3>Opposite Lloyds TSB,<br />87a High Street,<br />Bromsgrove,<br /> B61 8AQ";
		this.address[3]		= "<h3>Chelmsley Wood</h3>Opposite Argos,<br />Number 12 Chestnut Walk,<br /> Chelmsley Wood Shopping Centre,<br /> Chelmsley Wood,<br /> Birmingham,<br /> B37 5TT";
		this.address[4]		= "<h3>Droylsden</h3>Near the Halifax Building Society,<br />Unit 14, 8 Queens Walk,<br /> Droylsden,<br /> Manchester,<br /> M43 7AD";
		this.address[5]		= "<h3>Eltham</h3>Near to Eltham Police Station,<br />38 Well Hall Road,<br /> Eltham,<br /> SE9 6SF"; 
		this.address[6]		= "<h3>Enfield</h3>Near to the Co-op Supermarket, <br />147 Hertford Road,<br /> Enfield,<br /> Middlesex,<br /> EN3 5JG"; 
		this.address[7]		= "<h3>Hanley</h3>Opp Lloyds TSB,<br />37 Stafford Street,<br /> Hanley,<br /> ST1 1JU"; 
		this.address[8]		= "<h3>Harlow</h3>Near Dorringtons Bakery,<br />111 The Stow,<br /> Harlow,<br /> Essex,<br /> CM20 2AS";
		this.address[9]		= "<h3>Hayes</h3>642/644 Uxbridge Road,<br />Hayes,<br /> Middlesex,<br /> UB4 0RY"; 
		this.address[10]	= "<h3>Hendon</h3>Opposite Hendon Central Underground,<br />10 Central Circus,<br /> Hendon,<br /> London,<br /> NW4 3JS"; 
		this.address[11]	= "<h3>Holloway</h3>137 Holloway Road,<br />London,<br /> N7 8LX";
		this.address[12]	= "<h3>Huddersfield</h3>Opposite Aspley Marina, <br />66 Wakefield Road,<br /> Aspley,<br /> Huddersfield,<br /> West Yorkshire,<br /> HD1 3AJ"; 
		this.address[13]	= "<h3>Leicester</h3>On A47 heading towards city centre,<br />223 Hinckley Road,<br /> Leicester,<br /> Leicestershire,<br /> LE3 0TG";
		this.address[14]	= "<h3>Sheldon</h3>Opposite Halfords,<br />2160A Coventry Road,<br /> Sheldon,<br /> Birmingham,<br /> B26 3JB"; 
		this.address[15]	= "<h3>Slough</h3>A few doors down from KFC,<br />392 Farnham Road,<br /> Slough,<br /> Berkshire,<br /> SL2 1JD" 
		this.address[16]	= "<h3>Smethwick</h3>16 Westcross Shopping Centre,<br /> Oldbury Road,<br /> Warley,<br /> West Midlands,<br /> B66 1JG"; 
		this.address[17]	= "<h3>Southend-on-Sea</h3>Near the Sutton Arms Pub,<br />95 Southchurch Road, <br />Southend-on-Sea,<br /> Essex,<br />SS1 2NL";
		this.address[18]	= "<h3>Stockport</h3>A few doors down from Debenhams,<br />70 Princes Street,<br /> Stockport,<br /> SK1 1RJ";
		this.address[19]	= "<h3>Wigan</h3>Opposite the railway station,<br />39 Wallgate,<br /> Wigan,<br /> WN1 1BE"; 
		this.address[20]	= "<h3>Wythenshawe</h3>Wythenshawe Shopping Centre,<br />Opposite Asda Ground Level Car Park,<br />Kiosk 1, Wythenshawe Shopping Centre,<br /> Simonsway, <br />Wythenshawe,<br /> Manchester,<br />M22 5BZ";
	
	},
	addBranchEvents:function() {

		var obj 	 = this, temp, numMapLinks;	
		var mapLinks = document.body.getElementsByTagName("a");
           
		numMapLinks = 0;   
		   
		if(mapLinks) {
			for(var i=0 ; i<mapLinks.length ; i++) {
				
				if(mapLinks[i].className == 'setBranch') {					
					(function( ){   
						var index = numMapLinks;

						mapLinks[i].onclick = function () {
							temp = obj.geocodes[index].split(',');
							obj.setMap(temp[0],temp[1],index);											
						}
						
						numMapLinks++;
					})();
					
				}					
			}
		}
	
	},
	mapLoad:function() {

		this.map = new GMap2(document.getElementById("mapCanvas"));
		this.map.addControl(new GLargeMapControl());
		//this.map.addControl(new GMapTypeControl());
		this.map.setCenter(new GLatLng(this.lat,this.lng), this.defaultZoom, G_NORMAL_MAP);
	
	},
	setBranchMarkers:function() {
	
		var temp, point;
		
		this.mapIcon 					= new GIcon();
		this.mapIcon.image 				= 'images/gmaps/mapTick.png';
		this.mapIcon.shadow 			= 'images/gmaps/shadow.png';
		this.mapIcon.iconSize 			= new GSize(18,17);
		this.mapIcon.shadowSize 		= new GSize(27,17);
		this.mapIcon.iconAnchor 		= new GPoint(9,17);
		this.mapIcon.infoWindowAnchor 	= new GPoint(9,0);
		this.mapIcon.printImage 		= 'images/gmaps/printImage.gif';
		this.mapIcon.mozPrintImage 		= 'images/gmaps/mozPrintImage.gif';
		this.mapIcon.printShadow 		= 'images/gmaps/printShadow.gif';
		this.mapIcon.transparent 		= 'images/gmaps/transparent.png';
		this.mapIcon.imageMap 			= [17,0,17,1,15,2,15,3,16,4,16,5,17,6,17,7,17,8,17,9,17,10,16,11,16,12,15,13,14,14,13,15,12,16,5,16,3,15,2,14,2,13,1,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,1,4,2,3,2,2,3,1,5,0];

        this.markerOptions = { icon: this.mapIcon };

		for(var i=0 ; i < this.geocodes.length ; i++ ) {
		
			temp 			= this.geocodes[i].split(',');
			point			= new GLatLng(temp[0],temp[1]);
			this.markers[i] = new GMarker(point, this.markerOptions);
			this.addMapListener(point,this.markers[i],i);
			this.map.addOverlay(this.markers[i]);
			
		}

	},
	addMapListener:function(point, marker, index) {
		var obj = this;
		
		GEvent.addListener(marker, "click", function () {
			obj.map.setCenter(point, obj.closeZoom, G_NORMAL_MAP);
			marker.openInfoWindowHtml(obj.address[index]);
		});
	
	},
	retrieveGeocode:function(postcode, callbackFunction) {
	
		var obj = this;
	
		this.localSearch.setSearchCompleteCallback(null,function() {
			
			if (obj.localSearch.results[0]) {
				obj.userLat 	= obj.localSearch.results[0].lat;
				obj.userLng 	= obj.localSearch.results[0].lng;
				obj.point 		= new GLatLng(obj.userLat,obj.userLng);
				callbackFunction(obj.point,postcode);
			}
			
		});

		this.localSearch.execute(postcode + ", UK");

	},
	nearest:function(point,postcode) {

		var temp, distance = '', nearest, nearestIndex;
	
		// First calculate the distances from each store
		for(var i=0 ; i< branchLocator.geocodes.length ; i++) {
			temp 			= branchLocator.geocodes[i].split(',');
			branchLocator.distances[i] 	= parseInt(geocodeDist.calcDistance(point.lat(),point.lng(), temp[0],temp[1], geocodeDist.earthRadiusInMiles),10);
			
			// Figure out the nearest as we go through the loop
			if(i==0) {
				nearest 		= branchLocator.distances[i];
				nearestIndex	= i;
			}
			else {
				if(branchLocator.distances[i] < nearest)	{
					nearest 		= branchLocator.distances[i];
					nearestIndex 	= i;
				}
			}
		}
		
		temp = branchLocator.geocodes[nearestIndex].split(',');
		branchLocator.setMap(temp[0],temp[1],nearestIndex);
	}, 
	setMap:function(lat,lng,nearestIndex) {
	
		var point = new GLatLng(lat,lng);
		this.map.setCenter(point,this.closeZoom, G_NORMAL_MAP);
		this.markers[nearestIndex].openInfoWindowHtml(this.address[nearestIndex]);
		
	},
	checkPostcode:function() {
	
		var postcodeMsg	= document.getElementById('postcodeMsg');
		postcodeMsg.innerHTML = '';
		var postcode 	= document.getElementById('postcode');
		if(!postcode)	return;
			
		if(this.validatePostcode(postcode.value)) {
			this.retrieveGeocode(document.getElementById('postcode').value, branchLocator.nearest);
		}
		else {		
			postcodeMsg.innerHTML = '<strong>Please enter a valid postcode!</strong>';		
		}
	
	},
	validatePostcode:function(postcode) {

		var size, validPostcode;
		
		// Set validPostcode to true initially, then false later if any of the validation checks fail
		validPostcode 	= true;	

		// Retrieve postcode input element
		var pcodeElem	= document.getElementById('postcode');
		if(!pcodeElem)	return;
	
		// Trim string and get length
		postcode		= trim(postcode);
		size			= postcode.length;
		
		// Change postcode to uppercase and re-enter into input field 
		postcode		= postcode.toUpperCase();
		pcodeElem.value = postcode;
		
		// Check that length is valid
		if (size < 6 || size > 8) {
			validPostcode = false;
		}
		
		// Check that only characters a-z, A-Z, 0-9 and space has been entered
		var pattern = /^[0-9a-zA-Z\s]+$/;
		if(!pattern.test(postcode)) {
			validPostcode = false;
		}
		
		// Check if postcode has an invalid format
		if (!(isNaN(postcode.charAt(0))) || isNaN(postcode.charAt(size-3)) || !(isNaN(postcode.charAt(size-2))) || !(isNaN(postcode.charAt(size-1))) || !(postcode.charAt(size-4) == " ")) {
			validPostcode = false;
		}
		
		// Check that only one space has been entered in the postcode
		var count1 = postcode.indexOf(" ");
		var count2 = postcode.lastIndexOf(" ");
		if (count1 != count2) {
			validPostcode = false;
		}
	
		return validPostcode;
	}
}

// Used for calculating the distance between two geocode locations
var geocodeDist = {

	earthRadiusInMiles:			3956.0,
	earthRadiusInKilometers:	6367.0,
	
	toRadian:function(v) { 
		return v * (Math.PI / 180);
	},
	diffRadian:function(v1, v2) {
		return this.toRadian(v2) - this.toRadian(v1);
	},
	calcDistance:function(lat1, lng1, lat2, lng2, radius) {
		return radius * 2 * Math.asin( Math.min(1, Math.sqrt( ( Math.pow(Math.sin((this.diffRadian(lat1, lat2)) / 2.0), 2.0) + Math.cos(this.toRadian(lat1)) * Math.cos(this.toRadian(lat2)) * Math.pow(Math.sin((this.diffRadian(lng1, lng2)) / 2.0), 2.0) ) ) ) );
	}
}

// For outputting the google map scripts with appropriate API key (based on hostname)
function setMapAPI() {
	var apiKey;
	apiKey	= 'ABQIAAAABAteZEEgW5ZokG6YnvZnOhTuAtyH8mAqFJr6Ov8YyO8ZSNjEMhTERFNFJbDvq729o3gDjFBjFNuFAQ';		// Live API Key

	if (window.location.host == 'nca') {				// Set Local API Key
		apiKey = 'ABQIAAAABAteZEEgW5ZokG6YnvZnOhSX6ssehuhNB8vNI8dFPgb15yav4xQ1lV-gYpIMLLw33gSSxwQw-c8Bhw';
	}
	else if (window.location.host == '94.136.37.42:81') {	// Set test box API key
		apiKey = 'ABQIAAAABAteZEEgW5ZokG6YnvZnOhQ4URzEN6VCbdu9ummSOLD8KBQTzRTS4DSY-KGTDMMFdaYeOv5dW-56VA';
	}

	// output scripts
	document.write('<scr' + 'ipt src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=' + apiKey + '" type="text/javascript"></scr' + 'ipt>');
	document.write('<scr' + 'ipt src="http://www.google.com/uds/api?file=uds.js&amp;v=1.0&amp;key=' + apiKey + '" type="text/javascript"></scr' + 'ipt>');
}

//for opening links in new window
function externalLinks() { 
	 if (!document.getElementsByTagName) return; 
	 var anchors = 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"; 
	 } 
}

// for apply form validation
function checkForm() {

	var passedChecks	= true;
	var errorMsg 		= '';

	//first check that all form elements exist	
	if(document.getElementById("firstname") && document.getElementById("surname") && document.getElementById("contactPhone") && document.getElementById("email") && document.getElementById("privacyPolicy")) {
	
		//retrive First Name, Surname, Contact Number, Email Address field values
		var firstName 		= trim(document.getElementById("firstname").value);
		var surname 		= trim(document.getElementById("surname").value);
		var phoneNum		= trim(document.getElementById("contactPhone").value);
		var email			= trim(document.getElementById("email").value);
		var hearAbout		= document.getElementById("hearAbout");
		var branch			= document.getElementById("preferredBranch");

		//retrive check box status for privacy policy agrreement
		var pPolicy			= document.getElementById("privacyPolicy");
	
		if(firstName.length < 1) {
			passedChecks 	= false;
			errorMsg 		+= '<li>Enter your <b>First Name</b></li>';
		}
		
		if(surname.length < 1) {
			passedChecks 	= false;
			errorMsg 		+= '<li>Enter your <b>Surname</b></li>';
		}
	
		if(phoneNum.length < 1) {
			passedChecks	= false;
			errorMsg		+= '<li>Enter your <b>Contact Number</b></li>';
		}
		
		//check that email has been entered
		if(email.length < 1) {
			passedChecks 	= false;
			errorMsg 		+= '<li>Enter <b>Your Email</b></li>';
		}
		else {
			//check that email is valid
			if(!validEmail(email)) {
				passedChecks	= false;
				errorMsg	   += '<li>Enter a<b> Valid Email</b></li>';
			}
		}
		
		//check if 'preferred branch' value is selected
		if(!branch.selectedIndex) {
			passedChecks	= false;
			errorMsg	   += '<li>Please select a <b>Preferred Branch</b></b></li>';
		}
		
		//check if 'where heard about' value is selected
		if(!hearAbout.selectedIndex) {
			passedChecks	= false;
			errorMsg	   += '<li>Please select an option for <b>Where did you hear about NCA</b></b></li>';
		}
		
		//check that user agreed to privacy policy
		if(!pPolicy.checked) {
			passedChecks 	= false;
			errorMsg 		+= '<li>You must agree to our <a href="/privacy-policy.html">Privacy Policy</a> to apply</li>';
		}		
	
		//if there were form errors output them to errorMsg id
		if(!passedChecks) {
		
			var msgDiv = document.getElementById("formMsg");
		
			if(msgDiv)
				msgDiv.innerHTML = '<div><b>Please fix the following!</b></div><br /><ul>' + errorMsg + '</ul><br />';
		
			return false;
		
		}
		else
			return true;	//form passed checks
			
	}

}

function trim(str) {
	var trimmed = str.replace(/^\s+|\s+$/g, '');
	
	return trimmed;
}

function validEmail(email) {      
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	return emailPattern.test(email);
}

