	/*
	--------------------------------------------------------------------------------------------------------------
	
		Name:               Common.js
		Author:             MG
		Date Written:       06/02/2009
		Version:            1.0.0.0
		Purpose:            Common javascript styles
		Dependencies:       jQuery
		References:         http://www.jquery.com

	--------------------------------------------------------------------------------------------------------------
		
		Modification History
	
		1.0.0.0             06/02/2009          MG          Created
		1.0.0.0             17/02/2009          MG          Amended smiley face functions for Black css
	
	--------------------------------------------------------------------------------------------------------------	
	*/



	/* jQuery extensions
	---------------------------------------------------------------------------------------------- */
	
	jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
		return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
	};
	
	jQuery.fn.log = function (msg) {
		console.log("%s: %o", msg, this);
		return this;
	};

	

	$(document).ready(function()
	{		
		var colour = readCookie('site_colours');
		if (colour != 'colour_original') setColour(colour);
	
		var size = readCookie('site_font_size');
		if (size > 0) resizeText(size);

		fixesAndTweaks();
		setActiveTab();
		setEvents();


		/*
			Google Maps Directions
			----------------------
		
			If the iframe already exists then show it
			if not, then create it and make it fill the page
		
			The page's width and height are passed in the url 
			to directions.html so that the overlay div can fill the page
		*/
		
		$("a[title='Get directions']").click(function() {
			mapSetup();
		});
		$(".contactInformation a:first").click(function() {
			mapSetup();
		});
		
		
		function mapSetup(){
			if ($('#iframe').length) {
					$("#iframe").show();
				} else {
					var pageSize = getPageSize();		
					$("body > form > *:first-child").before('<iframe src="/_catalogs/masterpage/directions.html?lat=53.578226&lon=-2.430788&title=Bolton Council&width=' + pageSize[0] + '&height=' + pageSize[1] + '" id="iframe" scrolling="no" allowtransparency="true"></iframe>');
		
					$("#iframe").show();
					$("#iframe").css({
						'width': pageSize[0],
						'height': pageSize[1]
				});
			}
		}


		/*
			Page ratings
			------------
		
			{ If the thank you box doesn't exist }
				-- add click events for the smiley faces
		
			{ If the thank you box does exist } 
				-- white-out the faces
				-- add return false to the click event
				-- remove the hand pointer
		*/
		
		if (! $(".thankyou-msg-box").length) {
			if ($("div#faces").length) {
				$("#faces .voteGood").click(function() {
					clickFace(3);
					return false;
				});

				$("#faces .voteAverage").click(function() {
					clickFace(2);
					return false;
				});
			
				$("#faces .voteBad").click(function() {
					clickFace(1);
					return false;
				});
			}
		} else {
			$("a.voteGood, a.voteAverage, a.voteBad").css('cursor', 'default');
			$("a.voteGood, a.voteAverage, a.voteBad").click(function() {
				return false;
			});
			$("a.voteGood").css('backgroundImage', 'url(/Style%20Library/Bolton/website/imgs/vote-good-white.gif)');
		    $("a.voteAverage").css('backgroundImage', 'url(/Style%20Library/Bolton/website/imgs/vote-average-white.gif)');
		    $("a.voteBad").css('backgroundImage', 'url(/Style%20Library/Bolton/website/imgs/vote-bad-white.gif)')	
		}

	});
	
	
	
	
	/*
		Set click/hover events
	*/
	
	function setEvents()
	{
		$("#printWebPart").click(function () {
			printWebPart();
		});
	
		// toggle popular pages
		$("#popularPagesToggle").click(function() {
			toggleMenuItems($("#popularPages"), $(this));
		});
	
	
		// toggle popular downloads
		$("#popularDownloadsToggle").click(function() {
			toggleMenuItems($("#popularDownloads"), $(this));
		});
		
		
		// toggle 'More Useful Links'
		$("a.footerMoreUsefulLinks").click(function() {
			$("div#more-useful-links").toggle();
			return false;
		});
		
		
		// capture get directions onclick and set it to blank
		// CAN REMOVE LATER
		$("#contactInformation a:first").attr('onclick', '');	
				
		
		/*
			This sets a hover style for all table rows inside the pageContentDisplay div
		*/
				 
		$(".pageContentDisplay table > tbody > tr").hover(
			function () {
				$(this).children().addClass("hovertr");
			},
			function () {
				$(this).children().removeClass("hovertr");
			}
		);	
	}
	
	
	
	
	/*
		Highlight the active tab button
	*/
	
	function setActiveTab()
	{
		var url = location.href.split('/');
		var tab = url[url.length - 3].toLowerCase();
	
		switch(tab) {
			case "home":
				$("li.homeTab").addClass('homeTabOn');
				break;
				
			case "residents":
				$("li.residentsTab").addClass('residentsTabOn');
				break;
				
			case "business":
				$("li.businessTab").addClass('businessTabOn');
				break;
				
			case "visitors":
				$("li.visitorsTab").addClass('visitorsTabOn');
				break;
				
			case "parentsandcarers":
				$("li.parentsCarersTab").addClass('parentsCarersTabOn');
				break;
				
			case "youngpeople":
				$("li.youngPeopleTab").addClass('youngPeopleTabOn');
				break;
				
			case "olderpeople":
				$("li.olderPeopleTab").addClass('olderPeopleTabOn');
				break;
		}
	}
	
	
	
	
	function clickFace(rating)
	{
	    $("#faces input").val(rating);

		$("#faces a").removeAttr('class');
	    $("a#happy").addClass('voteGood');
	    $("a#average").addClass('voteAverage');
	    $("a#bad").addClass('voteBad');
	    
	    if (rating != 3)
		    $("a.voteGood").addClass('goodUnselected');
		if (rating != 2)
		    $("a.voteAverage").addClass('averageUnselected');
		if (rating != 1)
		    $("a.voteBad").addClass('badUnselected')
	
	    $("#popupVote").css("display", "block");
	}
	
	
	
	
	
	function fixesAndTweaks()
	{
		/*
			If div.welcomeImage is not empty then clean it up by removing some of the extra spans inside it, else delete the div
		*/
		if ($("div.welcomeImage").length) {
			if ($("div.welcomeImage").children().children().html()) {
				var html = $("div.welcomeImage").children().children().html();
				$("div.welcomeImage").html(html);
			} else {
				$("div.welcomeImage").remove();
			}
		}


		/*
			Trim the page title to remove extra sifr space
		*/	
		jQuery.trim($("div.pageTitle").html());		
		
		
		/*
			Move the back office link (only applicaa)
		*/
		if ($("a[id$='hlnkBackOffice']").length) {
			var link = $("a[id$='hlnkBackOffice']");
			$("ul#topnav li:last-child").after('<li><a href="' + link.attr('href') +'" title="' + link.attr('title') + '">Webpage Admin</a></li>');
			link.remove();
		}
		
		// removes the "Configure Styles and Layouts" link from SummaryLinkFieldControl
		if ($("img[src$=ConfigureStylesLayout.GIF]").length) {
			$("img[src$=ConfigureStylesLayout.GIF]").parent().parent().remove();
		}
		
		
		/*
			Remove underline from "bookmark" links
		*/
		$("a").not($("a[href]")).addClass('bookmark')
		
		
		/*
			Add external links disclaimer
		*/
		if ($("#panelLinks div#linkitem").length){
			$("#panelLinks > div:last").after("<p class=\"lnk-warning\">Bolton Council is not responsible for the content of external internet sites</p>");
		}
		
		
		/* Edit mode
		--------------------------------------------------------------------------- */
		// Remove the first of the empty rows from each of the start/end date cells
		$("tr.editableDates tr:has(td[height='2']):even").remove();
			
		// Make the date text boxes smaller 
		$("tr.editableDates input[type='text']").width(70);
				
		// Change the scheduling end date "immediately" label
		$(".editableEndDate label:first").text("Default");
				
		/* Remove all blank.gif imgs from tr.editableDates */
		$("tr.editableDates img[src~='blank.gif']").remove();
				
	}
	
	
	
	
	
	// toggle 'in this section', 'downloads' etc...
	function toggleMenuItems(list, img)
	{
		var imgPath = "/style%20library/bolton/website/imgs/icons/";
		var plus = "menuPlus.gif";
		var minus = "menuMinus.gif";
	
		if (img.attr('src') == imgPath + plus) {
			img.attr('src', imgPath + minus);
		} else {
			img.attr('src', imgPath + plus);	
		}
		list.slideFadeToggle(1000);
	}
	
	
	
	
	
	function printWebPart()
	{
		var contentText = $("div.pageContent div");
		var contactInfo = $("#contactInformation");
		var title = document.title;
	
		//Create html to print in new window
		var PrintingHTML = '\
			<html>\
			<head>\
				<title>' + title + '</title>\
				<style type="text/css">\
					body{\
					  font-family:Arial,sans-serif;\
					  font-size:0.9em;\
					  width: 700px;\
					  margin: 30px auto;\
					  border: 1px dashed #cecece;\
					  padding: 10px 20px;\
					}\
					p{\
					  margin: 4px 0;\
					}\
					p.smallPara{\
					  height: 0;\
					}\
					div.contact{\
					  padding-top: 30px;\
					}\
				</style>\
			</head>\
			<body>';
	
	
		PrintingHTML += "<h1>" + title + "</h1>";	
		
		if(contentText.html()) {
			PrintingHTML += contentText.html();
		}
		
		if(contactInfo.html()) {
			PrintingHTML += '<div class="contact">' + contactInfo.html() + '</div>';
		}
	
		PrintingHTML += '</body></html>';
	
		//Open new window to print
	 	var PrintingWindow = window.open(title + "(print)","PrintWebPart", "toolbar,width=800,height=600,scrollbars,resizable,menubar");
	  	PrintingWindow.document.open();
	  	PrintingWindow.document.write(PrintingHTML);
	  	PrintingWindow.document.close();
	}
	
	
	/* --------------------------- */
	/* ----- Rollover images ----- */
	/* --------------------------- */
	
	function MM_preloadImages() { //v3.0
	  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
	}
	
	function MM_swapImage() { //v3.0
	  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
	}
	
	function MM_swapImgRestore() { //v3.0
	  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
	}
	
	function MM_findObj(n, d) { //v4.01
	  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	  if(!x && d.getElementById) x=d.getElementById(n); return x;
	}
	
	
	
	
	
	/* Accessibility
	---------------------------------------------------------------------------------------------- */
	
	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 resizeText(size)
	{
		// If browser is IE6 remove any inline styles from left div
		var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;			
		if (IE6) {
			var leftDiv = document.getElementById('left');
			leftDiv.removeAttribute('style');
		}
		var accessibilityDiv = document.getElementById('accessibility');
		accessibilityDiv.removeAttribute('style');
	
		var fontz;
		var sizeCase = 0;
		switch (parseInt(size)) {
			case 1:
				var fontsz = 0.9;
				break;
			case 2:
				var fontsz = 1.05;
				sizeCase = 2;
				break;
			case 3:
				var fontsz = 1.3;
				sizeCase = 3;
				/* If IE6 then decrease font-size of left div */
				if (IE6) {
					leftDiv.style.fontSize = '0.9em';
				}
				accessibilityDiv.style.fontSize = '0.8em';
				break;
		}
		
		document.body.style.fontSize = fontsz + "em";
		createCookie('site_font_size', sizeCase, 365);		
	}
	
	
	
	function setColour(colour)
	{
		var stylesheet = document.getElementById('dynamicLoadedSheet');
		if (stylesheet) {
			window.setTimeout("document.getElementById('dynamicLoadedSheet').href = '/Style%20Library/Bolton/website/css/" + colour + ".css'", 0);
		} else {
			var cssNode = document.createElement('link');
			cssNode.type = 'text/css';
			cssNode.rel = 'stylesheet';
			cssNode.href = '/Style%20Library/Bolton/website/css/' + colour + '.css';
			cssNode.media = 'screen';
			cssNode.id	 = 'dynamicLoadedSheet';
			document.getElementsByTagName("head")[0].appendChild(cssNode);
		}
		createCookie('site_colours', colour, 365);
	}
	
	// Code to stop ie6 image flicker
	try { document.execCommand('BackgroundImageCache', false, true);} catch(e) {}
	
	
	
	
	// draggable edit menu panel
	function getObject(id) {
		var obj;
		if(document.getElementById) {
	        obj = document.getElementById(id);
	    }
	    else if(document.all) {
	        obj = document.all.item(id);
	    }
	    else {
	        obj = null;
	    }
	    return obj;
	}
	
	
	
	
	
	
	/* Misc functions
	---------------------------------------------------------------------------------------------- */
	
	
	function getPageSize()
	{
		var xScroll, yScroll;
			
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
	
		return [pageWidth,pageHeight];
	}
	
	
	
	function getUrlVars()
	{	
	    var vars = [], hash;
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	
	    for(var i = 0; i < hashes.length; i++) {
	        hash = hashes[i].split('=');
	        vars.push(hash[0]);
	        vars[hash[0]] = unescape(hash[1]);
	    }	    
	    return vars;
	}