$(document).ready(function(){
	var moveActive = 0;
	var initX = 0;
	var initY = 0;
	
	var initMarginLeft = 0;
	var initMarginTop = 0;
	
	// Init product overlay
	$("div#product-overlay").overlay({
		api: true,
		top: '2%',
		expose: { 
        	color: '#333', 
        	loadSpeed: 200, 
	        opacity: 0.9
    	},
		closeOnClick: false
	});
	
	// Disable arrows on <= 7 items
	if($('.product-overlay-thumbnails div.items a').length<=7) {
		$('a.browse').addClass('disabled');
	}
	
	// Center the first image
	centerCurrentImage($('#im1-medium img').width());

	// Make first thumb active
	$('.product-overlay-thumbnails .items a:first').addClass('active');
	

	/**
	* PRODUCT THUMB CLICKED
	**/
	$('.productthumb a').click(function(){
	
		$("div#product-overlay").overlay().load();
		$(this).blur();
		return false;
	});
	
	/**
	* PRODUCT MORE IMAGES CLICKED
	**/
	$('.moreimages a').click(function(){
		$("div#product-overlay").overlay().load();
		return false;
	});
	
	/** TEASER CLICKED */
	$('#teaser img').click(function(){
		$("div#product-overlay").overlay().load();
		return false;
	});
	
	



	/**
	* PRODUCT VIEWER JS
	**/
	
	// Make thumbs scrollabe
	$('.product-overlay-thumbnails').scrollable({
		size: 7
	});
	
	// Thumb cliked - show medium
	$('.product-overlay-thumbnails div.items a').click(function(){
	
			$(this).blur();

			// Img
			var img = $($(this).attr('rel')+'-medium');
	
	
			$('.product-overlay-window').fadeOut(200,function(){
		
				$('.product-overlay-window').html(
					$($(img).children('img').attr('rel')+'-medium').html()
				).children('img').css({
					marginLeft: parseInt(Math.round((878 - $(img).children('img').attr('width'))/2))+'px',
					marginTop: '10px'
				});
				
				$(this).fadeIn(200);
		});
	
		return false;			
	});
	
	// Medium clicked - show big
	$('.product-overlay-window img.medium').live('click',function(e){
	
	
		// Get clicked coordinates from IMG
		var imgX = parseInt(e.pageX - Math.round($(this).offset().left));
		var imgY = parseInt(e.pageY - Math.round($(this).offset().top));

		// Convert to percent
		var percentX = parseInt(Math.round(100*imgX/$(this).attr('width')));
		var percentY = parseInt(Math.round(100*imgY/$(this).attr('height')));
		
		// Decode entities and get big
		var bigImgHtml = $('#fordecode').html($($(this).attr('rel')+'-big').html()).val();
		
		// Start preloading
//		console.log('Preloading '+$(bigImgHtml).attr('src'));
		jQuery.preLoadImages($(bigImgHtml).attr('src'));
		
		
		// Find width and height on med img
		var medWidth = parseInt($(this).attr('width'));
		var medHeight = parseInt($(this).attr('height'));
		
		// Find width and height on big img
//		var bigWidth = parseInt($(bigImgHtml).attr('width'));
//		var bigHeight = parseInt($(bigImgHtml).attr('height'));
		var bigWidth = parseInt($($(this).attr('rel')+'-bigWidth').html());
		var bigHeight = parseInt($($(this).attr('rel')+'-bigHeight').html());		
		
		// Find window size
		var windowWidth = 878;
		var windowHeight = 398;

		// Convert percent to pixels (value for margin)
		var marginLeft = parseInt(-1*Math.round(bigWidth*(percentX/100)));
		var marginTop = parseInt(-1*Math.round(bigHeight*(percentY/100)));		
		
		// Correct margin to center clicked pos
		marginLeft += parseInt(Math.round(windowWidth/2));
		marginTop += parseInt(Math.round(windowHeight/2));

		
		// Correct margins, so they are valid
		var correctedMargins = correctMargins(marginLeft,marginTop,bigWidth,bigHeight,windowWidth,windowHeight);
		marginLeft = correctedMargins[0];
		marginTop = correctedMargins[1];
		
		// Set the margin if image is greater than window
		if(bigWidth>windowWidth) {
			// Do nothing
		} else {
			// Center the image
			marginLeft = parseInt(Math.round((windowWidth - bigWidth)/2));
		}
		
		if(bigHeight>windowHeight) {
			// Do nothing
		} else {
			marginTop = 10;
		}
		
		//console.log('Width: '+bigWidth);
		//console.log('Height: '+bigHeight);		

		//console.log('Animating');

		// Change to text-align left and create zoom effect
		$(this).animate({
			width: bigWidth+'px',
			height: bigHeight+'px',
			marginLeft: marginLeft+'px',
			marginTop: marginTop+'px'
		},500,'linear', function(){
			// Animation to big complete - replace DOM with the big element
			$('.product-overlay-window').html(bigImgHtml).children('img').css({
				marginLeft: marginLeft+'px',
				marginTop: marginTop+'px'
			});
			
		});

		return false;
	});
	
	
	// Prevent firefox dragging on medium
	$('.product-overlay-window img.medium').live('mousedown',function(e){
		e.preventDefault();
	});

	
	// Mousedown on big image
	$('.product-overlay-window img.big').live('mousedown',function(e){
		if(e.preventDefault) {
			e.preventDefault(); // disable firefox drag
		}
		
		
		
		moveActive = 1; // activate move
		
		// Save mouse click position
		initX = e.pageX;
		initY = e.pageY;
		
		// Save initial margin left and top
		initMarginLeft = parseInt($('.product-overlay-window img.big').css('margin-left'));
		initMarginTop = parseInt($('.product-overlay-window img.big').css('margin-top'));
	});
	
	
	// Mouse up on big image
	$('.product-overlay-window img.big').live('mouseup',function(e){
		moveActive = 0;
		
		// No move, zoom out
		if(initX==e.pageX && initY==e.pageY) {
			
		
			// Zoom out - set img back to medium
			var img = $($(this).attr('rel')+'-medium img');
			
			// Create zoom effect
			$(this).animate({
				width: $(img).attr('width')+'px',
				height:  $(img).attr('height')+'px',
				marginLeft: parseInt(Math.round((878 - $(img).attr('width'))/2))+'px',
				marginTop: '10px'
			}, function(){
				
				// Animation to small complete - now replace the DOM element with the medium again
				$('.product-overlay-window').html($($(this).attr('rel')+'-medium').html()).children('img').css({
					marginLeft: parseInt(Math.round((878 - $(img).attr('width'))/2))+'px',
					marginTop: '10px'
				});
				
				
			});
		}

		return false;
	});

	// Mouse out on big image
	$('.product-overlay-window img.big').live('mouseout',function(e){
		moveActive = 0;	
		$(this).parent().blur();
		return false;
	});
	
	// Mouse move on big image
	$('.product-overlay-window img.big').live('mousemove',function(e){
		if(moveActive==1) {
/*			console.log(initMarginTop);
			console.log(e.pageY);
			console.log(initY);
			console.log('-----');*/
			updateMarginOnBigImage(initMarginLeft + e.pageX - initX, initMarginTop + e.pageY - initY);
		}
	});
});

function updateMarginOnBigImage(marginLeft,marginTop) {
	var bigWidth = parseInt($('.product-overlay-window img.big').attr('width'));
	var bigHeight = parseInt($('.product-overlay-window img.big').attr('height'))
	
	// Find window size
	var windowWidth = 878;
	var windowHeight = 398;
	
	var margins = correctMargins(marginLeft,marginTop,bigWidth,bigHeight,windowWidth,windowHeight);
		
	// Set the margin if image is greater than window
	if(bigWidth>windowWidth) {
		$('.product-overlay-window img.big').css('margin-left',margins[0]+'px');
	} else {
		// Center the current
		centerCurrentImage();
	}
	
	if(bigHeight>windowHeight) {
		$('.product-overlay-window img.big').css('margin-top',margins[1]+'px');		
	} else {
		$('.product-overlay-window img.big').css('margin-top','10px');
	}
}

function correctMargins(marginLeft,marginTop,bigWidth,bigHeight,windowWidth,windowHeight) {	
	/**
	* Ensure margin is legal values
	* :: width must be between -(bigImageWidth-windowWidth) and 0
	* :: height must be between -(bigImageHeight-windowHeight) and 0
	**/
	
	// Min margin
	var minMarginLeft = parseInt(-1*(bigWidth-windowWidth));
	var minMarginTop = parseInt(-1*(bigHeight-windowHeight));
	
	// Ensure
	if(marginLeft < minMarginLeft) { marginLeft = minMarginLeft; }
	if(marginLeft > 0) { marginLeft = 0; }
	if(marginTop < minMarginTop) { marginTop = minMarginTop; }
	if(marginTop>0) { marginTop = 0; }
	
	return new Array(marginLeft,marginTop);
}

function centerCurrentImage(width){
	
	if(width>0) {
		var marginLeft = parseInt(
			Math.round(
				(878 - width)/2
			)
		);
	} else {
		var marginLeft = parseInt(
			Math.round(
				(878 - $('.product-overlay-window img').attr('width'))/2
			)
		);

	}

	
	
	$('.product-overlay-window img').css('margin-left',marginLeft+'px');
}

		
