/* 
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: 559,
		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)
		} // url del template html della lightbox
	},

	flags : {
		pageLoaded: false,
		activeSlideshow: false,
		active: false
	},

	browser: {
		msie6: $.browser.msie && ($.browser.version == "6.0"),
		msie7: $.browser.msie && ($.browser.version == "7.0"),
		ffox: $.browser.mozilla,
		safari: $.browser.safari,
		opera: $.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){
		$.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 ($(lightbox.caller).attr("rel") != undefined){
			lightbox.startIndex = parseInt($(lightbox.caller).attr("rel"));
			lightbox.currentIndex = parseInt($(lightbox.caller).attr("rel"));
		} else {
			lightbox.currentIndex = 0;
			lightbox.startIndex = 0;
		}
		lightbox.hideFlash();
		var myoverlay = '<div id="overlay" style="display:none"> </div>';
		$('body').append(myoverlay);
		$('#overlay').height($(document).height())
		.width($(document).width())
		.css('opacity','0.85')
		.bind('click',function(){
			lightbox.close();
			return false;
		});
		if (lightbox.loadSuccess) lightbox.launchSuccess();
		else lightbox.launchFailure();
		
		$(window).bind('resize', function(){
			if ($('#cnt_lbox').height() > 0){
				lightbox.alignCenter($('#cnt_lbox').height());
			}
			else lightbox.alignCenter(lightbox.options.defaultHeight);
		});
	},

	launchFailure: function(){
		$('#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)
			$('#overlay').fadeIn(lightbox.options.speed, function(){
				$('#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 {
			$('#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);
		}
	},
	
	refreshSitecensus: function(){
		if (lightbox.options.sitecensus.completeurl == "") lightbox.setupSitecensus();
		$('img#sitecensus').attr('src', lightbox.options.sitecensus.completeurl + "&rnd=" + new Date().getTime());
	},
	
	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=Luxury24";
		    dataUrl += "&url=".concat(url);
			dataUrl += "&rnd="+new Date().valueOf();
			if(uuid.length > 0 && title.length > 0) {
				$.ajax({
				   type: "GET",
				   url: serviceUrl,
				   data:dataUrl,
				   success: function(msg){
					$(document.body).append(msg);
				   }
				 });
			}
		}
	},
	
	alignCenter : function(height){
		var leftval = ($(window).width() / 2 ) - 450;
		var topval = ($(window).height() / 2) - (height / 2) + $(document).scrollTop();
		$('#overlay').height($(document).height()).width($(document).width())
		if (leftval < 0) leftval = 0;
		if (topval < 0) topval = 0;
		if (lightbox.options.animated)
			$('#lightbox').css('left', leftval + 'px').animate({'top' : topval + 'px'});
		else $('#lightbox').css('left', leftval + 'px').css('top', topval + 'px');
	},
	
	resizeLightbox : function(height, init) {
		if (height < lightbox.options.defaultHeight) height = lightbox.options.defaultHeight;
		if (lightbox.options.animated){
			$('#cnt_lbox').animate({"width": "930px", 'opacity': '1'}, lightbox.options.animationSpeed)
			.animate({'height' : height + 'px'}, lightbox.options.animationSpeed, function(){
				lightbox.showLightbox(init);
			});
		} else {
			$('#cnt_lbox').width(930).height(height);
			lightbox.showLightbox(init);
			$('#current_image .int').show();
		}
	},
	
	showLightbox: function(init){
		var h;
		if (init) lightbox.createLightbox();
		else lightbox.resizeImageBox();
		lightbox.alignCenter($('#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;
		$('#current_image .ext').height(h);	
	},
	
	createLightbox : function() {
		if (!lightbox.options.animated){
			$('body').append('<div id="lightbox"><div id="cnt_lbox"  style="display:none;" class="clearfix"> </div></div>');
			$('#cnt_lbox').show();
		}
		$('#cnt_lbox').css('opacity', '1');
		$('#cnt_lbox').append(lightbox.injectGalleryHtml());
		$('#gallery_title').append(lightbox.galleryItems.title);
		lightbox.resizeImageBox();
		$('#spot').append('<iframe name="bannerLB" id="bannerLB" scrolling="no" frameborder="0" allowtransparency="true" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" src="" ></iframe>');
		$('#bannerLB').load(lightbox.advLoad);
		$('a#close_lbox').bind('click', function(){
			lightbox.close();
			return false;
		});
		$('#firstLink').bind('click', function(){
			lightbox.showImage(0, true, true);
			return false;
		});
		$('#prevLink').click(function(){
			lightbox.showImage(-1, false, true);
			return false;
		});
		$('#nextLink').click(function(e){
			lightbox.showImage(1, false, true);
			return false;
		});
		$('#lastLink').bind('click', function(){
			lightbox.showImage(lightbox.galleryItems.images.length - 1, true, true);
			return false;
		});
		$('#startSlider').bind('click', lightbox.startSlideshow);
		$(document).keydown(lightbox.keyboard_navigation);
		lightbox.showImage(lightbox.startIndex, true, false); // e' la prima volta che lo faccio partire
		//return false;
	},

	advLoad: function(){
		var h = window.bannerLB.HEIGHT_DIMVideoBox //$('#bannerLB').contents().find('object').height();
		var offset_caption = $(".caption").outerHeight();
		var lbox_height = 0;
		var right_h = $(".piuvistilb").outerHeight() + $(".spot_footer").outerHeight();
		var left_h = lightbox.galleryItems.images[index].height + $(".lightbox_navigation").outerHeight() + offset_caption;
		if(h > 250) {
			lightbox.defaultHeight = 700;
			lbox_height = lightbox.defaultHeight + offset_caption;
			//nasconde il box piu visti se c'è il banner grande
			$(".piuvistilb").css("display","none");
		} 
		else{
			h = 250;
			$(".piuvistilb").css("display","block");
			right_h+=h;
			lightbox.defaultHeight = 559;
			if(right_h > left_h){
				lbox_height = $(".header").outerHeight() + right_h + 60;
			}
			else{
			lbox_height = lightbox.galleryItems.images[index].height + offset_caption + $(".header").outerHeight() + $(".lightbox_navigation").outerHeight() + 60;
		}
		}
		lightbox.resizeLightbox(lbox_height, false);
		$('#bannerLB').height(parseInt(h));
	},
	
	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 = $.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;
	},

	loading: function(){
		$('#current_image .int img').replaceWith('<img id="loadingImage" src="' + lightbox.options.loadingImage + '" />');
	},
	
	startSlideshow : function(){
		lightbox.flags.activeSlideshow = true;
		$('#current_image .int img').unbind();
		$(document).unbind('keydown');
		$('#startSlider').unbind('click', lightbox.startSlideshow);
		$('#startSlider').hide();
		$('#stopSlider').show();
		$('#stopSlider').bind('click', lightbox.stopSlideshow);
		lightbox.timerControl('start');
		return false;
	},

	stopSlideshow : function(){
		lightbox.timerControl('stop');
		$('#stopSlider').unbind('click', lightbox.stopSlideshow);
		$('#stopSlider').hide();
		$('#startSlider').show();
		$('#startSlider').bind('click', lightbox.startSlideshow);
		$('#current_image .int img')
			.click(function(){
				lightbox.showImage(1, false, false);
			})
			.hover(function(){
				$(this).css("cursor", "pointer");
			}, function(){
				$(this).css("cursor", "default");
			});
		$(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;
		}
		$('#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>';
			$('#gallery_pagination').append(paginationString);
			$('#' + tag).bind('click', function(){
				lightbox.showImage($('#' + 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;
		$('#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)
			$('#current_image .int img')
				.click(function(){
					lightbox.showImage(1, false, false);
				})
				.hover(function(){
					$(this).css("cursor", "pointer");
				}, function(){
					$(this).css("cursor", "default");
				});
		//lightbox.resizeLightbox(lightbox.galleryItems.images[index].height + 171, false); // per pub, spostato in load spot
		lightbox.setPagination();
		$('#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.
			$('#bannerLB').attr('src',lightbox.options.iframeSpotUrl)
				.load(function(){
					$('#cnt_lbox').focus(function(){
						$(document).focus();
					}).focus();
				});
		} else $('#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);
		$('#counter').empty();
		$('#counter').append("Immagine " + (index + 1) + " / " + lightbox.galleryItems.images.length);
	},

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

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

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

} // lightbox
