var $j = jQuery.noConflict();

function hideMenu(){
	// hmm
}

$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)) || (navigator.userAgent.match(/iPad/i))) {
		if (document.cookie.indexOf("iphone_redirect=false") == -1){
			iphone = true;
		}
	}
	
	var showcontent = false;
	
	//$j("#right_button, #left_button").fadeTo(0,0);
	
	function liveLeftHover(){
		if(!iphone){
			$j("#left_side").bind("mouseenter", function(){
				$j("#left_button").show().stop().fadeTo("normal", 1);
			}).bind("mouseleave", function () {
				$j("#left_button").stop().fadeTo("fast", 0, function(){$j("#left_button").hide();});
			});
		} else {
			$j("#left_button").show().fadeTo(0,1);
		}
	}
	function killLeftHover(){
		if(!iphone){
			$j("#left_side").unbind("mouseenter").unbind("mouseleave");
			$j("#left_button").stop().fadeTo("fast", 0, function(){$j("#left_button").hide();});
		} else {
			$j("#left_button").hide().fadeTo(0,0);
		}
	}
	
	function liveRightHover(){
		if(!iphone){
			$j("#right_side").bind("mouseenter", function(){
				$j("#right_button").show().stop().fadeTo("normal", 1);
			}).bind("mouseleave", function () {
				$j("#right_button").stop().fadeTo("fast", 0, function(){$j("#right_button").hide();});
			});
		} else {
			$j("#right_button").show().fadeTo(0,1);
		}
	}
	function killRightHover(){
		if(!iphone){
			$j("#right_side").unbind("mouseenter").unbind("mouseleave");
			$j("#right_button").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");
	}
	
	var currentHomeScheme = $j("body").attr("class");
	
	frontpageResize();
	
	if($j(".static-frontpage-backgrounds span").size() > 0){
		currentHomeScheme = $j(".static-frontpage-backgrounds span:eq(0)").attr("class");
	} else if ($j(".frontpage-backgrounds span").size() > 0){
		currentHomeScheme = $j(".frontpage-backgrounds span:eq(0)").attr("class");
	}
	
	//frontpageHeaderColours(currentHomeScheme);
	
	function frontpageHeaderColours(scheme){
		if(!menushow){
			var changes = $j("#header, #menu-main-nav, #navi-thumbs, #left_button, #right_button, #thumbnails-btn a");
			changes.removeClass("light");
			changes.removeClass("dark");
			
			changes.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;
	
	current = 1;
	var imageWidths = new Array();
	var imageHeights = new Array();
	var imageRatios = new Array();
	var imageCaptions = new Array();
	
	

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


// thumnbails code

	var showthumbs = false;

	if($j("#thumbnails").length){
	
		showthumbs = true;
	
		setThumbWidth();
		$j(window).resize(setThumbWidth);
		
		$j("#thumbnails a").click(function(e){
			e.preventDefault();
			showthumbs = false;
			current = $j(this).index()+1;
			hideThumbs();
			scrollToLeft(0,'easeInOutExpo', true);
			resetDim();	
			setActiveNavi();
			$j("#right_button").hide();
			$j("#left_button").hide();
			resetLeftRightNavi();
			if(menushow){
				hideMenu();
			}
			return false;
		});
		
		$j("#thumbnails-btn").click(function(e){
			e.preventDefault();
			if(menushow){
				hideMenu();
			}
			if($j("#thumbnails").is(":visible")){
				hideThumbs();
			} else {
				showThumbs();
			}
			return false;
		});
	
	}
	
	$j("#background-images").click(function(){
		if(menushow){
			hideMenu();
		}
	});
	

// navi click functions :	
	$j("#navi-thumbs a").click(function(e){
		e.preventDefault();
		current = $j(this).parent().index();
		scrollToLeft(1200,'easeInOutExpo', true);
		resetDim();	
		setActiveNavi();
		resetLeftRightNavi();
		if(menushow){
			hideMenu();
		}
		if(showthumbs){
			hideThumbs();
		}
		return false;
	});
	
	
	$j("#left_button, #left_side").click(function(e){
		e.preventDefault();
		var min = 1;
		if(current>min){
			current -= 1;
		}
		scrollToLeft(1200,'easeInOutExpo', true);
		resetDim();
		setActiveNavi();
		resetLeftRightNavi();
		if(menushow){
			hideMenu();
		}
		return false;
	});
	
	$j("#right_button, #right_side").click(function(e){
		e.preventDefault();
		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("#right_button").attr("href");
			
			if(location != nextloc){
				window.location = $j("#right_button").attr("href");
			} else {
				window.location = $j("#top_menu_small_links li:eq(0) a").attr("href");
			}
		}/*

		if(menushow){
			hideMenu();
		}
		
*/
		fadesideinfohalf();
		
		return false;
		
	});/*

	$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_button .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


function is_homepage(){
	return ($j(".static-frontpage-backgrounds, .frontpage-backgrounds, .frontpage").size() > 0);
}


function setThumbWidth(){
	var newwidth = $j(window).width();
	$j("#thumbnails").width(newwidth);
}

function hideThumbs(){
	showthumbs = false;

	swapMenuColours();
	
	$j("body").css("overflow-y", "hidden");
	
	$j("#thumbnails").stop(true,true).animate({top:$j(window).height()}, 500, function(){
		$j(this).hide();
		$j("#thumb-bg").stop().fadeOut(500, function(){
			$j("body").css("overflow-y", "visible");
		});
	});
		
}

function showThumbs(){
	showthumbs = true;
	
	$j("body").css("overflow-y", "hidden");
	
	$j("#thumb-bg").stop().fadeIn(500, function(){
		$j("#thumbnails").stop().show().css("top", $j(window).height());
		$j("#thumbnails").animate({top:0}, 500, function(){
			$j("body").css("overflow-y", "visible");
		});
	});
	
	swapMenuColours();
	
}


function resizeImages(){
	getImageSizes();
	
	var vH = $j(window).height()-60;
	var vW = $j(window).width();
	var vR = vW/vH;
	
	$j("#background-images-container").height(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 === 0 || (i === $j("#background-images .bg-image").size()-1)) && (newWidth < vW)){
				if(i === 0 && newWidth < vW){
				
					var x = Math.floor((vW - newWidth)/2);
					var newContainerWidth = newWidth + x;
					
					if (i === 0){
						$j("img", this).css("margin-left", x);
					}
					if (i === $j("#background-images .bg-image").size()-1){
						$j("img", this).css("padding-right", 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;
		});
			
	}
    
	
// 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 prevwidth = 0;
		
		if(current === 0){
			contentLeft = 0;
			imagesLeft = -prevwidth;
		} else if (current === 1){
			imagesLeft = 0;
		} 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);
		}
		
		
		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 (!(menushow || showthumbs)){
		//	if (current === 0){
		//		currentstyle = $j("#content-first").attr("class");
		//	} else {
				currentstyle = $j("#background-images td:eq("+(current-1)+")").attr("class");
		//	}
		//} 
		
		//if(menushow){
		//	currentstyle = $j("#top_menu").attr("class");
		//}
		if(!currentstyle){
			currentstyle = temp;
		} 
		//var changes = $j("#header, #menu-main-nav, #side_menu, #right_button, #navi-thumbs, #left_button, #right_button, #thumbnails-btn a, #menulink, #top-sub-menu");
		var changes = $j("#right_button, #left_button");
		changes.removeClass("light");
		changes.removeClass("dark");
		//alert(currentstyle);
		changes.addClass(currentstyle);
	}
// ---

	function updateMenuText(){
		$j("#i-numbers span").text(current);
		$j("#i-caption").text(imageCaptions[current-1]);
	}
	

// reset spans on top of bg images :	
	function resetDim(){
	
		updateMenuText();
	

		$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;
		temp-=1;
		maxtemp -= 1;

		
		// set class for right nav
		if (temp == maxtemp){
			$j("#right_button").addClass("end");
		} else if (temp == total) {
			$j("#right_button").addClass("loading");
		} else {
			$j("#right_button").removeClass("end").removeClass("loading");
		}
		
		if(total == 0){
			$j("#right_button").removeClass("loading").addClass("end");
			
		}
		
			
	}
// ---
	
// bottom bar of navi buttons :
	function setNaviSizes(){
		var vW = $j(window).width();
		var n = $j("#navi-thumbs span").size();
		
		var gutter = 1;
		
		$j("#navi-thumbs span:eq(0)").width(0).attr("margin", 0);
		n -= 1;
		
		var width = ((vW-60)-((n-1)*gutter))/n;
		
		$j("#navi-thumbs span").not("#navi-thumbs span:eq(0)").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 === 1){
			killLeftHover();
			killRightHover();
			if(iphone){
				$j("#right_button").show().fadeTo(0,1);
			}			
		} else {
			liveLeftHover();
			liveRightHover();
		}
	
	}
	
	function getImageSizes(){
	
		imageWidths = [];
		imageHeights = [];
		imageRatios = [];
		imageCaptions = [];
		
		$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]);
			
			imageCaptions.push(image[4]);
		});
	}
	
	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();
		}

	}
	
	
	var menushow = $j("#top_menu").is(":visible"); 

	
	var maxpages = parseInt($j("#small_links_navi #total").text(), 10) - 1;
	var currentpage = 0;
	//scrollMenu();
		
	
	var topmenuheight = $j("#top_menu").height() - 30;
	var thumbpadding = parseInt($j("#thumbnails").css("padding-top"), 10);
	$j("#main.extend").css("margin-top", topmenuheight);
	
	function slideContentUp(){
		if($j("#main.extend").length){
			$j("#main.extend").stop(true,true).animate({"margin-top": 0}, 500);
		}
		if($j("#thumbnails").length){
			$j("#thumbnails").stop(true,true).animate({"padding-top": thumbpadding}, 500);
		}
	}
	
	function slideContentDown(){
		if($j("#main.extend").length){
			$j("#main.extend").stop(true,true).animate({"margin-top": topmenuheight}, 500);
		}
		if($j("#thumbnails").length){
			$j("#thumbnails").stop(true,true).animate({"padding-top": thumbpadding+topmenuheight}, 500);
		}
	}
	
	var showsideinfo = true;
	
	function fadesideinfo(){
		showsideinfo = false;
		$j("#content_first").stop().fadeTo(500,0, function(){ $j(this).hide(); });
		$j("#background-images").css("cursor", "pointer");
		$j("#background-images").click(fadeSideInfoIn);
	}
	
	function fadesideinfohalf(){
		if(showsideinfo){
			$j("#content_first").stop().fadeTo(500,0.2);
			
		}
	}
	
	function fadeSideInfoIn(){
		showsideinfo = true;
		$j("#content_first").stop().fadeTo(500,1);
		$j("#background-images").css("cursor", "auto");
		if(menushow){
			hideMenu();
		}
	}
	
	
	
	$j("#content_first .close_x").click(fadesideinfo);
	
	$j("#content_first").hover(function() {
		if(showsideinfo){
			$j(this).stop().fadeTo(500,1);
		}
	}, function() {
		if(showsideinfo){
			$j(this).stop().fadeTo(500,0.2);
		}
	});

});
