$(document).ready(function(){
	
	if(window.location.hash != "") {
		getProduct(window.location.hash.substr(1));
	}
	
	$('.navi').navi();
	$('.navi ul ul').arrangeNaviElements();
	
	$('area').click(function(){
		$('#historia').html($($(this).attr('href')).html());
	});
	
	$('.slidernavi a').click(function(event){
		event.preventDefault();
		var href = $(this).attr('href');
		getProduct(href);
	});
});

function getProduct(href) {
	$.ajax({
		type: 'GET',
		url: 'ajaxwrapper.php',
		data: 'file=' + href,
		success: function(html) {
			$('.container .content').children('div').first().replaceWith(html);
			window.location.hash = href;
		}
	});
}

$.fn.arrangeNaviElements = function() {
	this.each(function(){
		var elements = $(this).children('li');
		if(elements.length > 10) {
			//$("li", this).remove();
			$(this).addClass('double');
			var middle = Math.ceil(elements.length / 2);
			//alert(elements.slice(0, middle).length);
			elements.slice(0, middle).wrapAll('<li class="group1" />').wrapAll('<ul class="group1" />');
			elements.slice(middle).wrapAll('<li class="group2" />').wrapAll('<ul class="group2" />');
		}
	});
};

$(function(){
	  //Get our elements for faster access and set overlay width
	  var div = $('div.slidernavi'),
	               ul = $('div.slidernavi ul'),
	               // unordered list's left margin
	               ulPadding = 15;

	  //Get menu width
	  var divWidth = div.width();

	  //Remove scrollbars
	  div.css({overflow: 'hidden'});

	  //Find last image container
	  var lastLi = ul.find('li:last-child');

	  //When user move mouse over menu
	  div.mousemove(function(e){

	    //As images are loaded ul width increases,
	    //so we recalculate it each time
	    var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

	    var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
	    div.scrollLeft(left);
	  });
});
