
var Backgrounds = {
    images: [],
    windowinfo: null,
    currentImage : '',
    currentIndex: 0, /* Object index in images array */
    timeToNextTransition : 8000,
    transitionTime : 2500,
    animating: false,
    timeoutHandler : null,
	$currentBGContainer : null,
	$clonedBGContainer : null,
    
    initialize: function(arrImages) {

        $(window).resize(function() {
	
			// this function call will be deprecated 
        	Backgrounds.onResizeWindowPlaceContent();
			
            var src = Backgrounds.pickRightImage();
            Backgrounds.animateFadeToNewImage(src);
        });
        
        $(window).scroll(function () {
        	Backgrounds.onResizeWindowPlaceContent();
        });

        Backgrounds.images = arrImages;

		Backgrounds.$currentBGContainer = $('#page_bg');
		Backgrounds.$clonedBGContainer = $('#page_bg_clone');
		
		Backgrounds.preloadFirst();
        //Backgrounds.preloadAll();

		//if(Backgrounds.images.length > 1){
		Backgrounds.setNextBGTimeout();
		//}
    },
    
    setNextBGTimeout : function(){
    	Backgrounds.timeoutHandler = setTimeout(function(){Backgrounds.next();}, Backgrounds.timeToNextTransition + Backgrounds.transitionTime);
    },
    
    preloadAll: function() {
        max = Backgrounds.images.length;
        for (j = 0; j < max; j++) {

            var collection = Backgrounds.images[j];

            for (i = 0; i < collection.size(); i++) {
                var image = collection[i];
                var objImage = new Image();
                objImage.src = image.src;
            }
        }
    },
    next: function() {
    	
    	Backgrounds.setNextBGTimeout();
    	
    	/*
    	if(Backgrounds.images.length < 2){
    		PPGContext.debug("next() cancelled");
    		return;
    	}
    	*/
    	
        Backgrounds.currentIndex ++;
        Backgrounds.currentIndex %= Backgrounds.images.length;

        var src = Backgrounds.pickRightImage();
		Backgrounds.animateFadeToNewImage(src);
    },
    
    cancelTimeoutAndNext : function(){
    	clearTimeout(Backgrounds.timeoutHandler);

    	Backgrounds.next();
    },
	
    preloadFirst: function () {
        var src = Backgrounds.pickRightImage();
        Backgrounds.currentImage = src;
		Backgrounds.setBackground(src);
    },

	setBackground : function(src){
		Backgrounds.$currentBGContainer.css('opacity', 0);
		Backgrounds.$clonedBGContainer.css('opacity', 1);
		Backgrounds.$clonedBGContainer.css('background-image', "url('" + src + "')");		
	},

    placeObject: function(src) {
		Backgrounds.$currentBGContainer.css('background-image',"url('" + src + "')");
		Backgrounds.currentImage = src;
        //document.getElementById('page_bg').style.background =  'url('+src+') no-repeat center';
    },
	swapBGContainers : function(){
		var tmp = Backgrounds.$currentBGContainer;
		Backgrounds.$currentBGContainer = Backgrounds.$clonedBGContainer;
		Backgrounds.$clonedBGContainer = tmp;
		/*Backgrounds.$currentBGContainer.setStyle({zIndex: 2});
		Backgrounds.$clonedBGContainer.setStyle({zIndex: 3});*/
	},
    updateWindowInfo: function() {
        Backgrounds.windowinfo =  {
            height: $(window).height(),
            width:  $(window).width()
        }
    },

	animateFadeToNewImage : function(newSrc){
		//PPGContext.debug(newSrc + '==' + Backgrounds.currentImage);
		if(newSrc == Backgrounds.currentImage){
			return;
		}
		
		if (Backgrounds.animating == true) {
            return; 
        }
		
        Backgrounds.placeObject(newSrc);

        Backgrounds.animating = true;
        
        Backgrounds.$currentBGContainer.animate({opacity: 1.0}, Backgrounds.transitionTime, function(){Backgrounds.$currentBGContainer.css('opacity', 1.0);});
        Backgrounds.$clonedBGContainer.animate({opacity: 0.0}, Backgrounds.transitionTime + 100, function(){
        	Backgrounds.$clonedBGContainer.css('opacity', 0);
        	Backgrounds.animating = false;
        	Backgrounds.swapBGContainers();
        });
        
	},
	
	

	// return image src from collection that best fits the current viewport size
	// for the current index of the collection
	// #############################################################################
	// #### this function assumes array of images at current index to be at least of size 1
    pickRightImage: function() {

        Backgrounds.updateWindowInfo();
        var resolutions = Backgrounds.images[Backgrounds.currentIndex];
        var image;
        for(i = 0; i < resolutions.length; i++) {

            image = resolutions[i];

            if (Backgrounds.windowinfo.width < image.w  && Backgrounds.windowinfo.height < image.h) {
				//console.log('pick ' + image.src);
                return image.src;
            }
        }
		//console.log('pick last ' + image.src +  ' - ' + resolutions.length);
		return image.src;
    },

	// this function should be merged to common script for all pages
	onResizeWindowPlaceContent : function(){
		
		Backgrounds.updateWindowInfo();
		
		// minimum
		var minWidth = 1024;
		var minHeight = 768;
		if(Backgrounds.windowinfo.width > minWidth){
			Backgrounds.$currentBGContainer.width(Backgrounds.windowinfo.width);
			Backgrounds.$clonedBGContainer.width(Backgrounds.windowinfo.width);
		} else {
			Backgrounds.$currentBGContainer.width(minWidth);
			Backgrounds.$clonedBGContainer.width(minWidth);
		} 
		if(Backgrounds.windowinfo.height > minHeight) {
			Backgrounds.$currentBGContainer.height(Backgrounds.windowinfo.height);
			Backgrounds.$clonedBGContainer.height(Backgrounds.windowinfo.height);
		} else {
			Backgrounds.$currentBGContainer.height(minHeight);
			Backgrounds.$clonedBGContainer.height(minHeight);
		}
		
		//Backgrounds.$currentBGContainer.css({'width' : $(document).width() + 'px', 'height' : $(document).height() + 'px'});
		//Backgrounds.$clonedBGContainer.css({'width' : $(document).width() + 'px', 'height' : $(document).height() + 'px'});
		
		
		var p = Math.ceil(Backgrounds.windowinfo.height / 2) - 170;
		
		//console.log('onResize ' + p + ', w' + $(document).width() + ', h' + $(document).height());
		if(p < 0){
			p = 0;
		}
		try{
			// optimize by caching the element is not an option since DOM is changed
			$('#mainDiv .home').css({'margin-top' : p + "px"});
		} catch(ex){
			
		}
	}

};


$(window).load(function() {
	Backgrounds.initialize(PPGContext.arrBackgrounds);
	Backgrounds.onResizeWindowPlaceContent();
});
