/*
 * Thickerbox - based on thickbox 3.1
 * By Toussaint Guglielmi (http://www.spyroland.net)
 * Thickbox originaly by Cody Lindley (http://www.codylindley.com)
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php

Changes from 3.1:
- added floating arrows above the image for prev/next image
	Activate by setting $.ThickBox.options.useFloatNav to true
	This disables the ability to close by clicking the image
- added an optional navbar above the box
	Activate by setting $.ThickBox.options.useNavBar to true
- allow for galeries of anything, using the navbar for browsing
	The navbar is automatically added if viewing an iframe/ajax
	The navbar is removed if viewing a modal iframe/ajax
- added an optional tb_keycodes array to replace the key commands
	You put additional keycodes via $.ThickBox.keyCodes
	Example: $.ThickBox.keyCodes[32] = "if(TB_Next){ goNext(); }";
- allow the personalisation of "close" link
	Set jQuery.ThickBox.options.closeHTML to the html code
	The link must be of id "TB_closeWindowButton"
	See default value for example
- allow the personalisation of the "next/prev" caption (or removal)
	Set jQuery.ThickBox.options.prevHTML to the html code for previous
	Set jQuery.ThickBox.options.nextHTML to the html code for next
	Ids of links must be TB_prev and TB_next
- look for parameters inside the gallery names
	rel="gallery1+navbar-floatnav" => enables navbar and disables floating arrows
	Settings belong to the gallery name, so they must in every item's rel
- allow the personalisation of the "image x/y" caption
	Set jQuery.ThickBox.options.imageXofYEVAL to code
	The code will be eval'ed to get the "Image X of Y" text
	Can include TB_ThisItem (X) and TB_NumItems (Y) and other variables (see code)
- config can be set using meta tags (name thickbox)
	Example: <meta name="thickbox" content="options.useFloatNav=true" />
	More subtle: <meta name="thickbox" content="options.prevHTML='<a href=\'#\' id=\'TB_prev\'>&lt; Prev</a>'" />
	Be careful of concurrency between metas and scripted jQuery.ThickBox.config (results unknown)
- imagesDir option
	Images for the loading image and navbar must be located in the imagesDir

- better default shortcuts (from my non-american-keyboard point of view)
- "namespace" using jQuery.ThickBox (à la imageBox)
- thickbox can be added to dom elements by using $(selector).thickbox()
- configuration can be changed with jQuery.ThickBox.config({ key : value})
- the caption is added to the alt attribute programatically (avoids quote collision)

TODO
- custom loading image with css (so the url can be raltive to the css)
- add a command to the navbar: diaporama
- move some essential formatting from the css to $().css() here ?

*/

//on page load init thickbox
$(document).ready(function(){
	$('a.thickbox, area.thickbox, input.thickbox').thickbox();//pass where to apply thickbox
	$('meta[@name=thickbox]').each(function(){
		eval("jQuery.ThickBox."+$(this).attr("content"));
	});
	jQuery.ThickBox.config({});
});

// add thickbox as a plugin
jQuery.fn.extend({
	thickbox: function() {
		return this.each(function() { tb_init(this); });
	}
});

if($('script[@src$=thickbox.js]').size()>0){
	TB_urlscript = $('script[@src$=thickbox.js]').attr('src').match('.*/');
} else {
	TB_urlscript = "";
}

// thickbox object
jQuery.ThickBox = {
	options : {
		imagesDir		: TB_urlscript,
		loadImage		: "thickbox-loading.gif",
		navBarClose		: "thickbox-navclose.gif",
		navBarPrev		: "thickbox-navprev.gif",
		navBarNext		: "thickbox-navnext.gif",
		useNavBar		: false,
		useFloatNav		: true,
		closeHTML		: "<a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key",
		prevHTML		: "&nbsp;&nbsp;<a href='#' id='TB_prev'>&lt; Prev</a>&nbsp;&nbsp;",
		nextHTML		: "&nbsp;&nbsp;<a href='#' id='TB_next'>Next &gt;</a>&nbsp;&nbsp;",
		imageXofYEVAL	: "'Image '+TB_ThisItem+' / '+TB_NumItems",
		overlayCaption	: ""//"Click in the background to close"
	},
	useNavBar : false,
	useFloatNav	: true,
	keyCodes	: new Array(),
	imgLoader	: null,

	config : function(options){
		if (options) jQuery.extend(jQuery.ThickBox.options, options);
		jQuery.ThickBox.imgLoader = new Image();// preload image
		jQuery.ThickBox.imgLoader.src = jQuery.ThickBox.options.imagesDir + jQuery.ThickBox.options.loadImage;
	}
};

// add thickbox to selected DOM elements
function tb_init(domChunk){
	$(domChunk).click(function(){
		tb_show(this);
		this.blur();
		return false;
	});
}

function tb_show(element){//function called when the user clicks on a thickbox link
	try {
		var caption = element.title || element.name || null;
		var url = element.href || element.alt;
		var imageGroup = element.rel || false;
		//
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+jQuery.ThickBox.options.imagesDir+jQuery.ThickBox.options.loadImage+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
		if(url.indexOf("?")!==-1){ //if 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);
		var useNavBar = jQuery.ThickBox.options.useNavBar;
		var useFloatNav = jQuery.ThickBox.options.useFloatNav;
		var overlayCaption = jQuery.ThickBox.options.overlayCaption;
		var isModal = false;
		
		// get additional config for this gallery
		if(imageGroup){
			if(imageGroup.indexOf('+navbar')>=0) useNavBar=true;
			if(imageGroup.indexOf('-navbar')>=0) useNavBar=false;
			if(imageGroup.indexOf('+floatnav')>=0) useFloatNav=true;
			if(imageGroup.indexOf('-floatnav')>=0) useFloatNav=false;
		}

		// #################### Code for a gallery of items
		// ############################################################
		var TB_Prev = false; var TB_PrevElt = null;
		var TB_Next = false; var TB_Next = null;
		var TB_ThisItem = 1;
		var TB_FoundURL = false;
		var TB_NumItems = 1;
		if(imageGroup){
			TB_TempArray = $("a[@rel="+imageGroup+"]").get();
			TB_NumItems = TB_TempArray.length;
			TB_ThisItem = 1+ $("a[@rel="+imageGroup+"]").index(element);
			if(TB_ThisItem){
				TB_FoundURL = true;
				if(TB_ThisItem>1) {
					TB_PrevElt = TB_TempArray[TB_ThisItem-1 -1];
					TB_Prev = true;
				}
				if(TB_ThisItem<TB_NumItems){
					TB_NextElt = TB_TempArray[TB_ThisItem+1 -1];
					TB_Next = true;
				}
			}
		}
		// ############################################################
		// ####################
		
		// #################### goprev / gonext
		// ############################################################
		function goPrev()
		{
			if(TB_Prev == true){
				$("#TB_window").remove();
				$("body").append("<div id='TB_window'></div>");
				tb_show(TB_PrevElt);
			}
			return false;
		}
		function goNext()
		{
			if(TB_Next == true){
				$("#TB_window").remove();
				$("body").append("<div id='TB_window'></div>");
				tb_show(TB_NextElt);
			}
			return false;
		}
		// ############################################################
		// ####################

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images

			imgPreloader = new Image();
			imgPreloader.onload = function(){
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			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
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			
			// ##### Compose the image and surrounds html to add to the TB_window
			var tbwinHTML = "<img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' />"
			var secondLine = eval(jQuery.ThickBox.options.imageXofYEVAL)
				+ (TB_Prev ? jQuery.ThickBox.options.prevHTML :"")
				+ (TB_Next ? jQuery.ThickBox.options.nextHTML : "");
			if(TB_NumItems==1 || !useFloatNav)
				tbwinHTML = "<a href='' id='TB_ImageOff' title='Close'>"+tbwinHTML+"</a>";
			if(caption)
				tbwinHTML += "<div id='TB_caption'>"+caption+"</div>";
			if(TB_NumItems>1 && secondLine)
				tbwinHTML += "<div id='TB_secondLine'>" + secondLine + "</div>";
			tbwinHTML += "<div id='TB_closeWindow'>" + jQuery.ThickBox.options.closeHTML + "</div>";
			$("#TB_window").append(tbwinHTML);
			$("#TB_Image").attr("alt",caption);
			// ############################################################
			
			$("#TB_closeWindowButton").click(tb_remove);
			if (TB_Prev) { $("#TB_prev").click(goPrev); }
			if (TB_Next) { $("#TB_next").click(goNext); }
			
			// ##### Floating Nav
			if(useFloatNav) {
			if(TB_Prev) {
				$("#TB_window").append('<a href="#" id="TB_FloatPrev"> </a>');
	 			$("#TB_FloatPrev").css({"left": 18,"top": 15,"width": imageWidth*2/5,"height":imageHeight});
				$("#TB_FloatPrev").click(goPrev);
			}
			if(TB_Next) {
				$("#TB_window").append('<a href="#" id="TB_FloatNext"> </a>');
				$("#TB_FloatNext").css({"right": 18,"top": 15,"width": imageWidth*2/5,"height":imageHeight});
				$("#TB_FloatNext").click(goNext);
			}
			}
			// ############################################################
			
			document.onkeydown = function(e){
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(jQuery.ThickBox.keyCodes[keycode] != undefined) {
					eval(jQuery.ThickBox.keyCodes[keycode]);
				} else
				switch(keycode) {
				case 27: // esc : close
					tb_remove();
					break;
				// case 33: // page up
				case 39: // [->]
				// case 190: // [,]
					// display previous image
					if(TB_Next){
						document.onkeydown = "";
						goNext();
					}
					break;
				// case 32: // space
				// case 34: // page down
				case 37: // [<-]
				// case 188: // [.]
					// display next image
					if(TB_Prev){
						document.onkeydown = "";
						goPrev();
					}
					break;
				}
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_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 = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			// make sure you can browse through items, except if on a modal
			if(TB_NumItems>1) useNavBar=true;
			if(params['modal']=="true") isModal = true;

			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window
				urlNoQuery = url.split('TB_');
				$("#TB_iframeContent").remove();
				if(params['modal'] != "true"){//iframe no modal : window bar
					$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'>"+jQuery.ThickBox.options.closeHTML+"</div></div>");
				}else{//iframe modal
					$("#TB_overlay").unbind();
				}
				$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
			}else{// not an iframe, ajax
				if($("#TB_window").css("display") != "block"){
					if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'>"+jQuery.ThickBox.options.closeHTML+"</div></div>");
					}else{//ajax modal
						$("#TB_overlay").unbind();
					}
					$("#TB_window").append("<div id='TB_ajaxContent' class='TB_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
					$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
					$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
					$("#TB_ajaxContent")[0].scrollTop = 0;
					$("#TB_ajaxWindowTitle").html(caption);
				}
			}
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if(url.indexOf('TB_inline') != -1){
				$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
				$("#TB_window").unload(function () {
					$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
				});
				tb_position();
				$("#TB_load").remove();
				$("#TB_window").css({display:"block"});
			}else if(url.indexOf('TB_iframe') != -1){
				tb_position();
				if($.browser.safari){//safari needs help because it will not fire iframe onload
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"});
				}
			}else{
				$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
					tb_position();
					$("#TB_load").remove();
					tb_init("#TB_ajaxContent a.thickbox");
					$("#TB_window").css({display:"block"});
				});
			}
		}

		// ##### Nav Bar
		if(useNavBar && !isModal) {
			$("#TBbarrenav").remove();
			$("body").append('<div id="TBbarrenav">'+'<div id="TBclose"><a href="#"><img src="'+jQuery.ThickBox.options.imagesDir+jQuery.ThickBox.options.navBarClose+'"/></a></div>'+'<div id="TBmiddle">'+(TB_NumItems>1?'<img id="TBprev" class="left" src="'+jQuery.ThickBox.options.imagesDir+jQuery.ThickBox.options.navBarPrev+'"/><span>' + TB_ThisItem + '&nbsp;/&nbsp;' + (TB_TempArray.length) + '</span><img id="TBnext" class="right disabled" src="'+jQuery.ThickBox.options.imagesDir+jQuery.ThickBox.options.navBarNext+'"/>':"")+'</div></div>');
			$("#TBclose").click(tb_remove);
			if(TB_Prev) $("#TBprev").click(goPrev); else $("#TBprev").hide();
			if(TB_Next) $("#TBnext").click(goNext); else $("#TBnext").hide();
			if(TB_NumItems==1) $("#TBbarrenav #TBmiddle span").hide();
		} else { // should not be necessary
			$("#TBbarrenav").remove();
		}
		// ############################################################

		if(!isModal){
			document.onkeyup = function(e){
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}
			};
		}
		
		if(overlayCaption && !isModal && document.getElementById("TB_overlayCaption") === null){
			$("#TB_overlay").append('<div id="TB_overlayCaption">'+jQuery.ThickBox.options.overlayCaption+'</div>');
		}

	} catch(e) {
		//nothing here
		// alert(e);
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect,#TBbarrenav').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_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 tb_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 tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}
