/*
 * 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 tb_pathToImage = "../image/elements/loadingAnimation.gif";

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

//on page load call tbv2_init
$(document).ready(function(){   
	tbv2_init('a.popup_content');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

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

function tbv2_show(caption, url, imageGroup, original_class) {//function called when the user clicks on a thickbox link
	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TBv2_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TBv2_HideSelect'></iframe><div id='TBv2_overlay'></div><div id='TBv2_window'></div>");
				$("#TBv2_overlay").click(tbv2_remove);
			}
		}else{//all others
			if(document.getElementById("TBv2_overlay") === null){
				$("body").append("<div id='TBv2_overlay'></div><div id='TBv2_window'></div>");
				$("#TBv2_overlay").click(tbv2_remove);
			}
		}
		
		if(tbv2_detectMacXFF()){
			$("#TBv2_overlay").addClass("TBv2_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TBv2_overlay").addClass("TBv2_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TBv2_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TBv2_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
				
			TBv2_PrevCaption = "";
			TBv2_PrevURL = "";
			TBv2_PrevHTML = "";
			TBv2_NextCaption = "";
			TBv2_NextURL = "";
			TBv2_NextHTML = "";
			TBv2_imageCount = "";
			TBv2_FoundURL = false;
			if(imageGroup){
				TBv2_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TBv2_Counter = 0; ((TBv2_Counter < TBv2_TempArray.length) && (TBv2_NextHTML === "")); TBv2_Counter++) {
					var urlTypeTemp = TBv2_TempArray[TBv2_Counter].href.toLowerCase().match(urlString);
						if (!(TBv2_TempArray[TBv2_Counter].href == url)) {						
							if (TBv2_FoundURL) {
								TBv2_NextCaption = TBv2_TempArray[TBv2_Counter].title;
								TBv2_NextURL = TBv2_TempArray[TBv2_Counter].href;
								TBv2_NextHTML = "<span id='TBv2_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TBv2_PrevCaption = TBv2_TempArray[TBv2_Counter].title;
								TBv2_PrevURL = TBv2_TempArray[TBv2_Counter].href;
								TBv2_PrevHTML = "<span id='TBv2_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TBv2_FoundURL = true;
							TBv2_imageCount = "Image " + (TBv2_Counter + 1) +" of "+ (TBv2_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tbv2_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
			
			TBv2_WIDTH = imageWidth + 30;
			TBv2_HEIGHT = imageHeight + 60;
			$("#TBv2_window").append("<a href='' id='TBv2_ImageOff' title='Close'><img id='TBv2_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TBv2_caption'>"+caption+"<div id='TBv2_secondLine'>" + TBv2_imageCount + TBv2_PrevHTML + TBv2_NextHTML + "</div></div><div id='TBv2_closeWindow'><a href='#' id='TBv2_closeWindowButton' title='Close'><img src='../images/popups/popupv2_close.gif' width='15' height='15'></a> or Esc Key</div>"); 		
			
			$("#TBv2_closeWindowButton").click(tbv2_remove);
			
			if (!(TBv2_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TBv2_window").remove();
					$("body").append("<div id='TBv2_window'></div>");
					tbv2_show(TBv2_PrevCaption, TBv2_PrevURL, imageGroup);
					return false;	
				}
				$("#TBv2_prev").click(goPrev);
			}
			
			if (!(TBv2_NextHTML === "")) {		
				function goNext(){
					$("#TBv2_window").remove();
					$("body").append("<div id='TBv2_window'></div>");
					tbv2_show(TBv2_NextCaption, TBv2_NextURL, imageGroup);				
					return false;	
				}
				$("#TBv2_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tbv2_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TBv2_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TBv2_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tbv2_position();
			$("#TBv2_load").remove();
			$("#TBv2_ImageOff").click(tbv2_remove);
			$("#TBv2_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 = tbv2_parseQuery( queryString );

			TBv2_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TBv2_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TBv2_WIDTH;
			ajaxContentH = TBv2_HEIGHT;
			
			if(url.indexOf('TBv2_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TBv2_');
					$("#TBv2_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TBv2_window").append("<div id='TBv2_title'><div id='TBv2_ajaxWindowTitle'>"+caption+"</div><div id='TBv2_closeAjaxWindow'><a href='#' id='TBv2_closeWindowButton' title='Close'><img src='../images/popups/popupv2_close.gif' width='15' height='15'></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TBv2_iframeContent' name='TBv2_iframeContent"+Math.round(Math.random()*1000)+"' onload='tbv2_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TBv2_overlay").unbind();
						$("#TBv2_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TBv2_iframeContent' name='TBv2_iframeContent"+Math.round(Math.random()*1000)+"' onload='tbv2_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TBv2_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						
						$("#TBv2_window").append("<div class='TBv2_bg'><div id='TBv2_title'><div id='TBv2_ajaxWindowTitle'>"+caption+"</div><div id='TBv2_closeAjaxWindow'><a href='#' id='TBv2_closeWindowButton'><img src='../images/popups/popupv2_close.gif' width='15' height='15'></a></div></div><div id='TBv2_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div></div> ");
						
						}else{//ajax modal
						$("#TBv2_overlay").unbind();
						$("#TBv2_window").append("<div id='TBv2_ajaxContent' class='TBv2_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
						$("#TBv2_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TBv2_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TBv2_ajaxContent")[0].scrollTop = 0;
						$("#TBv2_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TBv2_closeWindowButton").click(tbv2_remove);
			
				if(url.indexOf('TBv2_inline') != -1){	
					$("#TBv2_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TBv2_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TBv2_ajaxContent").children() ); // move elements back when you're finished
					});
					tbv2_position();
					$("#TBv2_load").remove();
					$("#TBv2_window").css({display:"block"}); 
				}else if(url.indexOf('TBv2_iframe') != -1){
					tbv2_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TBv2_load").remove();
						$("#TBv2_window").css({display:"block"});
					}
				}else{
					$("#TBv2_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tbv2_position();
						$("#TBv2_load").remove();
						tbv2_init("#TBv2_ajaxContent a.popup_content");
						$("#TBv2_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
					tbv2_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tbv2_showIframe(){
	$("#TBv2_load").remove();
	$("#TBv2_window").css({display:"block"});
}

function tbv2_remove() {
 	$("#TBv2_imageOff").unbind("click");
	$("#TBv2_closeWindowButton").unbind("click");
	$("#TBv2_window").fadeOut("fast",function(){$('#TBv2_window,#TBv2_overlay,#TBv2_HideSelect').trigger("unload").unbind().remove();});
	$("#TBv2_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 tbv2_position() {
$("#TBv2_window").css({marginLeft: '-' + parseInt((TBv2_WIDTH / 2),10) + 'px', width: TBv2_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TBv2_window").css({marginTop: '-' + parseInt((TBv2_HEIGHT / 2),10) + 'px'});
	}
}

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