/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * 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')
 *
 *  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' })
 *
 *  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... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax)
    else if (data.iframe) fillFaceboxFromIframe(data.ajax)
    else if (data.image) fillFaceboxFromImage(data.image)
    else if (data.div) fillFaceboxFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
		maxWidth			: .8,
		maxHeight			: .8,
		opacity      		: 0,
		overlay      		: true,
		overlayColor 		: "#000",
		border	   			: true,
		borderColor			: "#003264",
		borderRadius		: 10,
		borderSize			: 10,
		borderOpacity		: .8,
		loadingImage 		: '/images/facebox/loading.gif',
		closeImage   		: '/images/facebox/closelabel.gif',
		imageTypes   		: [ 'png', 'jpg', 'jpeg', 'gif' ],
		faceboxHtml  		: '\
			<div id="facebox"> \
				<div id="faceboxPopup"> \
					<div id="faceboxContent"> \
					</div> \
					<div id="faceboxFooter"> \
						<a class="button close_image close" title="close popup"><span></span>close</a> \
						<div style="clear:both;"></div> \
					</div> \
				</div> \
			</div>',
		iframe				: false
    },

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

      $('#faceboxContent').empty()
      $('#faceboxContent, #faceboxFooter').hide().end();
	  $('#faceboxPopup').append('<div class="loading" style="background-image:url('+$.facebox.settings.loadingImage+');"/>')
	  
	  $('#faceboxPopup').css({
	  	width:$('#facebox .loading').css("width")
	  });
	  $('#facebox').css({
		top: getPageScroll()[1] + (getPageHeight() / 10)
	  });
      $('#facebox').hide().fadeIn("fast");
	  
	  
      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      });
	  
	  $(window).bind('scroll', function(e) {
		positionFacebox();
	  });
	  
	  $(window).bind('resize', function(e) {
		positionFacebox();
	  });
	  
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
		$('#facebox').queue(function(){
			$(document).trigger('beforeReveal.facebox');
			if (klass) $('#faceboxContent').addClass(klass);
			$('#faceboxContent').empty().append(data);
			$('#facebox .loading').fadeOut("fast",function(){
				$(this).remove();
				$('#faceboxPopup').animate({width:$('#faceboxContent').width() + "px"},'fast',function(){
					$('#faceboxContent, #faceboxFooter').slideDown('fast',function(){positionFacebox();});
				});
			});
			$(document).trigger('reveal.facebox').trigger('afterReveal.facebox');
			$(this).dequeue();
		});
    },

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

  /*
   * Public, $.fn methods
   */

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

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

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]
	  
	  if(settings.iframe){
	  	fillFaceboxFromIframe(this.href, klass);
	  }else{
      	fillFaceboxFromHref(this.href, klass);
	  }
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
	//only load once
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true
	
    $(document).trigger('init.facebox')
    makeCompatible()
	
    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)
	$('#facebox').hide();
	
	//Add Iframe, for flash/forms issues in IE
	if($.browser.msie == true)
		$('#faceboxPopup').prepend('<iframe id="faceboxIframe" frameborder="0"/>')
	
	//Add border, if desired
	if ($.facebox.settings.border == true){
		$('#faceboxPopup').prepend('<div id="faceboxBorder"/>');
		$('#faceboxBorder').css({
			opacity:$.facebox.settings.borderOpacity,
			top: - $.facebox.settings.borderSize + "px",
			left: - $.facebox.settings.borderSize + "px",
			border:$.facebox.settings.borderSize + "px solid " + $.facebox.settings.borderColor,
			"border-radius": $.facebox.settings.borderRadius + "px",
			"-moz-border-radius": $.facebox.settings.borderRadius + "px",
			"-webkit-border-radius": $.facebox.settings.borderRadius + "px"
		});
	}
	
	//load images
    var preload = [ new Image(), new Image() ]
	
	//set loaded properties on load complete
	$(preload[0]).load(function(){
		$('#facebox .close_image').css({
			width:this.width / 3 + "px",
			height:this.height + "px"
		});
		$('#facebox .close_image span').css('backgroundImage', 'url(' + $.facebox.settings.closeImage +  ')');
	});
	
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage
	
	//Add functionality
    $('#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
  }
	// -----------------------------------------------------------------------------------
	
	//
	// getPageSize()
	// Returns array with page width, height and window width, height
	// Core code from - quirksmode.com
	// Edit for Firefox by pHaez
	//
	function getPageSize(){
		
		var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		
		//	console.log(self.innerWidth);
		//	console.log(document.documentElement.clientWidth);
		
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
		
		//	console.log("xScroll " + xScroll)
		//	console.log("windowWidth " + windowWidth)
		
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
		//	console.log("pageWidth " + pageWidth)
		
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	}

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

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $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, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.facebox.reveal($(target).clone().show(), klass)

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

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

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }
  
  function fillFaceboxFromIframe(href, klass) {
	  var data = '<iframe width="640" scrolling="auto" height="480" frameborder="0" marginwidth="0" marginheight="0" src="'+href+'"></iframe>'
	  $.facebox.reveal(data, klass);
  }

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

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

    if ($('#facebox_overlay').length == 0) 
      $("#facebox").before('<div id="facebox_overlay" title="click anywhere to exit, or press escape" />')

    $('#facebox_overlay')
      .css({
		opacity:0,
		backgroundColor:$.facebox.settings.overlayColor,
        top: getPageScroll()[1]
	  })
      .click(function() { $(document).trigger('close.facebox') })
      .fadeTo(200,$.facebox.settings.opacity)
    return false
  }

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

    $('#facebox_overlay').fadeOut(400, function(){
      $("#facebox_overlay").remove();
    })
    
    return false
  }
  
  function positionFacebox() {
	  
	  var fullHeight = getPageHeight();
	  var pageSize = getPageSize();
	  
      $('#facebox').css({
        top: getPageScroll()[1] + (pageSize[3] / 10)
      });
	  
	  $('#facebox_overlay').css({
        top: getPageScroll()[1]
      });
	  
	  if($('#faceboxContent').children().length > 0){
		  
		  var initWidth = $('#faceboxPopup').width();
		  
		  $('#faceboxPopup').css({
			width:"80%",
			height:"auto"
		  });
		  
		  $('#faceboxContent').css({
			width:"auto",
			height:"auto"
		  });
		  
		  if(pageSize[2] * $.facebox.settings.maxWidth < $('#faceboxContent').width()){
			  $('#faceboxContent').width(pageSize[2] * $.facebox.settings.maxWidth)
		  }
		  
		  if(pageSize[3] * $.facebox.settings.maxHeight < $('#faceboxContent').height()){
			  $('#faceboxContent').height(pageSize[3] * $.facebox.settings.maxHeight)
		  }
		  
		  var destWidth = $('#faceboxContent').width();
		  
		  $('#faceboxPopup').width(initWidth);
		  $('#faceboxPopup').stop().animate({width:destWidth + "px",height:$('#faceboxPopup').height() + "px"},"fast").css("overflow","visible");
	  }
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(400,function() {
      hideOverlay();
      $('#facebox .loading').remove();
    })
  })

})(jQuery);
