//
var products;
var lastProdindex = 0;
var aktProduct;

$(function()
{
      
	var lang = $.getCookie('language');
	
	var firstProdId = $('.productHeaderLink').attr('id').replace(/product_header_/,''); 
		  
   $.getJSON('pages/products/product-json.php?lang='+lang,function(res)
	{		
		products = res;
		$.each(products,function(i)
		 {
			 if(products[i].bild.length > 0)
			 {
				var img = new Image();
				img.src = 'images/products/'+products[i].bild;
			 }
		 });
		lastProdindex = getProdIndex(firstProdId);
		loadNextProduct();
	});
   
});

function getProdIndex(id)
{
	for(i in products)
	{
		if(products[i].id == id)
			return i;
	}
	return 0;
}

function loadNextProduct()
{
	var rand = 0;
	do
	{
		rand = Math.random();
	
		rand *= products.length;
		rand = Math.round(rand);
	}while(rand == lastProdindex);
	lastProdindex = rand;
	
		
	rand = (rand > products.length -1) ? products.length -1 : rand;
		
	aktProduct = products[rand];
	window.setTimeout('fadeToNextProduct();',3500);	

}

function fadeToNextProduct()
{	
	var prod = aktProduct;
	var html = '<div class="productHeader">';
	html += '<a href="index.php?path=products|productdetail&amp;id='+prod.id+'&amp;lang='+prod.language+'" class="productHeaderLink">';	
	html += prod.name+'</a></div>';
	html += '<div class="productContent">';
	if(prod.bild.length > 0)
	{
		html += '<a href="images/products/lrg/'+prod.bild+'" target="_blank" id="imgRandomProduct">';
		html += '<img src="images/products/'+prod.bild+'" alt="Bild zu: '+prod.name+'" class="productImage" border="0" />';
		html += '</a>';;
	}
	
	html += prod.kurzbeschreibung+'</div>';
	
	$('.startMiddleContent').fadeOut(500,function()
	{
		$('.startMiddleContent').html(html);
		$('.startMiddleContent').fadeIn(500);
	});	
	
	$('a#imgRandomProduct').fancybox();
	
	loadNextProduct();
}
