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