var itemsState = new Array();
var itemsCount;
var showItemContentSpeed = 400;

$(document).ready(function(){
	
	/* INITIALISATION */
	getItemsCount();
	$("div.item-content").hide();
	$("div.loading").hide();
	randomHeaderImages();
	
	//Adjustments if mobile
	if(mobile){
		$("div#main").css({'background-image' : 'url(images/bg_mobile.png)', 'width' : '700px'});
		$("div#main-bottom").css({'background-image' : 'url(images/bg_bottom_mobile.png)', 'width' : '800px'});
		$("div.site-content").css({'width' : '700px'});
	}
	
	//open item specified in url GET
	if (typeof(item) != "undefined"){
		onItemClick(item);
	}

});

function onItemClick(ID){
	//itemsState = undefined (virgin), = 1 (open), = 2 (closed)
	
	if(!itemsState[ID]){ //if item virgin, load it and open it
		itemsState[ID] = 1;
		$("div#loading-"+ID).show();
		loadItem(ID);
	}else if(itemsState[ID] == 2){ //if item closed, open it
		itemsState[ID] = 1;
		$("div#item-content-"+ID).slideDown(showItemContentSpeed);
	}else if(itemsState[ID] == 1){ //if item opened, close it
		itemsState[ID] = 2;
		$("div#item-content-"+ID).slideUp(showItemContentSpeed);
	}
}

function getItemsCount(){
	var data = "";
	$.ajax({
	  type: 'POST',
	  url: "getItemsCount.php",
	  data: data,
	  success: function(data){
		  	//alert(data);
			itemsCount = data;
		}
	});		
}

function loadItem(ID){
	
	var data = "i="+(ID);
	//alert(data);
	$.ajax({
	  type: 'POST',
	  url: "getItemContent.php",
	  data: data,
	  success: function(data){
			//alert(data);
			document.getElementById("item-content-"+ID).innerHTML = data;
			$("div#loading-"+ID).hide();
			$("div#item-content-"+ID).slideDown(showItemContentSpeed);
			$('a[rel*=lightbox]').lightBox();
		}
	});

}

function randomHeaderImages(){
	var t=setTimeout("getRndItemID()",4000);
}

function getRndItemID(){
	var data = "";
	//alert(data);
	$.ajax({
	  type: 'POST',
	  url: "getRndItemID.php",
	  data: data,
	  success: function(data){
			//alert(data);
			getRndHeaderImage(data);
		}
	});
}

function getRndHeaderImage(ID){
	
	//alert("received ID : " + ID);
	var data = "id="+ID;
	//alert(data);
	$.ajax({
	  type: 'POST',
	  url: "getRndHeaderImage.php",
	  data: data,
	  success: function(data){
			//alert(data);

			$("div#item-headerImage-"+ID).css({"background-image": "url(images/"+data+")"});
			
			randomHeaderImages(); // go back and do it again
		}
	});
}

