/* 
Lightbox in jQuery
vers. 1.0 - gestione singola lightbox
vers. 2.0 - gestione di diverse lightbox, con gallery items per parametro
*/

lightbox = {
	// NOTA: le opzioni sono comuni a tutte le lightbox per uniformita'
	options : {
		speed : 'slow', 
		animationSpeed : 800,
		animated: false,
		loadingImage: '/img2007/lightbox/loading.gif',
		delay: 5000,
		defaultHeight: 604,
		paginationModule: 11, 
		iframeSpotUrl: '',
		templateUrl: '/includes/lightbox.php', // url del template html della lightbox
		sitecensus: {
			url: '//secure-it.imrworldwide.com/cgi-bin/m?ci=ilsole-it&cg=0&si=', // -> parte costante della url per sitecensus
			completeurl: '', // parte variabile, la popolo la prima volta che carico la lightbox
			lboxparam: 'lb=1' // lasciare vuoto se non si vuole che sitecensus registri le visite con lightbox in modo separato (come url diversa)
		}
	},

	flags : {
		pageLoaded: false,
		activeSlideshow: false,
		active: false
	},
	
	browser: {
		msie6: $j.browser.msie && ($j.browser.version == "6.0"),
		msie7: $j.browser.msie && ($j.browser.version == "7.0"),
		ffox: $j.browser.mozilla,
		safari: $j.browser.safari,
		opera: $j.browser.opera
	},

	keyboard: { // i tasti per cui supportiamo eventi
		left_arrow: 37,
		right_arrow: 39,
		esc_key: 27
	},

	debug : function(logger){
		// tool per il debug differenziato su ie e firefox
		if (navigator.userAgent.indexOf('Firefox') != -1)
			console.log(logger);
		else window.alert(logger);
	},

	windowload : function(){
		lightbox.flags.pageLoaded = true;
	},
	
	initialize : function(json, caller){
		if (lightbox.flags.pageLoaded && !lightbox.flags.active) {
			lightbox.flags.active = true;
			lightbox.options.iframeSpotUrl = json.substring(json,json.indexOf('/',json.indexOf('/Gallery/')+10)) + "/spot_include.html";
			lightbox.caller = caller; // id del link che ha chiamato la lightbox
			lightbox.loadSuccess = false;
			lightbox.getGallery(json);
		}
	},
	
	getGallery : function(url){
		$j.ajax({
			url: url,
			type: 'GET',
			datatype: 'script', 
			success: function(responseText){
				lightbox.loadSuccess = true;
				eval(responseText);
				lightbox.galleryItems = galleryItems;
				lightbox.launch();
			},
			error: function(){
				lightbox.loadSuccess = false;
			 }
		});
	},

	launch: function(){
		lightbox.flags.activeSlideshow = false;
		if ($j(lightbox.caller).attr("rel") != undefined){
			lightbox.startIndex = parseInt($j(lightbox.caller).attr("rel"));
			lightbox.currentIndex = parseInt($j(lightbox.caller).attr("rel"));
		} else {
			lightbox.currentIndex = 0;
			lightbox.startIndex = 0;
		}
		lightbox.hideFlash();
		var myoverlay = '<div id="overlay" style="display:none"> </div>';
		$j('body').append(myoverlay);
		$j('#overlay').height($j(document).height())
		.width($j(document).width())
		.css('opacity','0.85')
		.bind('click',function(){
			lightbox.close();
			return false;
		});
		$j('html').css("overflow-x", "hidden");
		if (lightbox.loadSuccess) lightbox.launchSuccess();
		else lightbox.launchFailure();
		
		$j(window).bind('resize', function(){
			if ($j('#cnt_lbox').height() > 0){
				lightbox.alignCenter($j('#cnt_lbox').height());
			}
			else lightbox.alignCenter(lightbox.options.defaultHeight);
		});
	},

	launchFailure: function(){
		$j('#overlay').show();
		window.alert("ERROR getting Gallery Items");
		lightbox.close();
	},
	
	launchSuccess: function(){
		lightbox.options.paginationModule = (lightbox.galleryItems.images.length < lightbox.options.paginationModule ? lightbox.galleryItems.images.length : lightbox.options.paginationModule);
		if (lightbox.options.animated)
			$j('#overlay').fadeIn(lightbox.options.speed, function(){
				$j('#overlay').before('<div id="lightbox"><div id="cnt_lbox"  style="width: 1px; height: 1px;" class="clearfix"> </div></div>');
				lightbox.alignCenter(lightbox.options.defaultHeight);
				lightbox.resizeLightbox(lightbox.galleryItems.images[lightbox.startIndex].height + 171, true);
			});
		else {
			$j('#overlay').show();
			lightbox.alignCenter(lightbox.options.defaultHeight);
			lightbox.resizeLightbox(lightbox.galleryItems.images[lightbox.startIndex].height + 171, true); 
		}
		lightbox.setupSitecensus();
	},
		
	setupSitecensus: function(){
		// se il document.location contiene url con parametri, appendo il param lightbox come ulteriore param
		loc = escape(document.location.href);
		if(lightbox.options.sitecensus.lboxparam == "")
			lightbox.options.sitecensus.completeurl = lightbox.options.sitecensus.url + loc;
		else {
			if(document.location.href.indexOf("?") > 0) 
				lightbox.options.sitecensus.completeurl = lightbox.options.sitecensus.url + loc + escape("&" + lightbox.options.sitecensus.lboxparam);
			else 
				lightbox.options.sitecensus.completeurl = lightbox.options.sitecensus.url + loc + escape("?" + lightbox.options.sitecensus.lboxparam);
		}
	},

	alignCenter : function(height){
		var leftval = ($j(window).width() / 2 ) - 440;
		var topval = ($j(window).height() / 2) - (height / 2) + $j(document).scrollTop();
		$j('#overlay').height($j(document).height()).width($j(document).width())
		if (leftval < 0) leftval = 0;
		if (topval < 0) topval = 0;
		if (lightbox.options.animated)
			$j('#lightbox').css('left', leftval + 'px').animate({'top' : topval + 'px'});
		else $j('#lightbox').css('left', leftval + 'px').css('top', topval + 'px');
	},
	
	resizeLightbox : function(height, init) {
		
		if (height < $j(".rightbox").outerHeight() + $j(".header").outerHeight() + 20 ) {
			height = $j(".rightbox").outerHeight() + $j(".header").outerHeight() + 20 ;
		}
		
		if (lightbox.options.animated){
			$j('#cnt_lbox').animate({"width": "930px", 'opacity': '1'}, lightbox.options.animationSpeed)
			.animate({'height' : height + 'px'}, lightbox.options.animationSpeed, function(){
				lightbox.showLightbox(init);
			});
		} else {
			$j('#cnt_lbox').width(930).height(height);
			lightbox.showLightbox(init);
			$j('#current_image .int').show()
		}
	},
	
	showLightbox: function(init){
		var h;
		if (init){
			lightbox.createLightbox();
		} else {
			lightbox.resizeImageBox();
		}
		lightbox.alignCenter($j('#cnt_lbox').height()); 
	},
	
	resizeImageBox : function() {
		// resize del box che contiene l'immagine. Lo devo fare sempre, ma questa funzione viene chiamata da due punti diversi a seconda che init = true o false
		if (lightbox.galleryItems.images[lightbox.currentIndex].height < 288)
				h = 288;
		else h = lightbox.galleryItems.images[lightbox.currentIndex].height;
		$j('#current_image .ext').height(h);	
	},
	
	createLightbox : function() {
		if (!lightbox.options.animated){
			$j('body').append('<div id="lightbox"><div id="cnt_lbox"  style="display:none;" class="clearfix"> </div></div>');
			$j('#cnt_lbox').show();
		}
		$j('#cnt_lbox').css('opacity', '1');
		$j('#cnt_lbox').append(lightbox.injectGalleryHtml());
		$j('#gallery_title').append(lightbox.galleryItems.title);
		lightbox.resizeImageBox();
		$j('#spot').append('<iframe id="bannerLB" scrolling="no" frameborder="0" allowtransparency="true" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" src="" ></iframe>');
		$j('a#close_lbox').bind('click', function(){
			lightbox.close();
			return false;
		});
		$j('#firstLink').bind('click', function(){
			lightbox.showImage(0, true, true);
			return false;
		});
		$j('#prevLink').click(function(){
			lightbox.showImage(-1, false, true);
			return false;
		});
		$j('#nextLink').click(function(e){
			lightbox.showImage(1, false, true);
			return false;
		});
		$j('#lastLink').bind('click', function(){
			lightbox.showImage(lightbox.galleryItems.images.length - 1, true, true);
			return false;
		});
		$j('#startSlider').bind('click', lightbox.startSlideshow);
		$j(document).keydown(lightbox.keyboard_navigation);
		lightbox.showImage(lightbox.startIndex, true, false); // e' la prima volta che lo faccio partire
		//return false;
	},

	keyboard_navigation: function(e){
		switch(e.keyCode){
			case lightbox.keyboard.left_arrow:
				lightbox.showImage(-1, false, false);
				break;
			case lightbox.keyboard.right_arrow:
				lightbox.showImage(1, false, false);
				break;
			case lightbox.keyboard.esc_key:
				lightbox.close();
				break;
		}
	},

	injectGalleryHtml : function(){
		// faccio una get e recupero l'html
		var html = $j.ajax({
			url: lightbox.options.templateUrl,
			type: 'GET',
			datatype: 'html', 
			async: false,
			error: function(){
				// metto un messaggio di errore sulla lightbox
				window.alert("Errore caricamento template");
				lightbox.close();
			}
		}).responseText;
		return html;
	},

	refreshSitecensus: function(){
		// faccio il refresh del codice sitecensus -> si trova all'immagine id= "sitecensus" definito nel template di lightbox
		//$('img#sitecensus').attr('src', lightbox.options.sitecensus.completeurl);
		if(lightbox.options.sitecensus.completeurl == "") lightbox.setupSitecensus();
		$j('img#sitecensus').attr('src', lightbox.options.sitecensus.completeurl + "&rnd=" + new Date().getTime());
		/* omniture */
		var tmparray = s.pageName.split(":")
		tmparray[tmparray.length-1] = parseInt(lightbox.currentIndex)+1;
		s.pageName = tmparray.join(":");
		
		tmparray = s.prop4 .split(":")
		tmparray[tmparray.length-1] = parseInt(lightbox.currentIndex)+1;
		s.prop4  = tmparray.join(":");
		
		tmparray = s.hier1.split(",")
		tmparray[tmparray.length-1] = parseInt(lightbox.currentIndex)+1;
		s.hier1 = tmparray.join(",");
		/* Tracking */
		s.t()
	},
	
	countVisits: function(){
		if(typeof uuid != "undefined") {
		    var serviceUrl="/php/piuletti/artratingsvc.php";
		    var title = escape(document.title);
		    var DocRulesView = 'Libero';
		    var url = escape(document.URL);
		    var dataUrl = "uuid=" + uuid;
		    dataUrl += "&title=" + title;
		    dataUrl += "&DocRulesView=" + DocRulesView;
		    dataUrl += "&type=gallery&channel=Motori24";
		    dataUrl += "&url=".concat(url);
			dataUrl += "&rnd="+new Date().valueOf();
			
			if(uuid.length > 0 && title.length > 0) {
				$j.ajax({
				   type: "GET",
				   url: serviceUrl,
				   data:dataUrl,
				   success: function(msg){
					$j(document.body).append(msg);
				   }
				 });
			}
		}
	},
	
	loading: function(){
		$j('#current_image .int img').replaceWith('<img id="loadingImage" src="' + lightbox.options.loadingImage + '" />');
	},
	
	startSlideshow : function(){
		lightbox.flags.activeSlideshow = true;
		$j('#current_image .int img').unbind();
		$j(document).unbind('keydown');
		$j('#startSlider').unbind('click', lightbox.startSlideshow);
		$j('#startSlider').hide();
		$j('#stopSlider').show();
		$j('#stopSlider').bind('click', lightbox.stopSlideshow);
		lightbox.timerControl('start');
		return false;
	},

	stopSlideshow : function(){
		lightbox.timerControl('stop');
		$j('#stopSlider').unbind('click', lightbox.stopSlideshow);
		$j('#stopSlider').hide();
		$j('#startSlider').show();
		$j('#startSlider').bind('click', lightbox.startSlideshow);
		$j('#current_image .int img')
			.click(function(){
				lightbox.showImage(1, false, false);
			})
			.hover(function(){
				$j(this).css("cursor", "pointer");
			}, function(){
				$j(this).css("cursor", "default");
			});
		$j(document).keydown(lightbox.keyboard_navigation);
		lightbox.flags.activeSlideshow = false;
		return false;
	},
	
	timerControl : function(action) {
		if (action == 'start') {
			lightbox.timer = self.setInterval("lightbox.showImage(1, false, false)", lightbox.options.delay)
		} else {
			lightbox.timer = clearInterval(lightbox.timer);
			lightbox.timer = null;
		}
	},

	setPagination : function(){
		var rangeMax, rangeMin;
		var paginationString = '';
		var resto = lightbox.currentIndex % lightbox.options.paginationModule;
		
		if (lightbox.currentIndex != 0)
			rangeMin = lightbox.currentIndex - Math.floor(lightbox.options.paginationModule / 2) ;
		else rangeMin = 0;		
		rangeMax = rangeMin + lightbox.options.paginationModule - 1;
		//valori sui bordi
		if (rangeMax >= lightbox.galleryItems.images.length) {
			rangeMax = lightbox.galleryItems.images.length - 1;
			rangeMin = lightbox.galleryItems.images.length - lightbox.options.paginationModule;
		}
		if (rangeMin < 0){
			rangeMin = 0;
			rangeMax = lightbox.options.paginationModule - 1;
		}
		$j('#gallery_pagination').empty();
		for (var i = rangeMin; i <= rangeMax; i++){
			var tag = 'img' + i;
			paginationString ='\n<li id="' + tag + '" rel="' + i + '"><a href="javascript:void(0)" ';
			if (i == lightbox.currentIndex)
				paginationString +='class="selected"';
			paginationString +='>' + (i + 1);
			paginationString +='</a></li>';
			$j('#gallery_pagination').append(paginationString);
			$j('#' + tag).bind('click', function(){
				lightbox.showImage($j('#' + this.id).attr("rel"), true, true); // true = arriva dal click della paginazione
			});
		}
	},

	showImage : function(value, absolute, fromPagination){
		if (fromPagination)
			lightbox.stopSlideshow();
		if (!absolute)
			index = parseInt(lightbox.currentIndex) + parseInt(value);
		else {
			index = value;
		}
		index = lightbox.checkIndex(index);
		lightbox.currentIndex = index;
		$j('#current_image .int img').replaceWith('<img src="' + lightbox.galleryItems.images[index].src + '" width="' + lightbox.galleryItems.images[index].width + '" height="' + lightbox.galleryItems.images[index].height + '" />');
		if(!lightbox.flags.activeSlideshow)
			$j('#current_image .int img')
				.click(function(){
					lightbox.showImage(1, false, false);
				})
				.hover(function(){
					$j(this).css("cursor", "pointer");
				}, function(){
					$j(this).css("cursor", "default");
				});
		lightbox.resizeLightbox(lightbox.galleryItems.images[index].height + $j(".caption").outerHeight() + 171, false);		
		lightbox.setPagination();
		$j('#image_caption').html(lightbox.galleryItems.images[index].caption);
		lightbox.setCounter(index);
		
		// FIX IE6: devo ritornare il focus al document, su click fittizio della lightbox
		if(lightbox.browser.msie6){
			// su ie6 il caricamento dell'iframe non ritorna il focus al parent -> non funziona la nav da tastiera. per risolverlo
			// restituisco manualmente il focus al padre.
			$j('#bannerLB').attr('src',lightbox.options.iframeSpotUrl)
				.load(function(){
					$j('#cnt_lbox').focus(function(){
						$j(document).focus();
					}).focus();
				});
		} else $j('#bannerLB').attr('src',lightbox.options.iframeSpotUrl);
		lightbox.refreshSitecensus();
		lightbox.countVisits();
	},

	preloadImages : function (index){
		
	},
	
	checkIndex : function(index){
		if (index < 0) index = lightbox.galleryItems.images.length - 1;
		if (index >= lightbox.galleryItems.images.length) index = 0;
		return index;
	},
	
	setCounter : function(index) {
		index = parseInt(index);
		$j('#counter').empty();
		$j('#counter').append("Immagine " + (index + 1) + " / " + lightbox.galleryItems.images.length);
	},

	hideFlash: function(){
		$j('iframe').css('visibility', 'hidden');
		$j('object').css('visibility', 'hidden');
		$j('embed').css('visibility', 'hidden');
	},

	showFlash: function(){
		$j('iframe').css('visibility', 'visible');
		$j('object').css('visibility', 'visible');
		$j('embed').css('visibility', 'visible');
	},

	close: function(){
		if (!lightbox.loadSuccess)
			$j('#overlay').empty().remove();
		else {
			if (lightbox.timer != null)
				lightbox.stopSlideshow();
			$j(window).unbind('resize');
			$j(document).unbind('keydown');
			if (lightbox.options.animated){
			$j('#cnt_lbox').empty();
			$j('#cnt_lbox').animate({'height': '1px',	'opacity': '1'}, lightbox.options.animationSpeed).
				animate({'width' : '1px'}, lightbox.options.animationSpeed, function(){
					$j('#lightbox').empty().remove();
					$j('#overlay').fadeOut(lightbox.options.speed, function(){
						$j('#overlay').remove();
						lightbox.showFlash();
					});
				});
			} else {
				$j('#lightbox').empty().remove();
				$j('#overlay').remove();
				lightbox.showFlash();
			}
			$j('html').css("overflow-x", "auto");
		}
		lightbox.flags.active = false;
	} 

} // lightbox
