var $j = jQuery.noConflict();
$j(document).ready(function(){
	
// remove all image titles
	$j("[title]").removeAttr("title");

// stop right click on images
	$j("img").live("contextmenu", function(){return false;});

// stop drag and dropping images
	$j("img").live("mousedown", function(){return false;});

// check if iphone and assign boolean var
	var iphone = false;
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
		if (document.cookie.indexOf("iphone_redirect=false") == -1){
			iphone = true;
		}
	}

	var showcontent = $j("#content-first").is(":visible");
	if($j("#background-images").length === 0){
		showcontent = true;
	}
	
	$j('#right_buttons, #left_buttons').fadeTo(0,0);
	
	function liveLeftHover(){
		if(!iphone){
			$j('#left_side').bind("mouseenter", function(){
				$j('#left_buttons').show().stop().fadeTo('normal', 1);
			}).bind("mouseleave", function () {
				$j('#left_buttons').stop().fadeTo('fast', 0, function(){$j('#left_buttons').hide();});
			});
		} else {
			$j('#left_buttons').show().fadeTo(0,1);
		}
	}
	function killLeftHover(){
		if(!iphone){
			$j('#left_side').unbind("mouseenter").unbind("mouseleave");
			$j('#left_buttons').stop().fadeTo('fast', 0, function(){$j('#left_buttons').hide();});
		} else {
			$j('#left_buttons').hide().fadeTo(0,0);
		}
	}
	
	function liveRightHover(){
		if(!iphone){
			$j('#right_side').bind("mouseenter", function(){
				$j('#right_buttons').show().stop().fadeTo('normal', 1);
			}).bind("mouseleave", function () {
				$j('#right_buttons').stop().fadeTo('fast', 0, function(){$j('#right_buttons').hide();});
			});
		} else {
			$j('#right_buttons').show().fadeTo(0,1);
		}
	}
	function killRightHover(){
		if(!iphone){
			$j('#right_side').unbind("mouseenter").unbind("mouseleave");
			$j('#right_buttons').stop().fadeTo('fast', 1);
		}
	}
	
		
// adds left margin to feature text so it gets narrow as the window gets small :
	var menuwidth = $j('.menu ul').width();
	var featuremargin =  menuwidth + 290;
	$j('#blog-description').css('margin-left', featuremargin);
	


// frontpage script :

	$j(".tx-home-container a").hover(function(){
		showBg($j(this).attr("class").replace(/[^\d]/g, ""));
	}, function(){
		//showBg(null);
	});

// show first dynamic bg if no static bg found :
	if($j(".static-frontpage-backgrounds div").length === 0){
		showBg("0");
	}
	
	
	frontpageResize();
	
	if($j(".static-frontpage-backgrounds span").size() > 0){
		frontpageHeaderColours($j(".static-frontpage-backgrounds span:eq(0)").attr("class"));
	} else if ($j(".frontpage-backgrounds span").size() > 0){
		frontpageHeaderColours($j(".frontpage-backgrounds span:eq(0)").attr("class"));
	}
	
	function frontpageHeaderColours(scheme){
		$j("#header, #menu-main-nav").removeClass("light");
		$j("#header, #menu-main-nav").removeClass("dark");
		
		$j("#blog-description").parent().attr("class", "");
		
		$j("#header").addClass(scheme);
		$j("#menu-main-nav").addClass(scheme);
		$j("#blog-description").parent().addClass(scheme);
	}


	function showBg(no){
		$j(".tx-home-container a").removeClass("active");
		$j(".tx-home-container a:eq("+no+")").addClass("active");
		$j(".frontpage-backgrounds div").each(function(){
			if(no){
				if($j(this).hasClass(no)){
					$j(this).show();	
					frontpageHeaderColours($j("span", this).attr("class"));
				}
				else {
					$j(this).hide();
				}
			}
		});
	}
	
	
	function frontpageResize(){
		$j(".frontpage-backgrounds div, .static-frontpage-backgrounds div").each(function(){
		
			var iW = $j(this).width();
			var iH = $j(this).height();
			var iR = iW/iH;
			var vW = $j(window).width();
			var vH = $j(window).height();
			var vR = vW/vH;
			
			var newWidth;
			var newHeight;
			
			if(vR > iR){
			// screen is wider
				newWidth = vW;
				newHeight = newWidth/iR;
			} else {
				newHeight = vH;
				newWidth = newHeight * iR;
			}
			
			$j(this).parent().width(vW);
			$j(this).parent().height(vH);
			$j(this).width(newWidth);
			$j(this).height(newHeight);
			$j("img", this).width(newWidth);
			$j("img", this).height(newHeight);
			
			
			newLeft = (vW - newWidth) / 2;
			newTop = (vH - newHeight) / 2;
			
			$j(this).css("top", newTop);
			$j(this).css("left", newLeft);

		
		});
	}
	
	$j(window).resize(frontpageResize);



if($j(".static-frontpage-backgrounds div, .frontpage-backgrounds div").size() === 0){

// gallery script :


// loads images in sequentially based on info in #imagesinfo
	var allBgImages = new Array();
	
	$j("#imagesinfo ul").each(function(){
		var image = new Array();
		$j("li", this).each(function(){
			image.push($j(this).text());
		});
		allBgImages.push(image);
	});
		
	var max = allBgImages.length;
	//alert("batfight");
	if(max > 0){
		LoadImages(0,max);
	}



	
// generate arrays for widths, height, ratio :
	var imagegap = 0;
	var current;
	var imagesLoaded = 0;
	if(!showcontent){
		current = 1;
	} else {
		current = 0;
	}
	var imageWidths = new Array();
	var imageHeights = new Array();
	var imageRatios = new Array();
	
	

	resizeAndScroll();
	setNaviSizes();
	resetDim();
	resetLeftRightNavi();


// thumnbails code

	if($j("#thumbnails").length){
	
		setThumbWidth();
		$j(window).resize(setThumbWidth);
		
		$j("#thumbnails a").click(function(){
			current = $j(this).index()+1;
			$j("#thumb-bg").hide();
			$j(this).parent().hide();
			//$j("#header div").show();
			scrollToLeft(1200,'easeInOutExpo', true);
			resetDim();	
			setActiveNavi();
			resetLeftRightNavi();
		});
		
		$j("#thumbnails-btn").click(function(){
			if($j("#thumbnails").is(":visible")){
				hideThumbs();
			} else {
				showThumbs();
			}
		});
	
	}
	
	function setThumbWidth(){
		$j("#thumbnails").width($j(window).width()-270);
	}
	
	function hideThumbs(){
	
		swapMenuColours();
		
		$j("#thumbnails").stop().animate({top:$j(window).height()}, 500, function(){
			$j(this).hide();
			$j("#thumb-bg").stop().fadeOut(500);
		});
			
	}
	
	function showThumbs(){
	
		var changes = $j("#header, #menu-main-nav, #side_menu, #right_buttons, #navi-thumbs, #left_buttons, #right_buttons, #thumbnails-btn");
		changes.removeClass("light");
		changes.removeClass("dark");
		changes.addClass($j("body").attr("class"));
	
		$j("#thumb-bg").stop().fadeIn(500, function(){
			$j("#thumbnails").stop().show().css("top", $j(window).height());
			$j("#thumbnails").animate({top:0}, 500);
		});
	}
	
	

// navi click functions :	
	$j("#navi-thumbs a").click(function(){
		current = $j(this).parent().index();
		scrollToLeft(1200,'easeInOutExpo', true);
		resetDim();	
		setActiveNavi();
		resetLeftRightNavi();
	});
	
	
	$j(".prev").click(function(){
		var min = 1;
		if(showcontent){
			min = 0;
		}
		if(current>min){
			current -= 1;
		}
		scrollToLeft(1200,'easeInOutExpo', true);
		resetDim();
		setActiveNavi();
		resetLeftRightNavi();
	});
	$j(".next").click(function(){
		if(current<$j("#background-images td").size()){
		// if there is an image to scroll to
			current += 1;
			scrollToLeft(1200,'easeInOutExpo', true);
			resetDim();
			setActiveNavi();
			resetLeftRightNavi();
		} else if(current < max){
		// if next image is loading
			return false;
		} else {
		// if on last image
			var location = window.location.href.replace("#", "");
			var nextloc = $j("a", this).attr("href");
			
			if(location != nextloc){
				window.location = $j("a", this).attr("href");
			} else {
				window.location = $j("#menu_names li:eq(0) a").attr("href");
			}
		}
	});
	$j("#showhide").click(function(){
		$j("#sidemenu-container").slideToggle();
		var a = $j("a", this);
		if(a.text() == "Show"){
			a.text("Hide");
		} else {
			a.text("Show");
		}
		var leftbtn = $j("#left_buttons .prev");
		if(leftbtn.css("left").replace(/[^\d]/g,"")==270){
			leftbtn.css("left", 0);
		} else {
			leftbtn.css("left", 270);
		}
		
	});
	

// resize on window resize :
	$j(window).resize(function(){
		resizeAndScroll();
		setNaviSizes();
	});
	
} // endif (not frontpage)



function resizeImages(){
	getImageSizes();
	
	var vH = $j(window).height();
	var vW = $j(window).width();
	var vR = vW/vH;
	
	$j("#content-first span").height(vH);

	
		var i = 0;
		$j("#background-images .bg-image").each(function(){
			/*

			var currentRatio = imageRatios[i];
			var newWidth = vW;
			var newHeight = vH;
			var newTop = 0;
			if(currentRatio <= 1){
			// portrait
				if (vH > 500){
					newHeight = vH;
					newWidth = newHeight * currentRatio;
				} else {
					newHeight = 500;
					newWidth = newHeight * currentRatio;
				}
				
				// add left margin to first image if portrait
				
				if ((i==$j("#background-images .bg-image").size()-1)&&(newWidth < vW)){
					var x = Math.floor((vW - newWidth)/2);
					var newContainerWidth = newWidth + x;
				}



			} else {
			// landscape
				
				if (vR > currentRatio){
				// screen is wider
					newWidth = vW;
					newHeight = newWidth/currentRatio;
					
					newTop = (vH - newHeight) / 2;
					
				} else {
					newHeight = vH;
					newWidth = newHeight * currentRatio;
				}
			
			}
			
			$j(this).height(newHeight);
			$j('img', this).height(newHeight);
			
			
			if(newContainerWidth){
				$j(this).width(newContainerWidth+imagegap);
				$j('span', this).width(newContainerWidth);
			} else {
				$j(this).width(newWidth+imagegap);
				$j('span', this).width(newWidth);
				$j('span', this).height(newHeight);
			}
			
			$j('img', this).width(newWidth);
			$j('img', this).css("top", newTop);
			
			i += 1;
*/

			var width = $j("img", this).attr("width");
			var height = $j("img", this).attr("height");
			
			var containerHeight = $j(window).height();
			var containerWidth = $j(window).width();
			
			// set height to the height of screen and adjust width
			var newHeight = containerHeight;
			var newWidth = Math.floor(newHeight * ( width / height ));
						
			// if it's wider than screen, set width to screen width and adjust height
			if (newWidth > containerWidth){
				newWidth = containerWidth;
				newHeight = Math.floor(newWidth * ( height / width ));
			}
			
			var newTop = (containerHeight - newHeight) / 2;
			
			
			$j("img", this).css({
				"height": newHeight,
				"width": newWidth,
				"top": newTop
			});
			$j(this).css({
				"height": newHeight,
				"width": newWidth
			});
		});
			
	}
    
	
// resize all background images
	function resizeImagesOnce(){
		resizeImages();
		// don't resize after scroll
		scrollToLeft(0,'',false);
	}
// ---
	
// resize, scroll and resize again (in case scrollbar comes or goes)
	function resizeAndScroll(){
		resizeImages();
		// resize again after scroll :
		scrollToLeft(0,'',true);
	}
// ---
// scroll to centre "current" image	
	function scrollToLeft(speed, easing, resizeafter){
		var imagesLeft;
		var contentLeft;
		var prevwidth = $j("#content-first").width();
		
		if(current === 0){
			contentLeft = 0;
			imagesLeft = -prevwidth;
		} else {
			prevwidth = 0;
			var currentimg = current-1;
			if(currentimg >= 0){
				for(var i=0;i<currentimg;i++){
					prevwidth += ($j("#background-images td:eq("+i+")").width());
				}
			}
			currentimgWidth = $j("#background-images td:eq("+currentimg+") img").width();
			imagesLeft = prevwidth - (($j(window).width() - currentimgWidth)/2);
			contentLeft = imagesLeft + $j("#content-first").width();
		}
		
		$j("#content-first").stop().animate({left: -contentLeft}, speed, easing);
		
		if(resizeafter){
			$j("#background-images").stop().animate({"margin-left": -imagesLeft}, speed, easing, resizeImagesOnce);
		} else {
			$j("#background-images").stop().animate({"margin-left": -imagesLeft}, speed, easing);
		}
	}
// ---
// assign "light" or "dark" class to headers based off current image style	
	function swapMenuColours(){
		var currentstyle = $j("body").attr("class");
		var temp = currentstyle;
		if (current === 0){
			currentstyle = $j("#content-first").attr("class");
		} else {
			currentstyle = $j("#background-images td:eq("+(current-1)+")").attr("class");
		}
		if(!currentstyle){
			currentstyle = temp;
		} 
		var changes = $j("#header, #menu-main-nav, #side_menu, #right_buttons, #navi-thumbs, #left_buttons, #right_buttons, #thumbnails-btn");
		changes.removeClass("light");
		changes.removeClass("dark");
		changes.addClass(currentstyle);
	}
// ---
// reset spans on top of bg images :	
	function resetDim(){
	

		$j("#content-first span").stop().fadeTo("slow", 0.85);
		$j("#background-images img").stop().fadeTo("slow", 0.15);
		if (current === 0){
			$j("#content-first span").hide();
		} else {
			$j("#background-images td:eq("+(current-1)+") img").stop().fadeTo(0,1);
		}
		
		
		swapMenuColours();
		
		
		
		var total = $j("#background-images td").size()-1;
		var temp = current;
		var maxtemp = max;
		if(showcontent){
			total+=1;
		} else {
			temp-=1;
			maxtemp -= 1;
		}

		
		// set class for right nav
		if (temp==maxtemp){
			$j("#right_buttons").addClass("end");
		} else if (temp==total) {
			$j("#right_buttons").addClass("loading");
		} else {
			$j("#right_buttons").removeClass("end").removeClass("loading");
		}		
	}
// ---
	
// bottom bar of navi buttons :
	function setNaviSizes(){
		var vW = $j(window).width();
		var n = $j("#navi-thumbs span").size();
		
		var gutter = 1;
		
		if(!showcontent){
			$j("#navi-thumbs span:eq(0)").width(0).attr("margin", 0);
			n -= 1;
		}
		var width = ((vW-60)-((n-1)*gutter))/n;
		
		if(!showcontent) {
			$j("#navi-thumbs span").not("#navi-thumbs span:eq(0)").width(width);
		} else {
			$j("#navi-thumbs span").width(width);
		}
	}
// ---

// set active bottom button
	function setActiveNavi(){
		$j("#navi-thumbs a").removeClass("active");
		$j("#navi-thumbs a").each(function(){
			if($j(this).css("top").replace(/[^\d]/g, "") < 20){
				$j(this).animate({"top":"0px"},0);
			}
		});
		var currentnavi = $j("#navi-thumbs a:eq("+current+")");
		currentnavi.addClass("active");
		currentnavi.animate({"top": "-10px"}, "fast", "easeOutQuart",  function(){
			currentnavi.animate({"top":"0px"}, "fast", "easeInQuart");
		});
	}

// animate in navi buttons :
	function setNavi(){
		var imagesLoaded = $j("#background-images td").size();
		var naviLoaded=$j("#navi-thumbs a:visible").size();
						
		for(var i=0;i<=imagesLoaded;i++){
			if(i>=naviLoaded){
				$j("#navi-thumbs a:eq("+i+")").show().animate({"top": "0px"}, 400, "easeOutBack");
			}
		}
		
	}

// ---


	function resetLeftRightNavi(){
	
		if(current===0){
			killLeftHover();
			killRightHover();
			$j(".next").delay(300).stop().animate({"right":0}, 1000, "easeOutBounce");
		} else if (current===1 && showcontent===false){
			killLeftHover();
			killRightHover();
			
			$j(".next").delay(300).stop().animate({"right":0}, 1000, "easeOutBounce");
			
		} else {
			liveLeftHover();
			liveRightHover();
			$j(".next").stop().animate({"right":-80});
		}
	
	}
	
	function getImageSizes(){
	
		imageWidths = [];
		imageHeights = [];
		imageRatios = [];
		
		$j("#imagesinfo ul").each(function(){
			var image = new Array();
			
			$j("li", this).each(function(){
				image.push($j(this).text());
			});

			imageWidths.push(image[2]);
			imageHeights.push(image[3]);
			imageRatios.push(image[2]/image[3]);
		});
	}
	
	function LoadImages(no,max){
		
		if(no < max){
			var img = new Image();
			$j(img).load(function(){
				$j(this).attr("width", allBgImages[no][2]).attr("height", allBgImages[no][3]);
				var newtd = $j("<td>").attr("class", allBgImages[no][0]);
				var newdiv = $j("<div>").attr("class", "bg-image").append($j("<span>")).append(this);
				newtd.append(newdiv);
				$j("#background-images tr").removeClass("loading").append(newtd);
				
				if(no==0){
					resizeImagesOnce();
				} else {
					resizeImages();
				} 
				resetDim();
				setNavi();
				imagesLoaded += 1;
				
				// load thumbnails as large images load :
				if($j("#thumbnails").length){
					$j("#thumbnails a:eq("+ no +") span").fadeOut();
					$j("#thumbnails .thumbnails:eq("+no+")").fadeIn();
				}
				
				
				
				LoadImages(no+1,max);
			}).error(function(){
				// trigger the next image
				LoadImages(no+1,max);
			}).attr("src", allBgImages[no][1]);
		}
		
		if (no==1){
			resetLeftRightNavi();
			setActiveNavi();
		}

	}
});
