/*
 * jQuery bgSliding
 *
 * Copyright 2011, Marco Poglie
 * THINKPLACE scripts.
 * http://www.thinkplace.it
 * http://www.poglie.com
 * 
 */

(function($) {

    var bgSliding = function(element, options){
		//Defaults are below
		var settings = $.extend({}, $.fn.bgSliding.defaults, options);

        
        //Trigger the afterLoad callback
        settings.afterLoad.call(this);
		
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//															INIT-SETTING
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        var _element = $(element); // l'oggetto selezionato
		
		var figli = _element.children();
		var lunghezzaElement = figli.length;
		
		var obj_resize = {  width: 1620, height: 780, bgID: '.background-foto' };
		
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//															APRI - CREA
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// 
		var init = function(setting){
			fullscreenr(obj_resize);
			_element.css('display','none');
			_element.delay(settings.delay).fadeIn('slow', function() {
    			// Animation complete.
  			});
			
		}
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//															CONTROLLI (back - next - control)
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Backwards navigation
		$("#back").click(function() {
			stopAnimation();
			navigate("back");
		});
		
		// Forward navigation
		$("#next").click(function() {
			stopAnimation();
			navigate("next");
		});
		
		var interval;
		$("#control").toggle(function(){
			stopAnimation();
		}, function() {
			// Change the background image to "pause"
			$(this).css({ "background-image" : "url(images/btn_pause.png)" });
			
			// Show the next image
			navigate("next");
			
			// Start playing the animation
			interval = setInterval(function() {
				navigate("next");
			}, settings.slideshowSpeed);
		});
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//															RESIZING
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		var fullscreenrResizer = function(options) {
			// Set bg size
			var ratio = options.height / options.width;	
			// Get browser window size
			var browserwidth = $(window).width();
			var browserheight = $(window).height();
			// Scale the image
			if ((browserheight/browserwidth) > ratio){
				$(options.bgID).height(browserheight);
				$(options.bgID).width(browserheight / ratio);
			} else {
				$(options.bgID).width(browserwidth);
				$(options.bgID).height(browserwidth * ratio);
			}
			// Center the image
			$(this).css('left', (browserwidth - $(this).width())/2);
			$(this).css('top', (browserheight - $(this).height())/2);
				
		};
		var fullscreenr = function(options) {
			if(options.height === undefined) alert('Please supply the background image height, default values will now be used. These may be very inaccurate.');
			if(options.width === undefined) alert('Please supply the background image width, default values will now be used. These may be very inaccurate.');
			if(options.bgID === undefined) alert('Please supply the background image ID, default #bgimg will now be used.');
			var defaults = { width: 1280,  height: 1024, bgID: 'bgimg' };
			var options = $.extend({}, defaults, options); 
			
			//fullscreenrResizer(options);
			//
			fullscreenrResizer(options);
			$(window).bind("resize", function() {fullscreenrResizer(options); });
					
			return this; 		
		};	
		
		
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//															SLIDESHOW
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		var activeContainer = 1;	
		var currentImg = 0;
		var animating = false;
		var navigate = function(direction) {
			// Check if no animation is running. If it is, prevent the action
			if(animating) {
				return;
			}
			
			// Check which current image we need to show
			if(direction == "next") {
				currentImg++;
				if(currentImg == settings.photos.length + 1) {
					currentImg = 1;
				}
			} else {
				currentImg--;
				if(currentImg == 0) {
					currentImg = settings.photos.length;
				}
			}
			
			// Check which container we need to use
			var currentContainer = activeContainer;
			if(activeContainer == 1) {
				activeContainer = 2;
			} else {
				activeContainer = 1;
			}
			
			showImage(settings.photos[currentImg - 1], currentContainer, activeContainer);
			
		};
		
		var currentZindex = -1;
		var showImage = function(photoObject, currentContainer, activeContainer) {
			animating = true;
			
			// Make sure the new container is always on the background
			currentZindex--;
			
			// Set the background image of the new active container
			$("#headerimg" + activeContainer).css({
				//"background-image" : "url(images/" + photoObject.image + ")",
				"display" : "block",
				"z-index" : currentZindex
			});
			
			 $(document.createElement("img")).attr({ src: 'images/' + photoObject.image, title: 'CartieraGiorgione'}).addClass('background-foto').appendTo("#headerimg" + activeContainer);
			 fullscreenrResizer(obj_resize);
			 
			//$("#headerimg" + activeContainer).text('<img src="images/sfondi/azienda.jpg" width="1620" height="780" alt="cartiera giorgione azienda" id="background-foto"/>');
			// Hide the header text
			$("#headertxt").css({"display" : "none"});
			
			// Set the new header text
			$("#firstline").html(photoObject.firstline);
			$("#secondline")
				.attr("href", photoObject.url)
				.html(photoObject.secondline);
			$("#pictureduri")
				.attr("href", photoObject.url)
				.html(photoObject.title);
			
			
			// Fade out the current container
			// and display the header text when animation is complete
			$("#headerimg" + currentContainer).fadeOut(3000, 'easeInOutExpo',function() {
				$(this).text('');// svuoto l'immagine vecchia
				setTimeout(function() {
					$("#headertxt").css({"display" : "block"});
					animating = false;
				}, 500);
			});
		};
		
		var stopAnimation = function() {
			// Change the background image to "play"
			$("#control").css({ "background-image" : "url(images/btn_play.png)" });
			
			// Clear the interval
			clearInterval(interval);
		};
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//															GOOOOOOO
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//
		// We should statically set the first image
		navigate("next");
		
		//
		// Start playing the animation
		interval = setInterval(function() {
			navigate("next");
		}, settings.slideshowSpeed);
		
		
		
		
		
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//														  CHIUDI - CANCELLA
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		
		
		
		
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//															  MOSTRA
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		
		
		
		
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//															NASCONDI
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		
		
		
		
		//
        init(settings);
		
		
		return this;
    };
        
    $.fn.bgSliding = function(options) {
    
        return this.each(function(key, value){
            var element = $(this);
			
            // Rientro anticipato dell'attrubuto se questo elemento ha già un plugin istanza
            if (element.data('bgsliding')) return element.data('bgsliding');
            
			// COSTRUTTORE: -----------------------------
            var bgsliding = new bgSliding(this, options);
			// ------------------------------------------
			
            // memorizzo il l'istanza in data
            element.data('bgsliding', bgsliding);
        });

	};
	
	//Default settings
	$.fn.bgSliding.defaults = {
		delay: 0,
		slideshowSpeed: 5000,
		photos: [ {
					/*"title" : "Title",
					"image" : "im.jpg",
					"url" : "images/sfondi",
					"firstline" : "testo1",
					"secondline" : "testo2"*/
				}],
        afterLoad: function(){}
	};
	
	$.fn._reverse = [].reverse;
	
})(jQuery);
