/*
 * 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 cb_pathToImage = "images/loadingAnimation.gif";

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

//on page load call cb_init
jQuery(document).ready(function(){  
	cb_init('a.cakebox, area.cakebox, input.cakebox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = cb_pathToImage;
});

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

function cb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
	
	//console.log(caption+"::"+url+"::"+imageGroup);
	
	try {
		
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			jQuery("body","html").css({height: "100%", width: "100%"});
			jQuery("html").css("overflow","hidden");
			if (document.getElementById("cb_HideSelect") === null) {//iframe to hide select elements in ie6
				jQuery("body").append("<iframe id='cb_HideSelect'></iframe><div id='cb_overlay'></div><div id='cb_window'></div>");
				jQuery("#cb_overlay").click(cb_remove);
			}
		}else{//all others
			if(document.getElementById("cb_overlay") === null){
				jQuery("body").append("<div id='cb_overlay'></div><div id='cb_window'></div>");
				jQuery("#cb_overlay").click(cb_remove);
			}
		}
		
		if(cb_detectMacXFF()){
			jQuery("#cb_overlay").addClass("cb_overlay-mac-ff-background-hack");//use png overlay so hide flash
		}else{
			jQuery("#cb_overlay").addClass("cb_overlay-background");//use background and opacity
		}
		
		if(caption===null){caption="";}
		
		jQuery("body").append("<div id='cb_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		jQuery('#cb_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
				
			cb_PrevCaption = "";
			cb_PrevURL = "";
			cb_PrevHTML = "";
			cb_NextCaption = "";
			cb_NextURL = "";
			cb_NextHTML = "";
			cb_imageCount = "";
			cb_FoundURL = false;

			if(imageGroup){
				cb_TempArray = jQuery("a[@rel="+imageGroup+"]").get();
				for (cb_Counter = 0; ((cb_Counter < cb_TempArray.length) && (cb_NextHTML === "")); cb_Counter++) {
					var urlTypeTemp = cb_TempArray[cb_Counter].href.toLowerCase().match(urlString);
						if (!(cb_TempArray[cb_Counter].href == url)) {						
							if (cb_FoundURL) {
								cb_NextCaption = cb_TempArray[cb_Counter].title;
								cb_NextURL = cb_TempArray[cb_Counter].href;
								cb_NextHTML = "<a id='cb_next' href='#'>Next &gt;</a>";
							} else {
								cb_PrevCaption = cb_TempArray[cb_Counter].title;
								cb_PrevURL = cb_TempArray[cb_Counter].href;
								cb_PrevHTML = "<a id='cb_prev' href='#'>&lt; Prev</a>";
							}
						} else {
							cb_FoundURL = true;
							cb_imageCount = "Image " + (cb_Counter + 1) +" of "+ (cb_TempArray.length);											
						}
					}
				}
	
				imgPreloader = new Image();
				imgPreloader.onload = function(){		
				imgPreloader.onload = null;
	
				// preload patch from: http://drupal.org/files/issues/thickbox_preloadimage.patch
				prevImg = new Image();
				nextImg = new Image();
				var cb_links = jQuery('a[@class="thickbox"]');
				var i = -1;
				cb_links.each(function(n) { if (this.href == imgPreloader.src) { i = n; } });
				if (i != -1) {
					if (i > 0) { prevImg.src = cb_links[i-1].href; }
					if (i+1 < cb_links.length) { nextImg.src = cb_links[i+1].href; }
				}
		
		
				// Resizing large images - orginal by Christian Montoya edited by me.
				var pagesize = cb_getPageSize();
				var x = pagesize[0] - 150;
				var y = pagesize[1] - 170;
				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
					
					
				/* TODO: auto-calculate heights based on jQuery.height() of elements */
				cb_WIDTH = imageWidth + 30;
				cb_HEIGHT = imageHeight + 130;
				jQuery("#cb_window").append("<div id='cb_ImageWrapper' style='height:"+imageHeight+"px;width:"+imageWidth+"px;'><img id='cb_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></div><div id='cb_ImageHoverNav'>"+cb_PrevHTML+cb_NextHTML+"</div><div id='cb_caption'>"+caption+"<div id='cb_secondLine'>" + cb_imageCount + "</div></div>");
				jQuery("#cb_closeWindowButton").click(cb_remove);
					
				if (!(cb_PrevHTML === "")) {
					function goPrev(){
						if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);}
						jQuery("#cb_window").remove();
						jQuery("body").append("<div id='cb_window'></div>");
						cb_show(cb_PrevCaption, cb_PrevURL, imageGroup);
						return false;	
					}
					jQuery("#cb_prev").click(goPrev);
				}
					
				if (!(cb_NextHTML === "")) {		
					function goNext(){
						jQuery("#cb_window").remove();
						jQuery("body").append("<div id='cb_window'></div>");
						cb_show(cb_NextCaption, cb_NextURL, imageGroup);
						return false;
					}
					jQuery("#cb_next").click(goNext);
					
				}
		
				document.onkeydown = function(e){ 	
					if (e == null) { // ie
						keycode = event.keyCode;
					} else { // mozilla
						keycode = e.which;
					}
					if(keycode == 27){ // close
						cb_remove();
					} else if(keycode == 190 || keycode == 39){ // display next image
						if(!(cb_NextHTML == "")){
							document.onkeydown = "";
							goNext();
						}
					} else if(keycode == 188 || keycode == 37){ // display previous image
						if(!(cb_PrevHTML == "")){
							document.onkeydown = "";
							goPrev();
						}
					}	
				};
					
				cb_position();
				jQuery("#cb_load").remove();
				jQuery("#cb_ImageOff").click(cb_remove);
				jQuery("#cb_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 = cb_parseQuery( queryString );

			cb_WIDTH = (params['width']*1) || 630; //defaults to 630 if no paramaters were added to URL
			cb_HEIGHT = (params['height']*1) || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = cb_WIDTH;
			ajaxContentH = cb_HEIGHT;
		
			if(url.indexOf('cb_iframe') != -1) { // If we need to pull it in via iframe...
				urlNoQuery = url.split('cb_');
				jQuery("#cb_iframeContent").remove();
				if(params['modal'] != "true"){ //iframe no modal
					jQuery("#cb_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='cb_iframeContent' name='cb_iframeContent"+Math.round(Math.random()*1000)+"' onload='cb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
				}else{//iframe modal
					jQuery("#cb_overlay").unbind();
					jQuery("#cb_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='cb_iframeContent' name='cb_iframeContent"+Math.round(Math.random()*1000)+"' onload='cb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
				}
			} else { // not an iframe, ajax
				if(jQuery("#cb_window").css("display") != "block") {
					//console.log('ajax');
					if(params['modal'] != "true"){ //ajax no modal
						//console.log('ajax no modal');
						jQuery("#cb_window").append("<div id='cb_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
					} else { //ajax modal
						//console.log('ajax modal');
						jQuery("#cb_overlay").unbind();
						jQuery("#cb_window").append("<div id='cb_ajaxContent' class='cb_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
					jQuery("#cb_ajaxContent")[0].style.width = ajaxContentW +"px";
					jQuery("#cb_ajaxContent")[0].style.height = ajaxContentH +"px";
					jQuery("#cb_ajaxContent")[0].scrollTop = 0;
					jQuery("#cb_ajaxWindowTitle").html(caption);
				}
			}
				
			jQuery("#cb_closeWindowButton").click(cb_remove);
	
			if(url.indexOf('cb_inline') != -1){	
				jQuery("#cb_ajaxContent").append(jQuery('#' + params['inlineId']).children());
				jQuery("#cb_window").unload(function () {
					jQuery('#' + params['inlineId']).append( jQuery("#cb_ajaxContent").children() ); // move elements back when you're finished
				});
				cb_position();
				jQuery("#cb_load").remove();
				jQuery("#cb_window").css({display:"block"}); 
			}else if(url.indexOf('cb_iframe') != -1){
				cb_position();
				if($.browser.safari){//safari needs help because it will not fire iframe onload
					jQuery("#cb_load").remove();
					jQuery("#cb_window").css({display:"block"});
				}
				}else{
					jQuery("#cb_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						cb_position();
						jQuery("#cb_load").remove();
						cb_init("#cb_ajaxContent a.thickbox");
						jQuery("#cb_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
						cb_remove();
					}	
				};
			}
				
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function cb_showIframe(){
	jQuery("#cb_load").remove();
	jQuery("#cb_window").css({display:"block"});
}

function cb_remove() {
 	jQuery("#cb_imageOff").unbind("click");
	jQuery("#cb_closeWindowButton").unbind("click");
	jQuery("#cb_window").fadeOut("fast",function(){jQuery('#cb_window,#cb_overlay,#cb_HideSelect').trigger("unload").unbind().remove();});
	jQuery("#cb_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		jQuery("body","html").css({height: "auto", width: "auto"});
		jQuery("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function cb_position() {
jQuery("#cb_window").css({marginLeft: '-' + parseInt((cb_WIDTH / 2),10) + 'px', width: cb_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		jQuery("#cb_window").css({marginTop: '-' + parseInt((cb_HEIGHT / 2),10) + 'px'});
	}
}

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