var gal;
var ind = int1 = 0;

$(document).ready(function(){
	$("#previous").mouseover(function(){
		$(this).addClass("on");
	});
	$("#previous").mouseout(function(){
		$(this).removeClass("on");
	});
	$("#next").mouseover(function(){
		$(this).addClass("on");
	});	
	$("#next").mouseout(function(){
		$(this).removeClass("on");
	});
	
	if(document.getElementById("gContainer"))
	{
		gal = $("#gContainer .gItem").get();
		try{
			$(gal[ind]).show();
			$("#next").click(function(){
				var old = ind;
				if(ind == gal.length-1){
					ind = 0;
				}else{
					ind += 1;
				}
				$(gal[old]).fadeOut(300, showNext);
			});
			$("#previous").click(function(){
				var old = ind;
				if(ind == 0){
					ind = gal.length-1;
				}else{
					ind -= 1;
				}
				$(gal[old]).fadeOut(300, showNext);
			});
		} catch(e){}
	}
	else
	{
		try{
			gal = fisherYates($("#gContainerHome .gItem").get());
			$(gal[ind]).show();
			// start the slideshow
			slideshow();
		} catch(e){}
	}
	
});

function showNext(){
	$(gal[ind]).fadeIn(300);
}

// http://sedition.com/perl/javascript-fy.html
function fisherYates ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
   return myArray;
}

function slideshow()
{
	clearInterval(int1);
	int1 = setInterval(swapItems,3500);
}

function swapItems()
{
	var old = ind;
	if(ind == gal.length-1){
		ind = 0;
	}else{
		ind += 1;
	}
	$(gal[old]).fadeOut(300, showNext);	
}