var orig_width;
var orig_height;

$(window).load(function() {
	CustomScroller();
	function CustomScroller(){
		outerMargin=0;
		innerMargin=20;
		$('#customScrollBox').height($(window).height()-outerMargin);
		$('#dragger_container').height($(window).height()-innerMargin);
		visibleHeight=$(window).height()-outerMargin;
		if($('#customScrollBox  .container').height()>visibleHeight){ //custom scroll depends on content height
			$('#dragger_container').css('display','block');
			$('#dragger').css('display','block');
			totalContent=$('#customScrollBox  .content').height();
			draggerContainerHeight=$(window).height()-innerMargin;
			animSpeed=400; //animation speed
			easeType='easeOutCirc'; //easing type
			bottomSpace=1.05; //bottom scrolling space
			targY=0;
			draggerHeight=$('#dragger').height();
			$('#dragger').draggable({ 
				axis: 'y', 
				containment: 'parent', 
				drag: function(event, ui) {
					Scroll();
				}, 
				stop: function(event, ui) {
					DraggerOut();
				}
			});

			//scrollbar click
			$('#dragger_container').click(function(e) {
				var mouseCoord=(e.pageY - $(this).offset().top);
				var targetPos=mouseCoord+$('#dragger').height();
				if(targetPos<draggerContainerHeight){
					$('#dragger').css('top',mouseCoord);
					Scroll();
				} else {
					$('#dragger').css('top',draggerContainerHeight-$('#dragger').height());
					Scroll();
				}
			});

			//mousewheel
			$(function($) {
				$('#customScrollBox').bind('mousewheel', function(event, delta) {
					vel = Math.abs(delta*10);
					$('#dragger').css('top', $('#dragger').position().top-(delta*vel));
					Scroll();
					if($('#dragger').position().top<0){
						$('#dragger').css('top', 0);
						$('#customScrollBox .container').stop();
						Scroll();
					}
					if($('#dragger').position().top>draggerContainerHeight-$('#dragger').height()){
						$('#dragger').css('top', draggerContainerHeight-$('#dragger').height());
						$('#customScrollBox .container').stop();
						Scroll();
					}
					return false;
				});
			});

			function Scroll(){
				var scrollAmount=(totalContent-(visibleHeight/bottomSpace))/(draggerContainerHeight-draggerHeight);
				var draggerY=$('#dragger').position().top;
				targY=-draggerY*scrollAmount;
				var thePos=$('#customScrollBox  .container').position().top-targY;
				$('#customScrollBox .container').stop().animate({top: '-='+thePos}, animSpeed, easeType); //with easing
			}

			//dragger hover
			$("#dragger").mouseup(function(){
				DraggerOut();
			}).mousedown(function(){
				DraggerOver();
			});

			function DraggerOver(){
				$('#dragger').css('background', 'url(../images/round_custom_scrollbar_bg_over.png)');
			}

			function DraggerOut(){
				$('#dragger').css('background', 'url(../images/round_custom_scrollbar_bg.png)');
			}
		} else { //hide custom scrollbar if content is short
			$('#dragger').css('display','none');
			$('#dragger_container').css('display','none');
		}
	}

	//resize browser window functions
	$(window).resize(function() {
		FullScreenBackground(".bgimg"); //scale bg image
		$('#dragger').css('top',0); //reset content scroll
		$('#customScrollBox .container').css('top',0);
		$('#customScrollBox').unbind('mousewheel');
		CustomScroller();
	});

		$( "#v_slider" ).slider({
			orientation: "vertical",
			min: 12,
			max: 96,
			value: startHeight,
			slide: resAdjustImage
		});

		$( "#h_slider" ).slider({
			orientation: "horizontal",
			min: 12,
			max: 96,
			value: startWidth,
			slide: resAdjustImage
		});
});

$(document).ready(function(){
	FullScreenBackground(".bgimg"); //scale bg image
	itemIndex = 0;
	lastItemIndex = -1;
	//loading bg image
	$(".bgimg").load(function() {
		$("#preloader").fadeOut("fast"); //hide preloader
		$(this).fadeIn("slow"); //fadein background image
		$(this).removeAttr("width").removeAttr("height").css({width: "", height: ""}); //lose all previous dimensions in order to rescale new image data
		$(this).attr("title",$("#bg").data("newTitle")); //set new image title attribute
		FullScreenBackground(this); //scale new image
		$("#bg").data("nextImage",$($("#outer_container").data("selectedThumb")).next().attr("href")); //get and store next image
		if(itemIndex==lastItemIndex){ //check if it is the last image
			$("#bg").data("lastImageReached","Y");
		} else {
			$("#bg").data("lastImageReached","N");
		}
		//SlidePanels("close"); //close the left pane
	});

	//slide in/out left pane
	/*$("#outer_container").hover(
		function(){ //mouse over
			SlidePanels("open");
		},
		function(){ //mouse out
			//SlidePanels("close");
		}
	);*/
	
	//Clicking on thumbnail changes the background image
	$("#outer_container a").click(function(event){
                resAdjustImage()
		event.preventDefault();
		$("#bg .bgimg").css("display","none");
		$("#preloader").fadeIn("fast"); //show preloader
		//style clicked thumbnail
		$("#outer_container a").each(function() {
    		$(this).children(".selected").css("display","none");
  		});
		$(this).children(".selected").css("display","block");
		//get and store next image and selected thumb 
		$("#bg").data("lastImageReached","N");
		$("#outer_container").data("selectedThumb",this); 
		$("#bg").data("nextImage",$(this).next().attr("href")); 	
		$("#bg").data("newTitle",$(this).children("img").attr("title")); //get and store new image title attribute
		itemIndex=getIndex(this); //get clicked item index
		lastItemIndex=($("#outer_container a").length)-1; //get last item index
		$("#bg .bgimg").attr("src", this); //switch image
                $("#h_slider").slider('value',startWidth);
                $("#v_slider").slider('value',startHeight);
                adjustImage();
	}); 

	//clicking on large image loads the next one
	$("#bg .bgimg").click(function(event){
		if($("#bg").data("nextImage") && $("#bg").data("lastImageReached")!="Y"){ //if next image data is stored or last image selected
			$(this).css("display","none");
			$("#preloader").fadeIn("fast"); //show preloader
			$($("#outer_container").data("selectedThumb")).children(".selected").css("display","none"); //deselect thumb
			$($("#outer_container").data("selectedThumb")).next().children(".selected").css("display","block"); //select new thumb
			//store new selected thumb
			var selThumb=$("#outer_container").data("selectedThumb");
			$("#outer_container").data("selectedThumb",$(selThumb).next()); 
			$("#bg").data("newTitle",$($("#outer_container").data("selectedThumb")).children("img").attr("title")); //get and store new image title attribute
			itemIndex++;
			$(this).attr("src", $("#bg").data("nextImage")); //switch image
		}
	});
	
	//function to get element index (fuck you IE!)
	function getIndex(theItem){
		for ( var i = 0, length = $("#outer_container a").length; i < length; i++ ) {
			if ( $("#outer_container a")[i] === theItem ) {
				return i;
			}
		}
	}
	
	//toolbar (image view mode button) hover
	$("#toolbar").hover(
		function(){ //mouse over
			$(this).stop().fadeTo("fast",1);
		},
		function(){ //mouse out
			$(this).stop().fadeTo("fast",0.8);
		}
	); 
	$("#toolbar").stop().fadeTo("fast",0.8); //set its original state
	
	//Clicking on toolbar changes the image view mode
	$("#toolbar").click(function(event){
		if($("#toolbar").data("imageViewMode")=="normal"){
			ImageViewMode('full');
		} else {
			ImageViewMode('normal');
		}
	});

	//next image balloon tip
	$("#bg .bgimg").mouseover(function() {
		if($("#bg").data("nextImage") && $("#bg").data("lastImageReached")!="Y"){ //check if this is the first image
			$("#nextimage_tip").css("right",20);
			$("#nextimage_tip").stop().fadeTo("fast",1).delay(3000).fadeTo("fast",0,function(){$("#nextimage_tip").css("right",$(window).width());});
		}
	}); 

	//slide in/out left pane function
	function SlidePanels(action){
		var speed=900;
		var easing="easeInOutSine";
		if(action=="open"){
			$("#arrow_indicator").fadeTo("fast",0);
			$("#outer_container").stop().animate({left: 0}, speed,easing);
			$("#bg").stop().animate({left: 85}, speed,easing);
		} else {
			$("#outer_container").stop().animate({left: -210}, speed,easing);
			$("#bg").stop().animate({left: 0}, speed,easing,function(){$("#arrow_indicator").fadeTo("fast",1);});
		}
	}
});

//Image scale function
function FullScreenBackground(theItem){
	var winWidth=$(window).width()-240;
	var winHeight=$(window).height()-96;//56;
	var imageWidth=$(theItem).width();
	var imageHeight=$(theItem).height();
	var picHeight = imageHeight / imageWidth;
	var picWidth = imageWidth / imageHeight;
	if ($("#toolbar").data("imageViewMode")=="normal"){ //image view mode: full
		if ((winHeight / winWidth) < picHeight) {
			$(theItem).css("width",winWidth);
			$(theItem).css("height",picHeight*winWidth);
		} else {
			$(theItem).css("height",winHeight);
			$(theItem).css("width",picWidth*winHeight);
		};
	} else { //image view mode: fit
		if ((winHeight / winWidth) > picHeight) {
			$(theItem).css("width",winWidth);
			$(theItem).css("height",picHeight*winWidth);
		} else {
			$(theItem).css("height",winHeight);
			$(theItem).css("width",picWidth*winHeight);
		};
	}
	//center it
	$(theItem).css("margin-left",(winWidth - $(theItem).width()) / 2);
        $(theItem).css("margin-right",(winWidth - $(theItem).width()) / 2);
	$(theItem).css("margin-top",(winHeight - $(theItem).height()) / 2);
        
        orig_width = $(theItem).width();
        orig_height = $(theItem).height();
        adjustImage();
}

//image view mode function - full or fit
function ImageViewMode(theMode){
	$("#toolbar").data("imageViewMode", theMode); //store new mode
	FullScreenBackground(".bgimg"); //scale bg image
	//re-style button
	if(theMode=="full"){
		$("#toolbar").html("<span class='lightgrey'>IMAGE VIEW MODE &rsaquo;</span> FULL");
		$("#toolbar").css("width",125);
	} else {
		$("#toolbar").html("<span class='lightgrey'>IMAGE VIEW MODE &rsaquo;</span> FIT");
		$("#toolbar").css("width",115);
	}
}

function resAdjustImage() {
    loading = 0;
    startWidth=96;
    startHeight=96;
    adjustImage();
}

function adjustImage() {
    var theItem = ".bgimg";

    var setWidth = $("#h_slider").slider('value');
    var setHeight = $("#v_slider").slider('value');
    
    if (loading) {
        setWidth = startWidth;
        setHeight = startHeight;
    }
    
    var winWidth= ($(window).width()-240 );
    var winHeight=($(window).height()-96 );
    var imageWidth= orig_width * ( setWidth / 100);
    var imageHeight= orig_height * ( setHeight / 100);
    var picHeight = imageHeight / imageWidth;
    var picWidth = imageWidth / imageHeight;

    $(theItem).css("width",imageWidth);
    $(theItem).css("height",imageHeight);

    //center it
    $(theItem).css("margin-left",(winWidth - $(theItem).width()) / 2);
    $(theItem).css("margin-right",(winWidth - $(theItem).width()) / 2);
    $(theItem).css("margin-top",(winHeight - $(theItem).height()) / 2);
    
    if (setWidth > 10) {
        $("#size").html(setWidth + "in x " + setHeight + "in");
    }
}

var rotation = 0;
var mirror = 0;
var flip = 0;
function updateImg() {
    bgimg = document.getElementById('bgimg');
    var src = bgimg.src.toString();
    //remove params if there are any
    if (src.indexOf("&") > 0)
        src = src.substr(0, src.indexOf("&"));
    
    if (rotation != 0)
        src += "&rotate=" + rotation;
    
    if (mirror != 0)
        src += "&mirror=" + mirror;

    if (flip != 0)
        src += "&flip=" + flip;
    
    bgimg.src = src;
}

function mirrorImg() {
    mirror++;
    mirror = mirror % 2;
    updateImg();
}

function flipImg() {
    flip++;
    flip = flip % 2;
    updateImg();
}

function rotateImg(dir) {
    rotation += dir;
    if (rotation < 0) rotation += 4;
    rotation = rotation % 4;
    updateImg();
}
