/*
 * g21Lightbox (for jQuery)
 * version: 1.0 (24.11.2008)
 * version: 1.1 (21.02.2009)
 * @requires jQuery v 1.2 or later
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Usage:
 *  
 *  jQuery(document).ready(function($) {
 *    $('a[rel*=g21Lightbox]').g21Lightbox() 
 *  })
 *
 *  <a href="#terms" rel="g21Lightbox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="g21Lightbox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="g21Lightbox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.g21Lightbox('some html')
 *
 *  This will open a g21Lightbox with "some html" as the content.
 *    
 *    jQuery.g21Lightbox(function($) { $.ajaxes() })
 *
 *  This will show a loading screen before the passed function is called,
 *  allowing for a better ajax experience.
 *
 */
(function($) {
 /**
   *  The static g21Lightbox() function, can be passed a string or
   *  function.
   *
   *  You can also use it programmatically:
   * 
   *    jQuery.g21Lightbox('some html')
   *
   *  This will open a g21Lightbox with "some html" as the content.
   *    
   *    jQuery.g21Lightbox(function($) { $.ajaxes() })
   *
   *  This will show a loading screen before the passed function is called,
   *  allowing for a better ajax experience.
   */
  $.g21Lightbox = function(data) {
    g21Lightbox_init()
    g21Lightbox_loading()
    $.isFunction(data) ? data.call(this, $) : g21Lightbox_reveal(data)
    return $
  }

 /**
   * g21Lightbox settings, which can be modified through the g21Lightbox() method 
   * or directly.
   *
   *    jQuery('a[rel*=g21Lightbox]').g21Lightbox({ loading_image: '/images/lightbox-loading.gif' })
   *
   *    jQuery.g21Lightbox.settings.loading_image = '/images/lightbox-loading.gif'
   */
  $.g21Lightbox.settings = {
    loading_image : '/pix/lightbox-loading.gif',
    close_image   : '/pix/lightbox-closelabel.png',
    image_types   : [ 'png', 'jpg', 'jpeg', 'gif' ],
    next_image    : '/pix/lightbox-next.png',
    prev_image    : '/pix/lightbox-prev.png',
    play_image    : '/pix/lightbox-play.png',
    pause_image   : '/pix/lightbox-pause.png',
    slide_duration: 6,
    g21Lightbox_html_overlay  : '\
  <div id="g21Lightbox_overlay" style="display:none;"> \
  </div>',
    g21Lightbox_html  : '\
  <div id="g21Lightbox" style="display:none;"> \
    <div class="g21LightboxPopup"> \
      <table> \
        <tbody> \
          <tr> \
            <td class="tl"/><td class="b"/><td class="tr"/> \
          </tr> \
          <tr> \
            <td class="b"/> \
            <td class="g21LightboxBody"> \
              <div class="g21LightboxContent"> \
			    <div class="g21LightboxImage"></div> \
              </div> \
              <div class="g21LightboxFooter"> \
                <div class="g21LightboxNavigation"></div> \
                <a href="#" class="g21LightboxClose"> \
                  <img src="/pix/lightbox-loading.gif" title="close" class="close_image" /> \
                </a> \
                <span class="g21LightboxInfo"></span> \
              </div> \
            </td> \
            <td class="b"/> \
          </tr> \
          <tr> \
            <td class="bl"/><td class="b"/><td class="br"/> \
          </tr> \
        </tbody> \
      </table> \
    </div> \
  </div>'
  }
  var $s = $.g21Lightbox.settings

  $.fn.g21Lightbox = function(settings) {
    g21Lightbox_init(settings)

    var image_types = $s.image_types.join('|')
    image_types = new RegExp('\.' + image_types + '$', 'i')

    // suck out the images
    var images = []
	var titles = []
	var descriptions = []
	
	$(this).each(function() {
      if (this.href.match(image_types) && $.inArray(this.href, images) == -1) 
        images.push(this.href)
		titles.push(this.title)
		descriptions.push($(this).attr('description'))
    })
    if (images.length == 0) images = null 

    function click_handler() {
      if ($('#g21Lightbox .g21LightboxLoading').length == 1) return false
      g21Lightbox_loading()

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

      // div
      if (this.href.match(/#/)) {
        var url    = window.location.href.split('#')[0]
        var target = this.href.replace(url,'')
        g21Lightbox_reveal($(target).clone().show(), klass)

      // image
      } else if (this.href.match(image_types)) {
        g21Lightbox_reveal_image(this.href, images, klass, titles, descriptions)

	  // ajax
      } else {
        $.get(this.href, function(data) { g21Lightbox_reveal(data, klass) })
      }

      return false
    }

    return this.click(click_handler)
  }

/**
  * The init function is a one-time setup which preloads vital images
  * and other niceities.
  */
  function g21Lightbox_init(settings) {
    if ($s.inited && typeof settings == 'undefined')
      return true
    else 
      $s.inited = true

    if (settings) $.extend($s, settings)
		{
	    $('body').append($s.g21Lightbox_html)
		$('body').append($s.g21Lightbox_html_overlay)
		}
    var preload = [ new Image(), new Image() ]
    preload[0].src = $s.close_image
    preload[1].src = $s.loading_image

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

    $('#g21Lightbox .g21LightboxClose').click(g21Lightbox_close)
    $('#g21Lightbox .close_image').attr('src', $s.close_image)
  }

/**
  * The loading function prepares the g21Lightbox by displaying it
  * in the proper spot, cleaning its contents, attaching keybindings 
  * and showing the loading image.
  */
  function g21Lightbox_loading() {
    if ($('#g21Lightbox .g21LightboxLoading').length == 1) return true

	$('#g21Lightbox .g21LightboxContent .g21LightboxTitle').animate({ height:'toggle' }, 300, function() {
 	  $('#g21Lightbox .g21LightboxContent .g21LightboxTitle').remove();
    })
	$('#g21Lightbox .g21LightboxContent .g21LightboxDescription').animate({ height:'toggle' }, 300, function() {
	  $('#g21Lightbox .g21LightboxContent .g21LightboxDescription').remove();
    })

	$(document).unbind('.g21Lightbox')
    $('#g21Lightbox .g21LightboxImage, #g21Lightbox .g21LightboxInfo, #g21Lightbox .g21LightboxNavigation').empty()
//    $('#g21Lightbox .g21LightboxContent, #g21Lightbox .g21LightboxInfo, #g21Lightbox .g21LightboxNavigation').empty()
//    $('#g21Lightbox .g21LightboxBody').children().hide().end().append('<div class="g21LightboxLoading"></div>')
    $('#g21Lightbox .g21LightboxBody').append('<div class="g21LightboxLoading"></div>')

    var pageScroll = getPageScroll()

	var bodyHeight = $('body').height()
	$('#g21Lightbox_overlay').css({
      top: 0,
      left: 0,
      height: bodyHeight,
      width: '100%',
	  opacity: '0.5',
	  filter: 'Alpha(Opacity=50)'
	  }).show()

	$('#g21Lightbox').css({
      top:	pageScroll[1] + (getPageHeight() / 10),
      left:	pageScroll[0]
    }).fadeIn('normal')

    $(document).bind('keydown.g21Lightbox', function(e) {
      if (e.keyCode == 27) g21Lightbox_close()
    })
  }

/**
  * The g21Lightbox_reveal function sets the user-defined class (if any)
  * on the .content div, removes the loading image, and displays
  * the data.  If an extra_setup functino is provided, it will be run
  * right before the data is displayed but after it is added.
  */
  function g21Lightbox_reveal(data, klass, extra_setup) {
    $('#g21Lightbox .g21LightboxContent').addClass(klass)
	$('#g21Lightbox .g21LightboxContent .g21LightboxImage').append(data)
    $('#g21Lightbox .g21LightboxLoading').remove()
    if ($.isFunction(extra_setup)) extra_setup.call(this)
    $('#g21Lightbox .g21LightboxBody > *').fadeIn('normal')
  }

/**
  * Used to load and show an image in the g21Lightbox.  Involved in the slideshow business.
  */
  function g21Lightbox_reveal_image(href, images, klass, titles, descriptions) {
	if (images) var extra_setup = g21Lightbox_setup_gallery(href, images, klass, titles, descriptions)
    var image    = new Image()
    image.onload = function() {
	 var position = $.inArray(href, images)
	 // get title and description
	 var titlestring = ''
	 if(titles[position]) titlestring = '<div class="g21LightboxTitle" style="display:none; width:'+image.width+'px;">'+titles[position]+'</div>'
	 var descriptionstring = ''
	 if(descriptions[position]) descriptionstring = '<div class="g21LightboxDescription" style="display:none; width:'+image.width+'px;">'+descriptions[position]+'</div>'
	// create the image content
	g21Lightbox_reveal('<img style="display:none;" src="' + image.src + '" /> ', klass, extra_setup)

	// animate and fade in the content
	$('#g21Lightbox .g21LightboxContent .g21LightboxImage').animate({ width: image.width }, 600).animate({ height: image.height }, 600).fadeIn(function() {
	  $('#g21Lightbox .g21LightboxContent .g21LightboxImage img').fadeIn('normal', function() {
	    $('#g21Lightbox .g21LightboxContent').append(titlestring).find('.g21LightboxTitle').animate({ height:'toggle' }, 300)
	    $('#g21Lightbox .g21LightboxContent').append(descriptionstring).find('.g21LightboxDescription').animate({ height:'toggle' }, 300)
	  })
    })
	// load the next image in the background
      if (images.length > 1) {
        var position = $.inArray(href, images)
        var next = new Image()
        next.src = images[position+1] ? images[position+1] : images[0]
      }
    }
    image.src = href
  }

/**
  * Unbinds all listeners and closes the g21Lightbox.
  */
  function g21Lightbox_close() {
    g21Lightbox_stop_slideshow()
    $(document).unbind('.g21Lightbox')
    $('#g21Lightbox').fadeOut('normal',function() {
    //  $('#g21Lightbox .g21LightboxContent').removeClass().addClass('g21LightboxContent')
	  $('#g21Lightbox_overlay').fadeOut()
    })
    return false
  }

  function g21Lightbox_setup_gallery(href, images, klass, titles, descriptions) {
    var position = $.inArray(href, images)
    var jump = function(where) {
      g21Lightbox_loading()
      if (where >= images.length) where = 0
      if (where < 0) where = images.length - 1
      g21Lightbox_reveal_image(images[where], images, klass, titles, descriptions)
    }

    return function() {
	  // next or close
	  if(images.length > 1)
	    { $('#g21Lightbox .g21LightboxImage img').css('cursor', 'pointer').click(function() { jump(position + 1); return false }).end() }
	  else
		{ $('#g21Lightbox .g21LightboxImage img').css('cursor', 'pointer').click(function() { g21Lightbox_close(); return false }).end() }
	  // add navigation if more than 1 image
	  if(images.length > 1)
	    {
	    $('#g21Lightbox .g21LightboxNavigation').
          append('<img class="g21LightboxPrev" src="' + $s.prev_image + '"/>' +
          '<img class="g21LightboxPlay" src="' + ($s.playing ? $s.pause_image : $s.play_image) + '"/>' +
          '<img class="g21LightboxNext" src="' + $s.next_image + '"/>').
          find('img').css('cursor', 'pointer').end().
          find('.g21LightboxPrev').click(function() { jump(position - 1); return false }).end().
          find('.g21LightboxNext').click(function() { jump(position + 1); return false }).end()
        $('#g21Lightbox .g21LightboxInfo').append((position + 1) + ' of ' + images.length)
        $('#g21Lightbox .g21LightboxPlay').bind('click.g21Lightbox', function() {
          $s.playing ? g21Lightbox_stop_slideshow() : g21Lightbox_start_slideshow()
          return false
          })
		}

      $(document).bind('keydown.g21Lightbox', function(e) {
        if (e.keyCode == 39) jump(position + 1) // right
        if (e.keyCode == 37) jump(position - 1) // left
      })
    }
  }

  function g21Lightbox_start_slideshow() {
    $('#g21Lightbox .g21LightboxPlay').attr('src', $s.pause_image)
	// first change imidiately
	$('#g21Lightbox .g21LightboxNavigation .g21LightboxNext').click()
	// next changes with relay
	$s.playing = setInterval(function() { $('#g21Lightbox .g21LightboxNext').click() }, $s.slide_duration * 1000)
}

  function g21Lightbox_stop_slideshow() {
    $('#g21Lightbox .g21LightboxPlay').attr('src', $s.play_image)
    clearInterval($s.playing)
    $s.playing = false
  }

  // 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) 
  }

  // adapter 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
  }
})(jQuery);
