var $j = jQuery.noConflict();
$j(document).ready(function(){

	$j("img").live("contextmenu", function(){return false;});
	$j("img").live("mousedown", function(){return false;});

	
	$j("#dynamic-container").fadeTo(0,0.6);
	
	$j("#dynamic-container").hover(function(){
		$j(this).stop().fadeTo(200, 1);
	},function(){
		$j(this).stop().fadeTo(200, 0.6);
	});
	
// remove all image titles
	$j("[title]").removeAttr("title");

// 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;
	}
	if(!iphone){
		$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);
		}
	}
	/*

	function liveRightClick(){
	
		
		$j('#right_buttons').bind("click", function(){
			window.location = $j("a", this).attr("href");
		});
	}
	function killRightClick(){
		$j('#right_buttons').unbind("click");
	}
	

*/

// fancy boxes on posts/pages :

	$j('#info_content img, #info_container img, #page_container img').each(function(){ 
		if(!$j(this).hasClass("nolightbox")){
			$j(this).parent().addClass('lightbox');
		}
	});
	
	$j("a.lightbox").fancybox({
			'opacity'		: true,
			'overlayShow'	: false,
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'none'
	});

	
	
// hides items in side menu and adds click/hover bindings
/*
	function hideSideMenu(){
		$j("#filterby-container").hide();
	
		$j("#sidemenu-container #menu_names li").each(function(){
			$j(this).hide();
			if($j("a", this).hasClass("active")){
				$j(this).show();
			}
		});
			
		$j("#menu-click").bind("click", function(){
			$j("#sidemenu-container, #sidemenu-container #filterby-container, #sidemenu-container #menu_names li").slideDown();
			$j(this).text("Latest Works");
		});
		
		$j("#side_menu").bind("mouseleave", function(){
			$j("#sidemenu-container #menu_names li").each(function(){
				if(!$j("a", this).hasClass("active")){
					$j(this).slideUp();
				}
			});
			$j("#sidemenu-container #filterby-container").slideUp();
			
			$j("#menu-click").text("View All Works");
			
		});
	}
*/
// shows all items in side menu and removes bindings
/*
	function showSideMenu(){
		$j("#sidemenu-container #menu_names li, #filterby-container, #sidemenu-container").show();
		$j("#menu-click").unbind("click");
		$j("#side_menu").unbind("mouseleave");
	}
*/
	
	$j('.menu').append('<span>');


// spaces out menu to width of nearest grid :
	var oldwidth = $j('.menu ul').width();
	var n = Math.ceil((oldwidth + 20)/60);
	var newwidth = (40*n)+(20*(n-1));
	var numitems = $j('.menu li').size();
	var space = (newwidth-oldwidth)/(numitems-1);
	var active_cats = new Array();
	if(space < 15){
	// adds extra column if items are too crowded :
		newwidth += 60;
		space = (newwidth-oldwidth)/(numitems-1);
	}
	$j('.menu li').css('padding-right', space);

// adds left margin to feature text so it gets narrow as the window gets small :
	var featuremargin = newwidth + 290;
	$j('#blog-description').css('margin-left', featuremargin);
	
	
	function calcMenuWidth(){
		var rightmargin = $j('#blog-description').width();
		$j(".menu ul").css("margin-right", rightmargin);
	}
	
	
	
// filter-by menu :	
	$j('#menu_cats div').bind("click", function() {
		
		if ($j(this).hasClass('all_cats')) {
			$j(this).addClass('boldtext');
			$j('.check_box_inner', this).addClass('checked');
			$j('#menu_cats div').not(this).each(function() {  				
				$j(this).removeClass('boldtext');
				$j('.check_box_inner', this).removeClass('checked');
			});
			$j('#menu_names li').each(function() {
				$j(this).slideDown();
			});
			active_cats = [];
		} 
		
		
		else if ($j('.check_box_inner', this).hasClass('checked')){
				var checkcheck = false;
				$j('.check_box_inner', this).removeClass('checked');
				$j(this).removeClass('boldtext');
				var cat = $j(this).attr('class');
				//PULL OUT CHECKED CLASS
				var i; for (i = 0; i < active_cats.length; ++i) {
				if (cat == active_cats[i]) {
					active_cats.splice(i, 1);
				}
			}
			if (active_cats.length === 0) {
					$j('#menu_names li').slideDown();
				} else {		
					
					$j('#menu_names li').each(function() {
				    var isactive = false;
				    	var g; for (g = 0; g < active_cats.length; ++g) {
				    		if ($j(this).hasClass(active_cats[g])) {
				    			isactive = true;
				    		} 
				    	}
				    	if (isactive === true) {
				    		$j(this).slideDown();
				    	} else {
				    		$j(this).slideUp();
				    	}
				});
			}

			$j('#menu_cats div .check_box_inner').each(function() {
				if ($j(this).hasClass('checked')) {
					checkcheck = true;
				} 
			});
			if (checkcheck === false) {
				$j('.all_cats').addClass('boldtext');
				$j('.all_cats .check_box_inner').addClass('checked');
			}
		
		} 
		
		
		else {
			var cat = $j(this).attr('class');
			active_cats.push(cat);
			$j(this).addClass('boldtext');
			$j('.check_box_inner', this).addClass('checked');
			$j('.all_cats').removeClass('boldtext');
			$j('.all_cats .check_box_inner').removeClass('checked');
			$j('#menu_names li').each(function() {
				if (!$j(this).hasClass(cat)) {
					$j(this).slideUp();
				} 
			});
		
		}	
	
	});

// 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){
	//alert(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;
	if(!showcontent){
		current = 1;
	} else {
		current = 0;
	}
	var imageWidths = new Array();
	var imageHeights = new Array();
	var imageRatios = new Array();
	
// ---

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


// 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(){
		if(current>0){
			current -= 1;
		}
		scrollToLeft(1200,'easeInOutExpo', true);
		resetDim();
		setActiveNavi();
		resetLeftRightNavi();
	});
	$j(".next").click(function(){
		if(current<$j("#background-images td").size()){
			current += 1;
			scrollToLeft(1200,'easeInOutExpo', true);
			resetDim();
			setActiveNavi();
			resetLeftRightNavi();
		} else {
			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(){
	//alert($j("#background-images td").size());
	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==0)&&(newWidth < vW)){
					var x = Math.floor((vW - newWidth)/2);
					var newContainerWidth = newWidth + x;
					$j("img", this).css("margin-left", x);
				} */
				if ((i==$j("#background-images .bg-image").size()-1)&&(newWidth < vW)){
					var x = Math.floor((vW - newWidth)/2);
					var newContainerWidth = newWidth + x;
					//$j("img", this).css("margin-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 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");
		changes.removeClass("light");
		changes.removeClass("dark");
		changes.addClass(currentstyle);
	}
// ---
// reset spans on top of bg images :	
	function resetDim(){
		/* 	// old code

		$j("#background-images span, #content-first span").stop().fadeTo("slow", 1);
		if (current === 0){
			$j("#content-first span").hide();
		} else {
			$j("#background-images td:eq("+(current-1)+") span").hide();
		}
		
*/		

		$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;
		if(showcontent){
			total+=1;
		} else {
			temp-=1;
		}

		//alert(temp + ", " + total);
		if (temp==total){
			$j('#right_buttons').addClass("end");
			//liveRightClick();
		} else {
			$j('#right_buttons').removeClass("end");
			//killRightClick();
		}
		

		
		
		
	}
// ---
	
// 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);
		}
	}
// ---

	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();
			//showSideMenu();
		} else if (current===1 && showcontent===false){
			killLeftHover();
			//hideSideMenu();
			liveRightHover();
		} else {
			//hideSideMenu();
			liveLeftHover();
			liveRightHover();
		}
	
	}
	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();
				LoadImages(no+1,max);
			}).error(function(){
				// on error remove current
				//$j(curr).remove();
				// trigger the next image
				LoadImages(no+1,max);
			}).attr("src", allBgImages[no][1]);
		}
		
		if (no==1){
			resetLeftRightNavi();
			setActiveNavi();
		}

	}
});
