/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tbg_pathToImage = "images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tbg_init
jQuery(document).ready(function(){   
	tbg_init('a.thickboxgallery, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tbg_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tbg_init(domChunk){
	jQuery(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tbg_show(t,a,g);
	this.blur();
	return false;
	});
}

function tbg_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			jQuery("body","html").css({height: "100%", width: "100%"});
			jQuery("html").css("overflow","hidden");
			if (document.getElementById("TBG_HideSelect") === null) {//iframe to hide select elements in ie6
				jQuery("body").append("<iframe id='TBG_HideSelect'></iframe><div id='TBG_overlay'></div><div id='TBG_window'></div>");
				jQuery("#TBG_overlay").click(tbg_remove);
			}
		}else{//all others
			if(document.getElementById("TBG_overlay") === null){
				jQuery("body").append("<div id='TBG_overlay'></div><div id='TBG_window'></div>");
				jQuery("#TBG_overlay").click(tbg_remove);
			}
		}
		
		if(tbg_detectMacXFF()){
			jQuery("#TBG_overlay").addClass("TBG_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			jQuery("#TBG_overlay").addClass("TBG_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		jQuery("body").append("<div id='TBG_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		jQuery('#TBG_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TBG_PrevCaption = "";
			TBG_PrevURL = "";
			TBG_PrevHTML = "";
			TBG_NextCaption = "";
			TBG_NextURL = "";
			TBG_NextHTML = "";
			TBG_imageCount = "";
			TBG_FoundURL = false;
			if(imageGroup){
				TBG_TempArray = jQuery("a[rel="+imageGroup+"]").get();
				for (TBG_Counter = 0; ((TBG_Counter < TBG_TempArray.length) && (TBG_NextHTML === "")); TBG_Counter++) {
					var urlTypeTemp = TBG_TempArray[TBG_Counter].href.toLowerCase().match(urlString);
						if (!(TBG_TempArray[TBG_Counter].href == url)) {						
							if (TBG_FoundURL) {
								TBG_NextCaption = TBG_TempArray[TBG_Counter].title;
								TBG_NextURL = TBG_TempArray[TBG_Counter].href;
								TBG_NextHTML = "<span id='TBG_next'>&nbsp;&nbsp;<a href='#'>Prossimo &gt;</a></span>";
							} else {
								TBG_PrevCaption = TBG_TempArray[TBG_Counter].title;
								TBG_PrevURL = TBG_TempArray[TBG_Counter].href;
								TBG_PrevHTML = "<span id='TBG_prev'>&nbsp;&nbsp;<a href='#'>&lt; Precedente</a></span>";
							}
						} else {
							TBG_FoundURL = true;
							TBG_imageCount = (TBG_Counter + 1) +" / "+ (TBG_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tbg_getPageSize();
			var x = pagesize[0] - 100;
			var y = pagesize[1] - 100;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TBG_WIDTH = imageWidth + 30;
			TBG_HEIGHT = imageHeight + 60;
			jQuery("#TBG_window").append("<a href='' id='TBG_ImageOff' title='Close'><img id='TBG_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TBG_caption'>"+caption+"<div id='TBG_secondLine'>" + TBG_imageCount + TBG_PrevHTML + TBG_NextHTML + "</div></div><div id='TBG_closeWindow'><a href='#' id='TBG_closeWindowButton' title='Close'>Chiuso</a></div>"); 		
			
			jQuery("#TBG_closeWindowButton").click(tbg_remove);
			
			if (!(TBG_PrevHTML === "")) {
				function goPrev(){
					if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);}
					jQuery("#TBG_window").remove();
					jQuery("body").append("<div id='TBG_window'></div>");
					tbg_show(TBG_PrevCaption, TBG_PrevURL, imageGroup);
					return false;	
				}
				jQuery("#TBG_prev").click(goPrev);
			}
			
			if (!(TBG_NextHTML === "")) {		
				function goNext(){
					jQuery("#TBG_window").remove();
					jQuery("body").append("<div id='TBG_window'></div>");
					tbg_show(TBG_NextCaption, TBG_NextURL, imageGroup);				
					return false;	
				}
				jQuery("#TBG_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tbg_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TBG_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TBG_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tbg_position();
			jQuery("#TBG_load").remove();
			jQuery("#TBG_ImageOff").click(tbg_remove);
			jQuery("#TBG_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tbg_parseQuery( queryString );

			TBG_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TBG_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TBG_WIDTH - 30;
			ajaxContentH = TBG_HEIGHT - 45;
			
			if(url.indexOf('TBG_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TBG_');
					jQuery("#TBG_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						jQuery("#TBG_window").append("<div id='TBG_title'><div id='TBG_ajaxWindowTitle'>"+caption+"</div><div id='TBG_closeAjaxWindow'><a href='#' id='TBG_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TBG_iframeContent' name='TBG_iframeContent"+Math.round(Math.random()*1000)+"' onload='tbg_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					jQuery("#TBG_overlay").unbind();
						jQuery("#TBG_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TBG_iframeContent' name='TBG_iframeContent"+Math.round(Math.random()*1000)+"' onload='tbg_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if(jQuery("#TBG_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						jQuery("#TBG_window").append("<div id='TBG_title'><div id='TBG_ajaxWindowTitle'>"+caption+"</div><div id='TBG_closeAjaxWindow'><a href='#' id='TBG_closeWindowButton'>close</a> or Esc Key</div></div><div id='TBG_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						jQuery("#TBG_overlay").unbind();
						jQuery("#TBG_window").append("<div id='TBG_ajaxContent' class='TBG_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						jQuery("#TBG_ajaxContent")[0].style.width = ajaxContentW +"px";
						jQuery("#TBG_ajaxContent")[0].style.height = ajaxContentH +"px";
						jQuery("#TBG_ajaxContent")[0].scrollTop = 0;
						jQuery("#TBG_ajaxWindowTitle").html(caption);
					}
			}
					
			jQuery("#TBG_closeWindowButton").click(tbg_remove);
			
				if(url.indexOf('TBG_inline') != -1){	
					jQuery("#TBG_ajaxContent").append(jQuery('#' + params['inlineId']).children());
					jQuery("#TBG_window").unload(function () {
						jQuery('#' + params['inlineId']).append( jQuery("#TBG_ajaxContent").children() ); // move elements back when you're finished
					});
					tbg_position();
					jQuery("#TBG_load").remove();
					jQuery("#TBG_window").css({display:"block"}); 
				}else if(url.indexOf('TBG_iframe') != -1){
					tbg_position();
					if(jQuery.browser.safari){//safari needs help because it will not fire iframe onload
						jQuery("#TBG_load").remove();
						jQuery("#TBG_window").css({display:"block"});
					}
				}else{
					jQuery("#TBG_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tbg_position();
						jQuery("#TBG_load").remove();
						tbg_init("#TBG_ajaxContent a.thickboxgallery");
						jQuery("#TBG_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tbg_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tbg_showIframe(){
	jQuery("#TBG_load").remove();
	jQuery("#TBG_window").css({display:"block"});
}

function tbg_remove() {
 	jQuery("#TBG_imageOff").unbind("click");
	jQuery("#TBG_closeWindowButton").unbind("click");
	jQuery("#TBG_window").fadeOut("fast",function(){jQuery('#TBG_window,#TBG_overlay,#TBG_HideSelect').trigger("unload").unbind().remove();});
	jQuery("#TBG_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		jQuery("body","html").css({height: "auto", width: "auto"});
		jQuery("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tbg_position() {
jQuery("#TBG_window").css({marginLeft: '-' + parseInt((TBG_WIDTH / 2),10) + 'px', width: TBG_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		jQuery("#TBG_window").css({marginTop: '-' + parseInt((TBG_HEIGHT / 2),10) + 'px'});
	}
}

function tbg_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tbg_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tbg_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}



