/*

 *
 * Usage:
 *  
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=twittadbox]').twittadbox() 
 *  })
 *
 *  <a href="#terms" rel="twittadbox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="twittadbox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="twittadbox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.twittadbox('some html')
 *
 *  The above will open a twittadbox with "some html" as the content.
 *    
 *    jQuery.twittadbox(function($j) { 
 *      $j.get('blah.html', function(data) { $j.twittadbox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The twittadbox function can also display an ajax page or image:
 *  
 *    jQuery.twittadbox({ ajax: 'remote.html' })
 *    jQuery.twittadbox({ image: 'dude.jpg' })
 *
 *  Want to close the twittadbox?  Trigger the 'close.twittadbox' document event:
 *
 *    jQuery(document).trigger('close.twittadbox')
 *
 *  Twittadbox also has a bunch of other hooks:
 *
 *    loading.twittadbox
 *    beforeReveal.twittadbox
 *    reveal.twittadbox (aliased as 'afterReveal.twittadbox')
 *    init.twittadbox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $j(document).bind('reveal.twittadbox', function() { ...stuff to do after the twittadbox and contents are revealed... })
 *
 */
(function($j) {
  $j.twittadbox = function(data, klass) {
    $j.twittadbox.loading()

    if (data.ajax) fillTwittadboxFromAjax(data.ajax)
    else if (data.image) fillTwittadboxFromImage(data.image,klass)
    else if (data.div) fillTwittadboxFromHref(data.div)
    else if ($j.isFunction(data)) data.call($j)
    else $j.twittadbox.reveal(data, klass)
	 
  }

  /*
   * Public, $j.twittadbox methods
   */

  $j.extend($j.twittadbox, {
    settings: {
      opacity      : 0.2,
      overlay      : true,
      loadingImage : imagesUrl+'preloader.gif',
      closeImage   : imagesUrl+'icons/close.png',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      twittadboxHtml  : '\
    <div id="twittadbox" 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 id="fb_closeIcon" class="closeIcon"> \
                  <a href="#" class="close"> \
                    <img src="'+imagesUrl+'icons/close.png" 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 ($j('#twittadbox .loading').length == 1) return true
      showOverlay()

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

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

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

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

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

  /*
   * Public, $j.fn methods
   */

  $j.fn.twittadbox = function(settings) {
    init(settings)

    function clickHandler() {
      $j.twittadbox.loading(true)

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

      fillTwittadboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

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

    $j(document).trigger('init.twittadbox')
    makeCompatible()

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

    if (settings) $j.extend($j.twittadbox.settings, settings)
    $j('body').append($j.twittadbox.settings.twittadboxHtml)

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

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

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

    $js.loadingImage = $js.loading_image || $js.loadingImage
    $js.closeImage = $js.close_image || $js.closeImage
    $js.imageTypes = $js.image_types || $js.imageTypes
    $js.twittadboxHtml = $js.twittadbox_html || $js.twittadboxHtml
  }

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

    // image
    } else if (href.match($j.twittadbox.settings.imageTypesRegexp)) {
      fillTwittadboxFromImage(href, klass)
    // ajax
    } else {
      fillTwittadboxFromAjax(href, klass)
    }
  }

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

  function fillTwittadboxFromAjax(href, klass) {
    $j.get(href, function(data) { $j.twittadbox.reveal(data, klass) })
  }

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

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

    if ($j('twittadbox_overlay').length == 0) 
      $j("body").append('<div id="twittadbox_overlay" class="twittadbox_hide"></div>')

    $j('#twittadbox_overlay').hide().addClass("twittadbox_overlayBG")
      .css('opacity', $j.twittadbox.settings.opacity)
      .click(function() { $j(document).trigger('close.twittadbox') })
      .fadeIn(200)
    return false
  }

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

    $j('#twittadbox_overlay').fadeOut(200, function(){
      $j("#twittadbox_overlay").removeClass("twittadbox_overlayBG")
      $j("#twittadbox_overlay").addClass("twittadbox_hide") 
      $j("#twittadbox_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

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

})(jQuery);
