var gMap;
G_INCOMPAT = true;
var gMapCentre = null;
var mapOptions = {};
var markers = [];
var pinnedMarkers = {};
var openMarker;
var onLoads = $A();
var currentURL;
var bubbleCloseDelay;
var gMapKeys = {
	'702afc726dae80df9c67a4c4eb614ec1734015da' : 'ABQIAAAAD--iZLS4FYaIgMwYoJVePhQTn61ZxpYopCAm4MCXVywADRprWhRjS1EUTCQ-ooO8ih3FfAlqW-3SWw', // dev
	'221664e9783ae2f2a0bbf7ae9fbe0791594a23b1' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBSQF87atFVeoVqrcHD2QiPZ3wk6ChRWWEPExagY2YM_j3BsJq7AkBO0kQ', // test
	'909fd270618c5ac66eb9647c650cff046f048519' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBS5jk8olYNEh7uSyeysc98Cofdt2hQA8KZJmY9EmE4gLwps42dKLeiGiw', // staging
	'89e42a5a8e824fdb6116796b172ee3dc4bccf036' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBQywCooTAsxguXqGDJGV4qzHFmibBQayPyowzmMtWxiMN2L6vMYpwjOxg', // prod
	'1b1537225bd731c8df75524457c9b4d04af2e63a' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBRj2jLQAFBnksoTYzJiCGPUcpS1hBSRsW2KKmm0e6eijg-LtU1GGideZg', // OCC dev
	'a702d90fd7bfcd0c81ee61d37808f756c717faed' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBTb6yX33gL9hVccB383q0mGqPBv-BSQffICfTVkr7A2I6ii_RBjspCuVA', // OCC test
	'2a0e1a81f6f9ba552532fb4cfd07c8196a7ec6eb' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBRJgJcRMj4RwriKiLsKRvqJ1fFUHxR7nrsT6HPMo7YjnEJ7qVgHimZcrw', // OCC staging
	'c4db9988ffcf165212deffb2af6ec82b42b9ba6d' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBSgC97eEpzDWL9sZ0zM-oQ-hgaWARQvO-63j-i_BkMacxaZDYC2Cp1nKg', //OCC prod
	'5681781b3f74eebaa5670e67094d39ff8260fdee' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBQ1uUp4aJsc0uenU8emUHwSRNXepxSS74C-9C1KFCxGuybRTGoXnYAE3g', // smpl dev
	'57ea3425efac2048d8784d66306d92a71084fb5e' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBRS_EXOLTjOZ-YTHx9MqqyBqV501RR6XHB5v8Q-K33hYjm8oMDebWBU0A', // smpl test
	'b648dd3e752c38828348adedbdc7562fefbf95fe' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBSmOkznXT5iMY_5bmME-SfRiV45qRSHBagcZigQ4qH_nQn8GpRbRYHU9g', // smpl staging
	'8d949bf2ca58df5e3e31def5e74e60d81ca1c0ed' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBQEa0h_Y9rORK7UvFAk8DK_t7RyaxT5ya_LqPV-T_KwwQosO80ybD3Pdw', // smpl prod
	'beb4ec1b526bdac2223a92c682eda529a4de0013' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBSbzN7t9wDZUCaLb4ciwDDsSgi5iBSaeHyT8_zvctliDNwgoK2AY0TYCQ', // pni14 staging
	'a36746dce818377c219ee10b507029a03864109a' : 'ABQIAAAAZT8nAFNspgw6HGjqIwQgcBQzZUf73W1QGfDo55sFkCdvFpTWIBSNyK1EboGi-YtDEzhQecPWyG5EEA' // pni14 prod
}

/* Init sequence from Dean Edwards/Matthias Miller/John Resig */
function init() {

	if (arguments.callee.done) return;
	arguments.callee.done = true;
	
	if (_timer) {
		clearInterval(_timer);
		_timer = null;
	}
	
	stripeLists();
	stripeTables();
	if (!G_INCOMPAT) loadMap(mapOptions);
	
	try {
		loadAdmin();
		var log = new FRDLog(Level.ERROR, true);
		var level = window.location.search.match(/\blog=(\w+)\b/)[1];
		log.level = Level[level];
	} catch(e) { }
	
	onLoads.each(function(it, i) {
		it();
	});
	
};

if (document.addEventListener) { // Mozilla
	document.addEventListener("DOMContentLoaded", init, false);
}

/*@cc_on @*/
/*@if (@_win32)
	document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
	var script = document.getElementById("__ie_onload");
	script.onreadystatechange = function() {
		if (this.readyState == "complete") {
			init(); // call the onload handler
		}
	};
/*@end @*/

if (/WebKit/i.test(navigator.userAgent)) { // Safari
	var _timer = setInterval(function() {
		if (/loaded|complete/.test(document.readyState)) {
			init();
		}
	}, 10);
}


window.onload = init;

/* end init */


function stripeLists() {
	
	var lists = $$("ul.striped");

	lists.each(function(list, i) {
	
		var items = $A(list.getElementsByTagName("li"));
		
		items.each(stripe);
		
	});
	
}


function stripeTables() {

	var tables = $$("table.striped");

	tables.each(function(table, i) {
	
		var rows = $A(table.getElementsByTagName("tr"));
		
		rows.each(stripe);
		
	});
		
}


function stripe(it, i) {

	var el = $(it);
	
	if (el.parentNode.parentNode.className.match(/\bdouble\b/)) {
		i = Math.round(i/2);
	}
	
	el.setStyle({backgroundColor: ''});
	var current = el.className.replace(/\s?(even)|\s?(odd)|\s?(highlight)/g, "");
	var parity = i % 2 == 0 ? "even" : "odd";
	el.className = current + " " + parity;

}


function loadMap(options) {

	if (options == null) options = {};
	
	if (GBrowserIsCompatible()) {
		
		var mapDiv = $("map");

		if (mapDiv) {
		
			gMap = new GMap2(mapDiv);
			if (options.largeScale != null) gMap.addControl(new GLargeMapControl());
			if (options.mapType != null) gMap.addControl(new GMapTypeControl());
			if (options.overview != null) gMap.addControl(new GOverviewMapControl());
			
			if (gMapCentre == null) setMapCentre(new GLatLng(53.402050000000003,-2.9798369999999998));
			
			addMapMarkers();

		}
		

	}

	document.body.unload = GUnload;

}


function setMapCentre(point) {

	gMapCentre = point;
	
}


function showDetails(id) {

	stripeTables();
	
	var details = $(id + '-top');
	var base = $(id + '-bottom');
	
	if (details == null || base == null) {
		throw("Could not find " + id + " / " + details + " / " + base);
	}
	
	details.addClassName("highlight");
	base.addClassName("highlight");
		
	new Effect.ScrollTo(details);
	
	new Effect.Highlight(details, {duration: 3, startcolor: '#ffff66'});
	new Effect.Highlight(base, {duration: 3, startcolor: '#ffff66'});
		
}


function showInfoWindow(id) {
	
	var marker = pinnedMarkers[id];
	if (marker != null) marker.openInfoWindow($('marker'+id).innerHTML);
	new Effect.ScrollTo($('page'));
	
}


function addMapMarkers() {
	
	if (gMap != null && markers != null) {

		var renderBuffer = $A();
		
		var markerBounds = new GLatLngBounds(gMapCentre, gMapCentre);
		markers.each(function(it, i) {

			var point = new GLatLng(it.lat, it.lng);
			var marker = new GMarker(point);

			renderBuffer.push(marker);
			markerBounds.extend(point);

			GEvent.addListener(marker, 'click', it.action);
			
			GEvent.addListener(marker, 'mouseover', function() {
				if (gMap.markerTimeout != null) clearTimeout(gMap.markerTimeout);
				marker.openInfoWindow($('marker'+it.id).innerHTML);
			});
			
			GEvent.addListener(marker, 'mouseout', function() {
				gMap.markerTimeout = setTimeout(function() {marker.closeInfoWindow()}, window.bubbleCloseDelay);
			});

			pinnedMarkers[it.id] = marker;

		});
		

		if ($('homeInfo') != null) {

			var homeMarkerIcon = new GIcon(G_DEFAULT_ICON, '/images/search/circle-green.png');
			homeMarkerIcon.shadow = "/images/search/circle-shadow.png";
			homeMarkerIcon.iconSize = new GSize(20, 20);
			homeMarkerIcon.shadowSize = new GSize(37, 20);
			homeMarkerIcon.iconAnchor = new GPoint(9, 16);
			homeMarkerIcon.infoWindowAnchor = new GPoint(10, 10);
 			homeMarkerIcon.infoShadowAnchor = new GPoint(30, 30);
			var homeMarker = new GMarker(gMapCentre, homeMarkerIcon);
			
			GEvent.addListener(homeMarker, 'mouseover', function() {
				if (gMap.markerTimeout != null) clearTimeout(gMap.markerTimeout);
				homeMarker.openInfoWindow($('homeInfo').innerHTML);
			});
			
			GEvent.addListener(homeMarker, 'mouseout', function() {
				gMap.markerTimeout = setTimeout(function(){homeMarker.closeInfoWindow()}, window.bubbleCloseDelay);
			});
			
			renderBuffer.push(homeMarker);
			markerBounds.extend(gMapCentre);

		}
		
		gMap.setCenter(markerBounds.getCenter(), gMap.getBoundsZoomLevel(markerBounds));

		renderBuffer.each(function(it, i) {

			gMap.addOverlay(it);

		});
		
	}

}


function showNewSearchForm() {

	var f = $("newSearch");
	
	var display = Prototype.Browser.IE ? "block" : "table-row";
	
	if (f != null) f.setStyle({display: display});
	
	document.profileForm.doNewSearch.value = 'true';
	
	disableButton('newButton');
	enableButton('saveButton');
	
	return false;
	
}


function hideNewSearchForm() {

	var f = $("newSearch");
	
	if (f != null) f.setStyle({display: 'none'});
	
	document.profileForm.doNewSearch.value = 'false';
	
	enableButton('newButton');
	
	return false;
	
}


function disableButton(id) {

	var button = $(id);
	
	if (button == null) return;
	
	button.addClassName('disabled');
	
	button.getElementsBySelector('button').each(function(it, i) {

		it.addClassName('disabled');

	});

}


function enableButton(id) {

	var button = $(id);
	
	if (button == null) return;
		
	button.removeClassName('disabled');
	
	button.getElementsBySelector('button').each(function(it, i) {

		it.removeClassName('disabled');

	});

}


function confirmTCs(url) {

	currentURL = url;
	
	if (readCookie("TCs") != null) {
	
		acceptTCs();
		return;
		
	}
	
	var overlay = $('overlay');
	if (overlay == null) overlay = $(document.createElement('div'));
	overlay.setAttribute("id", "overlay");
	overlay.onclick = cancelTCs;
	
	document.getElementsByTagName("body")[0].appendChild(overlay);
	
	Position.prepare();
	overlay.setStyle({
		background: '#000',
		display: 'block',
		height: getDocumentHeight() + "px",
		left: 0,
		opacity: 0.2,
		position: 'absolute',
		top: 0, //Position.deltaY,
		width: getDocumentWidth(),
		zIndex: 999
	});

	var element = $("interstitial");
	
	var dimensions = element.getDimensions();

	var offset_top = (Position.deltaY + ((getWindowHeight() > dimensions.height) ? Math.floor((getWindowHeight() - dimensions.height) / 2) : 0));
	element.setStyle({
		display: 'block',
		top: ((dimensions.height <= getDocumentHeight()) ? ((offset_top != null && offset_top > 0) ? offset_top : '0') + 'px' : 0)
	});

}

function getWindowHeight(){
	return (self.innerHeight ||  document.documentElement.clientHeight || document.body.clientHeight || 0);
}

function getDocumentHeight(){
	return Math.max(document.body.scrollHeight,getWindowHeight());
}

function getWindowWidth(){
	return (self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0);
}

function getDocumentWidth(){
	return Math.max(document.body.scrollWidth, getWindowWidth());
}

function cancelTCs() {

	var overlay = $('overlay');
	var box = $('interstitial');
	
	box.setStyle({display: 'none'});
	overlay.setStyle({display: 'none'});

}

function acceptTCs() {

	createCookie('TCs', 'true', 30);
	cancelTCs();
	window.open(currentURL);
	
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function injectMap() {
	var name = window.location.hostname
	var key = gMapKeys[hexSha1(name)]
	document.writeln(unescape("%3Cscript src='http://maps.google.com/maps?file=api&v=2&key=" + key + "' type='text/javascript'%3E%3C/script%3E"));
}
