var LBI = {};

LBI.Data = {
	
	minPageWidth : 985,
	lightboxAssetWidth : 609,
	lightboxAssetHeight : 345,
	youtubeParams : '&enablejsapi=1&playerapiid=lightboxVideo&rel=0&showsearch=0&color1=0xe2e2e2&color2=0xffffff&loop=1',
	swfObjectParams : { 
							
		allowScriptAccess : "always",
		wmode : 'transparent'
								
	},
	numberOfGalleryItems : 16,
	numberNewsItemsOnPage : 5,
	playingIcon : '<img src="../assets/images/playing.gif" alt="Now playing" />',
	noQuicktimeMessage : $('<p>Install the latest <a target="_blank" href="http://www.apple.com/quicktime/download/">Quicktime</a> for a better experience</p>')
	
}

LBI.Common = {
	
	//handle cross-browser reading of CSS-set styles
	getStyle : function (el,stylename){
	
		if(el.style[stylename]){
		
			return el.style[stylename];
		
		}
		else if(el.currentStyle){
		
			//handle IE's style-name to styleName convention
			if(stylename.indexOf("-") != -1 && !el.currentStyle[stylename]){
			
				//get 1st char after -, uppercase, rem -
				var preHyphen = stylename.substr(0,stylename.indexOf("-"));
				var postHyphenFirstLetter = stylename.substr(stylename.indexOf("-")+1,1).toUpperCase();
				var postHyphenRemainder = stylename.substr(stylename.indexOf("-")+2);
				
				stylename = preHyphen + postHyphenFirstLetter + postHyphenRemainder;
			
			}
			
			return el.currentStyle[stylename];
		
		}
		else if(document.defaultView && document.defaultView.getComputedStyle){
		
			return document.defaultView.getComputedStyle(el,null).getPropertyValue(stylename);
		
		}
		
		else{
			
			return false;
			
		}
		
	},
	
	// handle cross-browser viewport height
	getViewPortHeight : function(){
		
		if(window.innerHeight){
		
			return window.innerHeight;
		
		}
		else if(document.documentElement && document.documentElement.clientHeight){
		
			return document.documentElement.clientHeight;
		
		}
		else if(document.body){
		
			return document.body.clientHeight;
		}
		else{
			
			return false;
			
		}
		
	},
	
	//handle cross-browser viewport width
	getViewPortWidth : function(){
		
		if(window.innerWidth){
		
			return window.innerWidth;
		
		}
		else if(document.documentElement && document.documentElement.clientWidth){
		
			return document.documentElement.clientWidth;
		
		}
		else if(document.body){
		
			return document.body.clientWidth;
		}
		else{
			
			return false;
			
		}
		
	},
	
	//find and compare viewport and body heights and widths. return the largest of each dimension in array
	getFullPageDimensions : function(){
		
		var newHeight = LBI.Common.getViewPortHeight();
		var newWidth  = LBI.Common.getViewPortWidth();
		
		// compare with body
		if(newWidth < document.body.clientWidth){
			
			newWidth = document.body.clientWidth;
			newWidth += parseInt(LBI.Common.getStyle(document.body,"margin-left"),10) + parseInt(LBI.Common.getStyle(document.body,"margin-right"),10);
		
		}
		
		if(newHeight < document.documentElement.scrollHeight){
		
			newHeight = document.documentElement.scrollHeight;
			newHeight += parseInt(LBI.Common.getStyle(document.body,"margin-top"),10) + parseInt(LBI.Common.getStyle(document.body,"margin-bottom"),10);
			
			//handle Firefox bug where it counts the scrollbar too for scrolling pages
			if(window.innerWidth && window.innerWidth > document.body.scrollWidth){newWidth -= 17;}
		
		}
		
		return [newWidth,newHeight];
	
	},
	
	//handle cross-browser viewport height
	getViewPortHeight : function(){
	
		if(window.innerHeight){
		
			return window.innerHeight;
		
		}
		else if(document.documentElement && document.documentElement.clientHeight){
		
			return document.documentElement.clientHeight;
		
		}
		else if(document.body){
		
			return document.body.clientHeight;
		
		}
		else{
			
			return false;
			
		}
	
	},
	
	//handle cross-browser retrieval of how far user has scrolled down
	getScrollTop : function(){
		
		if(window.pageYOffset){
		
			return window.pageYOffset;
		
		}
		else if(document.documentElement && document.documentElement.scrollTop){
		
			return document.documentElement.scrollTop;
		
		}
		else if(document.body){
		
			return document.body.scrollTop;
		}
		else{
			
			return false;
			
		}
		
	}
	
}


LBI.Custom = {
	
	//helps to handle hover effect in IE6
	hoverFix:function(){
		$(".hoverFix")
			.hover(
					function(){$(this).addClass("hover")},
					function(){$(this).removeClass("hover")}								
			)
			.focus(
				  function(){$(this).addClass("hover")}
			)
			.blur(
				  function(){$(this).removeClass("hover")}								
			)
	},
	
	formValidation:function(){
		$(".userData").submit(function(){
			var isOk=LBI.Custom.parentalCheck();
			if (!isOk) return false;
			$(".mandatory").each(function(){
										  
				if (this.type=="checkbox" && this.checked==false){
					isOk=false;
					$(this).addClass("required");
					this.focus();
					return false;					
				}
				if (this.value==""){
					isOk=false;
					$(this).addClass("required");
					this.focus();
					return false;
				}
			})
			
			return isOk;
		})
	},
	
	parentalCheck:function(){
		var div=$(".parentalCheck");
		var day=$("#day").attr("value");
		var month=$("#month").attr("value");

		var year=$("#year").attr("value");			
		
		var dob=new Date();
		dob.setFullYear(year);
		dob.setMonth(parseInt(month)-1);
		dob.setDate(parseInt(day));

		
		var now=new Date();
		
		var age=new Date(now.getTime()-dob.getTime());
		
		var userAge=age.getFullYear()-1970;
		var chk=$("#parentalCheck");
		
		if (userAge<18){
			div.slideDown()				
			if (!chk.attr("checked")){
				chk.focus();
				return false;
			}
		}else{
			chk.show();
			chk.attr("checked",true);
		}
		
		return true;
	},
		
	// stop background images flickering in IE6
	stopBackgroundImageFlicker: function(){
	
	    try {
            document.execCommand("BackgroundImageCache", false, true);
        } 
        
        catch(err) {}
    },
	
	homepage : {
		
		init : function(){
			
			// only do this stuff if on the home page
			if ($('.homeContent').length > 0){				
				LBI.Custom.homepage.registration();				
			}
			
		},
		
		handleLabels : function(){
			
			$('input[type="text"]').each(function(){												  
				this.baseVal = this.value;				
				$(this).focus(function(){								   
					if (this.value == this.baseVal){						
						this.value = '';			
					}					
				});
				
				$(this).blur(function(){														
					if(!(this.value)){						
						this.value = this.baseVal;					
					}					
					if ($(this).hasClass("mandatory")){
						if (this.value.length<1){				
							$(this).addClass("required")
						}else{				
							$(this).removeClass("required")
						}
					}					
				});				
			});
			
		},	
		
		registration : function(){			
			checkEmail=function(field){		
				var rexp=/^[a-z[\w\.-]*[a-z0-9]@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$/i;		
				return(field.value.search(rexp)!=-1);	
			}
				
			var theForm = $('#registerForm');
			
			theForm.submit(function() {
		
				var name=$("#name").get(0);
				var email=$("#email").get(0);
				var msgP=$("#validationMsg");
		
				//clearing the container
				msgP.empty();
		
				if(name.value.length==0){
					
					$("<span />").addClass("err").text("please insert your name!").appendTo(msgP);
					name.focus();
					
					return false;
		
				}	
		
				if(!checkEmail(email)){
			
					$("<span />").addClass("err").text("please check the e-mail address!").appendTo(msgP);
					email.focus();
			
					return false;
		
				}		
	
				$("<span />").addClass("info").text("sending your request...").appendTo(msgP);
				
				$.getJSON(this.action, function(json){
			
					//clearing the container
					msgP.empty();			
			
					var span=$("<span />").text(json.message).appendTo(msgP);
			
					span.addClass(json.isOk?"ok":"err");
			
				});

      			return false;
    
			});
			
		}
		
	},
	
	news : {
		
		init : function(){
			
			// only do this stuff if on the home page
			if ($('.newsContent').length > 0){			
				 LBI.Custom.news.pagination();				
			}
			
		},
		
		pagination : function(){
			
			var numberOfPages, thePaginationDiv, thePaginationText;
			
			var allTheItems = $('.leftColumn .newsList li');
			var numberOfItems = allTheItems.length;
			var currentPageNumber = 1;
			
			// hide the items that aren't on the first page
			for(var i = LBI.Data.numberNewsItemsOnPage; i<numberOfItems; i++){				
				$(allTheItems[i]).hide();				
			}
			
			// find out how many pages there are
			numberOfPages = Math.ceil(allTheItems.length / LBI.Data.numberNewsItemsOnPage);
			
			//create pagination
			thePaginationDiv = $('<div class="pagination"></div>');
			thePaginationText = $('<p>Page <span class="pageNumber">' + currentPageNumber + ' </span>of ' + numberOfPages + '</p>');
			thePaginationDiv.append(thePaginationText);
			
			$('.leftColumn .newsList').after(thePaginationDiv);
			
			var paginationClone=thePaginationDiv.clone(true);
			$('.leftColumn .newsList').before(paginationClone);
			
			// create the arrows if there is more than one page
			if (numberOfPages > 1){
					
				previousLink = $('<a class="previousPage" href="#content">Previous</a>');
				nextLink = $('<a class="nextPage" href="#content">Next</a>');				
				
				previousLink.click(function(){										
					var lastVisbleItem;					
					currentPageNumber = (parseInt($('.leftColumn .pageNumber').html(), 10)) - 1;
					
					var nextLink=$(".pagination .nextPage");
					var previousLink=$(".pagination .previousPage");
					
					// update pagination text
					$('.leftColumn .pageNumber').html(currentPageNumber + ' ');
					
					// change the list items that are visible
					lastVisibleItem = currentPageNumber * LBI.Data.numberNewsItemsOnPage;
					firstVisibleItem = lastVisibleItem - LBI.Data.numberNewsItemsOnPage;
					allTheItems.hide();
					
					for(var i = lastVisibleItem - LBI.Data.numberNewsItemsOnPage; i < lastVisibleItem;i++){						
						if(i < numberOfItems){					
							$(allTheItems[i]).show();							
						}						
					}
					
					// focus on the first link on the page
					$('a', $(allTheItems[firstVisibleItem])).get(0).focus();					
					if(currentPageNumber === 1){						
						previousLink.hide();						
					}
					
					// show the previous link
					nextLink.show();
					
					return false;
					
				});				
				
				nextLink.click(function(){										
					var lastVisbleItem, firstVisibleItem;					
					currentPageNumber = (parseInt($('.leftColumn .pageNumber').html(), 10)) + 1;
					
					var nextLink=$(".pagination .nextPage");
					var previousLink=$(".pagination .previousPage");
					
					// update pagination text
					$('.leftColumn .pageNumber').html(currentPageNumber + ' ');
					
					// change the list items that are visible
					lastVisibleItem = currentPageNumber * LBI.Data.numberNewsItemsOnPage;
					firstVisibleItem = lastVisibleItem - LBI.Data.numberNewsItemsOnPage;
					allTheItems.hide();
					
					for(var i = firstVisibleItem; i < lastVisibleItem;i++){						
						if(i < numberOfItems){					
							$(allTheItems[i]).show();							
						}						
					}
					
					// focus on the first link on the page
					$('a', $(allTheItems[firstVisibleItem])).get(0).focus();
					
					if(currentPageNumber === numberOfPages){						
						nextLink.hide();						
					}
					
					// show the previous link
					previousLink.show();
					
					return false;
				});
				
				thePaginationDiv.prepend(previousLink);
				thePaginationDiv.append(nextLink);
				
				paginationClone.prepend(previousLink.clone(true));
				paginationClone.append(nextLink.clone(true));				
				
				// hide the previous link initially as we will enter on the first page
				$(".pagination .previousPage").hide();
					
			}	
			
		}			
		
	},
	
	tabMenu:{
		init:function(){
			$(".tabMenu").each(function(){
				var tabMenu=$(this);
				
				LBI.Custom.tabMenu.updates(tabMenu);
				
				$(".selected", tabMenu).each(function(){
					var tabContent=$(".tabContent",this);
					
					//calculates the height of the content of the current tab
					tabContent.addClass("getOffset");
					var newHeight=(tabContent.get(0).scrollHeight);
					tabContent.removeClass("getOffset");
					
					tabMenu.animate({paddingBottom:newHeight+1},500);															  
				})
					
				
				var tabs=$(".tabTitle",this)
				tabs.addClass("noPngFix");
				tabs.parent("div").addClass("noPngFix");
				
				tabs.mouseup(function(){
									$(this).blur();
										})
				tabs.click(function(){
					var tabAnchor=$(this);					
					var li=tabAnchor.parents("li")
					if (li.hasClass("selected")) return false;
					
					var tabContent=$(".tabContent",li);
					
					//calculates the height of the content we are going to display
					tabContent.addClass("getOffset");
					var newHeight=(tabContent.get(0).scrollHeight);
					tabContent.removeClass("getOffset");
					
					tabMenu.animate({paddingBottom:newHeight+1},500);
									
					tabs.parents("li").removeClass("selected");
					li.addClass("selected");
					
					return false;
				})
				.each(function(){
					var tabAnchor=$(this);
					var tabContent=$(".tabContent",tabAnchor.parents("li"));
					
					var li=$(this).parents("li");
					var value=li.get(0).offsetHeight;
					//value=li.hasClass("selected")?value:value;
					
					tabContent.css({marginTop:value-1});						   
				})
				
				// this is to prevent layout issues as some content might be donwloaded after this function is called
				setInterval('LBI.Custom.tabMenu.updates($("ul.tabMenu"))',500)
			})
		},
		updates:function(tabMenu){
			
			$(".galleryHolder").each(function(){	// IE fix!
									this.style.position="relative";
									this.style.top="0px";
								})
			$(".selected", tabMenu).each(function(){
				var tabContent=$(".tabContent",this);
				//console.log(this)
				//calculates the height of the content of the current tab
				try{
					var newHeight=(tabContent.get(0).scrollHeight)+1;
				}catch(e){}
				
				tabMenu.animate({paddingBottom:newHeight},200);				
				
			})			
		}
	},
	
	starRating:function(container){
		
		$(".readOnlyVotes",container)
			.each(function(){
				var div=$(this);
				div.addClass("noPngFix");
				var valueSpan=$(".value",div).addClass("hidden");
				var value=parseFloat(valueSpan.text());
				
				//setting the tooltip
				div.attr("title",value);
				
				$("<div class='stars noPngFix'></div>")					
					.css("width",value*18)					
					.insertAfter(valueSpan)
			})
	},
	
	galleries: {
		
		init : function(){		
		
			// get the galleries
			var theGalleries = $('.galleryHolder');
			var theContainer = $('.PE_brightcoveHolder');
		
			var thePlayerCode = '';
			
			// brightcove player needs to be removed from the page when it is hidden or else it plays in the background in IE
			//LBI.Custom.galleries.handleBrightcove(theContainer);
		
			// create pagination
			LBI.Custom.galleries.enablePagination(theGalleries);
		
			// enable tabs
			LBI.Custom.galleries.enableTabs(theGalleries);
		
		
			LBI.Custom.galleries.lightbox.init();
			/*
			// set up image lightbox
			LBI.Custom.galleries.lightbox.imageLightbox();
		
			// set up video lightbox
			LBI.Custom.galleries.lightbox.videoLightbox();					  
			*/

		},
		
		handleBrightcove : function(theContainer){

			var thePlayer;
			
			if(theContainer.length > 0){
				
				thePlayer = theContainer.children()[0];
				thePlayerCode = theContainer.html();
				
				theContainer.html('');	
				
			}
			
		},
		
		enablePagination : function(container){

			$(".pagination a",container).click(function(){
					var pageBtn=$(this);
					var par=this.href.split("?")[1];
					var pag=pageBtn.parents(".pagination");
					var ul=pag.siblings(".gallery");

					$.get("entries.php?" + par,
								function(data){
									
									var html=$("<div>" + data + "</div>");									
									
									LBI.Custom.starRating(html);
									LBI.Custom.galleries.enablePagination(html);
																		
									ul.replaceWith($(".gallery",html));
									pag.replaceWith($(".pagination",html));																		
																		
									LBI.Custom.galleries.lightbox.init();
								})
					return false;
			})
		
		},
		
		enableTabs : function(theGalleries){
			
			var firstGalleryLink, theContainer;
						
			// get the links
			var galleryLinks = $('.galleryNavigation li a');
			
			for (var i=0; galleryLinks[i];i++){
				
				// create actions to add to onclick of the tab
	            swapGalleries = function(j){
					
					return function(){
	                    
	            		// if the link is wrapped in <strong>, do not proceed
						if ($(this).parent('strong').get(0)){
					
							return false;
				
						}
						else{
					
							// dehighlight the other tab and hide the other gallery
							if (j === 1){
								
								$($(galleryLinks[0]).parent('strong').get(0)).replaceWith($(galleryLinks[0]));
								$(theGalleries[0]).hide();
							
							}
							else{
							
								$($(galleryLinks[1]).parent('strong').get(0)).replaceWith($(galleryLinks[1]));
								$(theGalleries[1]).hide();
							
							}
							
							// highlight the tab
							$(this).wrap('<strong></strong>');
						
							// show the related gallery and focus on the first link
							$(theGalleries[j]).show();
							
							// if the gallery has the brightcove holder, need to put the brightcove player in it, otherwise, remove any players
							theContainer = $('.PE_brightcoveHolder', theGalleries[j]);
							
							if(theContainer.length > 0){
								
								theContainer.html(thePlayerCode);
								
							}
							else{
								
								theContainer = $('.PE_brightcoveHolder');
								
								theContainer.html('');
								
							}
							
							firstGalleryLink = $(theGalleries[j]).find('a').get(0);
							
							if(firstGalleryLink){
							
								firstGalleryLink.focus();
								
							}
					
							return false;
				
						}
	                       
	            	}
					
				}
				
				// append the actions to the tab links
				$(galleryLinks[i]).click(swapGalleries(i));
				
			}
			
		},
		
		lightbox: {
			
			imagesGroups: {},
			
			init:function(){
				
				$('.galleryHolder ul.gallery').each(function(){
				
					// creates an hash table containing all the images grouped by galleries names
					var anchors=$("a",this);
				
					if(anchors.length > 0){
				
						LBI.Custom.galleries.lightbox.imagesGroups[anchors.get(0).rel]=anchors;
										
						//set the image index (used by the click function)
						anchors.each(function(i){
							var id=this.href.split("videoId=")[1];
							this.parentNode.id=id;					
							$(this).attr("index",i).click(function(){
								LBI.Custom.galleries.lightbox.display(this);
							
								return false;
								
							});
															
						});
				
					}
					
				});
				
			},
			
			lbBackground : function(){
				// check if there's a BG already defined
				var bg=$(".lightboxBackground");
				if (bg.length>0) return bg;
				var pageDimensions;				
				var theBackground = $('<div class="lightboxBackground"></div>');				
				var sizeMe = function(){
					
					pageDimensions = LBI.Common.getFullPageDimensions();
				
					if (pageDimensions[0] > LBI.Data.minPageWidth){
						theBackground.css('width', pageDimensions[0]);
					}
					else{					
						theBackground.css('width', LBI.Data.minPageWidth);					
					}				
					theBackground.css('height', pageDimensions[1]);					
				}
				
				$('body').prepend(theBackground);
				sizeMe();
				
				// if the user resizes the window we want the background to resize accordingly
				$(window).bind('resize', sizeMe);
				theBackground.hide();
				
				return theBackground;
		
			},
			
			lbFrame:function(){
				//creates the lightBox frame html
				var lb=$(".lightbox");
				var isNew=(lb.length==0);
				
				if (isNew){
					lb=$('<div class="lightbox"><div class="cont"><div class="assetHolder"><div class="contentHolder"></div><ul class="buttonsPanel"><li class="previous"><a href="#"><span>Previous</span></a></li><li class="next"><a href="#"><span>Next</span></a></li></ul></div><div class="starRatingHolder"></div><p class="legend"></p><p class="extra"></p></div></div>');				
					$('body').prepend(lb);					
				}							
				
				var contentHolder=$(".contentHolder", lb);
				var legend=$(".legend", lb);
				var extra=$(".extra", lb);
				var buttonsPanel=$(".buttonsPanel",lb);
				var prev=$(".previous a",lb);
				var next=$(".next a",lb);				
				var assetHolder=$(".assetHolder", lb);
				var closeLink=$(".closeLink", lb);
				var starRatingHolder=$(".starRatingHolder",lb);
				
				var timerHnd=null;
				var start = null;
				var end = null;
				
				
				if (isNew){
					// create the close link and append it to the box
					closeLink=$('<a class="closeLink" href="#content"><img src="../assets/images/videoCloseFG.gif" alt="close X" title="close!" /></a>').insertAfter(assetHolder)
					

					contentHolder
						.mouseover(function(e){
							buttonsPanel.fadeIn("fast")
							clearInterval(timerHnd);
							timerHnd=setTimeout(function(){buttonsPanel.fadeOut("fast")},3000)										
						});
					
					buttonsPanel
						.mouseout(function(e){											   
							timerHnd=setTimeout(function(){buttonsPanel.fadeOut("fast")},200)										
						})
						.mouseover(function(){			
							clearInterval(timerHnd);
						})
						
					closeLink.click(function(){
							
						contentHolder.empty();						
						assetHolder.attr("class","assetHolder");						
						
						lb.fadeOut("fast",function(){$(".lightboxBackground").hide()})
						
						return false;
					});
					
				}						
					
				//returns an object to handle data visualisation
				return {
						frame:lb,
						contentHolder:contentHolder,
						legend:legend,
						extra:extra,
						closeLink:closeLink,
						prev:prev,
						next:next,
						assetHolder:assetHolder,
						starRatingHolder:starRatingHolder
					}
			},
			
			display:function(obj){				
				var lightBoxFrame=LBI.Custom.galleries.lightbox.lbFrame();
				
				var lightBoxBg=LBI.Custom.galleries.lightbox.lbBackground();
				lightBoxBg.show();
				lightBoxFrame.frame.fadeIn();						
				
				var obj=$(obj);
				
				var galleryId=obj.attr("rel");
				var galleryType=obj.attr("type");		
					
				var currentIndex=parseInt(obj.attr("index"));
				
				updateContent(obj)
				
				// handling the Prev and Next buttons
				lightBoxFrame.prev.get(0).onclick=function(){
												  currentIndex--;
												  currentIndex=currentIndex<0?LBI.Custom.galleries.lightbox.imagesGroups[galleryId].length-1:currentIndex;
												  var newItem=$(LBI.Custom.galleries.lightbox.imagesGroups[galleryId][currentIndex]);
												  
												  updateContent(newItem)
												  return false;
											}
				
				lightBoxFrame.next.get(0).onclick=function(){
												  currentIndex++;
												  currentIndex=LBI.Custom.galleries.lightbox.imagesGroups[galleryId].length>currentIndex?currentIndex:0;
												  var newItem=$(LBI.Custom.galleries.lightbox.imagesGroups[galleryId][currentIndex]);
												  
												  updateContent(newItem)
												  return false;
											}
				
				
				// position and display the lightbox
				var viewPortCenter = Math.round(LBI.Common.getViewPortHeight() / 2);
				var scrolledTop = LBI.Common.getScrollTop();
				var userViewCenter = parseInt(viewPortCenter) + parseInt(scrolledTop);
				var lightboxCenter = lightBoxFrame.frame.height() / 2;
				var theTop=0;
				
				if(LBI.Common.getViewPortHeight() < lightBoxFrame.frame.height()){
					theTop = scrolledTop;
				}
				else{										
					theTop = userViewCenter - lightboxCenter - 53;					
				}
					

				lightBoxFrame.frame.css('top', theTop);						
				lightBoxFrame.closeLink.focus();
					
					
				function updateContent(showingObj){
					//get the info about the gallery
					var galleryId=showingObj.attr("rel");
					var galleryType=showingObj.attr("type");					
					
					lightBoxFrame.starRatingHolder.empty();
					lightBoxFrame.contentHolder.empty();
					lightBoxFrame.contentHolder.hide();
					
					lightBoxFrame.assetHolder.attr("class","assetHolder");
					
					lightBoxFrame.assetHolder.addClass(galleryType);		//used to handle the prev/next positioning
					
					switch (galleryType) {						
						case "video":								
							var videoStr='<embed src="http://c.brightcove.com/services/viewer/federated_f9/10506222001?isVid=1&publisherID=1815805388" bgcolor="#FFFFFF" flashVars="playerID=10506222001&domain=embed&@videoPlayer=XXX" base="http://admin.brightcove.com" name="flashObj" width="610" height="349" seamlesstabbing="false" type="application/x-shockwave-flash" allowFullScreen="true" swLiveConnect="true" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed>'
							var videoId=showingObj.attr("href").split("videoId=")[1];
							videoStr=videoStr.replace("XXX",videoId);
							$(videoStr).appendTo(lightBoxFrame.contentHolder);
							
							lightBoxFrame.legend.text($("img",showingObj).attr("alt"));
							lightBoxFrame.extra.text("Video " + (currentIndex+1) + " of " + LBI.Custom.galleries.lightbox.imagesGroups[galleryId].length + "")					
							
							LBI.Custom.addStarRating({
													 		title:"Rate this video:",
															starsCount:5,
															ajaxUrl:"vote.php",
															queryItem:"stars",
															fixedString:"videoID=" + videoId,
															defaultVal:0,
															container:lightBoxFrame.starRatingHolder,
															onVote:function(data){
																	$("#" + videoId + " .stars").css("width",data.value*18);
																}
														})
							
							
						break;
						
						case "image":
							$("<img></img>")
								.attr("src",showingObj.attr("href"))
								.appendTo(lightBoxFrame.contentHolder);

							lightBoxFrame.legend.text($("img",showingObj).attr("alt"));
							lightBoxFrame.extra.text("Image " + (currentIndex+1) + " of " + LBI.Custom.galleries.lightbox.imagesGroups[galleryId].length)
						break;
					}
					lightBoxFrame.contentHolder.fadeIn(400);
				}									
								
			}		
			
		}
		
	},
	
	addStarRating:function(paramsObj){		
		var div=$('<div class="ratingWidget"></div>');
		
		var title=$("<span class='title'>" + paramsObj.title + "</span>").appendTo(div);
		
		var stars=new Array();
		var current=paramsObj.defaultVal-1;
		
		for(var x=0; x<paramsObj.starsCount;x++){
			var a=$('<a class="star" href="#' + (x+1) + '"></a>')
					.attr("index",x)
					.attr("title",x+1)
					.appendTo(div)
					.click(function(){
						$("a",div)
							.fadeOut(function(){$(this).remove()})
							
						title.text("Please wait...");									
						
						var cIndex=parseInt($(this).attr("index"));
						var urlToCall=paramsObj.ajaxUrl + "?" + paramsObj.fixedString + "&" + paramsObj.queryItem + "=" + (cIndex+1);
						$.getJSON(urlToCall,function(data){
												if (data.isOK){													
													$("a",div).remove();
													title.text("Thank you!");
													$("<div class='readOnlyVotes'><div class='stars' style='width:" + data.value*18 + "px'></div></div>")
														.css({"margin-top":"3px",float:'left',width:'90px'})
														.hide()
														.appendTo(div)
														.fadeIn();
													
													//callback to the onVote function
													paramsObj.onVote(data);
													return true;
												}
												
												$("a",div).remove();
												title.text("hoops! " + data.value);
												return false;
											})
						
						
						
						current=cIndex;
						
						for (var x=0;x<stars.length;x++){
							if(!(cIndex<x)){
								stars[x].addClass("selected");
							}else{
								stars[x].removeClass("selected");								
							}
						}						
					})
					.mouseover(function(){highLight.call(this,stars)})
					.focus(function(){highLight.call(this,stars)})
					.blur(function(){looseFocus.call(this,stars,current)})
					
					paramsObj.container
						.mouseout(function(){looseFocus.call(this,stars,current)})
						
					
					
			$("<span>"+(x+1)+"</span>").appendTo(a)			
			
			//set the default value
			if(!(x>paramsObj.defaultVal-1)) a.addClass("selected");
			
			stars.push(a);
		}
		
		div.appendTo(paramsObj.container)
		
		function highLight(stars){		
			var cIndex=$(this).attr("index");									
			for (var x=0;x<stars.length;x++){
				stars[x].removeClass("selected");		
				if(!(cIndex<x)){
					stars[x].addClass("hovering");
				}else{
					stars[x].removeClass("hovering");								
				}
			}
		}
		
		function looseFocus(stars,current){
			for (var x=0;x<stars.length;x++){
				stars[x].removeClass("hovering");
				if(!(current<x)){
					stars[x].addClass("selected");
				}				
			}			
		}
				
	},
	
	soundManager : {
		
		currentTrack : 1,			
		numberOfTracks : 0,		
		trackArray : [],		
		theTableRows : [],		
		isPaused : false,		
		titleTag:null,
		progressBar:null,
		qsObject:{},		//this object contains the URL query string
		
		
		init : function(){
			
			// get the query string and parses its values into an object (qsObject) 
			if(location.href.indexOf("?")>-1){
				//first check if there are params passed with the URL
				var parArray=location.href.split("?")[1].split("=");						
				for (var x=0;x<parArray.length;x+=2){
					LBI.Custom.soundManager.qsObject[parArray[x]]=parArray[x+1];
				}
			}

			// check if a particular track is required
			if(LBI.Custom.soundManager.qsObject["playTrack"]){
				LBI.Custom.soundManager.currentTrack=parseInt(LBI.Custom.soundManager.qsObject["playTrack"]);
			}					
			
			//changing the default behaviour of the music player A tag:
			$("a.musicPlayer")
				.click(function(){
					window.open(this.href,"player","location=0,status=0,scrollbars=0,width=320,height=372");
					return false;
				})
				
			
			if($('#musicPlayer').length > 0){
				
				LBI.Custom.soundManager.titleTag=$('#musicPlayer .cont h2');
				LBI.Custom.soundManager.progressBar=$('#musicPlayer .mp_ProgressBar span');				
				
				var theSubHeading, theTableHead;
				
				var theSongs = $('table .songURL');
				var qtContainer = $('.base');
				
				// check for QuickTime
				var isInstalled = false;
				var version = null;

				if (window.ActiveXObject) {
   
					var control = null;
    
					try {
        
						control = new ActiveXObject('QuickTime.QuickTime');
    			
					}
					catch (e) {
        
					// Do nothing
    
					}
     
					if (control) {
        
						// In case QuickTimeCheckObject.QuickTimeCheck does not exist
        				isInstalled = true;
    				
					}
    				
					try {
        
						// This generates a user prompt in Internet Explorer 7
        				control = new ActiveXObject('QuickTimeCheckObject.QuickTimeCheck');
    
					} 
					catch (e) {
        
						// do nothing
    
					}
    
					if (control) {
        
						// In case QuickTime.QuickTime does not exist
        				isInstalled = true;
						version = control.QuickTimeVersion.toString(16); // Convert to hex  
						version = version.substring(0, 1) + '.' + version.substring(1, 3);  
						version = parseFloat(version); 
    				}

				} 
				else {
    
					// Check navigator.plugins for "QuickTime Plug-in"
					if (navigator.plugins) {
      
	  					for (var np = navigator.plugins, i = np.length - 1; i >= 0; i--){
        
							if (np[i].name.indexOf('QuickTime') != -1) {
								
								isInstalled = true; 
								
							}
      
	  					}
					
					}
					
				}
		
				// if user has not got Quicktime, tell them
				if (!isInstalled) {
					
					$('#musicPlayer .cont h2')
						.addClass("error")
						.html(LBI.Data.noQuicktimeMessage);
						
					alert(LBI.Data.noQuicktimeMessage.text());
			
					return;
				}
				
				
				// store all the songs in an array
				LBI.Custom.soundManager.numberOfTracks = theSongs.length;
				
				for(var i=0;i<theSongs.length;i++){
					
					LBI.Custom.soundManager.trackArray.push($(theSongs[i]).attr('href'));
																				
				}	
				
				// put quicktime player for the first song into the page
				// The quicktime player must exist on the visible page for Firefox on a Mac to work.
				qtContainer.html('<div style="position:absolute;top:0; left: 0; z-index: -1"><object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"  codebase="http://www.apple.com/qtactivex/qtplugin.cab#version=7,2,1,0" width="1" height="1" type="video/quicktime" id="movie1"><param name="src" value="' + LBI.Custom.soundManager.trackArray[0] + '"><param name="autoplay" value="false"><param name="controller" value="false"><param name="loop" value="false"><param name="postdomevents" value="true" /><EMBED src="' + LBI.Custom.soundManager.trackArray[0] + '" width="1" height="1" autoplay="false" controller="false" loop="false" bgcolor="#000000" pluginspage="http://www.apple.com/quicktime/download/" EnableJavaScript="true" name="movie1"></EMBED></OBJECT></div>');
				
				// create the Playing column
				theTableRows = $('tbody tr');				
				theTableHead = $('thead tr');
				theTableHead.prepend($('<th>Now playing</th>'));
				theTableRows.prepend($('<td class="playing"></td>'));
				$($('.playing')[0]).html(LBI.Data.playingIcon);
				
				// set up the controls
				LBI.Custom.soundManager.controls.init();


				
			}
			/*
			var version=document.movie1.GetQuickTimeVersion();
			
			console.log(version);
			if (version<7.7){
				$('#musicPlayer .cont h2')
					.addClass("error")
					.html(LBI.Data.noQuicktimeMessage);
					
				alert(LBI.Data.noQuicktimeMessage.text());					
			}
			*/
		},
		
		controls : {
			
			theControls : $('<ul class="controls"></ul>'),
			
			theFirstItem : $('<li></li>'),
			
			theMiddleItem : $('<li class="middleItem"></li>'),
			
			theLastItem : $('<li></li>'),
			
			thePreviousButton : $('<a href="#" class="previous"><span>Previous</span></a>'),
			
			thePlayButton : $('<a href="#" class="play"><span>Play</span></a>'),
			
			thePauseButton : $('<a href="#" class="pause"><span>Pause</span></a>'),
			
			theNextButton : $('<a href="#" class="next"><span>Next</span></a>'),
				
			init : function(){				
				
				var theTracks = $('.tracks')[0];
				var theSongs = $('table .songURL');
				
				// draw the controls
				LBI.Custom.soundManager.controls.theLastItem.append(LBI.Custom.soundManager.controls.theNextButton);
				LBI.Custom.soundManager.controls.theMiddleItem.append(LBI.Custom.soundManager.controls.thePauseButton);
				LBI.Custom.soundManager.controls.theFirstItem.append(LBI.Custom.soundManager.controls.thePreviousButton);
				LBI.Custom.soundManager.controls.theControls.append(LBI.Custom.soundManager.controls.theFirstItem);
				LBI.Custom.soundManager.controls.theControls.append(LBI.Custom.soundManager.controls.theMiddleItem);
				LBI.Custom.soundManager.controls.theControls.append(LBI.Custom.soundManager.controls.theLastItem);
				LBI.Custom.soundManager.controls.theControls.insertBefore(theTracks);								
												
				
				minutes=function(time){
					return time.getMinutes()>9?time.getMinutes():"0"+time.getMinutes();
				}
				
				seconds=function(time){
					return time.getSeconds()>9?time.getSeconds():"0"+time.getSeconds();					
				}
				
				// add functions to the controls
				LBI.Custom.soundManager.controls.thePreviousButton.click(function(){					
					LBI.Custom.soundManager.controls.previousEvent();					
				});
				LBI.Custom.soundManager.controls.thePlayButton.click(function(){					
					LBI.Custom.soundManager.controls.playEvent();					
				});
				LBI.Custom.soundManager.controls.thePauseButton.click(function(){					
					LBI.Custom.soundManager.controls.pauseEvent();					
				});
				LBI.Custom.soundManager.controls.theNextButton.click(function(){					
					LBI.Custom.soundManager.controls.nextEvent();					
				});	
				
				// add functions to the tracks in the list
				trackLinks = function(j){
					
					return function(){
						
						LBI.Custom.soundManager.currentTrack = j + 1;
						
						// update the audio
						document.movie1.SetURL(LBI.Custom.soundManager.trackArray[LBI.Custom.soundManager.currentTrack - 1]);
				
						// start the audio
						LBI.Custom.soundManager.controls.playEvent();												
						
						return false;
						
					}
					
				}
				
				for(var i=0;i<theSongs.length;i++){					
					$(theSongs[i]).click(trackLinks(i));					
				}
				
				
				//Starts to play the first song in the list or the one specified in the query string, if any;
				$(window).load(function(){																	
					
					setTimeout(function(){
											document.movie1.SetURL(LBI.Custom.soundManager.trackArray[LBI.Custom.soundManager.currentTrack - 1]);				
											LBI.Custom.soundManager.controls.playEvent();
										},200);
					
					setInterval(function()	{
												try {
													var status=document.movie1.GetPluginStatus();
													var time=new Date(document.movie1.GetTime());
													var timeT=minutes(time) + ":" + seconds(time);
													
													var duration=new Date(document.movie1.GetDuration());
													var durationT=minutes(duration) + ":" + seconds(duration);										
													
													var isPlaying=(document.movie1.GetRate()==1);																								
													
													
													//downloading...
													if(status!="Complete"){
														LBI.Custom.soundManager.titleTag.text(status);
														LBI.Custom.soundManager.progressBar.css("width",1);
														return false;
													}
																										
													
													//pause
													if (!isPlaying){
														if(LBI.Custom.soundManager.controls.lastPerformedAction=="playing"){
															LBI.Custom.soundManager.controls.nextEvent();
														}

														LBI.Custom.soundManager.titleTag.html("<span class='time'>" + timeT + " / " + durationT + "</span>please wait...");																
														return false;
													}
													
													//playing
													LBI.Custom.soundManager.controls.lastPerformedAction="playing";
													LBI.Custom.soundManager.titleTag.html("<span class='time'>" + timeT + " / " + durationT + "</span>Now playing... ");			
													LBI.Custom.soundManager.progressBar.css("width",time*100/duration + "%");
												}catch(e){	
													alert(e);
												}
												
											},500)					
				})
				
			},
			
			previousEvent : function(){

				// keeps track of the last performed action. Useful for the the "continous" play feature
				LBI.Custom.soundManager.controls.lastPerformedAction="previous";
				
				if(LBI.Custom.soundManager.currentTrack === 1){					
					LBI.Custom.soundManager.currentTrack = LBI.Custom.soundManager.numberOfTracks;					
				}
				else{					
					LBI.Custom.soundManager.currentTrack = LBI.Custom.soundManager.currentTrack - 1;					
				}
				
				// update the audio
				document.movie1.SetURL(LBI.Custom.soundManager.trackArray[LBI.Custom.soundManager.currentTrack - 1]);
				
				// start the audio
				LBI.Custom.soundManager.controls.playEvent();
				
			},
			
			playEvent : function(){				
				// keeps track of the last performed action. Useful for the the "continous" play feature
				LBI.Custom.soundManager.controls.lastPerformedAction="play";	
				
				var previousTrack = $('table .playingRow');
				var currentTrack = $(theTableRows[LBI.Custom.soundManager.currentTrack - 1]);
				
				// play the audio
				document.movie1.Play();
				
				// swap this to a pause button
				LBI.Custom.soundManager.controls.thePlayButton.remove();
				LBI.Custom.soundManager.controls.theMiddleItem.append(LBI.Custom.soundManager.controls.thePauseButton);
				
				LBI.Custom.soundManager.controls.thePauseButton.click(function(){
					
					LBI.Custom.soundManager.controls.pauseEvent();
					
				});
				
				// remove info from previously playing track
				
				previousTrack.removeClass('playingRow');
				$('.playing', previousTrack).html('');				
				
				// add a class to the current table row to colour it
				currentTrack.addClass('playingRow');
				
				// insert the playing icon
				$('.playing', currentTrack).html(LBI.Data.playingIcon);	
							
				
				return false;
				
			},
			
			pauseEvent : function(){
				// keeps track of the last performed action. Useful for the the "continous" play feature
				LBI.Custom.soundManager.controls.lastPerformedAction="pause";				
				
				// stop the audio
				document.movie1.Stop();
				
				// swap this to a play button
				LBI.Custom.soundManager.controls.thePauseButton.remove();
				LBI.Custom.soundManager.controls.theMiddleItem.append(LBI.Custom.soundManager.controls.thePlayButton);
				

				
				LBI.Custom.soundManager.controls.thePlayButton.click(function(){					
					LBI.Custom.soundManager.controls.playEvent();					
				});
				
			},
			
			nextEvent : function(){
				// keeps track of the last performed action. Useful for the the "continous" play feature
				LBI.Custom.soundManager.controls.lastPerformedAction="next";				
				
				if(LBI.Custom.soundManager.currentTrack === LBI.Custom.soundManager.numberOfTracks){
					
					LBI.Custom.soundManager.currentTrack = 1;
					
				}
				else{
					
					LBI.Custom.soundManager.currentTrack = LBI.Custom.soundManager.currentTrack + 1;
					
				}
				
				// update the audio
				document.movie1.SetURL(LBI.Custom.soundManager.trackArray[LBI.Custom.soundManager.currentTrack - 1]);
				
				// start the audio
				LBI.Custom.soundManager.controls.playEvent();
				
			},
			
			// keeps track of the last performed action. Useful for the the "continous" play feature
			lastPerformedAction:null				 			
		}		
	}
};

//handle on document ready
$(document).ready(function(){
	
	$("body").addClass("hasJs");
	
   	LBI.Custom.stopBackgroundImageFlicker();
	LBI.Custom.homepage.init();
	LBI.Custom.news.init();
	LBI.Custom.galleries.init();
	LBI.Custom.starRating();
	LBI.Custom.formValidation();	
	LBI.Custom.hoverFix();
	LBI.Custom.homepage.handleLabels();
	
	LBI.Custom.soundManager.init();
	LBI.Custom.tabMenu.init();		

});
