/**
 * Background animation
 *
 * @author Viktor Boyko
 * @copyright BRTechnoligies
 *
 **/

jQuery.extend({
	    
    backgrounds: [1, 2, 3, 4, 5],
    update_time: 12,
    time: 1.5,
    
    loaded: 0,
    active: null,
    bg: null,
    
    bginit: function() {
	    $('#background').after($('<div />').attr('id', 'background2').addClass('dd').css({'display': 'none'}));
	    this.bg1 = $('#background');
	    this.bg2 = $('#background2');
	    this.active = 0;
	    this.bg = 0;
    },
    
    bgloader: function() {
	for(var j=0; j<=$.backgrounds.length-1; j++) {
	    this.preload($.backgrounds[j]);
	}
    },
    
    preload: function(bg) {
	$('<img />')
	    .attr({
		src: 'images/bg/'+bg+'.jpg'
	    })
	    .load(function(){
		    $.bgstart();
	    });
    },
    
    bgstart: function() {
	jQuery.loaded++;
	if(jQuery.loaded==$.backgrounds.length) {
	    setInterval("$.randomizer();", $.update_time*1000);
	}
    },
    
    randomizer: function() {
	    if(jQuery.active>0) {
			var show = $.bg1;
			var hide = $.bg2;
			jQuery.active = 0;
	    } else {
			var show= $.bg2;
			var hide = $.bg1;
			jQuery.active = 1;
	    }
	    show
			.css('backgroundImage', 'url(images/bg/'+$.getRan()+'.jpg)')
			.fadeIn($.time*1000);
	    hide.fadeOut($.time*1000);
    },
    
    getRan: function() {
	    var i = $.backgrounds[Math.floor(Math.random()*$.backgrounds.length)];
	    if(i!=$.bg) { this.bg = i; return i; } else return $.getRan();
    }
    
});


$(document).ready(function(){
    jQuery.bginit();
    jQuery.bgloader();
})

