var images = new Array({src: "1.jpg"},{src: "2.jpg"},{src:'3.jpg'}, {src: '4.jpg'});
var count = 0;
var imgDir = "/assets/templates/img/top_slide/";

$(function(){
	
	initGallery();
	
	$.each(images,function(i) {
		$('body').append('<div style="display: none;"><img id="loader_'+i+'" src="'+imgDir+this.src+'" /></div>'); 
		this.image = document.getElementById("loader_"+i);
		/*$('#loading_'+i).data('image', this).load(function () {
			$(this).data('image').loaded = true; 
		});*/
		
	}); 
	
	var checkLoadFinTimer = setInterval(function(){ checkLoadFin(checkLoadFinTimer);}, 200);
	
});

function checkLoadFin(checkLoadFinTimer) {
	var num = 0;
	
	
	$.each(images,function(i) {

		if(this.image != undefined && this.image.complete == true) { num++ };
		
	});
			
	if(num == images.length){
		clearInterval(checkLoadFinTimer);
		setInterval('startGallery()', 4000);
		return;
	}

}

function initGallery() {

	var frontPhoto = $('#front_photo');
	var _width = 520;
	var _height = 378;
	frontPhoto.css({'position': 'absolute', top: 0, left: 0, width: _width, height: _height}).attr('alt', '').parent().css({'position':'relative'}).append('<img id="back_photo" alt="photo" />');
	$('#back_photo').css({width: _width, height: _height}).attr("src", imgDir+images[0].src);
	
}

function startGallery() {
		
	var _front = $('#front_photo');
	var _back = $('#back_photo');
	
	var _frontImg = images[count].src ;
	var _backImg = (count == images.length - 1)? images[0].src : images[count+1].src ;
		
	
	if(_front.css('opacity') < .5 ) {
		_front.attr("src", imgDir+_frontImg).animate({opacity: 0}, 100,function(){_back.attr("src", imgDir+_backImg); _front.css({opacity: 1}).animate({opacity: 0},2000);});
		
	} else {
		_front.attr("src", imgDir+_frontImg).animate({opacity: 0},2000);
		_back.attr("src", imgDir+_backImg);
	}
	
	
	count = (count == images.length -1)? 0 : count + 1;
		
}
