/*
 * 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
*/

/*
 * Thinbox is a simplification of the Thickbox plugin
 *     Code follows a similar structure but has been updated to best practices where possible
 * author: Colin Campbell (colin.campbell@draftfcb.com)
*/

;(function($) {
	
	var detectMacFF = function() {
		var userAgent = navigator.userAgent.toLowerCase();
		return userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1;
	};
	
	var parseQuery = function(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;
	};
	
	$.fn.center = function(options) {
		var $this = $(this);
		if (options.width) {
			$this.css({
				marginLeft: '-' + String(parseInt((options.width/2), 10)) + 'px',
				position: 'absolute',
				width: String(options.width) + 'px'
			});
		}
		
		if (options.height && $.support.boxModel) {
			$this.css({
				marginTop: '-' + String(parseInt((options.height/2), 10)) + 'px'
			});
		}
		return $this;
	};
	
	$.fn.thinbox = function(options) {
		var settings = $.extend(true, {}, $.thinbox.defaults, options);
		// preload the loading image
		(new Image()).src = settings.loader;
		
		return this.each(function() {
			$this = $(this);
			$this.click(function() {
				try {
					$.thinbox($.extend(true, {}, settings, {
						url:$this.attr('href')
					}));
					$this.blur();
				}
				catch(e) {
					$.thinbox.remove();
				}
				return false;
			});
		});
	};
	
	$.thinbox = function(url, options) {
		
		var settings = $.extend(true, {}, $.thinbox.defaults, options);
		
		var toAppend = "<div id='thinbox'><div class='overlay'></div><div class='window'></div><div class='closewindow'>" + settings.closeText +"</div></div>";
		
		// if IE6
	    if (typeof document.body.style.maxHeight === "undefined") {
			$("body","html").css({height: "100%", width: "100%"});
			toAppend = "<iframe id='hideselect'></iframe>" + toAppend;
		}
		
		if(document.getElementById("thinbox") === null) $("body").append(toAppend);
		
		var $thinbox = $("#thinbox");
		var $overlay = $(".overlay", $thinbox);
		var $window = $(".window", $thinbox).css('opacity', 0).hide();
		var $close = $(".closewindow", $thinbox).hide();
		
		// detect Mac Firefox, because it sucks with Flash showing through
		if (detectMacFF()) $overlay.addClass("macFF-hack");
		else $overlay.addClass("overlay-background");
		
		$overlay.mousedown($.thinbox.remove);
		$window.mousedown($.thinbox.remove);
		
		var $loader = $("<div class='loader'><img src='" + settings.loader + "' /></div>").appendTo($overlay).show();
		
		var type = url.toLowerCase().match(/\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/);

		if (type == '.jpg' || type == '.jpeg' || type == '.png' || type == '.gif' || type == '.bmp') {
			var preloader = new Image();
			preloader.onload = function() {
				preloader.onload = null;
				$window
					.append("<img class='content' src='" + url + "' width='" + preloader.width + "' height='" + preloader.height + "'/>")
					.center({width: preloader.width});
				
				$.thinbox.showContent();
			};
			preloader.src = url;
		}
		else {
			var query = url.replace(/^[^\?]+\??/,'');
			var params = parseQuery(query);
			
			var width = settings.width || params['width'] * 1;
			var height = settings.height || params['height'] * 1;
			
			// iframe or ajax window
			if (settings.useIFrame) {
				$window.append("<iframe frameborder='0' hspace='0' src='"+url+"' class='content' name='content"+Math.round(Math.random()*1000)+"' onload='$.thinbox.showContent();'></iframe>");
			}
			else {
				$window.append("<div class='content'></div>");
				$(".content", $window).load(url += "&random=" + (new Date().getTime()), $.thinbox.showContent);
			}
			
			$window.center({width:width});
			$(".content", $window).css({width: width, height: height});
		}
	};
	
	$.thinbox.showContent = function() {
		var $thinbox = $("#thinbox");
		var $overlay = $(".overlay", $thinbox);
		var $window = $(".window", $thinbox);
		var $loader = $(".loader", $overlay);
		var $close = $(".closewindow", $thinbox);
		
		$loader.fadeOut(250, function() {
			$loader.remove();
			$.scrollTo(0, 250, {
				onAfter: function() {
					$window.show().animate({opacity:1}, 500, "swing");
					$close
						.show()
						.animate({opacity:1}, 200);
				}
			});
		});
	};
	
	$.thinbox.remove = function() {
		var $thinbox = $("#thinbox");
		var $overlay = $(".overlay", $thinbox);
		var $window = $(".window", $thinbox);
		var $close = $(".closewindow", $thinbox);
		
		$thinbox.animate({opacity:0}, 400, "swing", function() {
			$overlay.unbind();
			$window.unbind();

			$(".loader", $overlay).remove();
			$window.trigger("unload").unbind().remove();
			$(".hideselect", $thinbox).trigger("unload").unbind().remove();
			$thinbox.remove();
			
			//if IE 6
			if (typeof document.body.style.maxHeight == "undefined") {
				$("body","html").css({height: "auto", width: "auto"});
			}
		});
	};
	
	$.thinbox.defaults = {
		closeText: "Click anywhere to close",
		loader: "images/global/black/ui_loader.gif",
		width: 600,
		height: 400
	};
	
})(jQuery);
