/*
 * plainFacebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/plainFacebox/
 *
 * 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*=plainFacebox]').plainFacebox() 
 *  })
 *
 *  <a href="#terms" rel="plainFacebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="plainFacebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="plainFacebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.plainFacebox('some html')
 *
 *  The above will open a plainFacebox with "some html" as the content.
 *    
 *    jQuery.plainFacebox(function($) { 
 *      $.get('blah.html', function(data) { $.plainFacebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The plainFacebox function can also display an ajax page or image:
 *  
 *    jQuery.plainFacebox({ ajax: 'remote.html' })
 *    jQuery.plainFacebox({ image: 'dude.jpg' })
 *
 *  Want to close the plainFacebox?  Trigger the 'close.plainFacebox' document event:
 *
 *    jQuery(document).trigger('close.plainFacebox')
 *
 *  plainFacebox also has a bunch of other hooks:
 *
 *    loading.plainFacebox
 *    beforeReveal.plainFacebox
 *    reveal.plainFacebox (aliased as 'afterReveal.plainFacebox')
 *    init.plainFacebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.plainFacebox', function() { ...stuff to do after the plainFacebox and contents are revealed... })
 *
 */
(function($) {
  $.plainFacebox = function(data, klass) {
    $.plainFacebox.loading()

    if (data.ajax) fillplainFaceboxFromAjax(data.ajax)
    else if (data.iframe) fillplainFaceboxFromIframe(data.ajax)
    else if (data.image) fillplainFaceboxFromImage(data.image)
    else if (data.div) fillplainFaceboxFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.plainFacebox.reveal(data, klass)
  }

  /*
   * Public, $.plainFacebox methods
   */

  $.extend($.plainFacebox, {
    settings: {
      opacity      : .5,
      overlay      : true,
      loadingImage : 'images/facebox/loading.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      plainFaceboxHtml  : '\
		<div id="plainFacebox" style="display:none;"> \
			<div class="popup"> \
				<div class="body"> \
					<div class="content"> \
					</div> \
				</div> \
			</div> \
		</div>'
    },

    loading: function() {
      init()
      if ($('#plainFacebox .loading').length == 1) return true
      showOverlay()

      $('#plainFacebox .content').empty()
      $('#plainFacebox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.plainFacebox.settings.loadingImage+'"/></div>')

      $('#plainFacebox').css({
        marginTop:	- $('#plainFacebox').height() * .5 + "px",
        marginLeft:	- $('#plainFacebox').width()  * .5 + "px",
		display: "none"
      }).fadeIn(50);

      $(document).bind('keydown.plainFacebox', function(e) {
        if (e.keyCode == 27) $.plainFacebox.close()
        return true
      })
      $(document).trigger('loading.plainFacebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.plainFacebox');
      if (klass) $('#plainFacebox .content').addClass(klass);
      $('#plainFacebox .content').empty().append(data);
	  $('#plainFacebox .content').css({width:"auto", overflowX:"visible", height:"auto", overflowY:"visible"});
	  $('#plainFacebox .loading').remove();
      $('#plainFacebox .body').children().fadeIn('normal');
	  
	  //add Scroll Bars if too large
	  var maxWidth = 9 * $(window).width()/10;
	  var maxHeight = 9 * getPageHeight()/10;
	  
	  if($('#plainFacebox table').width() > maxWidth)
	  	$('#plainFacebox .content').css({width:maxWidth, overflowX:"scroll"});
	  if($('#plainFacebox table').height() > maxHeight)
	  	$('#plainFacebox .content').css({height:maxHeight, overflowY:"scroll"});
	  
      $('#plainFacebox').css({
        marginTop:	- $('#plainFacebox').height() * .5 + "px",
        marginLeft:	- $('#plainFacebox').width()  * .5 + "px"
	  });
      
	  $(document).trigger('reveal.plainFacebox').trigger('afterReveal.plainFacebox')
    },

    close: function() {
      $(document).trigger('close.plainFacebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.plainFacebox = function(settings) {
    init(settings)

    function clickHandler() {
      $.plainFacebox.loading(true)

      // support for rel="plainFacebox.inline_popup" syntax, to add a class
      // also supports deprecated "plainFacebox[.inline_popup]" syntax
      var klass = this.rel.match(/plainFacebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillplainFaceboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup plainFacebox on this page
  function init(settings) {
    if ($.plainFacebox.settings.inited) return true
    else $.plainFacebox.settings.inited = true

    $(document).trigger('init.plainFacebox')

    var imageTypes = $.plainFacebox.settings.imageTypes.join('|')
    $.plainFacebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.plainFacebox.settings, settings)
    $('body').append($.plainFacebox.settings.plainFaceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[1].src = $.plainFacebox.settings.loadingImage

    $('#plainFacebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#plainFacebox .close').click($.plainFacebox.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
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillplainFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.plainFacebox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.plainFacebox.settings.imageTypesRegexp)) {
      fillplainFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillplainFaceboxFromAjax(href, klass)
    }
  }

  function fillplainFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.plainFacebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillplainFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.plainFacebox.reveal(data, klass) })
  }
  
  function fillplainFaceboxFromIframe(href, klass) {
	  var data = '<iframe width="640" scrolling="auto" height="480" frameborder="0" marginwidth="0" marginheight="0" src="'+href+'"></iframe>'
	  $.plainFacebox.reveal(data, klass);
  }

  function skipOverlay() {
    return $.plainFacebox.settings.overlay == false || $.plainFacebox.settings.opacity === null 
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('plainFacebox_overlay').length == 0) 
      $("body").append('<div id="plainFacebox_overlay" class="plainFacebox_hide" title="click to exit, or press escape"></div>');

    $('#plainFacebox_overlay').hide().addClass("plainFacebox_overlayBG")
      .css('opacity', .5)// $.plainFacebox.settings.opacity)
      .click(function() { $(document).trigger('close.plainFacebox') })
      .fadeIn(200);
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#plainFacebox_overlay').fadeOut(400, function(){
      $("#plainFacebox_overlay").removeClass("plainFacebox_overlayBG")
      $("#plainFacebox_overlay").addClass("plainFacebox_hide") 
      $("#plainFacebox_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.plainFacebox', function() {
    $(document).unbind('keydown.plainFacebox')
	  $('#plainFacebox .content').empty();
    $('#plainFacebox').fadeOut(400,function() {
      $('#plainFacebox .content').removeClass().addClass('content');
      hideOverlay();
      $('#plainFacebox .loading').remove();
    })
  })

})(jQuery);