// JavaScript Document
jQuery(function()
{
	Rotator.init();
});

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)


var Rotator = {
	
	container:null,
	triggers:null,
	offerPage:null,
	textContainer:null,
	timeout:500,
	
	init: function(){
		Rotator.container = jQuery("#image-switch");
		Rotator.textContainer = jQuery("div.div-text-breve-offerte");
		Rotator.offerPage = jQuery("div.div-text-lungo");
		Rotator.title = jQuery("div.div-titoletti");
		Rotator.triggers = jQuery("img.switch");
		Rotator.triggers.bind('click', Rotator.onClick);
		
		jQuery.each(Rotator.triggers, function(key, value) { 
		  jQuery.preLoadImages(jQuery(value).attr('rel'));
		});
	},
	
	doFade: function(imgSrc){
		Rotator.container.fadeOut( Rotator.timeout, function(){ 
				jQuery("img", Rotator.container).attr('src',imgSrc);
				Rotator.container.fadeIn( Rotator.timeout);
		});
	},
	
	loadPage: function(page){
		Rotator.offerPage.fadeOut( Rotator.timeout, function(){ 
				Rotator.offerPage.load(page);
				Rotator.offerPage.fadeIn( Rotator.timeout);
		});
	},
	
	showText: function(text){
		Rotator.textContainer.fadeOut( Rotator.timeout, function(){ 
				Rotator.textContainer.html(text);
				Rotator.textContainer.fadeIn( Rotator.timeout);
		});
	},
	
	showTitle: function(text){
		Rotator.title.fadeOut( Rotator.timeout, function(){ 
				Rotator.title.html(text);
				Rotator.title.fadeIn( Rotator.timeout);
		});
	},
	
	onClick: function(evt){
		if(evt){
			evt.preventDefault();
			evt.stopPropagation();
		}
		
		var elem = jQuery(this);
		if(elem.hasClass('triggered')){
			return;
		}
		
		Rotator.triggers.removeClass('triggered');
		
		var source = elem.attr('rel');
		Rotator.doFade(source);
		
		var page = elem.attr('page');
		Rotator.loadPage(page);
		
		var text = elem.attr('text');
		Rotator.showText(text);
		
		var title = elem.attr('title');
		Rotator.showTitle(title);
		
		elem.addClass('triggered');
	}
	
}
