/*
 * face (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/face/
 *
 * 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*=face]').face()
 *  })
 *
 *  <a href="#terms" rel="face">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="face">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="face">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 *
 *    jQuery.face('some html')
 *    jQuery.face('some html', 'my-groovy-style')
 *
 *  The above will open a face with "some html" as the content.
 *
 *    jQuery.face(function($) {
 *      $.get('blah.html', function(data) { $.face(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The face function can also display an ajax page, an image, or the contents of a div:
 *
 *    jQuery.face({ ajax: 'remote.html' })
 *    jQuery.face({ ajax: 'remote.html' }, 'my-groovy-style')
 *    jQuery.face({ image: 'stairs.jpg' })
 *    jQuery.face({ image: 'stairs.jpg' }, 'my-groovy-style')
 *    jQuery.face({ div: '#box' })
 *    jQuery.face({ div: '#box' }, 'my-groovy-style')
 *
 *  Want to close the face?  Trigger the 'close.face' document event:
 *
 *    jQuery(document).trigger('close.face')
 *
 *  face also has a bunch of other hooks:
 *
 *    loading.face
 *    beforeReveal.face
 *    reveal.face (aliased as 'afterReveal.face')
 *    init.face
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.face', function() { ...stuff to do after the face and contents are revealed... })
 *
 */
(function($) {
  $.face = function(data, klass) {
    $.face.loading()

    if (data.ajax) fillfaceFromAjax(data.ajax, klass)
    else if (data.image) fillfaceFromImage(data.image, klass)
    else if (data.div) fillfaceFromHref(data.div, klass)
    else if ($.isFunction(data)) data.call($)
    else $.face.reveal(data, klass)
  }

  /*
   * Public, $.face methods
   */

  $.extend($.face, {
    settings: {
      opacity      : 0,
      overlay      : true,
      loadingImage : '/facebox/loading.gif',
      closeImage   : '/facebox/closelabel.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceHtml  : '\
    <div id="face" style="display:none;"> \
      <div class="popup"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
                <div class="content"> \
                </div> \
                <div class="facefooter"> \
                  <a href="#" class="close"> \
                    <img src="/facebox/closelabel.gif" title="close" class="close_image" /> \
                  </a> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#face .loading').length == 1) return true
      showOverlay()

      $('#face .content').empty()
      $('#face .body').children().hide().end().
        append('<div class="loading"><img src="'+$.face.settings.loadingImage+'"/></div>')

      $('#face').css({
        top:	getPageScroll()[1] + (getPageHeight() / 4),
        left:	$(window).width() / 2 - 205
      }).show()

      $(document).bind('keydown.face', function(e) {
        if (e.keyCode == 27) $.face.close()
        return true
      })
      $(document).trigger('loading.face')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.face')
      if (klass) $('#face .content').addClass(klass)
      $('#face .content').append(data)
      $('#face .loading').remove()
      $('#face .body').children().fadeIn('normal')
      $('#face').css('left', $(window).width() / 2 - ($('#face table').width() / 2))
      $(document).trigger('reveal.face').trigger('afterReveal.face')
    },

    close: function() {
      $(document).trigger('close.face')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.face = function(settings) {
    if ($(this).length == 0) return

    init(settings)

    function clickHandler() {
      $.face.loading(true)

      // support for rel="face.inline_popup" syntax, to add a class
      // also supports deprecated "face[.inline_popup]" syntax
      var klass = this.rel.match(/face\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillfaceFromHref(this.href, klass)
      return false
    }

    return this.bind('click.face', clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup face on this page
  function init(settings) {
    if ($.face.settings.inited) return true
    else $.face.settings.inited = true

    $(document).trigger('init.face')
    makeCompatible()

    var imageTypes = $.face.settings.imageTypes.join('|')
    $.face.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i')

    if (settings) $.extend($.face.settings, settings)
    $('body').append($.face.settings.faceHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.face.settings.closeImage
    preload[1].src = $.face.settings.loadingImage

    $('#face').find('.b:first, .bl').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#face .close').click($.face.close)
    $('#face .close_image').attr('src', $.face.settings.closeImage)
  }

  // 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 = $.face.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceHtml = $s.face_html || $s.faceHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillfaceFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      if (target == '#') return
      $.face.reveal($(target).html(), klass)

    // image
    } else if (href.match($.face.settings.imageTypesRegexp)) {
      fillfaceFromImage(href, klass)
    // ajax
    } else {
      fillfaceFromAjax(href, klass)
    }
  }

  function fillfaceFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.face.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillfaceFromAjax(href, klass) {
    $.get(href, function(data) { $.face.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.face.settings.overlay == false || $.face.settings.opacity === null
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('#face_overlay').length == 0)
      $("body").append('<div id="face_overlay" class="face_hide"></div>')

    $('#face_overlay').hide().addClass("face_overlayBG")
      .css('opacity', $.face.settings.opacity)
      .click(function() { $(document).trigger('close.face') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#face_overlay').fadeOut(200, function(){
      $("#face_overlay").removeClass("face_overlayBG")
      $("#face_overlay").addClass("face_hide")
      $("#face_overlay").remove()
    })

    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.face', function() {
    $(document).unbind('keydown.face')
    $('#face').fadeOut(function() {
      $('#face .content').removeClass().addClass('content')
      hideOverlay()
      $('#face .loading').remove()
    })
  })

})(jQuery);

