
(function($) {
  $.mobile = function(data, klass) {
    $.mobile.loading()

    if (data.ajax) fillmobileFromAjax(data.ajax)
    else if (data.image) fillmobileFromImage(data.image)
    else if (data.div) fillmobileFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.mobile.reveal(data, klass)
  }

  /*
   * Public, $.mobile methods
   */

  $.extend($.mobile, {
    settings: {
      opacity      : 0,
      overlay      : true,
      loadingImage : '/facebox/loading.gif',
      closeImage   : '/facebox/closelabel.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      mobileHtml  : '\
    <div id="mobile" 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="footer"> \
                  <a href="#" class="close"> \
                    <img src="/facebox/closelabel.gif" title="close" class="close_image" /> \
                  </a> \
                </div> \
                <div class="content"> \
                </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 ($('#mobile .loading').length == 1) return true
      showOverlay()

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

      $('#mobile').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	385.5
      }).show()

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

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

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

  /*
   * Public, $.fn methods
   */

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

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

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

      fillmobileFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

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

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

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

    if (settings) $.extend($.mobile.settings, settings)
    $('body').append($.mobile.settings.mobileHtml)

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

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

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

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.mobileHtml = $s.mobile_html || $s.mobileHtml
  }

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

    // image
    } else if (href.match($.mobile.settings.imageTypesRegexp)) {
      fillmobileFromImage(href, klass)
    // ajax
    } else {
      fillmobileFromAjax(href, klass)
    }
  }

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

  function fillmobileFromAjax(href, klass) {
    $.get(href, function(data) { $.mobile.reveal(data, klass) })
  }

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

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

    if ($('mobile_overlay').length == 0) 
      $("body").append('<div id="mobile_overlay" class="mobile_hide"></div>')

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

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

    $('#mobile_overlay').fadeOut(200, function(){
      $("#mobile_overlay").removeClass("mobile_overlayBG")
      $("#mobile_overlay").addClass("mobile_hide") 
      $("#mobile_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

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

})(jQuery);

