/*
 * 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 thick_pathToImage = "images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call thick_init
$(document).ready(function(){   
	thick_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = thick_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function thick_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	thick_show(t,a,g);
	this.blur();
	return false;
	});
}

function thick_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
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("THICK_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='THICK_HideSelect'></iframe><div id='THICK_overlay'></div><div id='THICK_window'></div>");
				$("#THICK_overlay").click(thick_remove);
			}
		}else{//all others
			if(document.getElementById("THICK_overlay") === null){
				$("body").append("<div id='THICK_overlay'></div><div id='THICK_window'></div>");
				$("#THICK_overlay").click(thick_remove);
			}
		}
		
		if(thick_detectMacXFF()){
			$("#THICK_overlay").addClass("THICK_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#THICK_overlay").addClass("THICK_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='THICK_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#THICK_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
				
			THICK_PrevCaption = "";
			THICK_PrevURL = "";
			THICK_PrevHTML = "";
			THICK_NextCaption = "";
			THICK_NextURL = "";
			THICK_NextHTML = "";
			THICK_imageCount = "";
			THICK_FoundURL = false;
			if(imageGroup){
				THICK_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (THICK_Counter = 0; ((THICK_Counter < THICK_TempArray.length) && (THICK_NextHTML === "")); THICK_Counter++) {
					var urlTypeTemp = THICK_TempArray[THICK_Counter].href.toLowerCase().match(urlString);
						if (!(THICK_TempArray[THICK_Counter].href == url)) {						
							if (THICK_FoundURL) {
								THICK_NextCaption = THICK_TempArray[THICK_Counter].title;
								THICK_NextURL = THICK_TempArray[THICK_Counter].href;
								THICK_NextHTML = "<span id='THICK_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								THICK_PrevCaption = THICK_TempArray[THICK_Counter].title;
								THICK_PrevURL = THICK_TempArray[THICK_Counter].href;
								THICK_PrevHTML = "<span id='THICK_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							THICK_FoundURL = true;
							THICK_imageCount = "Image " + (THICK_Counter + 1) +" of "+ (THICK_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = thick_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
			
			THICK_WIDTH = imageWidth + 30;
			THICK_HEIGHT = imageHeight + 60;
			$("#THICK_window").append("<a href='' id='THICK_ImageOff' title='Close'><img id='THICK_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='THICK_caption'>"+caption+"<div id='THICK_secondLine'>" + THICK_imageCount + THICK_PrevHTML + THICK_NextHTML + "</div></div><div id='THICK_closeWindow'><a href='#' id='THICK_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$("#THICK_closeWindowButton").click(thick_remove);
			
			if (!(THICK_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#THICK_window").remove();
					$("body").append("<div id='THICK_window'></div>");
					thick_show(THICK_PrevCaption, THICK_PrevURL, imageGroup);
					return false;	
				}
				$("#THICK_prev").click(goPrev);
			}
			
			if (!(THICK_NextHTML === "")) {		
				function goNext(){
					$("#THICK_window").remove();
					$("body").append("<div id='THICK_window'></div>");
					thick_show(THICK_NextCaption, THICK_NextURL, imageGroup);				
					return false;	
				}
				$("#THICK_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					thick_remove();
				} else if(keycode == 190){ // display previous image
					if(!(THICK_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(THICK_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			thick_position();
			$("#THICK_load").remove();
			$("#THICK_ImageOff").click(thick_remove);
			$("#THICK_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 = thick_parseQuery( queryString );

			THICK_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			THICK_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = THICK_WIDTH - 30;
			ajaxContentH = THICK_HEIGHT - 45;
			// ############# add variable to refresh parent page on demand
			if(url.indexOf('Refreshparent') != -1)
				{THICK_RefreshParent = true;}
				else {THICK_RefreshParent = false;}
				// end add variable to refresh parent page on demand
			if(url.indexOf('THICK_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('THICK_');
					$("#THICK_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#THICK_window").append("<div id='THICK_title'><div id='THICK_ajaxWindowTitle'>"+caption+"</div><div id='THICK_closeAjaxWindow'><a href='#' id='THICK_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='THICK_iframeContent' name='THICK_iframeContent"+Math.round(Math.random()*1000)+"' onload='thick_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#THICK_overlay").unbind();
						$("#THICK_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='THICK_iframeContent' name='THICK_iframeContent"+Math.round(Math.random()*1000)+"' onload='thick_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#THICK_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#THICK_window").append("<div id='THICK_title'><div id='THICK_ajaxWindowTitle'>"+caption+"</div><div id='THICK_closeAjaxWindow'><a href='#' id='THICK_closeWindowButton'>close</a> or Esc Key</div></div><div id='THICK_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#THICK_overlay").unbind();
						$("#THICK_window").append("<div id='THICK_ajaxContent' class='THICK_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
						$("#THICK_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#THICK_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#THICK_ajaxContent")[0].scrollTop = 0;
						$("#THICK_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#THICK_closeWindowButton").click(thick_remove);
			
				if(url.indexOf('THICK_inline') != -1){	
					$("#THICK_ajaxContent").append($('#' + params['inlineId']).children());
					$("#THICK_window").unload(function () {
						$('#' + params['inlineId']).append( $("#THICK_ajaxContent").children() ); // move elements back when you're finished
					});
					thick_position();
					$("#THICK_load").remove();
					$("#THICK_window").css({display:"block"}); 
				}else if(url.indexOf('THICK_iframe') != -1){
					thick_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#THICK_load").remove();
						$("#THICK_window").css({display:"block"});
					}
				}else{
					$("#THICK_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						thick_position();
						$("#THICK_load").remove();
						thick_init("#THICK_ajaxContent a.thickbox");
						$("#THICK_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
					thick_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function thick_showIframe(){
	$("#THICK_load").remove();
	$("#THICK_window").css({display:"block"});
}

function thick_remove() {
 	$("#THICK_imageOff").unbind("click");
	$("#THICK_closeWindowButton").unbind("click");
	$("#THICK_window").fadeOut("fast",function(){$('#THICK_window,#THICK_overlay,#THICK_HideSelect').trigger("unload").unbind().remove();});
	$("#THICK_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 = "";
// Refresh parent page on demand
if (THICK_RefreshParent == true)
{var sURL = unescape(window.location.pathname);
window.location.reload( true );}
// end Refresh parent page on demand
	return false;
}

function thick_position() {
$("#THICK_window").css({marginLeft: '-' + parseInt((THICK_WIDTH / 2),10) + 'px', width: THICK_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#THICK_window").css({marginTop: '-' + parseInt((THICK_HEIGHT / 2),10) + 'px'});
	}
}

function thick_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 thick_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 thick_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}


