/*
 *.thickbox_top 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 TBtop_pathToImage = "_images/loadingAnimation.gif";

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

//on page load call TBtop_init
$(document).ready(function(){   
	TBtop_init('a.thickbox_top, area.thickbox_top, input.thickbox_top');//pass where to apply.thickbox_top
	imgLoader = new Image();// preload image
	imgLoader.src = TBtop_pathToImage;
});

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

function TBtop_show(caption, url, imageGroup) {//function called when the user clicks on a.thickbox_top 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("TBtop_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TBtop_HideSelect'></iframe><div id='TBtop_overlay'></div><div id='TBtop_window'></div>");
				$("#TBtop_overlay").click(TBtop_remove);
			}
		}else{//all others
			if(document.getElementById("TBtop_overlay") === null){
				$("body").append("<div id='TBtop_overlay'></div><div id='TBtop_window'></div>");
				$("#TBtop_overlay").click(TBtop_remove);
			}
		}
		
		if(TBtop_detectMacXFF()){
			$("#TBtop_overlay").addClass("TBtop_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TBtop_overlay").addClass("TBtop_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TBtop_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TBtop_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
				
			TBtop_PrevCaption = "";
			TBtop_PrevURL = "";
			TBtop_PrevHTML = "";
			TBtop_NextCaption = "";
			TBtop_NextURL = "";
			TBtop_NextHTML = "";
			TBtop_imageCount = "";
			TBtop_FoundURL = false;
			if(imageGroup){
				TBtop_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TBtop_Counter = 0; ((TBtop_Counter < TBtop_TempArray.length) && (TBtop_NextHTML === "")); TBtop_Counter++) {
					var urlTypeTemp = TBtop_TempArray[TBtop_Counter].href.toLowerCase().match(urlString);
						if (!(TBtop_TempArray[TBtop_Counter].href == url)) {						
							if (TBtop_FoundURL) {
								TBtop_NextCaption = TBtop_TempArray[TBtop_Counter].title;
								TBtop_NextURL = TBtop_TempArray[TBtop_Counter].href;
								TBtop_NextHTML = "<span id='TBtop_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TBtop_PrevCaption = TBtop_TempArray[TBtop_Counter].title;
								TBtop_PrevURL = TBtop_TempArray[TBtop_Counter].href;
								TBtop_PrevHTML = "<span id='TBtop_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TBtop_FoundURL = true;
							TBtop_imageCount = "Image " + (TBtop_Counter + 1) +" of "+ (TBtop_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = TBtop_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
			
			TBtop_WIDTH = imageWidth + 30;
			TBtop_HEIGHT = imageHeight + 60;
			$("#TBtop_window").append("<a href='' id='TBtop_ImageOff' title='Close'><img id='TBtop_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TBtop_caption'>"+caption+"<div id='TBtop_secondLine'>" + TBtop_imageCount + TBtop_PrevHTML + TBtop_NextHTML + "</div></div><div id='TBtop_closeWindow'><a href='#' id='TBtop_closeWindowButton' title='Close'>X</a></div>"); 		
			
			$("#TBtop_closeWindowButton").click(TBtop_remove);
			
			if (!(TBtop_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TBtop_window").remove();
					$("body").append("<div id='TBtop_window'></div>");
					TBtop_show(TBtop_PrevCaption, TBtop_PrevURL, imageGroup);
					return false;	
				}
				$("#TBtop_prev").click(goPrev);
			}
			
			if (!(TBtop_NextHTML === "")) {		
				function goNext(){
					$("#TBtop_window").remove();
					$("body").append("<div id='TBtop_window'></div>");
					TBtop_show(TBtop_NextCaption, TBtop_NextURL, imageGroup);				
					return false;	
				}
				$("#TBtop_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					TBtop_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TBtop_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TBtop_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			TBtop_position();
			$("#TBtop_load").remove();
			$("#TBtop_ImageOff").click(TBtop_remove);
			$("#TBtop_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 = TBtop_parseQuery( queryString );

			TBtop_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TBtop_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TBtop_WIDTH - 30;
			ajaxContentH = TBtop_HEIGHT - 45;
			
			if(url.indexOf('TBtop_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TBtop_');
					$("#TBtop_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TBtop_window").append("<div id='TBtop_title'><div id='TBtop_ajaxWindowTitle'>"+caption+"</div><div id='TBtop_closeAjaxWindow'><a href='#' id='TBtop_closeWindowButton' title='Close'></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TBtop_iframeContent' name='TBtop_iframeContent"+Math.round(Math.random()*1000)+"' onload='TBtop_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TBtop_overlay").unbind();
						$("#TBtop_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TBtop_iframeContent' name='TBtop_iframeContent"+Math.round(Math.random()*1000)+"' onload='TBtop_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TBtop_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TBtop_window").append("<div id='TBtop_title'><div id='TBtop_ajaxWindowTitle'>"+caption+"</div><div id='TBtop_closeAjaxWindow'><a href='#' id='TBtop_closeWindowButton'></a></div></div><div id='TBtop_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TBtop_overlay").unbind();
						$("#TBtop_window").append("<div id='TBtop_ajaxContent' class='TBtop_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
						$("#TBtop_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TBtop_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TBtop_ajaxContent")[0].scrollTop = 0;
						$("#TBtop_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TBtop_closeWindowButton").click(TBtop_remove);
			
				if(url.indexOf('TBtop_inline') != -1){	
					$("#TBtop_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TBtop_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TBtop_ajaxContent").children() ); // move elements back when you're finished
					});
					TBtop_position();
					$("#TBtop_load").remove();
					$("#TBtop_window").css({display:"block"}); 
				}else if(url.indexOf('TBtop_iframe') != -1){
					TBtop_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TBtop_load").remove();
						$("#TBtop_window").css({display:"block"});
					}
				}else{
					$("#TBtop_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						TBtop_position();
						$("#TBtop_load").remove();
						TBtop_init("#TBtop_ajaxContent a.thickbox_top");
						$("#TBtop_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
					TBtop_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function TBtop_showIframe(){
	$("#TBtop_load").remove();
	$("#TBtop_window").css({display:"block"});
}

function TBtop_remove() {
 	$("#TBtop_imageOff").unbind("click");
	$("#TBtop_closeWindowButton").unbind("click");
	$("#TBtop_window").fadeOut("fast",function(){$('#TBtop_window,#TBtop_overlay,#TBtop_HideSelect').trigger("unload").unbind().remove();});
	$("#TBtop_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 TBtop_position() {
$("#TBtop_window").css({marginLeft: '-' + parseInt((TBtop_WIDTH / 2),10) + 'px', width: TBtop_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TBtop_window").css({marginTop: '-' + parseInt((TBtop_HEIGHT / 2),10) + 'px'});
	}
}

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


