/*
 * 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 ]
 *
 */
(function($) {
  $.light = function(data, klass) {
    $.light.loading()

    if (data.ajax) filllightFromAjax(data.ajax, klass)
    else if (data.image) filllightFromImage(data.image, klass)
    else if (data.div) filllightFromHref(data.div, klass)
    else if ($.isFunction(data)) data.call($)
    else $.light.reveal(data, klass)
  }

  /*
   * Public, $.light methods
   */

  $.extend($.light, {
    settings: {
      opacity      : 0.2,
      overlay      : true,
      loadingImage : './i./loading.gif',
      closeImage   : './i/closelabel.jpg',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      lightHtml  : '\
    <div id="light" style="display:none;"> \
      <div class="popup"> \
        <div class="content"> \
        </div> \
        <a href="#" class="close"><img src="/light/closelabel.png" title="close" class="close_image" /></a> \
      </div> \
    </div>'
    },

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

      $('#light .content').empty()
      $('#light .body').children().hide().end().
        append('<div class="loading"><img src="'+$.light.settings.loadingImage+'"/></div>')

      $('#light').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	$(window).width() / 2 - 205
      }).show()

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

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.light')
      if (klass) $('#light .content').addClass(klass)
      $('#light .content').append(data)
      $('#light .loading').remove()
      $('#light .body').children().fadeIn('normal')
      $('#light').css('left', $(window).width() / 2 - ($('#light .popup').width() / 2))
      $(document).trigger('reveal.light').trigger('afterReveal.light')
    },

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

  /*
   * Public, $.fn methods
   */

  $.fn.light = function(settings) {
    if ($(this).length == 0) return

    init(settings)

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

      // support for rel="light.inline_popup" syntax, to add a class
      // also supports deprecated "light[.inline_popup]" syntax
      var klass = this.rel.match(/light\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      filllightFromHref(this.href, klass)
      return false
    }

    return this.bind('click.light', clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup light on this page
  function init(settings) {
    if ($.light.settings.inited) return true
    else $.light.settings.inited = true

    $(document).trigger('init.light')
    makeCompatible()

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

    if (settings) $.extend($.light.settings, settings)
    $('body').append($.light.settings.lightHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.light.settings.closeImage
    preload[1].src = $.light.settings.loadingImage

    $('#light').find('.b:first, .bl').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#light .close').click($.light.close)
    $('#light .close_image').attr('src', $.light.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 = $.light.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.lightHtml = $s.light_html || $s.lightHtml
  }

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

    // image
    } else if (href.match($.light.settings.imageTypesRegexp)) {
      filllightFromImage(href, klass)
    // ajax
    } else {
      filllightFromAjax(href, klass)
    }
  }

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

  function filllightFromAjax(href, klass) {
    $.get(href, function(data) { $.light.reveal(data, klass) })
  }

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

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

    if ($('#light_overlay').length == 0)
      $("body").append('<div id="light_overlay" class="light_hide"></div>')

    $('#light_overlay').hide().addClass("light_overlayBG")
      .css('opacity', $.light.settings.opacity)
      .click(function() { $(document).trigger('close.light') })
      .fadeIn(200)
    return false
  }

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

    $('#light_overlay').fadeOut(200, function(){
      $("#light_overlay").removeClass("light_overlayBG")
      $("#light_overlay").addClass("light_hide")
      $("#light_overlay").remove()
    })

    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.light', function() {
    $(document).unbind('keydown.light')
    $('#light').fadeOut(function() {
      $('#light .content').removeClass().addClass('content')
      $('#light .loading').remove()
      $(document).trigger('afterClose.light')
    })
    hideOverlay()
  })

})(jQuery);
