

/*
----------------- Global object containing commonoly used funcitons -----------------*/

	var g = {
		
	
	// Prenvent default action
		stopDefault: function (e) {
			if (window.event) {
				window.event.returnValue = false;
			} 
			if (e && e.preventDefault) {
				e.preventDefault();
			}
		},
	
	
	// Cross browser add event
		addEvent: function (elm, evType, fn, useCapture) {
			if (elm.addEventListener) {
				elm.addEventListener(evType, fn, useCapture);
				return true;
			} else if (elm.attachEvent) {
				var r = elm.attachEvent('on' + evType, fn);
				return r;
			} else {
				elm['on' + evType] = fn;
			}
		}
	};	


/*
-----------------   Fire Functions as soon as DOM is ready -----------------------------------*/	

	$(document).ready(function() {
		$("div#pg-scroll").css({width:"1560px"});
		submitButton(); 																			/* Form button handling */
		buttons();																					/* Rounded buttons */							
		galleryCarousel.carouselButtons();															/* Picture Gallery Carousel*/					
		galleryCarousel.pictureGalleryHandling();
		//galleryCarousel.pgHandling();
		carouselButtons("puff-carousel-wrapper", "pcar", 4, "puff-carousel-wrapper .fixed-wrapper");/* Puff Carousel - (element wrapper, button identifiyer, number of default items, append item to) */
		carouselIndicator ("puff-carousel-wrapper", 4, 3, "pcar");
		carouselButtons("picture-carousel", "piccar", 3, "picture-carousel");						/* Picture Carousel */
		carouselIndicator ("picture-carousel", 3, 0, "piccar");
		carouselNavigation();																		/* Carousel buttons */
		
		if ($("div#accordian").length > 0) {
			//alert('hi')
			$('div#accordian ul').hide();
			var firstlist = $('div#accordian .firstlist');
			$(firstlist[0]).next().show();
			//$('#firstaccordian').next().show();
			//var accordianId = $('div.sixcol');
			//alert(accordianId[0].id)
			//$('div#accordian ul').eq(accordianId[0].id).show();	
			//'div#accordian> ul:gt(0)').hide();													/* Close accordian except first section */
		}
		//newWindowIcon();																			/* Add new window icon to external links */
		//sendLinktoFriendlForm.formVisibility();	
		articleEmailForm.formVisibility();	
		if ($("li.ratethis").length > 0) {
			$('<li class="r lastcol"><a href="#" onclick="window.print()">Print Article</a></li>').insertAfter('li.ratethis');
		}

		// TV Guide Carousel
		if ($('#tvguide-carousel').length) {
			tvGuideCarousel.setInitialPos();
		}
		
		photoGalleryRefresh("photos", "7"); // Gallery name, number of items -1

	
	});
	
	


/*
-----------------  Photo Gallery with page refresh  --------------------------------------------------------------------------*/	

function photoGalleryRefresh(galleryName, noOfItems) {
	
	
	var currentURL = window.location;						// Get page URL when loaded
	var urlString = String(currentURL);						// Convert URL to string for manipulation
	var startPos = urlString.indexOf("photoid");			// Find the strart of the string photoid within the URL
	var restOfString = urlString.substr(startPos +7);		// Add the length of photoid to the String to get the end position. leaaving only the number
	var photoId = parseInt(restOfString);					// Convert the number to a number type for manipluation
	var photoArrayPos = photoId - 1; 						// Minus 1 as array starts at 0
	var numberOfThumbs = $('#photos li').size();			// FInd number of list items
	var lastSetStartingItem = numberOfThumbs - noOfItems;	// Find the first item of the last set
	
	/* Create buttons */
		$('#' + galleryName + '-thumbnails').append('<a href="" id="' + galleryName + '-prev" class="carousel-navigation-left" target="_self">Previous</a><a href="" id="' + galleryName + '-next" class="carousel-navigation-right" target="_self">Next</a>');
		
	/* If there is no number at the end of the URL it must be the first item */
		if (!photoId) {
			$('#' + galleryName + ' ' + 'li:first-child').addClass('current-gallery-thumb')
		} else {
			$('#' + galleryName + ' ' +  'li.current-gallery-thumb').eq(0).removeClass("current-gallery-thumb")	
		}
	
	/* 
		Position UL based on arrary number
		To find the amount to move the UL to the left, calculate the difference between the window size and the number of thumbnails	
		If the item sits in the first or last set of viewied images then dont move
	*/
		if (photoArrayPos > noOfItems) {
		/*if (photoArrayPos > noOfItems && photoArrayPos < lastSetStartingItem - 1) {*/
			var windowWidth = $('#' + galleryName + '-window').outerWidth();
			var thumbNailSize = $('#' + galleryName + ' ' + 'li').find('a').eq(0).outerWidth();
			var reduceBy =  ((thumbNailSize + 10) * photoId)  - windowWidth;
			var negativeReduceBy = "-" + reduceBy + "px";
			$('#' + galleryName).css({position:"relative", left: negativeReduceBy})
		}	
	
	
	/* Match that number with the listItem in the array and give it the class current-gallery-thumb. */
		$('#' + galleryName + ' ' + 'li').eq(photoArrayPos).addClass('current-gallery-thumb')
		var nextItemURL =  $('#' + galleryName + ' ' + 'li.current-gallery-thumb').eq(0).next().find("a").attr("href")
		var prevItemURL =  $('#' + galleryName + ' ' + 'li.current-gallery-thumb').eq(0).prev().find("a").attr("href")
		$('#' + galleryName + '-prev').attr('href', prevItemURL)
		$('#' + galleryName + '-next').attr('href', nextItemURL)
	
	/*
		Set the href of the next and previous buttons	
		If there is not previous item set return false to prevent page refresh
	*/
		if (photoId === 1 || !photoId) {
			$('#' + galleryName + '-prev').attr('onclick', 'return false').addClass('disabelleft')
		} else {
			$('#' + galleryName + '-prev').attr('href', prevItemURL)
		}
		
		
		if (photoId === numberOfThumbs) {
			$('#' + galleryName + '-next').attr('onclick', 'return false').addClass('disabelright')
		} else {
			$('#' + galleryName + '-next').attr('href', nextItemURL)
		}
}



/*
-----------------  TV Guide  --------------------------------------------------------------------------*/	

var tvGuideCarousel = {
	
	currentPosition: 0,
	//guideUl = $('#tvguide-listings'),
	
	setInitialPos: function() {
		//alert('hi')
		liveNow = $('.current-programme');
		var currentProg = $(liveNow[0]).position(); // Find the positon of the current item
		var currentProgLeft = currentProg.left;
		//alert(currentProgLeft);
		var minusPos = parseInt("-" + currentProgLeft); // Set this position to a negative number	as we are sliding left
		$('#tvguide-listings').css({left: minusPos});
		tvGuideCarousel.currentPosition = minusPos;
		
		// Add Buttons
		$('<a href="" id="tvguide-prev" class="carousel-navigation-left">Previous</a><a href="" id="tvguide-next" class="carousel-navigation-right">Next</a>').appendTo('#tvguide-carousel')
	},
	

	guideCarousel: function () {
		
		$('a#tvguide-next').click( function(e) {		
			e.preventDefault();
			if ($('a#tvguide-prev').is('.disabelleft'))   {
				$('a#tvguide-prev').removeClass('disabelleft')
			}
			var currentItem = $('.current-programme')[0];
			
			if ($(this).is('.disabelright')) {
						return false;
			} else {
				var currentItemWidth = $(currentItem).outerWidth();
				var nextItemWidth = $(currentItem).next().outerWidth();
				var newPosition = tvGuideCarousel.currentPosition - currentItemWidth;
				//alert(newPosition + " " + currentItemWidth)
				$('#tvguide-listings').animate({left: newPosition});
				$(currentItem).next().addClass('current-programme');
				$(currentItem).removeClass('current-programme')
				tvGuideCarousel.currentPosition = newPosition;
				// Test to see if we have reached the last item, this is done by finding the width of all list items, 
				// From here we can determine how much of the UL is left to display by subtracting the currentPositin from the totalWidth
				// If the area is less than the window area, then we should disable the button to prevent any more scrolling
				var totalLiWidth = 0;
				$("#tvguide-listings li").each( function() {
					var itemWidth = $(this).outerWidth();
					totalLiWidth = itemWidth + totalLiWidth;
				})
				var visibleArea = totalLiWidth -  Math.abs(tvGuideCarousel.currentPosition);
				if (visibleArea < 730) {
					$(this).addClass('disabelright')
				}
				

			}
			return false;
		});
		
		$('a#tvguide-prev').click( function(e) {		
				e.preventDefault();
				if ($('a#tvguide-next').is('.disabelright'))   {
					$('a#tvguide-next').removeClass('disabelright')
				}
				var currentItem = $('.current-programme')[0];
				if ($(currentItem).is('#firstguide') && $(this).is('.disabelleft')) {
						return false;
				} else {
					var prevItem = $(currentItem).prev();
					var currentItemWidth = $(currentItem).outerWidth();
					var prevItemWidth = $(currentItem).prev().outerWidth();
					var newPosition = tvGuideCarousel.currentPosition + prevItemWidth;
					$('#tvguide-listings').animate({left: newPosition});
					$(currentItem).prev	().addClass('current-programme');
					$(currentItem).removeClass('current-programme')
					tvGuideCarousel.currentPosition = newPosition;
					if($(prevItem).is('#firstguide')) {
						$(this).addClass('disabelleft');
					}
				}
			return false;
		});
	}
};


/*
-----------------  Form Validation  --------------------------------------------------------------------------*/	

		
		/*------- Convert submit button to link ----------*/
			function submitButton() {
					$("form .formsubmit").each( function() {
					var currentForm = this;
					var buttonText = currentForm.value;
					$(currentForm).before('<div class="button-container fleft wbg"><a href="#">' + buttonText + '</a></div>').remove(); 
				});
			};
			
			var sendLinktoFriendlForm = {
			
				
				// Hide form, and toggle its state
				formVisibility: function () {
					$('#stfbutton').click(function(e) {
						e.preventDefault();
						if ($("#stfform").is(":hidden")) {
							$("#stfform").slideDown("slow");
						} else {
							$("#stfform").slideUp("slow");
			
						}
					})
				},
				
				// Validation rules
				emailFormValidation: function () {
					if(!document.getElementById("stfform")) {
						return false;
					}
					$("#stfform").RSV({
						displayType: "display-html",
						errorTextIntro: "Please correct the following errors:",
						errorFieldClass: "errorfield",
						rules: [
							"required,youremail,Enter an email address for the sender",
							"valid_email,youremail,Enter a valid email address for the sender",
							"required,friendsemail,Enter an email address for the recipitent",
							"valid_email,friendsemail,Enter a valid email address for the recipitent"	
						]
					});
				},
				
				//Submit eamilarticle form
				submitEmailArticleForm: function () {
					if(!document.getElementById("stfform")) {
						return false;
					}
					$('#stfform div.js-button-container').click(function(e) {
						e.preventDefault();
						$('#stfform').submit();
					});
				}
			};
			
			var articleEmailForm = {
			
				
				// Hide form, and toggle its state
				formVisibility: function () {
					//$('#article-email').hide();
					$('#emailarticle-link').click(function(e) {
						e.preventDefault();
						if ($("#article-email").is(":hidden")) {
							$("#article-email").slideDown("slow");
						} else {
							$("#article-email").slideUp("slow");
			
						}
					})
				},
				
				// Validation rules
				emailFormValidation: function () {
					if(!document.getElementById("article-email")) {
						return false;
					}
					$("#article-email").RSV({
						//onCompleteHandler: myOnComplete,
						displayType: "display-html",
						errorTextIntro: "Please correct the following errors:",
						errorFieldClass: "errorfield",
						rules: [
							"required,recipientemail,Enter an email address for the recipitent",
							"valid_email,recipientemail,Enter a valid email address for the recipitent",		
							"required,youremail,Enter an email address for the sender",
							"valid_email,youremail,Enter a valid email address for the sender",		
							"required,name,Enter your name",
							"length<1001,message,The message must be no longer than 1000 characters"
						]
					});
				},
				
				//Submit eamilarticle form
				submitEmailArticleForm: function () {
					if(!document.getElementById("article-email")) {
						return false;
					}
					$('#article-email div.js-button-container').click(function(e) {
						e.preventDefault();
						$('#article-email').submit();
					});
				}
			};

		

	

/*
-----------------  Accordian -----------------------------------*/	

	function accordiananimation() {
			$('div#accordian').addClass("accordian-active");
			$('div#accordian> h3').wrapInner('<a></a>');
			$('#accordian h3.firstlist a').addClass("open-state")
			$('div#accordian> h3').click(function() {
				
				var innerLink = this.firstChild;
				if (innerLink.className === "open-state") {
					$(innerLink).removeClass("open-state");
				} else {
					$('div#accordian> h3 a').each( function() {
						$(this).removeClass("open-state");
					});									
					$(innerLink).addClass("open-state");	
				}
				
				var $nextUl = $(this).next();
				var $visibleSiblings = $nextUl.siblings('ul:visible');
				if ($visibleSiblings.length ) {
						$visibleSiblings.slideUp('normal', function() {
							$nextUl.slideToggle('normal');
							return false;
						});
				} else {
					$nextUl.slideToggle('normal');
				}
			});
		};
		
					
		
/*
-----------------  Carousel  --------------------------------------------------------------------------*/	

	
	// Carousel (jCarouselLite -Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com) 
		(function($) {                                        
			$.fn.jCarouselLite = function(o) {
				o = $.extend({
					btnPrev: null,
					btnNext: null,
					btnGo: null,
					mouseWheel: false,
					auto: null,
					speed: 450,
					easing: null,
					vertical: false,
					circular: true,
					visible: 2,
					start: 0,
					scroll: 2,
					beforeStart: null,
					afterEnd: null
				}, o || {});
			
				return this.each(function() {                           // Returns the element collection. Chainable.
				
					
					var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
					var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;
					if(o.circular) {
						ul.prepend(tLi.slice(tl-v-1+1).clone())
						  .append(tLi.slice(0,v).clone());
						o.start += v;
					}
			
					var li = $("li", ul), itemLength = li.size(), curr = o.start;
									
					div.css("visibility", "visible");
			
					li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
					ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
					div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"});
			
					var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
					var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
				   
					var divSize = liSize * v;                           // size of entire div(total length for just the visible items)
			
					//li.css({width: li.width(), height: li.height()});
					ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
			
					div.css(sizeCss, divSize+"px");                     // Width of the DIV. length of visible images
			
					
					if(o.btnPrev)
						$(o.btnPrev).click(function() {
							var findParentPrevButton = $(o.btnPrev).parent("div")[0];
							if (findParentPrevButton.id === "pg-wrapper") {
								var current = $("li.currentthumb")[0];
								if (current.id === "lastthumb" || current.id === "secondlastthumb" || current.id === "thirdlastthumb" || current.id === "fourthlastthumb" ) {
									return false;
								} else {
									return go(curr-o.scroll);
								}
							} else {
								return go(curr-o.scroll);
							}
						});
			
					if(o.btnNext)
						$(o.btnNext).click(function() {
							// Test if the page has a picture gallery
							// Added by CL - If the thumbnail is one of the first 3 then dont scroll
							var findParentNextButton = $(o.btnNext).parent("div")[0];
							if (findParentNextButton.id === "pg-wrapper") {
								var current = $("li.currentthumb")[0];
								if (current.id === "firstthumb" || current.id === "secondthumb" || current.id === "thirdthumb") {
								//if (current.id === "lis0" || current.id === "lis1" || current.id === "lis2" || current.id === "lis3" || current.id === "lis4" || current.id === "lis5" || current.id === "lis6" || current.id === "lis7") {	
									return false;
								} else {
									return go(curr+o.scroll);
								
								}
							} else {
								return go(curr+o.scroll);
							}
							
						});
			
					if(o.btnGo)
						$.each(o.btnGo, function(i, val) {
							$(val).click(function() {
								return go(o.circular ? o.visible+i : i);
							});
						});
			
					if(o.mouseWheel && div.mousewheel)
						div.mousewheel(function(e, d) {
							return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
						});
			
					if(o.auto)
						setInterval(function() {
							go(curr+o.scroll);
						}, o.auto+o.speed);
			
					function vis() {
						return li.slice(curr).slice(0,v);
					};
			
					function go(to) {
						if(!running) {
			
							if(o.beforeStart)
								o.beforeStart.call(this, vis());
			
							if(o.circular) {            // If circular we are in first or last, then goto the other end
								if(to<=o.start-v-1) {           // If first, then goto last
									ul.css(animCss, -((itemLength-(v*2))*liSize)+"px");
									// If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
									curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll;
								} else if(to>=itemLength-v+1) { // If last, then goto first
									ul.css(animCss, -( (v) * liSize ) + "px" );
									// If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
									curr = to==itemLength-v+1 ? v+1 : v+o.scroll;
								} else curr = to;
							} else {                    // If non-circular and to points to first or last, we just return.
								if(to<0 || to>itemLength-v) return;
								else curr = to;
							}                           // If neither overrides it, the curr will still be "to" and we can proceed.
			
							running = true;
			
							ul.animate(
								animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
								function() {
									if(o.afterEnd)
										o.afterEnd.call(this, vis());
									running = false;
								}
							);
							// Disable buttons when the carousel reaches the last/first, and enable when not
							if(!o.circular) {
								$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
								$( (curr-o.scroll<0 && o.btnPrev)
									||
								   (curr+o.scroll > itemLength-v && o.btnNext)
									||
								   []
								 ).addClass("disabled");
							}
			
						}
						return false;
					};
				});
			};
			
			function css(el, prop) {
				return parseInt($.css(el[0], prop)) || 0;
			};
			function width(el) {
				return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
			};
			function height(el) {
				return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
			};
	
		})(jQuery);	
		
	
	// Carousel setup variables 
		function carouselNavigation() {				
			// Picture Gallery 
				$("#pg-window").jCarouselLite({
				  btnNext: "#pg-right",
				  btnPrev: "#pg-left",
				  visible: 8,
				  scroll: 1,
				  circular: false
				});
			// Puff Carousel	
				$("#pcar-window").jCarouselLite({
				  btnNext: "#pcar-right",
				  btnPrev: "#pcar-left",
				  visible: 4,
				  scroll: 4,
				  circular: false,
				  speed: 800
				});
			// Picture Carousel	
				$("#piccar-window").jCarouselLite({
				  btnNext: "#piccar-right",
				  btnPrev: "#piccar-left",
				  visible: 3,
				  scroll: 3,
				  circular: false,
				  speed: 800
				});
		};

	
	
	// Picture Gallery Carousel
		var galleryCarousel = {
		
			// Add buttons to the gallery, only if there are more than 8 items.
				carouselButtons: function () {
					$("#thumbwindow-cover").show();
					if (($("#picture-gallery").length > 0) && ($("#pg-scroll li").length > 8))  {
						$('<a href="#" onClick="return false" id="pg-left" class="carousel-navigation-left disabelleft">Pictures gallery - Left</a><a href=#"" onClick="return false" id="pg-right" class="carousel-navigation-right">Picutres gallery - Right</a>').appendTo("#pg-wrapper")
					}
				},
		
			// Give items id based on their position within the list
				identifyItems: function() {
					var thumbid = ["firstthumb", "secondthumb", "thirdthumb", "currentthumb", "fourthlastthumb", "thirdlastthumb", "secondlastthumb", "lastthumb"] 
					var lis = $("#pg-scroll li");
					var lisLength = parseInt(lis.length);
					if (lisLength > 8) {					
						var lastItem = lisLength - 1;
						var secondlastItem = lisLength - 2;
						var thirdlastItem = lisLength - 3;
						var fourthlastitem = lisLength - 4; 
						lis[0].id = thumbid[0];
						lis[0].className = thumbid[3];
						lis[1].id = thumbid[1];
						lis[2].id = thumbid[2];
						//lis[3].className = thumbid[3];
						lis[lastItem].id = thumbid[7];
						lis[secondlastItem].id = thumbid[6];
						lis[thirdlastItem].id = thumbid[5];
						lis[fourthlastitem].id = thumbid[4];
					}
				},
	
			
			// Handle the passing of the currentThumb class, which identifies what image is being viewed
			// From this we can extract the image that should be displayed in the main gallery and the caption below it.
				slideMainGallery: function() {
					if (document.getElementById("pg-right") || document.getElementById("pg-left")) {

						// Right button	
						$("a#pg-right").click(function() {
							var current = $("li.currentthumb")[0];
							if (current.id !== "lastthumb") {
								// Pass the currentThumb class to help identify what thumbnail is being viewed
									$(current).removeClass("currentthumb");
									$(current).next().addClass("currentthumb");
								// Set the current Thumb to be the thumbnail that was passed the className	
									var current = $("li.currentthumb")[0];
								// Find the href of the current thumbnail image
									var linkHref = current.firstChild.href;
								// Set the main gallery image to the value retrieved from the thumbnail href
									$("#gallery-placeholder > img")[0].src = linkHref;
								// Set the caption below the main image to the value retrieved from the thumbnail img alt text
									imageAlt = current.firstChild.firstChild.alt;
									$('#gallery-caption').html(imageAlt)
							}
							// Animage the covering window indicator based on what is being viewd.
								animateWindowFrame(current, "right");
						})
							
					// Left button
						$("a#pg-left").click(function() {
							var current = $("li.currentthumb")[0];
							
							if (current.id !== "firstthumb") {
									$(current).removeClass("currentthumb");
									$(current).prev().addClass("currentthumb");
									var current = $("li.currentthumb")[0];
									var linkHref = current.firstChild.href;
									$("#gallery-placeholder > img")[0].src = linkHref;
									imageAlt = current.firstChild.firstChild.alt;
									$('#gallery-caption').html(imageAlt)
							}
								animateWindowFrame(current, "left");
						})
						} else {
							// No buttons are available so the window should jump based on the users click
							// To do this each li is given a unique id, which is captured in the pictureGalleryHandling function
							var idNumber = 0;
							$("#pg-scroll li").each(function (i) {
							this.id = "lis" + idNumber;
							idNumber = idNumber + 1;
							});
						}
					},

				
					pgHandling: function() {
						//var currentLeftPosition = 0;
						$("#thumbwindow-cover").css({position:"absolute", top:"5px", left:"55px"})
						$("#pg-scroll a").click(function(e) {
							e.preventDefault();
							var currentImage = this;
							var currentPosition = $(this).position();
							var leftPosition = parseInt(currentPosition.left) + 55;
							$("#thumbwindow-cover").animate({left: leftPosition + "px"})
							//alert(leftPosition + "px")
							alert( "left: " + currentPosition.left + ", top: " + currentPosition.top )
						})
					},
				
				// Display image and caption when the user clicks a thumbnail
				// If there are less than 8 thumbnails shift the window onclick 
					pictureGalleryHandling: function () {
						if (!document.getElementById('picture-gallery')) {
							return false;
						}
						var firstAlt = $('img#firstgallery');
						$('#gallery-caption').html(firstAlt[0].alt)
						// This id will only be available if their are 8 or less list items
							if ("li#lis0") {
								$("#thumbwindow-cover").css({left: "55px"});
							};
						$("#pg-scroll img").click(function(e) {
							e.preventDefault();
								var linkHref = current.firstChild.href;
								$("#gallery-placeholder > img")[0].src = linkHref;
							// Get the thumbnail alt text and use it for the main image caption
								imageAlt = this.alt;
								$('#gallery-caption').text(imageAlt)
							// Handle clicking on images and move window based on that	
									var currentId = this.parentNode.parentNode.id;
									switch (currentId) {
										case "lis1":
											$("#thumbwindow-cover").animate({left: "115px"});
											break; 
										case "lis2":
											$("#thumbwindow-cover").animate({left: "175px"});
											break; 					
										case "lis3":
											$("#thumbwindow-cover").animate({left: "235px"});
											break; 	
										case "lis4":
											$("#thumbwindow-cover").animate({left: "295px"});
											break; 	
										case "lis5":
											$("#thumbwindow-cover").animate({left: "355px"});
											break;
										case "lis6":
											$("#thumbwindow-cover").animate({left: "415px"});
											break; 	 						
										default:
											$("#thumbwindow-cover").animate({left: "55px"});
											break;
									};
								
								return false;
						})
					}
	}
	
	
	
	// Animate movement of window frame 
		function animateWindowFrame (moveMe, direction) {
				switch (moveMe.id) {
				case "firstthumb":
					$("#thumbwindow-cover").animate({left: "55px"});
					// Add a class to the first item so it can be styled differently, disabled
					if (direction === "left") {
						$("#pg-left").addClass("disabelleft");
					}
					break;   
				case "secondthumb":
					$("#thumbwindow-cover").animate({left: "115px"});
					if (direction === "right") {
						$("#pg-left").removeClass("disabelleft");
					}
					break; 
				case "thirdthumb":
					$("#thumbwindow-cover").animate({left: "175px"});
					break; 					
				case "fourthlastthumb":
					$("#thumbwindow-cover").animate({left: "295px"});
					break; 	
				case "thirdlastthumb":
					$("#thumbwindow-cover").animate({left: "355px"});
					break; 	
				case "secondlastthumb":
					$("#thumbwindow-cover").animate({left: "415px"});
					if (direction === "left") {
						$("#pg-right").removeClass("disabelright");
					}
					break; 	 	
				case "lastthumb":
					$("#thumbwindow-cover").animate({left: "475px"});
					// Add a class to the last items so it can be styled differently, disabled
					if (direction === "right") {
						$("#pg-right").addClass("disabelright");
					}
					break; 	 	
				default:
					$("#thumbwindow-cover").animate({left: "235px"});
					break;
			};
	
		}


/*  Picture and Puff Carousel handling
	
	Values are passed in to create buttons, the position indicator, and then slide the indicator based on the set 
	of images being show

---------------------------------------------------------------------------------------------------------------*/
	
		//Create buttons
			function carouselButtons(buttonWrapper, buttonName, defaultItems, appendIt) {
				if (($("#" + buttonWrapper).length > 0) && ($("#" + buttonWrapper + " li").length > defaultItems)) {
					$('<div class="carousel-buttons clearing"><div id="' + buttonName + '-butts" class="fright"><a href="#" onClick="return false" id="' + buttonName + '-left" class="carousel-navigation-left disabelleft">More from stv - Left</a><div id="' + buttonName + '-indicator" class="indicator clearing"></div><a href=#"" onClick="return false" id="' + buttonName + '-right" class="carousel-navigation-right">More from stv - Right</a></div></div>').appendTo("#" + appendIt)[0];
				}
			}
		
		// Create the indicator, this is based on the number of list items within the given carousel
			function carouselIndicator (buttonWrapper, defaultItems, minusItems, buttonName) {
				if (($("#" + buttonWrapper + " li").length > defaultItems)) {
					var generatedLis = $("#" + buttonWrapper + " li");
					var lis = parseInt(generatedLis.length) - minusItems;
					var numberOfIndicators = lis / defaultItems;
					var getWholeNumberOfIndicators = Math.round(numberOfIndicators);
					$("div#" + buttonName + "-indicator").append("<img src='/assets/img/britannia-high/indicator-dot-current.gif' alt='' width='12' height='21' id='" + buttonName + "-firstdot' class='currentdot' />");
					for (var i = 2; i < getWholeNumberOfIndicators; i++) {
						$("div#" + buttonName + "-indicator").append("<img src='/assets/img/misc/indicator-dot.gif' alt='' width='12' height='21' id='" + buttonName + "-indicator" + [i] + "' />");
					}			
					$("div#" + buttonName + "-indicator").append("<img src='/assets/img/misc/indicator-dot.gif' alt='' width='12' height='21' id='" + buttonName + "-lastdot' />");
				}
			}
		
		// Move the indicator left or right, this function is dependent of the buttons being created 
			function slideIndicator(buttonName) {
				if ($("a#" + buttonName + "-right") && $("a#" + buttonName + "-left")) {
					// Calculate the number of dots, so we can find the second last dot which is used as a trigger to remove disabelright
					var numberOfDots = $("div #" + buttonName + "-indicator img").length;
					var secondLastDot = parseInt(numberOfDots) - 1;
					// Indicator Left
						$("a#" + buttonName + "-left").click(function() {
						var current = $("#" + buttonName + "-butts #" + buttonName + "-indicator img.currentdot")[0];
							if (current.id !==  buttonName + "-firstdot") {
								$(current).removeClass("currentdot").attr({src: "/assets/img/misc/indicator-dot.gif"});
								var passDot = $(current).prev().addClass("currentdot").attr({src: "/assets/img/britannia-high/indicator-dot-current.gif"});
							}
							// Find what position the dot is at.  If on the firstDot or lastDot add or remove the class "disabled"
								var findDot = $("div #" + buttonName + "-indicator .currentdot")[0];
								if (findDot.id === buttonName + "-firstdot") {
									$(this).addClass("disabelleft")
								}
								if (findDot.id === buttonName + "-indicator" + secondLastDot) {
									$("a#" + buttonName + "-right").removeClass("disabelright");
								}

						});			
					// Indicator right
						$("a#" + buttonName + "-right").click(function() {
							var current = $("#" + buttonName + "-butts #" + buttonName + "-indicator img.currentdot")[0];
							if (current.id !==  buttonName + "-lastdot") {
								$(current).removeClass("currentdot").attr({src: "/assets/img/misc/indicator-dot.gif"});
								var passDot = $(current).next().addClass("currentdot").attr({src: "/assets/img/britannia-high/indicator-dot-current.gif"});
							}
							// Find what position the dot is at.  If on the firstDot or lastDot add or remove the class "disabled"
								var findDot = $("div #" + buttonName + "-indicator .currentdot")[0];
								if (findDot.id === buttonName + "-lastdot") {
									$(this).addClass("disabelright")
								}
								if (findDot.id === buttonName + "-indicator2") {
									$("a#" + buttonName + "-left").removeClass("disabelleft");
								}
						});		
				}
			}



/*
----------------- Buttons -----------------------------------*/	
	
	
	function buttons() {
			$("div.button-container").addClass("js-button-container").removeClass("button-container").each(function (i) {
			var next = this;
			if (next.firstChild.className !== "emptybut") {
				$(next).prepend("<div class='emptybut'></div>");
			}
			});
			$(".js-button-container > a").wrap("<div class='button'><span></span></div>");
	};
	
/*
-----------------  Social Bookmarking  -----------------------------------*/	


	var socialBookmarking = {
			bookmark: function () {
			if (!document.getElementById("bookmarking-sites")) return false;
			//var bookmarkingSites = g.idTn("bookmarking-sites", "a");
			var bookmarkingSites = $("#bookmarking-sites a");
			var bookmarkIntro = $("#bookmark-into");
			if (!bookmarkIntro) return false;
			$(bookmarkIntro).addClass("hide");
					
				if ($("body.programmes").length > 0) {
					var programmeTitle = $("#programme-title h1 span").text();
					var subheading = $(".subhead")[0];
					var pageHeader = programmeTitle + " | " + $(subheading).text();
				}
	
				for (var i = 0; i < bookmarkingSites.length; i++) {
				
				var titleText = encodeURIComponent(pageHeader);
				/* Build URL based on what link is selected */
				bookmarkingSites[i].onclick = function () {	
					var socialBookmarkSite = this.href;
					var thisPageURL = encodeURIComponent(location.href);			
					switch (socialBookmarkSite) {
					case "http://www.stumbleupon.com/":
						var socialLink = socialBookmarkSite+ 'submit?url=' + thisPageURL + '&title=' + titleText;
						break;   
					case "http://www.facebook.com/sharer.php":
						var socialLink = socialBookmarkSite+ '?u=' + thisPageURL + '&=' + titleText;
						break; 
					case "http://www.google.com/bookmarks/":
						var socialLink = socialBookmarkSite+ 'mark?op=edit&bkmk=' + thisPageURL + '&title=' + titleText;
						break; 					
					case "http://technorati.com/":
						var socialLink = socialBookmarkSite+ 'faves?add=' + thisPageURL + '&t=' + titleText;
						break; 	
					case "http://www.furl.net/":
						var socialLink = socialBookmarkSite+ 'storeIt.jsp?u=' + thisPageURL + '&t=' + titleText;
						break; 	
					default:
						var socialLink = socialBookmarkSite+ '?url=' + thisPageURL + '&title=' + titleText;
						break;
					}
					var thisLink = this.href;
					window.open(socialLink); 
					g.stopDefault(thisLink);
					return false;
				}
			}
		}
	};

	
/*
-----------------  New window  -----------------------------------*/	

/* New window Icon */
	function newWindowIcon() {
		$("a[@rel$='external']").append(" <img src='/assets/img/misc/icon-new-window.gif' alt='(link open in new browser window)'").click(function(){
			this.target = "_blank";
		});
	}



// Set font size smaller for Opera on Mac
function operaCheck() {		
	if (navigator.appVersion.indexOf("Win") == -1) {
		if ($.browser.opera) {
			$("body").css({fontSize: "60%"})
		}
	}
};



/*
----------------- 11. Load events on page load -----------------------------*/

 $(window).load(function () {
	socialBookmarking.bookmark();
	accordiananimation();
	galleryCarousel.identifyItems();
	galleryCarousel.slideMainGallery();
	slideIndicator("pcar");
	slideIndicator("piccar");
	sendLinktoFriendlForm.emailFormValidation();
	sendLinktoFriendlForm.submitEmailArticleForm();
	articleEmailForm.emailFormValidation();
	articleEmailForm.submitEmailArticleForm();
	tvGuideCarousel.guideCarousel();

});
	

