/*
 * 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 fb_pathToImage = "images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call fb_init
$(document).ready(function(){   
	fb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = fb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function fb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	fb_show(t,a,g);
	this.blur();
	return false;
	});
}

function fb_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("FB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='FB_HideSelect'></iframe><div id='FB_overlay'></div><div id='FB_window'></div>");
				$("#FB_overlay").click(fb_remove);
			}
		}else{//all others
			if(document.getElementById("FB_overlay") === null){
				$("body").append("<div id='FB_overlay'></div><div id='FB_window'></div>");
				$("#FB_overlay").click(fb_remove);
			}
		}
		
		if(fb_detectMacXFF()){
			$("#FB_overlay").addClass("FB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#FB_overlay").addClass("FB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='FB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#FB_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
				
			FB_PrevCaption = "";
			FB_PrevURL = "";
			FB_PrevHTML = "";
			FB_NextCaption = "";
			FB_NextURL = "";
			FB_NextHTML = "";
			FB_imageCount = "";
			FB_FoundURL = false;
			if(imageGroup){
				FB_TempArray = $("a[rel="+imageGroup+"]").get();
				for (FB_Counter = 0; ((FB_Counter < FB_TempArray.length) && (FB_NextHTML === "")); FB_Counter++) {
					var urlTypeTemp = FB_TempArray[FB_Counter].href.toLowerCase().match(urlString);
						if (!(FB_TempArray[FB_Counter].href == url)) {						
							if (FB_FoundURL) {
								FB_NextCaption = FB_TempArray[FB_Counter].title;
								FB_NextURL = FB_TempArray[FB_Counter].href;
								FB_NextHTML = "<span id='FB_next'>��<a href='#'>Next ></a></span>";
							} else {
								FB_PrevCaption = FB_TempArray[FB_Counter].title;
								FB_PrevURL = FB_TempArray[FB_Counter].href;
								FB_PrevHTML = "<span id='FB_prev'>��<a href='#'>< Prev</a></span>";
							}
						} else {
							FB_FoundURL = true;
							FB_imageCount = "Image " + (FB_Counter + 1) +" of "+ (FB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = fb_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
			
			FB_WIDTH = imageWidth + 30;
			FB_HEIGHT = imageHeight + 60;
			$("#FB_window").append("<a href='' id='FB_ImageOff' title='Close'><img id='FB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='FB_caption'>"+caption+"<div id='FB_secondLine'>" + FB_imageCount + FB_PrevHTML + FB_NextHTML + "</div></div><div id='FB_closeWindow'><a href='#' id='FB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$("#FB_closeWindowButton").click(fb_remove);
			
			if (!(FB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#FB_window").remove();
					$("body").append("<div id='FB_window'></div>");
					fb_show(FB_PrevCaption, FB_PrevURL, imageGroup);
					return false;	
				}
				$("#FB_prev").click(goPrev);
			}
			
			if (!(FB_NextHTML === "")) {		
				function goNext(){
					$("#FB_window").remove();
					$("body").append("<div id='FB_window'></div>");
					fb_show(FB_NextCaption, FB_NextURL, imageGroup);				
					return false;	
				}
				$("#FB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					fb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(FB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(FB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			fb_position();
			$("#FB_load").remove();
			$("#FB_ImageOff").click(fb_remove);
			$("#FB_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 = fb_parseQuery( queryString );

			FB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			FB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = FB_WIDTH - 30;
			ajaxContentH = FB_HEIGHT - 45;
			
			if(url.indexOf('FB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('FB_');
					$("#FB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#FB_window").append("<div id='FB_title'><div id='FB_ajaxWindowTitle'>"+caption+"</div><div id='FB_closeAjaxWindow'><a href='#' id='FB_closeWindowButton' title='Close' style='color:#aa0101;'>close <img align='absbottom' src='images/close.gif' border='0' /></a></div></div><iframe frameborder='0' scrolling='no' hspace='0' src='"+urlNoQuery[0]+"' id='FB_iframeContent' name='FB_iframeContent"+Math.round(Math.random()*1000)+"' onload='fb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#FB_overlay").unbind();
						$("#FB_window").append("<iframe frameborder='0' scrolling='no' hspace='0' src='"+urlNoQuery[0]+"' id='FB_iframeContent' name='FB_iframeContent"+Math.round(Math.random()*1000)+"' onload='fb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#FB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#FB_window").append("<div id='FB_title'><div id='FB_ajaxWindowTitle'>"+caption+"</div><div id='FB_closeAjaxWindow'><a href='#' id='FB_closeWindowButton'>close</a> or Esc Key</div></div><div id='FB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#FB_overlay").unbind();
						$("#FB_window").append("<div id='FB_ajaxContent' class='FB_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
						$("#FB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#FB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#FB_ajaxContent")[0].scrollTop = 0;
						$("#FB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#FB_closeWindowButton").click(fb_remove);
			
				if(url.indexOf('FB_inline') != -1){	
					$("#FB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#FB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#FB_ajaxContent").children() ); // move elements back when you're finished
					});
					fb_position();
					$("#FB_load").remove();
					$("#FB_window").css({display:"block"}); 
				}else if(url.indexOf('FB_iframe') != -1){
					fb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#FB_load").remove();
						$("#FB_window").css({display:"block"});
					}
				}else{
					$("#FB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						fb_position();
						$("#FB_load").remove();
						fb_init("#FB_ajaxContent a.thickbox");
						$("#FB_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
					fb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function fb_showIframe(){
	$("#FB_load").remove();
	$("#FB_window").css({display:"block"});
}

function fb_remove() {
 	$("#FB_imageOff").unbind("click");
	$("#FB_closeWindowButton").unbind("click");
	$("#FB_window").fadeOut("fast",function(){$('#FB_window,#FB_overlay,#FB_HideSelect').trigger("unload").unbind().remove();});
	$("#FB_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 fb_position() {
//$("#FB_window").css({marginLeft: '-' + parseInt((FB_WIDTH / 2),10) + 'px', width: FB_WIDTH + 'px'});
$("#FB_window").css({marginLeft: '-' + parseInt((FB_WIDTH / 2),10) + 'px', width: parseInt(FB_WIDTH-1) + 'px'}); // fixed bleeding white on right edge
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
	    //$("#FB_window").css({ marginTop: '-' + parseInt((FB_HEIGHT / 2), 10) + 'px' });
	    $("#FB_window").css({ marginTop: '15px' });
	}
}

function fb_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 fb_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 fb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}


