/*
	facebox v1.1.5 - a full featured, light-weight, customizable lightbox based on jQuery 1.3
	(c) 2009 Jack Moore - www.colorpowered.com - jack@colorpowered.com
	Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/

(function(jQuery){
var clone, loadedWidth, loadedHeight, interfaceHeight, interfaceWidth, index, related, closeModal, loadingElement, modal, modalWrap, modalOverlay, modalLoadingOverlay, modalContent, loaded, modalClose, btc, bml, bmr, bbc;
function setModalOverlay(){
	jQuery([modalOverlay]).css({"position":"absolute", width:jQuery(window).width(), height:jQuery(window).height(), top:jQuery(window).scrollTop(), left:jQuery(window).scrollLeft()});
}
function keypressEvents(e){
	if(e.keyCode == 37){
		jQuery(document).unbind('keydown.colorKeys');
		jQuery("a#contentPrevious").click();
	} else if(e.keyCode == 39){
		jQuery(document).unbind('keydown.colorKeys');
		jQuery("a#contentNext").click();
	}
}
function clearLoading(){
	if(jQuery("#faceboxInlineTemp").length > 0){
		jQuery(loaded).children().insertAfter("#faceboxInlineTemp");
	}
	if(loadingElement){jQuery(loadingElement).remove();}
}

closeModal = function(){
	clearLoading();
	jQuery(modal).stop(true, false).removeData("open").fadeOut("slow", function(){
		jQuery(modalOverlay).fadeOut("fast");
		jQuery(loaded).remove();
	});
	jQuery(document).unbind('keydown.colorKeys');
	jQuery(window).unbind('resize scroll', setModalOverlay);
	// re enable scrolling on the page when the facebox is closed
	jQuery("body").removeClass("facebox-overflow").removeClass("facebox-overflow-padding");
  	jQuery("html").removeClass("facebox-overflow");
};

// Convert % values to pixels
function setSize(size, dimension){
	return (typeof size == 'string') ? (size.match(/%/) ? (dimension/100)*parseInt(size, 10) : parseInt(size, 10)) : size;
}

//Initialize the modal: store common calculations, preload the interface graphics, append the html.
jQuery(function(){
	jQuery("body").append(
		jQuery([
			modalOverlay = jQuery('<div id="modalBackgroundOverlay" />')[0], 
			modal = jQuery('<div id="facebox" />')[0]
		]).hide()
	);
	jQuery(modal).append(
		jQuery([
			modalWrap = jQuery('<div id="modalWrap" />')[0]
		])
	).css("opacity", 0).show();
	jQuery(modalWrap).append(
		jQuery([
			jQuery('<div><div id="borderTopLeft"></div><div id="borderTopCenter"></div><div id="borderTopRight"></div></div>')[0],
			bml = jQuery('<div id="borderMiddleLeft" />')[0],
			modalContent = jQuery('<div id="modalContent" />')[0],
			bmr = jQuery('<div id="borderMiddleRight" />')[0],
			jQuery('<div><div id="borderBottomLeft"></div><div id="borderBottomCenter"></div><div id="borderBottomRight"></div></div>')[0]
		])
	);
	jQuery(modalContent).append(
		jQuery([
			loaded = jQuery('<div id="modalLoadedContent"><a id="contentPrevious" href="#"></a><a id="contentNext" href="#"></a><span id="contentCurrent"></span><br id="modalInfoBr"/><span id="contentTitle"></span><div id="preloadPrevious"></div><div id="preloadNext"></div><div id="preloadClose"></div></div>')[0], 
			modalLoadingOverlay = jQuery('<div id="modalLoadingOverlay" />')[0],
			modalClose = jQuery('<a id="modalClose" href="#"></a>')[0]
		])
	);

	jQuery(document).bind("keydown.colorClose", function(e){
		if (e.keyCode == 27) { closeModal(); }
	});

	jQuery(modalClose).click(function(){
		closeModal();
		return false;
	});

	btc = jQuery("#borderTopCenter")[0];
	bbc = jQuery("#borderBottomCenter")[0];

	interfaceHeight = jQuery(btc).height()+jQuery(bbc).height()+jQuery(modalContent).outerHeight(true) - jQuery(modalContent).height();//Subtraction needed for IE6
	interfaceWidth = jQuery(bml).width()+jQuery(bmr).width()+jQuery(modalContent).outerWidth(true) - jQuery(modalContent).width();

	loadedHeight = jQuery(loaded).outerHeight(true);
	loadedWidth = jQuery(loaded).outerWidth(true);

	jQuery(loaded).empty();
	jQuery(modal).css({"padding-bottom":interfaceHeight,"padding-right":interfaceWidth}).hide();//the padding removes the need to do size conversions during the animation step.

	//Archaic rollover code because IE8 is a piece of shit.  Hopefully they'll fix their css-rollover bug so the following code can be removed.
	jQuery("#contentPrevious, #contentNext, #modalClose").live('mouseover', function(){jQuery(this).addClass("hover");});
	jQuery("#contentPrevious, #contentNext, #modalClose").live('mouseout', function(){jQuery(this).removeClass("hover");});
});

jQuery.fn.facebox = function(settings, callback) {
    
	function modalPosition(mWidth, mHeight, speed, loadedCallback){
	
		var winHeight = document.documentElement.clientHeight;
		var posTop = winHeight/2 - mHeight/2 + jQuery(window).scrollTop();
		var posLeft = document.documentElement.clientWidth/2 - mWidth/2 + jQuery(window).scrollLeft();
		//keeps the box from expanding to an inaccessible area offscreen.
		if(mHeight > winHeight){posTop -=(mHeight - winHeight);}
		if(posTop < 0){posTop = 0;} 
		if(posLeft < 0){posLeft = 0;}
	
		mWidth = mWidth - interfaceWidth;
		mHeight = mHeight - interfaceHeight;
	
		function modalDimensions(that){
			modalContent.style.width = btc.style.width = bbc.style.width = that.style.width;
			modalContent.style.height = bml.style.height = bmr.style.height = that.style.height;
		}
	
		jQuery(modal).animate({height:mHeight, width:mWidth, top:posTop, left:posLeft}, {duration: speed,
			complete: function(){
				if (loadedCallback) {loadedCallback();}
				modalDimensions(this);
				if (jQuery.browser.msie && jQuery.browser.version < 7) {setModalOverlay();}
			},
			step: function(){
				modalDimensions(this);		
			}
		});
	}
	
	function disableScroll() {
		if (!settings.scroll) {
			jQuery("body").addClass("facebox-overflow");
		  	jQuery("html").addClass("facebox-overflow");
			
			if (jQuery(document).height() > jQuery(window).height()) {
				jQuery("body").addClass("facebox-overflow-padding");
			}
			
		}
	}
	
	var preloads = [];
	function preload(){
		if(settings.preloading !== false && related.length>1 && related[index].href.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(.*))?jQuery/i)){
			var previous, next;
			previous = index > 0 ? related[index-1].href : related[related.length-1].href;
			next = index < related.length-1 ? related[index+1].href : related[0].href;
			return [jQuery("<img />").attr("src", next), jQuery("<img />").attr("src", previous)];
		}
		return false;
	}
	
	function contentNav(){
		jQuery(modalLoadingOverlay).show();
		if(jQuery(this).attr("id") == "contentPrevious"){
			index = index > 0 ? index-1 : related.length-1;
		} else {
			index = index < related.length-1 ? index+1 : 0;
		}
		loadModal(related[index].href, related[index].title);
	}
	
	function centerModal (object, contentInfo){
		if(jQuery(modal).data("open")!==true){ return false; }

		var speed = settings.transition=="none" ? 0 : settings.transitionSpeed;
		jQuery(loaded).remove();
		loaded = jQuery(object)[0];
	
		jQuery(loaded).hide()
		.css({width:(settings.fixedWidth)?settings.fixedWidth - loadedWidth - interfaceWidth:jQuery(loaded).width()}).css({height:(settings.fixedHeight)?settings.fixedHeight - loadedHeight - interfaceHeight:jQuery(loaded).height()})
		.attr({id:"modalLoadedContent"})
		.append(contentInfo)
		
		setTimeout(function() {
			jQuery(loaded).prependTo(jQuery(modalContent));
		}, settings.transitionSpeed);
		

		if(jQuery("#modalPhoto").length > 0 && settings.fixedHeight){
			var topMargin = (parseInt(jQuery(loaded)[0].style.height, 10) - parseInt(jQuery("#modalPhoto")[0].style.height, 10))/2;
			jQuery("#modalPhoto").css({marginTop:(topMargin > 0?topMargin:0)});
		}
	
		function setPosition(s){
			modalPosition(parseInt(loaded.style.width, 10)+loadedWidth+interfaceWidth, parseInt(loaded.style.height, 10)+loadedHeight+interfaceHeight, s, function(){
				if(jQuery(modal).data("open")!==true){
					return false;
				}
				jQuery(loaded).show();
				jQuery(document).bind('keydown.colorKeys', keypressEvents);
				if (callback) {
					callback();
				}
				if (settings.transition === "fade"){
					jQuery(modal).animate({"opacity":1}, speed);
				}
				return true;
			});
		}
		if (settings.transition == "fade") {
			jQuery(modal).animate({"opacity":0}, speed, function(){setPosition(0);});
		} else {
			setPosition(speed);
		}
		var preloads = preload();
		return true;
	}
	
	function loadModal(href, title, content){
		clearLoading();
			
		var contentInfo = "<p id='contentTitle'></p>";
		if(related.length>1){
			contentInfo += "<span id='contentCurrent'> " + settings.contentCurrent + "</span>";
			contentInfo = contentInfo.replace(/\{current\}/, index+1).replace(/\{total\}/, related.length);
			contentInfo += "<div class='remove-nav'><a id='contentPrevious' href='#'>"+settings.contentPrevious+"</a><a id='contentNext' href='#'>"+settings.contentNext+"</a></div> ";
		}
		if (settings.inline) {
			loadingElement = jQuery('<div id="faceboxInlineTemp" />').hide().insertBefore(jQuery(href)[0]);
			clone = jQuery(href).clone(true);
			centerModal(jQuery(href).wrapAll("<div />").parent(), contentInfo);
			finishLoad();
		} else if (settings.string) {
			centerModal(content, contentInfo);
			finishLoad();
		} else if (settings.iframe) {
			centerModal(jQuery("<div><iframe id='modalIframe' name='iframe_"+new Date().getTime()+" 'frameborder=0 src =" + href + "></iframe></div>"), contentInfo);//timestamp to prevent caching.
			setTimeout(function() {
				jQuery("#modalIframe").load(function() {
					finishLoad();
				});
			}, settings.transitionSpeed);
		} else if (settings.form) {
				var form = jQuery(settings.form).parents("form:first");		
				centerModal(jQuery("<div><iframe id='modalIframe' name='modalIframe' frameborder='0'></iframe></div>"), contentInfo);//timestamp to prevent caching.
				setTimeout(function() {
					form.attr("target", 'modalIframe');
					form.append(settings.form.clone())
					if (settings.action) {
						form.attr("action", settings.action)
					}
					form.find("input.facebox:last, button.facebox:last").click().remove();
					jQuery("#modalIframe").load(function() {
						finishLoad();
					});
				}, settings.transitionSpeed);
		} else if (href.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(.*))?jQuery/i)){
			loadingElement = new Image();
			loadingElement.onload = function(){
				loadingElement.onload = null;
				centerModal(jQuery("<div />").css({width:this.width, height:this.height}).append(jQuery(this).css({width:this.width, height:this.height, display:"block", margin:"auto"}).attr('id', 'modalPhoto')), contentInfo);
				if(related.length > 1){
					jQuery(this).css({cursor:'pointer'}).click(contentNav);
				}
				finishLoad();
			};
			loadingElement.src = href;
		}else {
			loadingElement = jQuery('<div />').load(href, function(data, textStatus){
				if(textStatus == "success"){
					centerModal(jQuery(this), contentInfo);
				} else {
					centerModal(jQuery("<p>Request unsuccessful.</p>"));
				}
			});
		}
	}
	
	function finishLoad() {
		jQuery(".remove-nav").remove();
		jQuery("#contentCurrent").remove();
		jQuery(modalLoadingOverlay).fadeOut(parseInt(settings.transitionSpeed/2));
				
				var iframe_loaded = jQuery(modal).find("iframe:first");

				/*if (iframe_loaded.length) {

					var iframe_name = iframe_loaded.attr("name");

					if (iframe_name !== "") {

						var top_loc = top.document.location;
						
						var doc_loc = top.frames[iframe_name].location;

						if (top_loc.host === doc_loc.host && top_loc.protocol === doc_loc.protocol) {

							iframe_loaded.contents().find(".close-facebox").click(function() {
								closeModal(); return false;
							});

						}

					}

				}*/
				
				try {
					iframe_loaded.contents().find(".close-facebox").click(function() {
						closeModal(); return false;
					});
				}
				catch(err) {
				}

                jQuery(modal).find(".close-facebox").click(function() {
                 	closeModal(); return false;
                });
	}

	settings = jQuery.extend({}, jQuery.fn.facebox.settings, settings);
	
	jQuery(this).unbind("click.facebox").bind("click.facebox", function () {
			
		if (settings.form) {
				var form = jQuery(settings.form).parents("form:first");
				if (!form.valid()) {
					return false;
				}
		}
		
		if(settings.fixedWidth){ settings.fixedWidth = setSize(settings.fixedWidth, document.documentElement.clientWidth);}
		if(settings.fixedHeight){ settings.fixedHeight = setSize(settings.fixedHeight, document.documentElement.clientHeight);}
		if (this.rel && 'nofollow' != this.rel) {
			related = jQuery("a[rel='" + this.rel + "']");
			index = jQuery(related).index(this);
		}
		else {
			related = jQuery(this);
			index = 0;
		}

		if (jQuery(modal).data("open") !== true) {
			jQuery(document).bind('keydown.colorKeys', keypressEvents);
			jQuery(modalClose).html(settings.modalClose);
			jQuery(modalOverlay).css({"opacity": settings.bgOpacity});
			jQuery(modal).data("open", true).css({"opacity":1});
			jQuery([modal, modalLoadingOverlay, modalOverlay]).show();

			modalPosition(setSize(settings.initialWidth, document.documentElement.clientWidth), setSize(settings.initialHeight, document.documentElement.clientHeight), 0);

			if (jQuery.browser.msie && jQuery.browser.version < 7) {
				jQuery(window).bind("resize scroll", setModalOverlay);
			}
		}

		disableScroll();	
		
		setTimeout(function() {
			loadModal(settings.href ? settings.href : related[index].href, settings.title ? settings.title : related[index].title, settings.ajaxContent);
		}, parseInt(settings.transitionSpeed/2))
		
		jQuery("a#contentPrevious, a#contentNext").die().live("click", contentNav);

		if(settings.overlayClose!==false){
			jQuery(modalOverlay).css({"cursor":"pointer"}).click(function(){closeModal();});
		}

		return false;
	});

	if(settings.open!==false && jQuery(modal).data("open")!==true){
		jQuery(this).triggerHandler('click.facebox');
	}

	return this.each(function() { 
	});
};

/*
	facebox Default Settings.
	
	The facebox() function takes one argument, an object of key/value pairs, that are used to initialize the modal.
	
	Please do not change these settings here, instead overwrite these settings when attaching the facebox() event to your anchors.
	Example (Global)	: jQuery.fn.facebox.settings.transition = "fade"; //changes the transition to fade for all facebox() events proceeding it's declaration.
	Example (Specific)	: jQuery("a[href='http://www.google.com']").facebox({fixedWidth:"90%", fixedHeight:"450px", iframe:true});
*/
jQuery.fn.facebox.settings = {
	transition : "elastic", // Transition types: "elastic", "fade", or "none".
	transitionSpeed : 500, // Sets the speed of the fade and elastic transitions, in milliseconds.
	initialWidth : "150", // Set the initial width of the modal, prior to any content being loaded.
	initialHeight : "150", // Set the initial height of the modal, prior to any content being loaded.
	fixedWidth : false, // Set a fixed width for div#loaded.  Example: "500px"
	fixedHeight : false, // Set a fixed height for div#modalLoadedContent.  Example: "500px"
	inline : false, // Set this to the selector of inline content to be displayed.  Example "#myHiddenDiv" or "body p".
	iframe : false, // If 'true' specifies that content should be displayed in an iFrame.
	href : false, // This can be used as an alternate anchor URL for facebox to use, or can be used to assign a URL for non-anchor elments such as images or form buttons.
	title : false, // This can be used as an alternate anchor title.
	bgOpacity : 0.65, // The modalBackgroundOverlay opacity level. Range: 0 to 1.
	preloading : true, // Allows for preloading of 'Next' and 'Previous' content in a shared relation group (same values for the 'rel' attribute), after the current content has finished loading.  Set to 'false' to disable.
	contentCurrent : "image {current} of {total}", // the format of the contentCurrent information
	contentPrevious : "previous", // the anchor text for the previous link in a shared relation group (same values for 'rel').
	contentNext : "next", // the anchor text for the next link in a shared relation group (same 'rel' attribute').
	modalClose : "close", // the anchor text for the close link.  Esc will also close the modal.
	open : false, //Automatically opens facebox. (fires the click.facebox event without waiting for user input).
	overlayClose : true,  //If true, enables closing facebox by clicking on the background overlay.
	scroll: false, // If true it will disable the scroll bar from the main window.
	form: false,
	action: false
};

})(jQuery);

var FaceBox = {

	initialize: function() {
	
	jQuery(".facebox").each(function(){

		var link = jQuery(this);
                link.removeAttr("onclick");
		var attr = "rel";
		var nodeName = this.nodeName;

		var metadata = {
			width: 800,
			height: 600,
			scroll: false,
			speed: 500,
			href: false,
			form: false,
			iframe: true,
			inline: false,
			action: false
		}

		var win = jQuery(window);
		var win_width = win.width();
		var win_height = win.height();

		if (nodeName === "INPUT" || nodeName === "BUTTON") {
			attr = "alt";
		}

		metadata = jQuery.extend({}, metadata, link.metadata({type: "attr", name: attr}));

		if (metadata.width > win_width) {
			metadata.width = win_width - 100
		}

		if (metadata.height > win_height) {
			metadata.height = win_height - 100
		}

		if (nodeName === "INPUT" || nodeName === "BUTTON") {
			metadata.iframe = false;
			metadata.form = link;
		}

		link.facebox({
			fixedWidth: metadata.width, 
			fixedHeight: metadata.height, 
			iframe: metadata.iframe, 
			inline: metadata.inline, 
			scroll: metadata.scroll, 
			transitionSpeed: metadata.speed, 
			href: metadata.href, 
			form: metadata.form,
			action: metadata.action
		});		

	});
	
	}

}

FaceBox.initialize();