// JavaScript Document

var gcounter = 1; //global counter

$(document).ready(
				  
function(){
	make_gallery(gallerynames);
	loop_top();
	}
);

function loop_top(){
	//reset all boolean 'loading' parameters
	load_all();
	}

function loop_top2(){
	switch_all();
}

function loop_top3(){
	
	$('#powerstrip').animate({opacity: '1'}, timehold, function(){loop_top();});
	
}

function load_all(){
	load_next(0);
}

function load_next(ix){
	//called to load the next slide. 	
	var wih = whoishidden(gallerynames[ix]);
	
	// check which img is ready to be replaced
	if(wih != false){
		
		$(wih).attr('src', next_img(gallerynames[ix]))
				.one("load", function(){ 
					    load_next_inter(ix);
						})
				.each(function(){
                		
						}
					);//end load
	}
	
	else{
 		load_next(ix);
 	}
	
}


function load_next_inter(ix){
	
			
			var next = parseInt(ix) + parseInt(1);

			if(next < gallerynames.length){
				
				load_next(parseInt(next));
			
			}
			else{
				loop_top2();
			}		
	
	
	
}



function switch_all(){
	//increments all galleries in gallerynames
	
	for( var i in gallerynames )
	{
	switchstates(i);
	}
	gcounter++;

}


function whoishidden(galleryname){
	//returns the div id of the image that is no visible... useful for figuring out which one to load an image into.
	if( $('#img2_' + galleryname).css('opacity') == 0 ){
		return ('#img2_' + galleryname);
	}
	else if( $('#img2_' + galleryname).css('opacity') == 1 ){
		return ('#img1_' + galleryname);	
	}
	else{	
		return false;
	}
	
}

function next_img(galleryname){
	//return path of next image to be displayed
	
	var nextimg = galleries[galleryname][(gcounter % galleries[galleryname].length)]
	return(nextimg);
}

function switchstates(index){
	galleryname = gallerynames[index];
	//do the fade. really just one element fades in and out on top of the other one.
	if( $('#img2_' + galleryname).css('opacity') == 0 ){
		$('#img2_' + galleryname).animate({ opacity: '1'}, timefade, function(){ if(index == (gallerynames.length - 1)){ loop_top3(); } });
	}
	else{	
		$('#img2_' + galleryname).animate({ opacity: '0'}, timefade, function(){ if(index == (gallerynames.length - 1)){ loop_top3(); }  });
	}
	
}




function make_gallery(namesarray){
	
	for(i = 0 ; i < namesarray.length; i++){
		
		
		var tempimg1 = $('<img></img>')
						.addClass('gallery_img')
						.attr("id", "img1_" + namesarray[i])
						.attr("src", galleries[namesarray[i]][0]);
						
		var tempimg2 = $('<img></img>')
						.addClass('gallery_img')
						.attr("id", "img2_" + namesarray[i])
						.attr("src", galleries[namesarray[i]][0])
						.css('opacity', '1');
		
		
		var tempdiv = $('<div></div>')
						.addClass('instrip')//div is instrip
						.attr("id", "g_" + namesarray[i])//unique class name
						.append(tempimg1)
						.append(tempimg2);
		
		$('#powerstrip').append(tempdiv);
		
		
		
	}
}


