var BACKGROUNDS = {
	"img" : [
			"/assets/img/backgrounds/bg1.jpg",
			"/assets/img/backgrounds/bg2.jpg",
			"/assets/img/backgrounds/bg3.jpg",
			"/assets/img/backgrounds/bg4.jpg",
			"/assets/img/backgrounds/bg5.jpg",
			"/assets/img/backgrounds/bg6.jpg"
	]
};

var cForm = {
	init : function() {
		if ( $("#contactform .error span").length ) {
			$(".errorHeader").show();
		} else $(".errorHeader").hide();
	}
};

var myCarousel = {
	config : {
		$wrapper : $("#heros"),
		groupSize : 3,
		currentGroup : 1
	},
/************************
/ Initialisation method
/************************/
	init : function(customConfig) {
		if (myCarousel.config && typeof(myCarousel.config) == "object") {
			$.extend(myCarousel.config, customConfig);
		}
		$("#maintext,#heros").css("min-height","500px");
		// initialise variables
		var $wrapper = myCarousel.config.$wrapper,
			groupSize = myCarousel.config.groupSize,
			currentGroup = myCarousel.config.currentGroup;
		var numberOfCaseStudies = $wrapper.find("li").length,
			numberOfGroups = Math.ceil( numberOfCaseStudies / groupSize ),
			lastGroupSize = numberOfCaseStudies % groupSize,
			csArray = $wrapper.find("li").get();
		if (lastGroupSize === 0) {
			lastGroupSize = groupSize;
		}
		// Initialise carousel
		$wrapper.find("li").remove();

		for (i=0; i<groupSize; i++) {
			$wrapper.find("ul").append(csArray[i]);
		}
		// add prev and next buttons - prev button is hidden via CSS
		$("#heros").append("<div id='csButtons'><a href='#' class='prev hide'>Prev</a><a href='#' class='next hide'>Next</a></div>");
		if (currentGroup < numberOfGroups) {
			$("#csButtons .next").removeClass("hide");
		}
		// bind click event to prev link
		$wrapper.find(".prev").click(function(){
			myCarousel.prevGrp(csArray,$wrapper,numberOfGroups);
			return false;
		});
		// bind click event to next link
		$wrapper.find(".next").click(function(){
			myCarousel.nextGrp(csArray,$wrapper,numberOfGroups,lastGroupSize);
			return false;
		});
	},
/************************
/ Prev method
************************/
	prevGrp : function(csArray,$wrapper,numberOfGroups) {
		var groupSize = myCarousel.config.groupSize;
		myCarousel.config.currentGroup --;
		var arrPtr = (myCarousel.config.currentGroup * groupSize) - 3 ;
		// remove case study LIs
		$wrapper.find("li").remove();
		// if we're not on the last group, make sure the next link is visible
		if ( (myCarousel.config.currentGroup < numberOfGroups) && ($wrapper.find(".next").hasClass("hide")) ) {
			$wrapper.find(".next").removeClass("hide");
		}
		// if we're on the first group, hide the Prev link
		if ( myCarousel.config.currentGroup === 1) {
			// remove the prev link
			$wrapper.find(".prev").addClass("hide");
		}
		// inject case study markup
		myCarousel.addGrp($wrapper,csArray,arrPtr)
	},
/************************
/ Next method
/************************/
	nextGrp : function(csArray,$wrapper,numberOfGroups,lastGroupSize) {
		var groupSize = myCarousel.config.groupSize,
			arrPtr = (myCarousel.config.currentGroup * groupSize);
		myCarousel.config.currentGroup ++;
		// remove case study LIs
		$wrapper.find("li").remove();
		// if we're not on the first group, make sure the prev link is visible
		if ( ( myCarousel.config.currentGroup > 1 ) && ($wrapper.find(".prev").hasClass("hide")) ) {
			$wrapper.find(".prev").removeClass("hide");
		}
		// if we're on the last group, set groupSize and hide the Next link
		if ( myCarousel.config.currentGroup === numberOfGroups) {
			groupSize = lastGroupSize;
			$wrapper.find(".next").addClass("hide");
		}
		// inject case study markup
		myCarousel.addGrp($wrapper,csArray,arrPtr,numberOfGroups,lastGroupSize)
	},
/************************
/ Add Group method
/************************/
	addGrp : function($wrapper,csArray,arrPtr,numberOfGroups,lastGroupSize) {
		var groupSize = myCarousel.config.groupSize;
		var currentGroup = myCarousel.config.currentGroup;
		if (currentGroup === numberOfGroups) {
			groupSize = lastGroupSize;
		}
		arrPtr --;
		for (i=0; i < groupSize; i++) {
			arrPtr ++;
			$wrapper.find("ul").append(csArray[arrPtr]);
		}
		$wrapper.find("li").hide().fadeIn(100);
	}
};

var FINSTAT = {
	init : function() {
		var $fsTable = $("#financial-statement table");
		$fsTable.find("thead th").each(function(i){
			if ( i>0 ) { $(this).addClass("hdr"); }
		});
		$fsTable.find("tbody tr").each(function(){
			$(this).find("td").each(function(i){								
				if ( i>0 ) { $(this).addClass("num"); }
			});
		});
	}
};

var gMap = {
// ***
// *** Google Maps Initialisation - calls all other methods ***
// ***
	init : function(pgId) {
		//gMap.mapInit(gMap.config.directionsDisplay);
		switch (pgId)
		{
			case "contact":
				initializeContact();
				break;
			case "hq":
				initializeHQ();
				break;
			case "midlands":
				initializeMidlands();
				break;
			case "northwest":
				initializeNorthWest();
				break;
			case "north":
				initializeNorth();
				break;
			case "northeast":
				initializeNorthEast();
				break;
			case "ireland":
				initializeIreland();
				break;
			case "scotland":
				initializeScotland();
				break;
			case "plant":
				initializePlant();
				break;
			case "pipelines":
				initializePipelines();
				break;
		}
		gMap.getDirToggle();
		gMap.removeStartVal();
		gMap.getDirections();
	},
// ***
// *** Slide open/close the get directions panel beneath the map ***
// ***
	getDirToggle: function() {
		$("#gmap a.getdir").toggle(
			function() {
				$("#route").slideDown(200);
				return false;
			},
			function() {
				$("#route").slideUp(100);
				return false;
			}
		);
	},
// ***
// *** Remove current value when user clicks on start location field ***
// ***
	removeStartVal: function() {
		$("#start").focus(function() {
			var inputValue = $(this).val();
			$(this).val("");
			$("#start").blur(function() {
				if ($(this).val() == "") {
					$(this).val(inputValue);
				}						  
			});
		});
	},
// ***
// *** Get journey directions when user clicks Go
// ***
	getDirections: function() {
		$("#rSubmit").click(function() {
			var routeStart = $("#start").attr("value") + ", UK";
			var routeEnd = null;
			var destination = $("#end").attr("value");
			switch(destination)
			{
			case "1":
				routeEnd = "Hiview House, 81 Highgate Road, London, NW5 1TN, UK";
			  	break;
			case "2":
				routeEnd = "Hawks Green Lane, Staffordshire, WS11 7LH, UK";
			  	break;
			case "3":
				routeEnd = "Wigan Road, Golborne, Warrington, WA3 3UB, UK";
			  	break;
			case "4":
				routeEnd = "Rotherham Road, Dinnington, Sheffield, S25 3RD, UK";
			  	break;
			case "5":
				routeEnd = "Long Causeway, Cross Green, Leeds, LS9 0NY, UK";
			  	break;
			case "6":
				routeEnd = "Great Connell, Newbridge, Co. Kildare, Ireland";
			  	break;
			case "7":
				routeEnd = "45 Mackenzie Street, Paisley, PA3 1LQ, UK";
			  	break;
			case "8":
				routeEnd = "Sanderson Close, London, NW5 1TN, UK";
			  	break;
			case "9":
				routeEnd = "Rushcliffe House, Newark Road, New Ollerton, Nottingham, NG22 9PZ, UK";
			  	break;
			default:
			  	routeEnd = "81 Highgate Road, London, NW5 1TN, UK";
			}
			calcRoute(routeStart,routeEnd);
			return false;
		});
	}
};

var grpStruct = {
	config : {
		$wrapper : $("#group-structure")
	},
	init : function(customConfig) {
		if (grpStruct.config && typeof(grpStruct.config) == "object") {
			$.extend(grpStruct.config, customConfig);
		}
		var $wrapper = grpStruct.config.$wrapper;
		$wrapper.find(".gs-company-info").hide();
		$wrapper.find(".gs-content > ul > li").append("<div class='overlay-off'></div>");
		grpStruct.showOverlay();
		grpStruct.infoShowHide();
		$wrapper.removeClass("hide");
	},
	showOverlay : function(gsHeight) {
		var $wrapper = grpStruct.config.$wrapper;
		var gsWidth = $wrapper.width();
		var gsHeight = $wrapper.height();
		$wrapper.find(".overlay").height(gsHeight).width(gsWidth).show()
			.mouseover(function() {
				$(this).fadeOut(400);
			});
	},
	infoShowHide : function() {
		var $wrapper = grpStruct.config.$wrapper;
		$wrapper.find(".gs-content > ul > li").hoverIntent(
			function() {
				$(this).find("div.overlay-off").hide();
				$(this).find(".gs-company-info").show();
			},
			function() {
				$(this).find(".gs-company-info").hide();
				$(this).find("div.overlay-off").show();
			}
		);
	}
};

var imgViewer = {
	config : {
		$wrapper : $("#image-viewer"),
		index : 0
	},
	init : function(customConfig) {
		// configuration
		if (imgViewer.config && typeof(imgViewer.config) == "object") {
			$.extend(imgViewer.config, customConfig);
		}
		// initialise vars
		var $wrapper = imgViewer.config.$wrapper,
			numImgs = $wrapper.find("li").length,		// number of case studies
			tArray = [numImgs],							// thumbnail images
			lArray = [numImgs],							// large images
			fArray = [numImgs];							// fullsize images
		// load arrays
		$wrapper.find("li").each(function(i) {
			tArray[i] = $(this).find(".thumb").attr("src"); // thumbnails
			lArray[i] = $(this).find(".large").attr("src");	// large images
			fArray[i] = $(this).find(".full").attr("src");	// fullsize images
		});
		// Prepare the page markup and initialise the viewer widget
		imgViewer.imgSetup($wrapper, numImgs, tArray, lArray, fArray);
		// Call the lightbox with custom images
		$wrapper.find(".iv-large li a").lightBox({
			imageLoading: '/assets/img/ajax-loader.gif',
			imageBtnClose: '/assets/img/btn_lightbox_close.gif',
			imageBtnPrev: '/assets/img/btn_lightbox_prev.gif',
			imageBtnNext: '/assets/img/btn_lightbox_next.gif'		
		});
		// Image selected function
		imgViewer.imgSelect($wrapper, fArray);
	},
	imgSetup : function($wrapper, numImgs, tArray, lArray, fArray) {
		// Remove existing markup within #image-viewer		
		$wrapper.children().remove();
		// Inject new markup structure
		$wrapper.append(
			  "<div class='iv-large'>"
			+ "<ul></ul>"
			+ "</div>"
			+ "<div class='iv-thumbs'>"
			+ "<ul></ul>"
			+ "</div>"
		);
		// Inject open lightbox button
		//$wrapper.find(".iv-large").append("<a class='open-lb' title='View full-size image' href='" + fArray[0] + "'>Open</a>");
		for (i=0; i<numImgs; i++) {
			// Inject the large image markup
			$wrapper.find(".iv-large ul")
				.append("<li><a title='Click to view full-size image' href='" + fArray[i] + "'><img alt='Click to view full-size image' src='" + lArray[i] + "'/></a>");
			// Inject the thumbnail image markup
			$wrapper.find(".iv-thumbs ul")
				.append("<li><img src='" + tArray[i] + "' alt='Click to select this image'  title='Click to select this image' />"  + "</li>");
			$wrapper.find(".iv-thumbs li:nth-child(3)").addClass("last");
		}
		// display the images
		$wrapper.find(".iv-large img").eq(0).show();
		$wrapper.find(".iv-thumbs img").show();
	},
	imgSelect : function($wrapper, fArray) {
		// Click event for thumbnails
		$wrapper.find(".iv-thumbs li").live("click", function() {
			// Which thumbnail has been clicked?
			imgViewer.config.index = $(".iv-thumbs li").index(this);
			// Find the associated large image and display
			$wrapper.find(".iv-large img").hide();
			$wrapper.find(".iv-large img").eq(imgViewer.config.index).fadeIn(300);
			// Update the open-lb button href for new large image
			$wrapper.find(".iv-large .open-lb").attr("href", fArray[imgViewer.config.index]);
			return false;
		});
	}
};

/*
var SHOWEXTRA3 = {
	init : function() {
		var $form = $("#Step3");
		var $add = "<li class='addRemove'>" + "<ul>" + "<li class='add'><span><a href='#' class='addAnother'>Add another entry</a></span></li>" + "</ul>" + "</li>";
		var $remove = "<li class='addRemove'>" + "<ul>" + "<li class='remove'><span><a href='#' class='removeThis'>Remove this entry</a></span></li>" + "</ul>" + "</li>";
		var $addRemove = "<li class='addRemove'>" + "<ul>" + "<li class='add'><span><a href='#' class='addAnother'>Add another entry</a></span></li>" + "<li class='remove'><span><a href='#' class='removeThis'>Remove this entry</a></span></li>" + "</ul>" + "</li>";

		$form.find("fieldset.eduHistory").eq(0).find("ul").append($add);
		$form.find("fieldset.eduHistory").eq(1).find("ul").append($addRemove);
		$form.find("fieldset.eduHistory").eq(2).find("ul").append($addRemove);
		$form.find("fieldset.eduHistory").eq(3).find("ul").append($remove);

		var edu = $form.find("fieldset.eduHistory");
		var arr = $.makeArray(edu);
		
		for(i=1;i<4;i++){
			$form.find("fieldset.eduHistory").eq(1).remove();
		}
		
		$form.find("a.addAnother").live("click",function(){
			var n = $form.find("fieldset.eduHistory").length;
		
			$form.find("fieldset.eduHistory:last li.addRemove").hide();
			$form.find("fieldset.eduHistory:last").after(arr[n]);
			if (n===3){
				$form.find("fieldset.eduHistory:last").after("<div class='warningHeader'>You can only add a maximum of 4 Education History sections</div>");
				$form.find("div.warningHeader").delay(2000).fadeOut(500);
			}
			var x = parseInt($form.find("input.hidden[name='numSections']").val()) + 1;
			$form.find("input.hidden[name='numSections']").attr("value",x);
			return false;
		});

		$form.find("a.removeThis").live("click",function(){
			$(this).closest("fieldset").remove();											 
			var m = $form.find("fieldset.eduHistory").length;											 
			$form.find("fieldset.eduHistory:last li.addRemove").show();
			var y = parseInt($form.find("input.hidden[name='numSections']").val()) - 1;
			$form.find("input.hidden[name='numSections']").attr("value",y);
			return false;
		});
	}
};
*/

var SHOWEXTRA = {
	init : function()
	{
		var $form = $("form"),
			$add = "<li class='addRemove'>" + "<ul>" + "<li class='add'><span><a href='#' class='addAnother'>Add another entry</a></span></li>" + "</ul>" + "</li>",
			$remove = "<li class='addRemove'>" + "<ul>" + "<li class='remove'><span><a href='#' class='removeThis'>Remove this entry</a></span></li>" + "</ul>" + "</li>",
			$addRemove = "<li class='addRemove'>" + "<ul>" + "<li class='add'><span><a href='#' class='addAnother'>Add another entry</a></span></li>" + "<li class='remove'><span><a href='#' class='removeThis'>Remove this entry</a></span></li>" + "</ul>" + "</li>",
			initNum = parseInt($("form input[name='currentBlockCount']").val()),
			c = $("fieldset.eduHistory",$form).length;
		
		for(i=0;i<c;i++)
		{
			switch(i)
			{
				case 0:
					$("fieldset.eduHistory",$form).eq(i).find("ul").append($add);
					break;
				case c-1:
					$("fieldset.eduHistory",$form).eq(i).find("ul").append($remove);
					break;
				default:
					$("fieldset.eduHistory",$form).eq(i).find("ul").append($addRemove);
			}
		}

		// create an array containing all fieldset instances
		var edu = $("fieldset.eduHistory",$form);
		var arr = $.makeArray(edu);
		
		// initialise the fieldsets
		$("fieldset.eduHistory",$form).remove();
		for(i=0;i<initNum;i++)
		{
			//Add buttons before "fieldset.eduQuals" block if form is "Step3" otherwise add before "fieldset.actions" block
			if ($form.find("fieldset.eduQuals").length) $form.find("fieldset.eduQuals").before(arr[i]);
			else $form.find("fieldset.actions").before(arr[i]);
						
			if (i<initNum-1) {
				$form.find("fieldset.eduHistory:last li.addRemove").hide();
			}
		}
		$form.find("input.hidden[name='numSections']").attr("value",initNum);
		
		// click event for add another section
		$form.find("a.addAnother").live("click",function()
		{
			var n = $form.find("fieldset.eduHistory").length;
		
			$form.find("fieldset.eduHistory:last li.addRemove").hide();
			$form.find("fieldset.eduHistory:last").after(arr[n]);
			
			// if this is the last section, display a warning message and then fade it out
			if (n===c-1)
			{
				var id = $("#content form").attr("id");
				//console.log(id);
				switch(id)
				{
					case "Step3":
						$form.find("fieldset.eduHistory:last").after("<div class='warningHeader'>You can only add a maximum of 4 <em>Education History</em> sections</div>");
						break;
					case "Step4":
						$form.find("fieldset.eduHistory:last").after("<div class='warningHeader'>You can only add a maximum of 8 <em>Other Qualification</em> sections</div>");
					case "Step5":
						$form.find("fieldset.eduHistory:last").after("<div class='warningHeader'>You can only add a maximum of 4 <em>Previous Employment</em> sections</div>");
						break;
				}
				$form.find("div.warningHeader").delay(2000).fadeOut(500);
			}
			
			// increment the hidden field
			var x = parseInt($form.find("input.hidden[name='numSections']").val()) + 1;
			$form.find("input.hidden[name='numSections']").attr("value",x);
			return false;
		});

		// click event for remove this entry
		$form.find("a.removeThis").live("click",function()
		{
			$(this).closest("fieldset").remove();											 
			var m = $form.find("fieldset.eduHistory").length;											 
			$form.find("fieldset.eduHistory:last li.addRemove").show();
			
			// increment the hidden field
			var y = parseInt($form.find("input.hidden[name='numSections']").val()) - 1;
			$form.find("input.hidden[name='numSections']").attr("value",y);
			return false;
		});
	}
};


var COMMON = {
	cacheBgs : function() {
		$("body").prepend("<div id='bckgrnds' style='position:absolute;top:0;left:0;display:none;'></div>");
		var n = BACKGROUNDS.img.length;
		for (i=0;i<n;i++) {
			$("#bckgrnds").append("<img src='" + BACKGROUNDS.img[i] + "' alt='' />");
		}
	},
	openPrintDialog : function() {
		
		$(".print").click(function() {
			window.print();
			return false;
		});
		
	},
	checkThirdNav : function() {
		
		if ( $("#secondlevel li.thirdlevel a.in").length ) {
			$("#secondlevel > li > span > a.in").removeClass("in");
		}
		
	},
	inputFocus : function() {
		var $search = $("#search");
		var fVal = null,
			bVal = null;
		$search.focus(function(){
			fVal = $(this).val();
			$search.val("");
			$search.blur(function(){
				bVal = $(this).val();
				if ( bVal === "" ) {
					$search.val(fVal);
				} else {
					$search.val(bVal);	
				}
			});
		});
	},
	newWin : function() {
		$("a.newWin").click(function() {
			window.open(this.href);
			return false;
		});
	},
	caseStudyLanding : function() {
		if ( $("h1:contains('Case Studies')") && $("#accordion").length ) {
			$("#content").height(800);
		}
	},
	randomBg : function() {
		var rn = Math.floor(Math.random()*6);
		bgi = "url(" + BACKGROUNDS.img[rn] + ")";
		$("body").css("background-image",bgi);
	}
};

var cForm = {
	init : function() {
		if ( $("#contactform .error span").length ) {
			$(".errorHeader").show();
		} else $(".errorHeader").hide();
	}
};

