/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * Modified by Pham Dac Loc
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *  
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox() 
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.facebox('some html')
 *    jQuery.facebox('some html', 'Title of box')
 *
 *  The above will open a facebox with "some html" as the content.
 *    
 *    jQuery.facebox(function($) { 
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page or image:
 *  
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ image: 'dude.jpg' })
 *
 *  Facebox can display an alert:
 *    jQuery.facebox('some html', 'Title of box', 'alert')
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *   
 *  Change title of facebox (can be used by script embeded in content loaded via ajax)
 *  jQuery.facebox({ title: 'Some title' })
 *
 */
(function($) {
	var interval;
	
	$.facebox = function(data, title, mode) {
		if (data.title) {
			changeFaceboxTitle(data.title);
			return;
		}
	
		$.facebox.loading()

		if (data.ajax) fillFaceboxFromAjax(data.ajax, title)
		else if (data.image) fillFaceboxFromImage(data.image)
		else if (data.div) fillFaceboxFromHref(data.div, title)
		else if ($.isFunction(data)) data.call($)
		else $.facebox.reveal(data, title, mode)
	}

	/*
   * Public, $.facebox methods
   */

	$.extend($.facebox, {
		settings: {
			opacity      : 0,
			sticky	   : false,
			overlay      : true,
			imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
			faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="fpopup"> \
		<div class="ui-widget-header ui-helper-clearfix"> \
		  <h4 id="facebox-title"></h4> \
		  <a href="javascript:;" class="facebox-close"><img src="/images/facebox-close.png" title="close" class="close_image" /></a> \
		  <br clear="all"> \
		</div> \
		<div class="fcontent"> \
		</div> \
      </div> \
    </div>'
		},

		loading: function(settings) {
			init()
			if(settings) $.extend($.facebox.settings, settings);
			if ($('#facebox .loading').length == 1) return true
			showOverlay()

			$('#facebox .fcontent').empty()
			$('#facebox .fpopup').children().hide().end();

			$('#facebox').css({
				top:	getPageScroll()[1] + (getPageHeight() / 10)
			});

			$(document).bind('keydown.facebox', function(e) {
				if (e.keyCode == 27) $.facebox.close()
				return true
			})
			$(document).trigger('loading.facebox')
		},

		reveal: function(data, title, mode) {
			$('#facebox').show();
			$(document).trigger('beforeReveal.facebox')
			$('#facebox #facebox-title').text(title)

			if( mode ) {
				if( mode == 'alert')
					data = '<div class="facebox-alert"><div class="ui-widget"><div class="ui-state-highlight ui-corner-all" style="padding:10px; max-width:800px">'+data+'</div></div></div>';
			}

			$('#facebox .fpopup').children().fadeIn('normal')
			$('#facebox .fcontent').append(data)
			$('#facebox .loading').remove()
	  
			if (mode) {
				if(mode == 'alert') {
					$('#facebox .fcontent').append('<div class="facebox-submit"><button id="close-alert">Close</button></div>');
					$('#close-alert').click(function() {
						$.facebox.close();
					});
				}
			}

			// position the box
			$('#facebox').css('left', $(window).width() / 2 - ($('#facebox').width() / 2))
			$('#facebox').css('top', $(window).height() / 4 - ($('#facebox').height() / 4))
	
			// change facebox's position from fixed to absolute if its height exceeds window's height
			interval = setInterval(function() {
				var facebox = $('#facebox');
				if( facebox.length == 0) return;
				if( facebox.height() > $(window).height()) {
					var offset = $('#facebox').offset();
					facebox.css({
						position:'absolute', 
						top:offset.top
						});
				} else {
					facebox.css({
						position:'fixed'
					});
					$.facebox.reposition();
				}
			}, 1000);
	
			$(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
		},

		close: function() {
			$(document).trigger('close.facebox')
			return false
		},

		reposition: function() {
			$('#facebox').css('left', $(window).width() / 2 - ($('#facebox').width() / 2));
			$('#facebox').css('top', $(window).height() / 4 - ($('#facebox').height() / 4))
		}
	})

	/*
   * Public, $.fn methods
   */

	$.fn.facebox = function(settings) {
		init()

		function clickHandler() {
			$.facebox.loading(settings)

			fillFaceboxFromHref($(this).attr('href'), $(this).attr('title'));
			return false
		}

		return this.click(clickHandler)
	}

	/*
   * Private methods
   */

	// called one time to setup facebox on this page
	function init() {
		if( $.facebox.settingsInited ) return;
		else $.facebox.settingsInited = true;
	
		$(document).trigger('init.facebox')
		makeCompatible()

		var imageTypes = $.facebox.settings.imageTypes.join('|')
		$.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

		$('body').append($.facebox.settings.faceboxHtml)

		$('#facebox .facebox-close').click($.facebox.close)
	}
  
	// getPageScroll() by quirksmode.com
	function getPageScroll() {
		var xScroll, yScroll;
		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;	
		}
		return new Array(xScroll,yScroll) 
	}

	// Adapted from getPageSize() by quirksmode.com
	function getPageHeight() {
		var windowHeight
		if (self.innerHeight) {	// all except Explorer
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowHeight = document.body.clientHeight;
		}	
		return windowHeight
	}

	// Backwards compatibility
	function makeCompatible() {
		var $s = $.facebox.settings

		$s.imageTypes = $s.image_types || $s.imageTypes
		$s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
	}

	// Figures out what you want to display and displays it
	// formats are:
	//     div: #id
	//   image: blah.extension
	//    ajax: anything else
	function fillFaceboxFromHref(href, title) {
		// div
		if (href.match(/#/)) {
			var url    = window.location.href.split('#')[0]
			var target = href.replace(url,'')
			$.facebox.reveal($(target).clone().show())

		// image
		} else if (href.match($.facebox.settings.imageTypesRegexp)) {
			fillFaceboxFromImage(href)
		// ajax
		} else {
			fillFaceboxFromAjax(href, title)
		}
	}

	function fillFaceboxFromImage(href) {
		var image = new Image()
		image.onload = function() {
			$.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>')
		}
		image.src = href
	}

	function fillFaceboxFromAjax(href, title) {
		$.get(href, function(data) {
			$.facebox.reveal(data, title)
		})
	}
  
	function changeFaceboxTitle(title) {
		if($('#facebox-title').length)
			$('#facebox-title').text(title);
		else {
			$(document).bind('reveal.facebox', function() {
				$('#facebox-title').text(title);
			})
		}
	}

	function skipOverlay() {
		return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null;
	}

	function showOverlay() {
		if (skipOverlay()) return;

		if ($('facebox_overlay').length == 0) 
			$("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

		$('#facebox_overlay').hide().addClass("facebox_overlayBG")
		//      .css('opacity', $.facebox.settings.opacity)      // change opacity in CSS instead
		.fadeIn(200);
		if( ! $.facebox.settings.sticky) $('#facebox_overlay').click(function() {
			$(document).trigger('close.facebox')
		});
		return false;
	}

	function hideOverlay() {
		if (skipOverlay()) return

		$('#facebox_overlay').fadeOut(200, function(){
			$("#facebox_overlay").removeClass("facebox_overlayBG")
			$("#facebox_overlay").addClass("facebox_hide") 
			$("#facebox_overlay").remove()
		})
    
		return false
	}

	/*
   * Bindings
   */

	$(document).bind('close.facebox', function() {
		clearInterval(interval);
		$(document).unbind('keydown.facebox')
		$('#facebox').fadeOut(function() {
			$('#facebox .fcontent').removeClass().addClass('fcontent')
			hideOverlay()
			$('#facebox .loading').remove()
		})
	})

})(jQuery);

