/*
 * Thickbox 3.1 (modified)
 */

var tb_pathToImage = "../images/thickbox-loading.gif";

// on page load call tb_init
$(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//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 tb_init(domChunk){
	$(domChunk).click(function(){
		var caption = this.title || this.name || null;
		var url = this.href || this.alt;
		var imageGroup = this.rel || false;
		tb_show (caption, url, imageGroup, false);
		this.blur();
		return false;
	});
}

// function called when the user clicks on a thickbox link
function tb_show(caption, url, imageGroup, highRes) {

	try {
		// if IE 6
		if (typeof document.body.style.maxHeight === "undefined") {
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			//iframe to hide select elements in ie6
			if (document.getElementById("tb-hideSelect") === null) {
				$("body").append("<iframe id='tb-hideSelect'></iframe><div id='tb-overlay'></div><div id='tb-window'></div>");
				$("#tb-overlay").click(tb_remove);
			}
		// all others
		} else {
			if(document.getElementById("tb-overlay") === null) {
				$("body").append("<div id='tb-overlay'></div><div id='tb-window'></div>");
				$("#tb-overlay").click(tb_remove);
			}
		}
		
		// use png overlay so hide flash
		if (tb_detectMacXFF()) {
			$("#tb-overlay").addClass("tb-overlay-Mac-FFBGHack");
		// use background and opacity
		} else {
			$("#tb-overlay").addClass("tb-overlay-bg");
		}
		
		if (caption===null) {caption="";}
		$("body").append("<div id='tb-load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#tb-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
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
					if (!(TB_TempArray[TB_Counter].href == url)) {
						if (TB_FoundURL) {
							TB_NextCaption = TB_TempArray[TB_Counter].title;
							TB_NextURL = TB_TempArray[TB_Counter].href;
							TB_NextHTML = "<span id='tb-next'> &nbsp;&nbsp;&nbsp; <a href='#' title='next View of Style " + imageGroup + "'> n e x t  &raquo; </a></span>";
						} else {
							TB_PrevCaption = TB_TempArray[TB_Counter].title;
							TB_PrevURL = TB_TempArray[TB_Counter].href;
							TB_PrevHTML = "<span id='tb-prev'><a href='#' title='previous View of Style " + imageGroup + "'>  &laquo; p r e v </a> &nbsp;&nbsp;&nbsp; </span>";
						}
					} else {
						TB_FoundURL = true;
						TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);
					}
				}
			}
			
			imgPreloader = new Image();
			imgPreloader.onload = function(){
			imgPreloader.onload = null;
			
			// resize large images
			var pagesize = tb_getPageSize();
			if (highRes) {
				var x = pagesize[0] - 0;
				var y = pagesize[1] - 60;
			} else {
				var x = pagesize[0] - 0;
				var y = pagesize[1] - 90;
			}
			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;
				}
			}
			
			// size the TB window around the image
			if (highRes) {
				TB_WIDTH = imageWidth + 0;
				TB_HEIGHT = imageHeight + 40;
			} else {
				TB_WIDTH = imageWidth + 0;
				TB_HEIGHT = imageHeight + 60;
			}
			
			// get cookie values and check if image already exists in favorites
			var cookieExists = false;
			var cookieValues = $.cookie('JoliFavs');
			var cookieArray = [];
			if (cookieValues != null) {
				cookieArray = cookieValues.split(",");
				for (var citt=0; citt < cookieArray.length; citt++) {
					if (cookieArray[citt] == imageGroup) {
						cookieExists = true;
					}
				}
			}
			
			// set the 'change favorite' html
			var changeFavHTML = "";
			var addFavHTML = "<a href='#' id='tb-changeFav' title='add Style " + imageGroup + " to My Favorites'>add to Favorites</a>";
			var removeFavHTML = "<a href='#' id='tb-changeFav' title='remove Style " + imageGroup + " from My Favorites'>remove from Favorites</a>";
			if (cookieExists) {
				changeFavHTML = removeFavHTML;
			} else {
				changeFavHTML = addFavHTML;
			}
			
			// create HTML to insert the image and it's controls
			if (highRes) {
				$("#tb-window").append(
					"<a href='#' id='tb-nullify' title='use mouse buttons and wheel to Zoom and Pan'>" +
						"<div><img id='tb-image' src='" + url + "' width='" + imageWidth + "' height='" + imageHeight + "' alt='Bridal Dress Style " + imageGroup + "' title='use the  +  and  -  buttons at top left of image to Zoom and the mouse to Pan' onLoad='shiftzoom.add(this);' /></div>" +
					"</a>" +
					"<div id='tb-caption'>" +
						"<div id='tb-caption-line'>" +
							"Style " + imageGroup +
							"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
							"<a href='#' id='tb-closeWindowButton' title='close High-res Image Viewer'> c l o s e </a>" +
						"</div>" +
					"</div>"
				);
			} else {
				$("#tb-window").append(
					"<a href='#' id='tb-highres' title='open High-res Image of Style " + imageGroup + "'>" +
						"<div><img id='tb-image' src='" + url + "' width='" + imageWidth + "' height='" + imageHeight + "' alt='Bridal Dress Style " + imageGroup + "' title='open High-res Image of Style " + imageGroup + "' /></div>" +
					"</a>" +
					"<div id='tb-caption'>" +
						"<div id='tb-caption-line'>" +
							"Style " + imageGroup +
							"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
							"<a href='#' id='tb-closeWindowButton' title='close Image Viewer'> c l o s e </a>" +
						"</div>" +
						"<div id='tb-caption-line'>" + TB_PrevHTML + TB_imageCount + TB_NextHTML + "</div>" +
						"<div id='tb-caption-line'>" +
							changeFavHTML +
							"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
							"<a href='#' id='tb-highres-text' title='open High-res Image of Style " + imageGroup + "'>open High-res</a>" +
						"</div>" +
					"</div>"
				);
			}
			
			// prev image
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					$("#tb-window").remove();
					$("body").append("<div id='tb-window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup, false);
					return false;
				}
				$("#tb-prev").click(goPrev);
			}
			
			// next image
			if (!(TB_NextHTML === "")) {
				function goNext(){
					$("#tb-window").remove();
					$("body").append("<div id='tb-window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup, false);
					return false;
				}
				$("#tb-next").click(goNext);
			}
			
			// change Favorites
			function changeFav() {				
				if (cookieExists) {
					// change text in TB, remove image from favorites gallery
					$('#tb-changeFav').html(addFavHTML);
					$('.container-favorites #' + imageGroup).hide();
					// remove the image from the favorites cookie
					for (var citt=0; citt < cookieArray.length; citt++) {
						if (cookieArray[citt] == imageGroup) {
							cookieArray.splice(citt,1);
						}
					}
					cookieValues = cookieArray.join();
					$.cookie('JoliFavs', cookieValues, {expires:365});
					cookieExists = false;
				} else {
					// add the image to the favorites cookie
					cookieArray[cookieArray.length] = imageGroup;
					cookieValues = cookieArray.join();
					$.cookie('JoliFavs', cookieValues, {expires:365});
					// change text in TB, add image to favorites gallery
					$('#tb-changeFav').html(removeFavHTML);
					$('.container-favorites #' + imageGroup).show();
					cookieExists = true;
				}
				return false;
			}
			$("#tb-changeFav").click(changeFav);
			
			// load high-res image
			function loadHighRes(){
				$("#tb-window").remove();
				$("body").append("<div id='tb-window'></div>");
				url = url.replace(/medium/i, "large");
				tb_show(caption, url, imageGroup, true);
				return false;
			}
			$("#tb-highres").click(loadHighRes);
			$("#tb-highres-text").click(loadHighRes);
			
			// if high-res image do nothing on image click
			function goNullify(){
				return false;
			}
			$("#tb-nullify").click(goNullify);
			
			// close image
			function tb_removeHighRes(){
				$("#tb-window").remove();
				$("body").append("<div id='tb-window'></div>");
				url = url.replace(/large/i, "medium");
				tb_show(caption, url, imageGroup, false);
				return false;
			}
			if (highRes) {
				$("#tb-closeWindowButton").click(tb_removeHighRes);
			} else {
				$("#tb-closeWindowButton").click(tb_remove);
			}
			
			// key controllers
			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#tb-load").remove();
			$("#tb-imageOff").click(tb_remove);
			$("#tb-window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}
		
		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
	
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#tb-load").remove();
	$("#tb-window").css({display:"block"});
}

function tb_remove() {
 	$("#tb-imageOff").unbind("click");
	$("#tb-closeWindowButton").unbind("click");
	$("#tb-window").fadeOut("fast",function(){$('#tb-window,#tb-overlay,#tb-hideSelect').trigger("unload").unbind().remove();});
	$("#tb-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 tb_position() {
	$("#tb-window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#tb-window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_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 tb_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 tb_detectMacXFF() {
	var userAgent = navigator.userAgent.toLowerCase();
	if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
		return true;
	}
}
