/*
Thumbnail scroller jQuery plugin
Author: malihu [http://manos.malihu.gr]
Homepage: manos.malihu.gr/jquery-thumbnail-scroller
*/
(function($){  
 $.fn.thumbnailScroller=function(options){  
	var defaults={ //default options
		scrollerType:"hoverPrecise", //values: "hoverPrecise", "hoverAccelerate", "clickButtons"
		scrollerOrientation:"horizontal", //values: "horizontal", "vertical"
		scrollEasing:"easeOutCirc", //easing type
		scrollEasingAmount:800, //value: milliseconds
		acceleration:2, //value: integer
		scrollSpeed:600, //value: milliseconds
		noScrollCenterSpace:0, //value: pixels
		autoScrolling:0, //value: integer
		autoScrollingSpeed:8000, //value: milliseconds
		autoScrollingEasing:"easeInOutQuad", //easing type
		autoScrollingDelay:2500 //value: milliseconds
	};
    var $loader = $("#fp_loading");
    var current = 1;
    $(document).mousemove(function(e){
      			window.mouseXPos = e.pageX;
      			window.mouseYPos = e.pageY;
   		});
    adjustArrows(current);
    $(".jTscroller").find("li").children("img").each(function(){
        $(this).bind("mouseup", function(e){
            $(".jTscroller").find("li").children("img").css("opacity", 0.7);
            $(this).css("opacity", 1);
            e.preventDefault();
            $loader.show();
            current = $(".jTscroller").find("li").children("img").index(this)+1;
            adjustArrows(current);
            var that = this;
            var $image = $(this);
            var alt = $image.attr('alt');
            if(alt == "vimeo"){
                var $iframe = $(".jTscroller").find('li:nth-child('+current+')').children("iframe");
                var $previousPayload = $('img.fp_preview');
                if($previousPayload == null) {
                    $previousPayload = $('iframe.fp_preview');
                }
                var $newimg         = $iframe.clone();
                var $currImage  = $previousPayload;
                $currImage.stop();
                $newimg.insertAfter($currImage);
                $newimg.fadeOut(0);
                $newimg.addClass('fp_preview');
                $loader.hide();
                $currImage.fadeOut(500,function(){
                    $(this).remove();
                    $newimg.fadeIn(500);
                });
            }
            else {
                //$('<img class="fp_preview"/>').load(function(){
                    var $previousPayload = $('img.fp_preview');
                    if($previousPayload.length == 0) {
                        $previousPayload = $('iframe.fp_preview');
                    }
                    var $newimg         = $("<img class=\"fp_preview\" src=\""+$image.attr('alt')+"\" />"); //$(this);
                    var $currImage  = $previousPayload;
                    $currImage.stop();
                    $newimg.insertAfter($currImage);
                    $newimg.fadeOut(0);
                    $loader.hide();
                    $currImage.fadeOut(500,function(){
                        $(this).remove();
                        $newimg.fadeIn(500);
                    });
                //}).attr('src',$image.attr('alt'));
            }
        });
    });
    function adjustArrows(current){
    	var totalThumbs = $(".jTscroller").find("li").length;
    	if (current==totalThumbs ){
    		$("#fp_next").addClass("fp2_next").removeClass("fp_next");
    		$("#fp_prev").removeClass("fp2_prev").addClass("fp_prev");
    	} 
    	else if (current==1)
    	{
    		$("#fp_next").addClass("fp_next").removeClass("fp2_next");
    		$("#fp_prev").addClass("fp2_prev").removeClass("fp_prev");
    	} else{
    		$("#fp_next").addClass("fp_next").removeClass("fp2_next");
    		$("#fp_prev").addClass("fp_prev").removeClass("fp2_prev");
    	}
    }
    function centerImage() {
    	adjustArrows(current);
        var totalThumbs = $(".jTscroller").find("li").length;
        var $li = $(".jTscroller").find("li:nth-child("+current+")");
        var $image = $li.children("img");
        var clipWidth = $(".jThumbnailScroller").outerWidth(true);
        var itemMax = $(".jTscroller").find("li:first-child").outerWidth(true);
        var posX = $li.position().left;
        if(posX > (itemMax*totalThumbs)-clipWidth/2)
            return;
        var center = (-current*itemMax) + (clipWidth / 2) + (itemMax/2)+10;
        if(posX < clipWidth/2)
            center = 0;
		$(".jTscroller").stop(true,false).animate({left:center},options.scrollEasingAmount,options.scrollEasing); 
    }
    function showPrev() {
        if(current==1)
            return;
        $(".jTscroller").find("li").children("img").css("opacity", 0.7);
        current--;
        var $image = $(".jTscroller").find("li:nth-child("+current+")").children("img");
        $image.css("opacity",1);
        $loader.show();
        var alt = $image.attr('alt');
        if(alt == "vimeo"){
            var $iframe = $(".jTscroller").find('li:nth-child('+current+')').children("iframe");
            var $previousPayload = $('img.fp_preview');
            if($previousPayload == null) {
                $previousPayload = $('iframe.fp_preview');
            }
            var $newimg         = $iframe.clone();
            var $currImage  = $previousPayload;
            $currImage.stop();
            $newimg.insertAfter($currImage);
            $newimg.fadeOut(0);
            $newimg.addClass('fp_preview');
            $loader.hide();
            $currImage.fadeOut(500,function(){
                $(this).remove();
                $newimg.fadeIn(500);
            });
        }
        else {
            //$('<img class="fp_preview"/>').load(function(){
                var $previousPayload = $('img.fp_preview');
                if($previousPayload.length == 0) {
                    $previousPayload = $('iframe.fp_preview');
                }
                var $newimg         = $("<img class=\"fp_preview\" src=\""+$image.attr('alt')+"\" />"); //$(this);
                var $currImage  = $previousPayload;
                $currImage.stop();
                $newimg.insertAfter($currImage);
                $newimg.fadeOut(0);
                $loader.hide();
                $currImage.fadeOut(500,function(){
                    $(this).remove();
                    $newimg.fadeIn(500);
                });
            //}).attr('src',$image.attr('alt'));
        }
        centerImage();
    }
    $(".jTscroller").find("li:first-child").children("img").css("opacity",1);
    function showNext() {
        var totalThumbs = $(".jTscroller").children("li").length;
        if(current == totalThumbs)
            return;
        $(".jTscroller").find("li").children("img").css("opacity", 0.7);
        current++;
        var $image = $(".jTscroller").find("li:nth-child("+current+")").children("img");
        $image.css("opacity", 1);
        $loader.show();
        var alt = $image.attr('alt');
        if(alt == "vimeo"){
            var $iframe = $(".jTscroller").find('li:nth-child('+current+')').children("iframe");
            var $previousPayload = $('img.fp_preview');
            if($previousPayload == null) {
                $previousPayload = $('iframe.fp_preview');
            }
            var $newimg         = $iframe.clone();
            var $currImage  = $previousPayload;
            $currImage.stop();
            $newimg.insertAfter($currImage);
            $newimg.fadeOut(0);
            $newimg.addClass('fp_preview');
            $loader.hide();
            $currImage.fadeOut(500,function(){
                $(this).remove();
                $newimg.fadeIn(500);
            });
        }
        else {
            //$('<img class="fp_preview"/>').load(function(){
                var $previousPayload = $('img.fp_preview');
                if($previousPayload.length == 0) {
                    $previousPayload = $('iframe.fp_preview');
                }
                var $newimg         = $("<img class=\"fp_preview\" src=\""+$image.attr('alt')+"\" />"); //$(this);
                var $currImage  = $previousPayload;
                $currImage.stop();
                $newimg.insertAfter($currImage);
                $newimg.fadeOut(0);
                $loader.hide();
                $currImage.fadeOut(500,function(){
                    $(this).remove();
                    $newimg.fadeIn(500);
                });
            //}).attr('src',$image.attr('alt'));
        }
        centerImage();
    }
    $("#fp_prev").click(showPrev);
    $("#fp_next").click(showNext);
	var options=$.extend(defaults,options);
    return this.each(function(){ 
		//cache vars
		var $this=$(this);
		var $scrollerContainer=$this.children(".jTscrollerContainer");
		var $scroller=$this.children(".jTscrollerContainer").children(".jTscroller");
		var $scrollerNextButton=$this.children(".jTscrollerNextButton");
		var $scrollerPrevButton=$this.children(".jTscrollerPrevButton");
		//set scroller width
		if(options.scrollerOrientation=="horizontal"){
			$scrollerContainer.css("width",999999); 
			var totalWidth=$scroller.outerWidth(true);
			$scrollerContainer.css("width",totalWidth);
		}else{
			var totalWidth=$scroller.outerWidth(true);
		}
		var totalHeight=$scroller.outerHeight(true); //scroller height
		//do the scrolling
		if((totalWidth>$this.width() || totalHeight>$this.height())&& $($scrollerContainer).find("li").length>5){ //needs scrolling		
			var pos;
			var mouseCoords;
			var mouseCoordsY;
			if(options.scrollerType=="hoverAccelerate"){ //type hoverAccelerate
				var animTimer;
				var interval=8;
				//console.log($this);
				/*$this.find("img").hover(function(e){
					console.log(e);
				});*/
				$this.hover(function(){ //mouse over
					$this.mousemove(function(e){
						pos=findPos(this);
						mouseCoords=(e.pageX-pos[1]);
						mouseCoordsY=(e.pageY-pos[0]);
						
					});
					clearInterval(animTimer);
					animTimer = setInterval(Scrolling,interval);
				},function(){  //mouse out
					clearInterval(animTimer);
					$scroller.stop();
				});
				$scrollerPrevButton.add($scrollerNextButton).hide(); //hide buttons
			}else if(options.scrollerType=="clickButtons"){
				ClickScrolling();
			}else{ //type hoverPrecise
				pos=findPos(this);
				$this.mousemove(function(e){
					mouseCoords=(e.pageX-pos[1]);
					mouseCoordsY=(e.pageY-pos[0]);
					var mousePercentX=mouseCoords/$this.width(); if(mousePercentX>1){mousePercentX=1;}
					var mousePercentY=mouseCoordsY/$this.height(); if(mousePercentY>1){mousePercentY=1;}
					var destX=Math.round(-((totalWidth-$this.width())*(mousePercentX)));
					var destY=Math.round(-((totalHeight-$this.height())*(mousePercentY)));
					//console.log(destX);
					$scroller.stop(true,false).animate({left:destX},options.scrollEasingAmount,options.scrollEasing); 
				});
				$scrollerPrevButton.add($scrollerNextButton).hide(); //hide buttons
			}
			//auto scrolling
			if(options.autoScrolling>0 ){
				AutoScrolling();
				
			}
		} else {
			//no scrolling needed
			$scrollerPrevButton.add($scrollerNextButton).hide(); //hide buttonshttp://www.youtube.com/watch?v=As8cmHb-aKU
		}
		//"hoverAccelerate" scrolling fn
		var scrollerPos;
		var scrollerPosY;
		function Scrolling(){
			if((mouseCoords<$this.width()/2) && ($scroller.position().left>=0)){
				$scroller.stop(true,true).css("left",0); 
			}else if((mouseCoords>$this.width()/2) && ($scroller.position().left<=-(totalWidth-$this.width()))){
				$scroller.stop(true,true).css("left",-(totalWidth-$this.width())); 
			}else{
				if((mouseCoords<=($this.width()/2)-options.noScrollCenterSpace) || (mouseCoords>=($this.width()/2)+options.noScrollCenterSpace)){
					scrollerPos=Math.round(Math.cos((mouseCoords/$this.width())*Math.PI)*(interval+options.acceleration));
					$scroller.stop(true,true).animate({left:"+="+scrollerPos},interval,"linear"); 
				}else{
					$scroller.stop(true,true);
				}
			}
			var total = window.mouseXPos-$scroller.offset().left;
			//console.log("scrolling :"+window.mouseXPos+"-"+$scroller.offset().left+":"+total / $scroller.find("li:first").outerWidth());
	var img = Math.ceil(total / $scroller.find("li:first").outerWidth());
	//console.log(img);
	$scroller.find('li').not('li:nth-child('+parseInt(img)+')').children("img").css("opacity", 0.6);
 	$scroller.find('li:nth-child('+parseInt(img)+')').children("img").css("opacity", 1);

			/*
			if((mouseCoordsY<$this.height()/2) && ($scroller.position().top>=0)){
				$scroller.stop(true,true).css("top",0); 
			}else if((mouseCoordsY>$this.height()/2) && ($scroller.position().top<=-(totalHeight-$this.height()))){
				$scroller.stop(true,true).css("top",-(totalHeight-$this.height())); 
			}else{
				if((mouseCoordsY<=($this.height()/2)-options.noScrollCenterSpace) || (mouseCoordsY>=($this.height()/2)+options.noScrollCenterSpace)){
					scrollerPosY=Math.cos((mouseCoordsY/$this.height())*Math.PI)*(interval+options.acceleration);
					$scroller.stop(true,true).animate({top:"+="+scrollerPosY},interval,"linear"); 
				}else{
					$scroller.stop(true,true);
				}
			}*/
		}
		//auto scrolling fn
		var autoScrollingCount=0;
		function AutoScrolling(){
			$scroller.delay(options.autoScrollingDelay).animate({left:-(totalWidth-$this.width()),top:-(totalHeight-$this.height())},options.autoScrollingSpeed,options.autoScrollingEasing,function(){
			
				$scroller.animate({left:0,top:0},options.autoScrollingSpeed,options.autoScrollingEasing,function(){
					autoScrollingCount++;
					if(options.autoScrolling>1 && options.autoScrolling!=autoScrollingCount){
						AutoScrolling();
					}
				});
			});
		}
		//click scrolling fn
		function ClickScrolling(){
			$scrollerPrevButton.hide();
			$scrollerNextButton.show();
			$scrollerNextButton.click(function(e){ //next button
				e.preventDefault();
				var posX=$scroller.position().left;
				var diffX=totalWidth+(posX-$this.width());
				var posY=$scroller.position().top;
				var diffY=totalHeight+(posY-$this.height());
				$scrollerPrevButton.stop().show("fast");
				if(options.scrollerOrientation=="horizontal"){
					if(diffX>=$this.width()){
						$scroller.stop().animate({left:"-="+$this.width()},options.scrollSpeed,options.scrollEasing,function(){
							if(diffX==$this.width()){
								$scrollerNextButton.stop().hide("fast");
							}
						});
					} else {
						$scrollerNextButton.stop().hide("fast");
						$scroller.stop().animate({left:$this.width()-totalWidth},options.scrollSpeed,options.scrollEasing);
					}
				}else{
					if(diffY>=$this.height()){
						$scroller.stop().animate({top:"-="+$this.height()},options.scrollSpeed,options.scrollEasing,function(){
							if(diffY==$this.height()){
								$scrollerNextButton.stop().hide("fast");
							}
						});
					} else {
						$scrollerNextButton.stop().hide("fast");
						$scroller.stop().animate({top:$this.height()-totalHeight},options.scrollSpeed,options.scrollEasing);
					}
				}
			});
			$scrollerPrevButton.click(function(e){ //previous button
				e.preventDefault();
				var posX=$scroller.position().left;
				var diffX=totalWidth+(posX-$this.width());
				var posY=$scroller.position().top;
				var diffY=totalHeight+(posY-$this.height());
				$scrollerNextButton.stop().show("fast");
				if(options.scrollerOrientation=="horizontal"){
					if(posX+$this.width()<=0){
						$scroller.stop().animate({left:"+="+$this.width()},options.scrollSpeed,options.scrollEasing,function(){
							if(posX+$this.width()==0){
								$scrollerPrevButton.stop().hide("fast");
							}
						});
					} else {
						$scrollerPrevButton.stop().hide("fast");
						$scroller.stop().animate({left:0},options.scrollSpeed,options.scrollEasing);
					}
				}else{
					if(posY+$this.height()<=0){
						$scroller.stop().animate({top:"+="+$this.height()},options.scrollSpeed,options.scrollEasing,function(){
							if(posY+$this.height()==0){
								$scrollerPrevButton.stop().hide("fast");
							}
						});
					} else {
						$scrollerPrevButton.stop().hide("fast");
						$scroller.stop().animate({top:0},options.scrollSpeed,options.scrollEasing);
					}
				}
			});
		}
	});  
 };  
})(jQuery); 
//global js functions
//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];
}

