$(document).ready(function() {
	var sideMenuSelected = $("#sideMenu a.selected");
	var menuDelay = 600;
	var sideMenuTimeout;
	
	/*$("#sideMenu a").mouseover(function() {		
		$("#sideMenu a").removeClass('selected');
		$(this).addClass('selected');
		window.clearTimeout(sideMenuTimeout);
	}).mouseout(function(){
		sideMenuTimeout = window.setTimeout(function(){
			$("#sideMenu a").removeClass('selected');
			$(sideMenuSelected).addClass('selected');
		}, menuDelay);
	});*/
	
	var bch = $(window).height();
	$("#blogContent").css("height", (bch - 416) + "px");
	
	bchh = $(window).height();
	$("#blogContentOuter").css("height", (bchh - 365) + "px");
	
	var fw = $("#footerWrapper");	
	var footerOffset = fw.offset();
	var footerHeight = fw.height();
	
	var mc = $("#mainContent");			

	if(mc.length) {
		var mcOffset = mc.offset();			
		var mcBottom = mcOffset.top + mc.height() + 50;
	
		if((mcBottom + footerHeight) < bch) {
			fw.css({'position':'fixed', 'width':'100%', 'top':bch + 'px', 'left':'0px', 'margin':'-' + footerHeight + 'px 0 0 0'});
		} else {
			fw.css({'position':'relative', 'width':'100%', 'top':'0px', 'left':'0px', 'margin':'0'});
		}
	} else {
		fw.css({'position':'fixed', 'width':'100%', 'top':bch + 'px', 'left':'0px', 'margin':'-' + footerHeight + 'px 0 0 0'});
	}
	
	$("#gallery #restoreButt a").live("click", function(e){
		e.preventDefault();
		$('#gallery').empty();
		$('#restore').children().appendTo('#gallery');		
		$('div[id="outer_container2"]').attr("id", "outer_container");
		
		resetElements(false, false, false);
		hideControls();
		
		$("#restoreButt").fadeToggle("fast");
		//$("#toolbar").fadeToggle("fast");		
		$("#wrapper").fadeToggle("fast");
		$("#headerWrapper").slideToggle("fast");
		$("#footerWrapper").slideToggle("fast");
		return false;		
	});

	$("#gallery #toolbar a").live("click", function(e){
		e.preventDefault();
		var mode = $(this).attr("rel");
		ImageViewMode(mode);
		
		if($(this).attr("rel") == "full") {			
			$(this).html("<img src='images/toolbar_n_icon.png' width='46' height='46' />").attr("rel", "normal").attr("title", "Restore");
		} else {
			$(this).html("<img src='images/toolbar_fs_icon.png' width='46' height='46' />").attr("rel", "full").attr("title", "Maximise");
		}

		return false;		
	});

	$("#gallery").bind("copy paste contextmenu", function(e) {
		e.preventDefault();
		return false;
	});
	
	$(".galleryLink").live("click", function(e){		
		e.preventDefault();		
		$('#restore').empty();
		$('#gallery').children(':not(#restoreButt)').appendTo('#restore');
		$('div[id="outer_container"]').attr("id", "outer_container2");
		$("#gallery").load("getGalleryImages.inc.php", {galleryID: $(this).attr("rel")}, function(){

			resetElements(true, true, false);
			
			$("#headerWrapper").slideToggle("fast");
			$("#footerWrapper").slideToggle("fast");
			$("#wrapper").fadeToggle("fast");
			$("#restoreButt").fadeToggle("fast");
			//$("#toolbar").fadeToggle("fast");
		});		
		return false;		
	});
	
	/****
	FULLSCREEN BACKGOUND IMAGE WITH JQUERY
	Original script: http:// manos.malihu.gr/fullscreen-backgound-image-with-jquery
	Modified by Innivo June 2011
	****/	
	
	// config
	var $defaultViewMode; 						// set default images view mode: full, normal, original
	var $tsMargin; 								// first and last thumbnail margin (for better cursor interaction) 
	var $scrollEasing; 							// scroll easing amount (0 for no easing) 
	var $scrollEasingType; 						// scroll easing type 
	var $thumbnailsContainerOpacity; 			// thumbnails area default opacity
	var $thumbnailsContainerMouseOutOpacity; 	// thumbnails area opacity on mouse out
	var $thumbnailsOpacity; 					// thumbnails default opacity
	var $nextPrevBtnsInitState; 				// next/previous image buttons initial state ("hide" or "show")
	var $keyboardNavigation; 					// enable/disable keyboard navigation ("on" or "off")
	var $showTitle;								// show image caption
	var $showThumbs;							// show thumbnail navigation
	var $showLoader;							// show loader
	var $buttNavigation;						// flag for prev / next arrows
	var $loadFromCookie;						// flag for cookie load
	
	// cache vars
	var $thumbnails_wrapper;
	var $outer_container;
	var $thumbScroller
	var $thumbScroller_container;
	var $thumbScroller_content;
	var $thumbScroller_thumb;
	var $bgimg;
	
	// elements of the gallery
	var $preloader;
	var $toolbar;
	var $toolbar_a;
	var $img_title;
	var $nextImageBtn;
	var $prevImageBtn;

	// slideshow vars
	var slideshow_enabled; 					// enable or disable the slideshow on page load
	var slideshow_delay; 					// slideshow delay in msec.
	var slideshow_timeout;					// ref to setTimeout
	
	function galleryInit($showThumbsInit, $buttNavigationInit, $loadFromCookieInit) {
		
		if($showThumbsInit){
			$showThumbs = true;
		}		
		if($buttNavigationInit){
			$buttNavigation = true;
		}		
		if($loadFromCookieInit){
			$loadFromCookie = true;
		}
				
		$toolbar.data("imageViewMode",$defaultViewMode); // default view mode
		ShowHideNextPrev($nextPrevBtnsInitState);
		
		// thumbnail scroller
		$thumbScroller_container.css("marginLeft",$tsMargin+"px"); // add margin
		sliderLeft=$thumbScroller_container.position().left;
	
		sliderWidth=$outer_container.width();
		$thumbScroller.css("width",sliderWidth);
		var totalContent=0;
		fadeSpeed=200;
		
		var $the_outer_container = document.getElementById("outer_container");
		var $placement=findPos($the_outer_container);
		
		$thumbScroller_content.each(function () {
			var $this=$(this);
			totalContent+=$this.innerWidth();
			$thumbScroller_container.css("width",totalContent);
			$this.children().children().children("#gallery .thumb").fadeTo(fadeSpeed, $thumbnailsOpacity);
		});
	
		$thumbScroller.mousemove(function(e){
			if($thumbScroller_container.width()>sliderWidth){
				var mouseCoords=(e.pageX - $placement[1]);
				var mousePercentX=mouseCoords/sliderWidth;
				var destX=-((((totalContent+($tsMargin*2))-(sliderWidth))-sliderWidth)*(mousePercentX));
				var thePosA=mouseCoords-destX;
				var thePosB=destX-mouseCoords;
				if(mouseCoords>destX){
					$thumbScroller_container.stop().animate({left: -thePosA}, $scrollEasing,$scrollEasingType); // with easing
				} else if(mouseCoords<destX){
					$thumbScroller_container.stop().animate({left: thePosB}, $scrollEasing,$scrollEasingType); // with easing
				} else {
					$thumbScroller_container.stop();  
				}
			}
		});
	
		if($showThumbs === true) {	
			$thumbnails_wrapper.fadeTo(fadeSpeed, $thumbnailsContainerOpacity);
	
			$thumbnails_wrapper.hover(
				function(){ // mouse over
					var $this=$(this);
					$this.stop().fadeTo("slow", 1);
				},
				function(){ // mouse out
					var $this=$(this);
					$this.stop().fadeTo("slow", $thumbnailsContainerMouseOutOpacity);
				}
			);
	
			$thumbScroller_thumb.hover(
				function(){ // mouse over
					var $this=$(this);
					$this.stop().fadeTo(fadeSpeed, 1);
				},
				function(){ // mouse out
					var $this=$(this);
					$this.stop().fadeTo(fadeSpeed, $thumbnailsOpacity);
				}
			);
		} else {
			$thumbnails_wrapper.hide();	
		}
	
		// on window resize scale image and reset thumbnail scroller
		$(window).resize(function() {
			FullScreenBackground("#bgimg",$bgimg.data("newImageW"),$bgimg.data("newImageH"),false);
			if($showThumbs) {
				$thumbScroller_container.stop().animate({left: sliderLeft}, 400,"easeOutCirc"); 
				var newWidth=$outer_container.width();
				$thumbScroller.css("width",newWidth);
				sliderWidth=newWidth;
				$placement=findPos($the_outer_container);
			}
			
			bch = $(window).height();
			$("#blogContent").css("height", (bch - 416) + "px");
			
			bchh = $(window).height();
			$("#blogContentOuter").css("height", (bchh - 365) + "px");


			//fw = $("#footerWrapper");	
			footerOffset = fw.offset();
			footerHeight = fw.height();
			
			//mc = $("#mainContent");
			if(mc.length) {			
				mcOffset = mc.offset();			
				mcBottom = mcOffset.top + mc.height() + 50;
				
				if((mcBottom + footerHeight) < bch) {
					fw.css({'position':'fixed', 'width':'100%', 'top':bch + 'px', 'left':'0px', 'margin':'-' + footerHeight + 'px 0 0 0'});
				} else {
					fw.css({'position':'relative', 'width':'100%', 'top':'0px', 'left':'0px', 'margin':'0'});
				}
			} else {
				fw.css({'position':'fixed', 'width':'100%', 'top':bch + 'px', 'left':'0px', 'margin':'-' + footerHeight + 'px 0 0 0'});
			}
			
			if(api !== undefined) {
				api.getContentPane();
				api.reinitialise();
			}
		});
	
		// next/prev images keyboard arrows
		if($keyboardNavigation=="on"){
			$(document).keydown(function(ev) {
				if(ev.keyCode == 39) { // right arrow
					SwitchImage($outer_container.data("nextImage"));
					var $this=$("#gallery #outer_container a[href='"+$outer_container.data("nextImage")+"']");
					GetNextPrevImages($this);
					GetImageTitle($this);
					return false; // don't execute the default action (scrolling or whatever)
				} else if(ev.keyCode == 37) { // left arrow
					SwitchImage($outer_container.data("prevImage"));
					var $this=$("#gallery #outer_container a[href='"+$outer_container.data("prevImage")+"']");
					GetNextPrevImages($this);
					GetImageTitle($this);
					return false; // don't execute the default action (scrolling or whatever)
				}
			});
		}

		var first = 0;
		var last = ($("#gallery .content").length - 1);
	
		// load 1st image
		var the1stImg = new Image();
		the1stImg.onload = CreateDelegate(the1stImg, theNewImg_onload);

		if($loadFromCookie && $.getCookie("bgimg") != "") {
			the1stImg.src = $.getCookie("bgimg");		
			var index = $.getCookie("index");
			first = index;
			last = index - 1;
		} else {
			the1stImg.src = $bgimg.attr("src");
		}
		
		if($buttNavigation) {
			$("#gallery .nextImageBtn, #gallery .prevImageBtn, #gallery #restoreButt a, #gallery #toolbar a").css("display", "block");
		} else {
			$("#gallery .nextImageBtn, #gallery .prevImageBtn, #gallery #restoreButt a, #gallery #toolbar a").css("display", "none");
		}
		
		$outer_container.data("nextImage", $("#gallery .content").eq(first).next().find("a").attr("href"));
		$outer_container.data("prevImage", $("#gallery .content").eq(last).find("a").attr("href"));

		if($("body").hasClass('home')) {
			slideshow_enabled = true;
		}

		if(slideshow_enabled){
			if(slideshow_timeout !== undefined) {
				window.clearTimeout(slideshow_timeout);
			}
			slideshow_timeout = window.setTimeout(slideshow_loop, slideshow_delay);
		}
	}

	// Clicking on thumbnail changes the background image
	$("#gallery #outer_container a").live("click", function(event){
		increase_delay_func();
		event.preventDefault();
		var $this=$(this);
		GetNextPrevImages($this);
		GetImageTitle($this);
		SwitchImage(this);
		ShowHideNextPrev("show");
	}); 
	
	// next/prev images buttons
	$("#gallery .nextImageBtn").live("click", function(event){
		increase_delay_func();
		event.preventDefault();
		SwitchImage($outer_container.data("nextImage"));
		var $this=$("#gallery #outer_container a[href='"+$outer_container.data("nextImage")+"']");
		GetNextPrevImages($this);
		GetImageTitle($this);
	});
	
	$("#gallery .prevImageBtn").live("click", function(event){
		increase_delay_func();
		event.preventDefault();
		SwitchImage($outer_container.data("prevImage"));
		var $this=$("#gallery #outer_container a[href='"+$outer_container.data("prevImage")+"']");
		GetNextPrevImages($this);
		GetImageTitle($this);
	});

	function slideshow_loop(){
		$("#gallery .nextImageBtn").trigger("click");
	}

	function increase_delay_func(){
		if(slideshow_enabled) {
			window.clearTimeout(slideshow_timeout);
			slideshow_timeout = window.setTimeout(slideshow_loop, slideshow_delay);
		}
	}
	
	function BackgroundLoad($this,imageWidth,imageHeight,imgSrc){
		$this.fadeOut(0,function(){
			$this.attr("src", "").attr("src", imgSrc); 					// change image source
			FullScreenBackground($this,imageWidth,imageHeight,false); 	// scale background image
			
			if($showLoader) {
				$preloader.fadeOut(0,function(){$this.fadeIn(0);});
			} else {
				$this.fadeIn(0);
			}
			
			if($showTitle === true) {
				var imageTitle=$img_title.data("imageTitle");
				if(imageTitle){
					//$this.attr("alt", imageTitle).attr("title", imageTitle);
					$img_title.fadeOut("fast",function(){
						$img_title.html(imageTitle).fadeIn();
					});
				} else {
					$img_title.fadeOut("fast",function(){
						$img_title.html($this.attr("title")).fadeIn();
					});
				}
			}
		});
	}
		
	function ShowHideNextPrev(state){
		if(state=="hide"){
			$nextImageBtn.fadeOut();
			$prevImageBtn.fadeOut();
		} else {
			$nextImageBtn.fadeIn();
			$prevImageBtn.fadeIn();
		}
	}
	
	// get image title
	function GetImageTitle(elem){
		var title_attr=elem.children("img").attr("title"); // get image title attribute
		$img_title.data("imageTitle", title_attr); // store image title
	}
	
	// get next/prev images
	function GetNextPrevImages(curr){
		var nextImage=curr.parents("#gallery .content").next().find("a").attr("href");
		if(nextImage==null){ // if last image, next is first
			var nextImage=$("#gallery .content").first().find("a").attr("href");
		}
		$outer_container.data("nextImage",nextImage);
		var prevImage=curr.parents("#gallery .content").prev().find("a").attr("href");
		if(prevImage==null){ // if first image, previous is last
			var prevImage=$("#gallery .content").last().find("a").attr("href");
		}
		$outer_container.data("prevImage",prevImage);
	}
	
	// switch image
	function SwitchImage(img){
		if($showLoader) {
			$preloader.fadeIn("fast"); // show preloader
		}
		
		var index = 0;
		var $images = $("#gallery .content img");
		for(var i = 0; i < $images.length; i++) {		
			if($("#gallery .content a").eq(i).attr('href') == img) {
				break;
			} else {
				index++;	
			}
		}
		
		var theNewImg = new Image();
		theNewImg.onload = CreateDelegate(theNewImg, theNewImg_onload);
		theNewImg.src = img;
		
		if($loadFromCookie) {
			$.setCookie("bgimg",img);
			$.setCookie("index",index);
		}
	}
	
	// get new image dimensions
	function CreateDelegate(contextObject, delegateMethod){
		return function(){
			return delegateMethod.apply(contextObject, arguments);
		}
	}
	
	// new image on load
	function theNewImg_onload(){
		$bgimg.data("newImageW",this.width).data("newImageH",this.height);
		BackgroundLoad($bgimg,this.width,this.height,this.src);
	}
	
	// Image scale function
	function FullScreenBackground(theItem,imageWidth,imageHeight,toggle){
		var winWidth=$(window).width();
		var winHeight=$(window).height();
		
		if($toolbar.data("imageViewMode")!="original"){ // scale
			var picHeight = imageHeight / imageWidth;
			var picWidth = imageWidth / imageHeight;
			
			if(!toggle){
				if(picHeight > picWidth) {
					$toolbar.data("imageViewMode", "normal");
					$("#gallery #toolbar a").html("<img src='images/toolbar_fs_icon.png' width='46' height='46' />").attr("rel", "full").attr("title", "Maximise");					
				} else {
					$toolbar.data("imageViewMode", "full");			
					$("#gallery #toolbar a").html("<img src='images/toolbar_n_icon.png' width='46' height='46' />").attr("rel", "normal").attr("title", "Restore");
				}
			}
			
			if($toolbar.data("imageViewMode")=="full"){ // fullscreen size image mode
				if ((winHeight / winWidth) < picHeight) {
					$(theItem).attr("width",winWidth);
					$(theItem).attr("height",picHeight*winWidth);
				} else {
					$(theItem).attr("height",winHeight);
					$(theItem).attr("width",picWidth*winHeight);
				};
			} else { // normal size image mode
				if ((winHeight / winWidth) > picHeight) {
					$(theItem).attr("width",winWidth);
					$(theItem).attr("height",picHeight*winWidth);
				} else {
					$(theItem).attr("height",winHeight);
					$(theItem).attr("width",picWidth*winHeight);
				};
			}
			//$(theItem).css("margin-left",(winWidth-$(theItem).width())/2);
			$(theItem).css("margin-left",0);
			$(theItem).css("margin-top",(winHeight-$(theItem).height())/2);
		} else { // no scale
			$(theItem).attr("width",imageWidth);
			$(theItem).attr("height",imageHeight);
			//$(theItem).css("margin-left",(winWidth-imageWidth)/2);
			$(theItem).css("margin-left",0);
			$(theItem).css("margin-top",(winHeight-imageHeight)/2);
		}
	}
	
	// Image view mode function - fullscreen or normal size
	function ImageViewMode(theMode){
		$toolbar.data("imageViewMode", theMode);
		FullScreenBackground($bgimg,$bgimg.data("newImageW"),$bgimg.data("newImageH"),true);
		return false;
	}
	
	// function to find element Position
	function findPos(obj) {
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			curleft = obj.offsetLeft
			curtop = obj.offsetTop
			while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft
				curtop += obj.offsetTop
			}
		}
		return [curtop, curleft];
	}

	function resetElements($showThumbsInit, $buttNavigationInit, $loadFromCookieInit) {
		
		if(api !== undefined) {
			api.getContentPane();
			api.reinitialise();
		}
		
		if(!$loadFromCookieInit) {
			$.clearCookie("bgimg");
			$.clearCookie("index");
		}

		// config	
		$defaultViewMode = "full"; 					// set default images view mode: full, normal, original
		$tsMargin = 30; 							// first and last thumbnail margin (for better cursor interaction) 
		$scrollEasing = 600; 						// scroll easing amount (0 for no easing) 
		$scrollEasingType = "easeOutCirc"; 			// scroll easing type 
		$thumbnailsContainerOpacity = 0.8; 			// thumbnails area default opacity
		$thumbnailsContainerMouseOutOpacity = 0; 	// thumbnails area opacity on mouse out
		$thumbnailsOpacity = 0.6; 					// thumbnails default opacity
		$nextPrevBtnsInitState = "hide"; 			// next/previous image buttons initial state ("hide" or "show")
		$keyboardNavigation = "off"; 				// enable/disable keyboard navigation ("on" or "off")
		$showTitle = true;							// show image caption
		$showThumbs = false;						// show thumbnail navigation
		$showLoader = false;						// show loader
		$buttNavigation = false;					// flag for prev / next arrows
		$loadFromCookie = false;					// flag for cookie load

		// cache vars
		$thumbnails_wrapper = $("#gallery #thumbnails_wrapper");
		$outer_container = $("#gallery #outer_container");
		$thumbScroller = $("#gallery .thumbScroller");
		$thumbScroller_container = $("#gallery .thumbScroller .container");
		$thumbScroller_content = $("#gallery .thumbScroller .content");
		$thumbScroller_thumb = $("#gallery .thumbScroller .thumb");
		$bgimg = $("#gallery #bgimg");
		
		// elements of the gallery
		$preloader = $("#gallery #preloader");
		$toolbar = $("#gallery #toolbar");
		$toolbar_a = $("#gallery #toolbar a");
		$img_title = $("#gallery #img_title");
		$nextImageBtn = $("#gallery .nextImageBtn");
		$prevImageBtn = $("#gallery .prevImageBtn");
		
		// slideshow vars
		slideshow_enabled = false; 					// enable or disable the slideshow on page load
		slideshow_delay = 4000; 					// slideshow delay in msec.
		slideshow_timeout;							// ref to setTimeout
	
		if($showThumbsInit) {
			$thumbnails_wrapper.css("display", "block");
		} else {
			$thumbnails_wrapper.css("display", "none");
		}
				
		galleryInit($showThumbsInit, $buttNavigationInit, $loadFromCookieInit);
	}

	function hideControls() {
		$nextImageBtn.hide();
		$prevImageBtn.hide();
		$thumbScroller.hide();
	}

	$(window).load(function() {
		resetElements(false, false, false);
	});
	

	var settings = {
		showArrows: false
	};
	var pane = $('.scroll-pane');
	
	if(pane.length > 0) {
		pane.jScrollPane(settings);
		var api = pane.data('jsp');
	}
	
	$('#sideMenu').scrollFollow({
		speed: 600,
		offset: 98
	});
});
