var showingDetail = false;
var isVerticalImage;
var isGalleryVisible = false;
var totalImageNum = 0;

function stretchImage() {
	var bg = $('.greatImg');
	var marginTop = 106;
	var winWidth = $(window).width() - 305;
	var winHeight = $(window).height() - marginTop;
	var winRatio = winHeight / winWidth;
	var bgRatio = bg.height() / bg.width();
	var viewingArea = winWidth - 220;
	
	if (bg.height() < bg.width()) {
		// orizzontale
		isVerticalImage = false;
		bg.css('margin-top', marginTop + 'px');
		bg.width(winWidth);
		var bgHeight = winWidth * bgRatio;
		if (bgHeight > winHeight) {
			bg.height(winHeight);
			bg.width(winHeight / bgRatio);
		} else {
			bg.height(bgHeight);
		}
		$('#big-img').css('left', 'auto');
		$('#big-img').css('right', '40px');
	} else {
		// verticale
		isVerticalImage = true;
		bg.height(winHeight + marginTop);
		bg.width((winHeight + marginTop) / bgRatio);
		bg.css('margin-top', '0px');
		$('#big-img').css('right', 'auto');
		$('#big-img').css('left', (viewingArea/2 - (bg.width() + 70)/2));
	}
	$('#big-img').width(bg.width());
	$('#big-img').fadeIn('fast');
}

function showScroll() {
	$('#slideshow-activator').css('z-index', '10');
	$('#selected-thumb .button-caption').hide();
	$('#slideshow-countdown').show();
	$('#gallery-grayer').show();
	$('#caption').hide();
	$('#credits').hide();
	$('#captioncommon').hide();
	isGalleryVisible = true;
}

function hideScroll() {
	$('#slideshow-activator').css('z-index', '3');
	$('#selected-thumb .button-caption').show();
	$('#slideshow-countdown').hide();
	$('#gallery-grayer').hide();
	if ($('#caption').html() != '') {
		$('#caption').show();
	}
	if ($('#credits').html() != '') {
		$('#credits').show();
	}
	if ($('#captioncommon').html() != '') {
		$('#captioncommon').show();
	}
	isGalleryVisible = false;
}

function scrollToThumb (thumbId, callback) {
	var thumb = $('#' + thumbId);
	var newOffset = $('#slideshow-countdown').offset().top -
					thumb.offset().top - thumb.height() - 1;

	$('#slideshow-countdown').animate(
	    {top: newOffset},
	    1000,
	    'swing',
	    callback
	);
}

function showThrobber() {
	var greatImg = $('.greatImg');
	var throbber = $('#throbber');
	var position = greatImg.offset(); 
	var width = greatImg.width(); 
	var height = greatImg.height();
	throbber.css({
		'top': position.top + 'px',
		'left': position.left + 'px',
		'width': width + 'px',
		'height': height + 'px'
	});
	throbber.fadeIn('fast');
}

function hideThrobber() {
	$('#throbber').fadeOut('fast');
}

function selectImage (thumbId) {
	$('#big-img').fadeOut('fast', function() {
		$('.greatImg').remove();
		$('#caption').hide();
    	$('#credits').hide();
    	$('#captioncommon').hide();
		var newBigImg = loadImage(
	        gallery[thumbId].big,
	        {},
	        function () {
    	        $(newBigImg).attr('class', 'greatImg');
    	        $('#big-img').appendChild(newBigImg);
    	        stretchImage();
    	    	$('#selthumb-img img').attr('src', gallery[thumbId].thumb);
    	    	updateCaption(thumbId);
    	    	if ($('#caption').html() != '') {
    	    		if (!isGalleryVisible) {
    	    			$('#caption').show();
    	    		}
    	    	}
    	    	if ($('#credits').html() != '') {
    	    		if (!isGalleryVisible) {
    	    			$('#credits').show();
    	    		}
    	    	}
    	    	if (alwaysShowCaptionCommon == 'true' && captioncommon != '' ) {
    	    		if (!isGalleryVisible) {
    	    			$('#captioncommon').show();
    	    		}
    	    	}
    	    	udpateDetail(thumbId);
    	    	hideThrobber();
	        }
	    );
	}).fadeIn('fast').css("visibility","visible");
}

function updateNavigationLinks (id) {
	var path = sprintf('/%s/%s/%s/%s/', brand, season, gender, page);
	if (id > 0) {
		$('#previous-link').parent().attr('href', path + id);
	} else {
		$('#previous-link').parent().attr('href', '#');
	}
	$('#next-link').parent().attr('href', path + (id+2));
}

function updateImageNumber(number) {
	$('#gallery-actual-index').html(number);
}

function positionateCaption() {
	var position = $(window).width() - 285 - $('.greatImg').width() - $('#big-img').position().left;
	if (position < 0) {
		position = 0;
	}
	
	var posY = $(window).height()/100*7;
	$('#credits').css({'right': position,'bottom': posY});
	if ($('#credits').html()!='') {
		posY+=21;
	};
	$('#captioncommon').css({'right': position,'bottom': posY});
	if ($('#captioncommon').html()!='') {
		posY+=21;
	};
	$('#caption').css({'right': position,'bottom': posY});
}

function updateCaption(id) {
	var captionDiv = $('#caption');
	var creditsDiv = $('#credits');
	var captionCommonDiv = $('#captioncommon');
	if (alwaysShowCaptionCommon == 'true') {
		$('#captioncommon').html(captioncommon);
	}
	if (id != null) {
		if (gallery[id].caption != '') {
			captionDiv.html(gallery[id].caption);
		} else {
			if (captioncommon != '' && alwaysShowCaptionCommon == 'false') {
				captionDiv.html(captioncommon);
			} else {
				captionDiv.hide();
				captionDiv.html('');
			}
		}
		creditsDiv.html(gallery[id].credits);
	}
	positionateCaption();
}

function positionateDetail() {
	var position;
	if (isVerticalImage) {
		position = $('#big-img').position().left + $('.greatImg').width() + 287;
	} else {
		position = $("#gallery-navigation").position().left - 100;
	}
	$('#detail-button').css('left', position + 'px');
}

function udpateDetail(id) {
	if (gallery[id].detail_visible=="True") {
		var img = $('#detail-button img');
		$('#detail-button').attr('class', 'detail-' + id);
		img.attr('src', gallery[id].detail_thumb);
		positionateDetail();
		$('#detail-button').show();
	} else {
		$('#detail-button').hide();
	}
}

function showDetail(id, skipSelectImage) {
	var greatImg = $('.greatImg');
	if (showingDetail) {
		if (!skipSelectImage) {
			showThrobber();
			selectImage(id);
		}
		$('#detail-button-caption').html('Detail');
		$('#bigx').hide();
		showingDetail = false;
	} else {
		/*$('#caption').hide();
		$('#credits').hide();
		$('#captioncommon').hide();*/
		$('#big-img').fadeOut('fast', function() {
			$('.greatImg').remove();
			var newBigImg = loadImage(
		        gallery[id].detail_big,
		        {},
		        function () {
	    	        $(newBigImg).attr('class', 'greatImg');
	    	        $('#big-img').appendChild(newBigImg);
	    	        stretchImage();
	    	        hideThrobber()
	        	});
		}).fadeIn('fast');
		$('#detail-button-caption').html('Close');
		$('#bigx').show();
		showingDetail = true;
	}
}

function selectGalleryThumb(id) {
	var thumb = $("#slideshow-countdown img[id="+id+"]");
	if (showingDetail) {
    	showDetail(id, true);
    }
    $('#slideshow-countdown .selected').fadeTo('fast', 1);
    $('#slideshow-countdown .selected').removeClass('selected');
    thumb.addClass('selected');
    thumb.fadeTo('fast', 0.5);
    updateNavigationLinks(id-1);
    updateImageNumber(id);
}

var arrowover = function(){
	$(this).css("opacity","0.8");
}
var arrowout = function(){
	$(this).css("opacity","1");
}

$(document).ready(function() {
	var thumbHeight = 105 + 2; // 2 = bordo sopra e sotto
	// div with hidden overflow
	var scrollWindow = $('#slideshow-box');
	var marginTop = scrollWindow.position().top;
	var marginBottom = $("#footer").height();
	// scrolling div
	var scrollDiv = $('#slideshow-countdown');
	totalImageNum = $('#slideshow-countdown img').length;
	var divHeight = thumbHeight * totalImageNum;
	var scrollWindowHeight = $(window).height() - marginTop - marginBottom;
	var scrollWindowCenter = scrollWindow.position().top + (scrollWindowHeight / 2);
	var windowPos = scrollWindow.css('top').split('px')[0];
	var mouseY = null;
	
	$('#big-img').css("visibility","hidden");
	
	if (totalImageNum>1) {
		// setting definitive heights
		scrollDiv.css('height', divHeight);
		if (navigator.appName != 'Microsoft Internet Explorer') {
			scrollWindow.css('height', scrollWindowHeight);
		}
		
		hideScroll();
	
		/*
		 * delta calculation based on distance from scrollWindow center
		 */
		beginScrollThumbs = function() {
			var delta = 0;
			if (mouseY) {
				delta = (mouseY / scrollWindowHeight);
				// incrementing scrolling speed
				delta *= -8;
				delta *= delta *= delta;
			}
			// creating non scrolling area
			if (delta > 60) {
				delta -= 60;
			} else if (delta < -60) {
				delta += 60;
			}
			// scrolling
			if (delta != 0) {
				scrollThumbsWithDelta(delta);
			}
			scrollThread = setTimeout("beginScrollThumbs()", 100);
		}
		
		
		/*
		 * move the scrolling div inside boundaries
		 */
		scrollThumbsWithDelta = function(delta) {
			var offset = scrollDiv.position().top;
			if (offset+delta >= 0) {
				delta = 0;
				offset = 0;
			} else if (offset+delta < -(divHeight - $(window).height() + marginTop + marginBottom)) {
				delta = 0;
				offset = -(divHeight-$(window).height() + marginTop + marginBottom+1);
			}
			var value = Math.ceil(offset + delta);
			scrollDiv.css({'top': value + 'px'});
		}
		
		// listeners
		
		$('#slideshow-activator').bind('mouseleave', function(){
			hideScroll();
	        clearTimeout( scrollThread );
	    });
		
		$('#selthumb-img').bind('mouseleave', function(){
			hideScroll();
			//clearTimeout( scrollThread );
		});
	    
		$('#slideshow-activator').bind('mouseenter', function(){
			showScroll();
			/*if (divHeight > ($(window).height() - windowPos - marginTop - marginBottom)) {
				beginScrollThumbs();
			}*/
	    });
		
		$('#selthumb-img').bind('mouseenter', function(){
			showScroll();
			/*if (divHeight > ($(window).height() - windowPos - marginBottom)) {
				beginScrollThumbs();
			}*/
		});
		
		scrollWindow.bind('mouseenter', function(){
			showScroll();
			//alert (divHeight+" > ("+$(window).height()+" - "+windowPos+" - "+marginTop+" - "+marginBottom+")");
			if (divHeight > ($(window).height() - windowPos - marginTop - marginBottom)) {
				beginScrollThumbs();
			}
		});
		scrollWindow.bind('mouseleave', function(){
			clearTimeout( scrollThread );
		});
	
	    $().mousemove(function(e){
	        mouseY = e.pageY - scrollWindowCenter;
	    });
	    
	    $('#slideshow-countdown img').click(function(e){
	        var thumbId = $(this).attr('id');
	        showThrobber();
	        selectImage(thumbId-1);
	        selectGalleryThumb(thumbId);
	    });
	    
	    $('#previous-link').bind('mouseleave', arrowout);
		$('#previous-link').bind('mouseenter', arrowover);
		$('#next-link').bind('mouseleave', arrowout);
		$('#next-link').bind('mouseenter', arrowover);
		
		$(window).keydown(function(event) {
	    	if (event.keyCode == 37) {
	    		// left
	    		var thumbId = parseInt($('#gallery-actual-index').html());
	    		if (thumbId-1 < 1) {
		    		thumbId = totalImageNum+1;
		    	}
	    		showThrobber();
	    		selectImage(thumbId-2);
	            selectGalleryThumb(thumbId-1);
	    	} else if (event.keyCode == 39) {
	    		// right
	    		var thumbId = parseInt($('#gallery-actual-index').html());
	    		if (thumbId >= totalImageNum) {
		    		thumbId = 0;
		    	}
	    		showThrobber();
	    		selectImage(thumbId);
	            selectGalleryThumb(thumbId+1);
	    	}
	    });
	    
	    $('#previous-link').click(function(e) {
	    	e.preventDefault();
	    	var thumbId = parseInt($('#gallery-actual-index').html());
	    	if (thumbId-1 < 1) {
	    		thumbId = totalImageNum+1;
	    	}
	    	showThrobber();
			selectImage(thumbId-2);
	        selectGalleryThumb(thumbId-1);
	    });
	    
	    $('#next-link').click(function(e) {
	    	e.preventDefault();
	    	var thumbId = parseInt($('#gallery-actual-index').html());
	    	if (thumbId >= totalImageNum) {
	    		thumbId = 0;
	    	}
	    	showThrobber();
			selectImage(thumbId);
	        selectGalleryThumb(thumbId+1);
	    });
	} else {
		$('#gallery-navigation').css("visibility","hidden");
		$('#selected-thumb').css("visibility","hidden");
		$('#slideshow-activator').css("visibility","hidden");
	}
	
    $('#detail-button').click(function(e) {
    	var imgId = $(this).attr('class').split('-')[1];
    	showThrobber();
    	showDetail(imgId, false);
    });
    
    $('#detail-button').bind('mouseleave', arrowout);
	$('#detail-button').bind('mouseenter', arrowover);
    
    $(window).resize(function() {
    	stretchImage();
    	positionateCaption();
    	positionateDetail();
    	scrollWindowHeight = $(window).height() - marginTop - marginBottom;
    	scrollWindowCenter = scrollWindow.position().top + (scrollWindowHeight / 2);
    	scrollWindow.css('height', scrollWindowHeight);
    });
    
    selectGalleryThumb(detail);
    
    // accedo con un url diretto ad una immagine
   	selectImage(directImageId);
});

$(window).load(function() {
	stretchImage();
	positionateCaption();
	positionateDetail();
});

init = function () {}
