/****************************************
* SpaceBox v 0.0.1                      *
*       heavily inspired and cloned     *
*       from jquery's facebox.          *
*       MIT LICENSE                     *
*  author: scott@0x7a69.net             *
****************************************/
(function() {
  $.spacebox = function(data, klass) {
    $.spacebox.loading();
    if (data.ajax) { 
      fillSpaceboxFromAjax(data.ajax);
      } else if (data.image) {
      fillSpaceboxFromImage(data.image);
      } else if (data.div) {
      fillSpaceboxFromHref(data.div);
      } else if (Object.isFunction(data)) {
      data.call($);
      } else {
      $.spacebox.reveal(data, klass);
      }
    return false;
   }
    Object.extend($.spacebox, 
      {settings: {
      opacity      : 0.6,
      overlay      : true,
      loadingImage : '/spacebox/images/loading.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      spaceboxHtml  : '<div id="spacebox" style="display:none;"><div class="popup"><div class="body"><div class="content"></div><a class="close_button"></a></div></div></div>'
    },
    loading: function() {
      init();
      if ($$('#spacebox .loading').length == 1) { return true; }
      showOverlay();
      $$('#spacebox .content').invoke('update');
      $$('#spacebox .body').first().hide().up().insert('<div class="loading"><br/><img src="'+$.spacebox.settings.loadingImage+'"/></div>');
      var width = (document.viewport.getDimensions().width / 3 - ($$('#spacebox .content').first().getWidth() / 3));
      $('spacebox').setStyle({left: width+"px", top: "100px"}).show();
      $(document).observe('keydown', function(e){
        if (Event.KEY_ESC != e.keyCode) {
          return; 
        }
        $.spacebox.close(); 
        return true;
      });
      $(document).fire('spacebox:loading');
    },
    reveal: function(data, klass) {
      $(document).fire('spacebox:beforeReveal');
      if (klass) { $$('#spacebox .content').first().addClass(klass); }
      $$('#spacebox .content').first().insert(data);
      $$('#spacebox .loading').invoke('remove');
      $$('#spacebox .body').first().show();
      var width = (document.viewport.getDimensions().width / 2 - ($$('#spacebox .content').first().getWidth() / 2));
      $('spacebox').style.left =  width + "px";
      $(document).fire('spacebox:reveal');
     $(document).fire('spacebox:afterReveal');
    },
    close: function() {
      document.fire('spacebox:close');
      return false;
    }
  })
  function init(settings) {
    if ($.spacebox.settings.inited)  { 
      return true;
    }  else { 
      $.spacebox.settings.inited = true; 
    }
    $(document).fire('spacebox:init');
    var imageTypes = $.spacebox.settings.imageTypes.join('|');
    $.spacebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i');
    if (settings) { $.extend($.spacebox.settings, settings); }
    $(document.body).insert($.spacebox.settings.spaceboxHtml);
    var preload = new Image();
    preload.src = $.spacebox.settings.loadingImage;
    $$('#spacebox .close_button').each(function(cb) { cb.observe('click', function() { $.spacebox.close(); }) });
  }
  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);
  }
  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;
  }
  function fillSpaceboxFromHref(href, klass) {
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0];
      var target = href.replace(url,'').replace('#', '');
      var clone = $(target).cloneNode(true);
//      $(clone).select('*[id]').concat(clone).invoke('writeAttribute', { id: null });
//      rename all the ids to _modal, instead of nuking them, i still need them
       $(clone).select('*[id]').each(function(c) {
            c.writeAttribute({id: c.id + '_modal'});
       });
       clone.writeAttribute({id: clone.id + '_modal'});
      $.spacebox.reveal(clone, klass)
    } else if (href.match($.spacebox.settings.imageTypesRegexp)) {
      fillSpaceboxFromImage(href, klass);
    } else {
      fillSpaceboxFromAjax(href, klass);
    }
  }
  function fillSpaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.spacebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass);
    }
    image.src = href;
  }
  function fillSpaceboxFromAjax(href, klass) {
    new Ajax.Request(href, {method: 'get', evalScripts: true, evalJS: true, onSuccess: function(transport) { $.spacebox.reveal(transport.responseText, klass); } });
  }
  function skipOverlay() {
    return ( $.spacebox.settings.overlay == false || $.spacebox.settings.opacity === null ) ;
  }
  function showOverlay() {
    if (skipOverlay()) { return; }
    if ($('spacebox_overlay') == null)  {
      $(document.body).insert('<div id="spacebox_overlay" class="spacebox_hide spacebox_overlayBG" style="opacity: '+$.spacebox.settings.opacity+';"></div>');
    }
    $('spacebox_overlay').observe('click', function() { $(document).fire('spacebox:close'); });
    return false;
  }
  function hideOverlay() {
    if (skipOverlay())  { return; }
      $("spacebox_overlay").remove();
    return false;
  }
 Element.addMethods({
    spaceboxInit: function(element, settings) {
     init(settings);
     element = $(element);
      element.onclick = function() {
        $.spacebox.loading(true);
        var klass = element.rel.match(/spacebox\[?\.(\w+)\]?/);
        if (klass) { klass = klass[1]; }
        fillSpaceboxFromHref(this.href, klass);
        return false;
      }
    }
  });
  document.observe('spacebox:close', function(event) {
    $(document).stopObserving('keydown');
    Effect.Fade('spacebox', {duration: 0.1, afterFinish: function() {
      $$('#spacebox .content').invoke('removeClassName').invoke('addClassName', 'content');
      hideOverlay.delay(0.3);
      $$('#spacebox .loading').invoke('remove');
   }});
  })
})();
document.observe("dom:loaded", function() {
  $$('a[rel*=spacebox]').invoke('spaceboxInit');
});
