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

  /*
   * Public, $.exxcire methods
   */
	httpurl = SITE_URL;
  $.extend($.exxcire, {
    settings: {
      opacity      : 0,
      overlay      : true,
      loadingImage : httpurl+'img/loading.gif',
      closeImage   : httpurl+'img/msgbox/closelabel.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      exxcireHtml  : '\
    <div id="exxcire" style="display:none;visibility:visible;"> \
      <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> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

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

      $('#exxcire .content').empty()
      $('#exxcire .body').children().hide().end().
        append('<div class="loading" style="width:450px;"><img src="'+$.exxcire.settings.loadingImage+'"/></div>')

      $('#exxcire').css({    top:	getPageScroll()[1] + (getPageHeight() / 10),    left:	( $(window).width()  - 491 ) / 2 }).show()
	
      $(document).bind('keydown.exxcire', function(e) {
        if (e.keyCode == 27) $.exxcire.close()
        return true
      })
      $(document).trigger('loading.exxcire')
    },

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

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

  /*
   * Public, $.fn methods
   */

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

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

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

      fillexxcireFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

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

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

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

    if (settings) $.extend($.exxcire.settings, settings)
    $('body').append($.exxcire.settings.exxcireHtml)

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

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

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

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.exxcireHtml = $s.exxcire_html || $s.exxcireHtml
  }

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

    // image
    } else if (href.match($.exxcire.settings.imageTypesRegexp)) {
      fillexxcireFromImage(href, klass)
    // ajax
    } else {
      fillexxcireFromAjax(href, klass)
    }
  }

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

  function fillexxcireFromAjax(href, klass) {
    $.get(href, function(data) { $.exxcire.reveal(data, klass) })
  }

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

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

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

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

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

      $('#exxcire_overlay').fadeOut(200, function(){
      $("#exxcire_overlay").removeClass("exxcire_overlayBG")
      $("#exxcire_overlay").addClass("exxcire_hide") 
      $("#exxcire_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

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

})(jQuery);
