(function($) {
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function() {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			
			var s = arguments[i];
			if(s==null) {
				continue;
			}
			
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);
		}
	}
})(jQuery);

function movepop(x,y)
{
	var win_w = $(window).width();
	var win_h = $(window).height();
	var pop_w = $('#popup').width();
	var pop_h = $('#popup').height();
		
	// Small offset for the cursor. 
	// Show the popup on left side if it's going to go too far in the right
	var d_x = (x+pop_w) >= win_w-32 ? (-pop_w-30) : 24;
	var d_y = ((y+pop_h) >= win_h-32) && (y-pop_h > $(window).scrollTop()) ? (-pop_h-30) : 16;
	
	// Readjust coordinates according to the parent image position
	var pop_left = (x+d_x) - $('#page_img').offset().left;
	var pop_top = (y+d_y) - $('#page_img').offset().top;
	
	$('#popup').css({left: pop_left, top: pop_top});
}

function rebuild_page(d)
{
	if(typeof(d.item_list) != 'object') {
		return;
	}
	
	$('.overlay').remove();
	$('.page_price').remove();
	$('#page_items').empty();
	
	for(var i=0;i<d.item_list.length;i++) {
		var item = d.item_list[i];
		
		// Overlay
		var _w = Math.round($('#page_img').width() * item.w);
		var _h = Math.round($('#page_img').height() * item.h);
		var _x = Math.round($('#page_img').width() * item.x) - 11;
		var _y = Math.round($('#page_img').height() * item.y) - 13;
		
 		var a = $('<a></a>')
 			.attr('href', item.url+'&popup=1')
 			.addClass('overlay')
 			.addClass('products_thickbox')
 			.attr('id', 'overlay_'+item.id)
 			.insertAfter($('#page_img'));
				
		$('#overlay_'+item.id)
			.width(_w)
			.height(_h)
			.css('top', _y+'px')
			.css('left', _x+'px');
		
		// Price
		if(item.price_x > 0 && item.price_y > 0) {
			var p_x = Math.round($('#page_img').width() * item.price_x)-11;
			var p_y = Math.round($('#page_img').height() * item.price_y)-13;
			
			//<div class="page_price" id="page_price_'.$it->id.'" style="position:absolute;top:'.$price_y.'px;left:'.$price_x.'px;">'.$price.'</div>
			var p = $('<div></div>')
				.addClass('page_price')
				.attr('id', 'page_price_'+item.id)
				.html(item.price_html_2)
				.insertAfter($('#page_img'));
				
			$('#page_price_'+item.id)
				.css('position', 'absolute')
				.css('top', p_y+'px')
				.css('left', p_x+'px');
		}
		
		var extra_class = i%4==3 ? ' page_items_separator_last': '';
		
		// Description Box
		$('#page_items').append(
			'<div class="page_items_separator'+extra_class+'">'+
			'<div id="page_item_'+item.id+'">'+
				'<a href="'+item.url+'"><img src="'+item.photo_thumb+'" width="225" height="167" alt="" />'+item.promo_icon+'</a>'+
				'<div class="popup_wrapper">'+
					'<h3 class="marque">'+item.brand_name+'</h3>'+
					'<h2 class="sku_name"><a href="'+item.url+'">Item #'+item.sku+'</a></h2>'+
					'<p>'+item.description+'</p>'+
					'<div class="popup_price">'+item.price_html+'</div>'+
				'</div>'+
			'</div>'+
			'</div>'
		);
		
	}
	
	// Previous / Next page link
	$('#page_prev a').attr('href', d.previous_url);
	$('#page_next a').attr('href', d.next_url);
	
	$.preLoadImages(d.previous_img, d.next_img);
	
	// Update page title. TODO: Ajax history 
	document.title = d.page_title;
	
	// Reattach all events so navigation continues working
	attach_overlay_events();
}

function attach_overlay_events() 
{
	$('.overlay').hover(
		function(e)
		{
			var id = $(this)[0].id.split('_')[1];
			$('#popup').html($('#page_item_'+id).html());
			movepop(e.pageX, e.pageY);
			$('#popup').stop().fadeTo(300, 1.0);
		},
		function()
		{
	
			$('#popup').stop().fadeTo(300, 0.0, function() {
				$('#popup').hide();
				//$('#popup').css({left: 5000, top: 5000});
			});
		}
	);
	
	$('.overlay').mousemove(
		function(e) 
		{ 
			movepop(e.pageX, e.pageY);
		}
	);
	
	$('.products_thickbox').colorbox({
		width:"960px", 
		height:"550px", 
		iframe:true
	}, 		
		function () {
		//jScrollPane
		$('#cboxIframe body').jScrollPane();
		}
	
	);
	
	
	
	$('.legend_thickbox').colorbox({
		width:"900px", 
		height:"460px",   
		iframe:true
	}); 
}



// Remet le caroussel au debut
function mycarousel_initCallback(carousel)
{
	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function() {
		carousel.startAuto(0);
	});
	
	carousel.buttonPrev.bind('click', function() {
		carousel.startAuto(0);
	});
	
	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function() {
		carousel.stopAuto();
	}, function() {
		carousel.startAuto();
	});
};

$(document).ready(function(){
	
	// Preload previous + next images
	$.preLoadImages(
		'images/catalog_leftarrow_hover.png', 
		'images/catalog_rightarrow_hover.png'
	);
	
	$('#mycarousel').jcarousel({
		auto: 0,
		scroll: 2,
		wrap: 'last',
		initCallback: mycarousel_initCallback
		
	});
	
	// Tooltip
	$('.tool').tipsy(
		{fade: true}
	);
	
	
	$('ul li.btn').hover(function(){
		$(this).find('span.mask').fadeIn(10);
	}, function(){
		$(this).find('span.mask').fadeOut('fast');
	});
	
	attach_overlay_events();
	
	
	$('#page_list a, #page_prev a, #page_next a, .category_select').click(function()
	{
		var url = this.href;
		$.get(url+'?ajax=1', function(data) {
			var d = eval('('+data+')');
			
				if(d.page.image) {
					var new_img = $('#page_img').clone(true);
					$(new_img)
						.load(function(){
							//alert($('#page_img')[0].src);
							$('.page_price').remove();
							$('#loader').fadeIn(800);
							$('#page_img').fadeOut(500, function() {
								
								$('#loader').hide()
								
								this.src = d.page.image;
								rebuild_page(d);
								
								$('#page_img').fadeIn(500, function() { 
									$('#loader').hide(); 
								});
							});
						})
						.attr('src', d.page.image);

				}
				// Track ajax call with google analytics
				if(typeof(pageTracker) == 'object') {
					try {
						if(root_url) {
							// Convert absolute to relative url
							var rel = url.split(root_url);
							if(rel.length == 2) {
								url = rel[1];
							}
						}
						pageTracker._trackPageview(url);
					}
					catch(e) {}
				}
		});
		return false;
	});
	
});
