/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
*/

// Object.prototype.attachEvent = function (sEvent, fnHandler, bUseCapture) 
// {
//     this.addEventListener(sEvent.indexOf('on') == 0 ? sEvent.replace('on', '') : sEvent, fnHandler, bUseCapture);
// }

var agt=navigator.userAgent.toLowerCase();
var NiceBrowser=(typeof encodeURIComponent != 'undefined') && (typeof document.getElementById != 'undefined');
var SafariBrowser=(agt.indexOf('safari')!=-1);
var OperaBrowser=(typeof window.opera=="undefined"?false:true);
var OperaVersion=(OperaBrowser?parseInt(agt.charAt(agt.lastIndexOf("opera")+6)):false);
var AjaxEnabled=Ajax.getTransport();

var MozBrowser = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1) && (agt.indexOf('compatible') == -1) && (!OperaBrowser) && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var IEBrowser=(navigator.appVersion.indexOf('MSIE') != -1) && !OperaBrowser;
var IEBrowserPNG=false;
var IEBrowserOld=false;
var weReady=false;

if (!OperaBrowser && IEBrowser && window.attachEvent)
{
  var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
  IEBrowserPNG = (rslt != null && Number(rslt[1]) >= 5.5 && Number(rslt[1]) < 7);
  IEBrowserOld = (rslt != null && Number(rslt[1]) < 6);
}

var JSList = new Array();

if (!JSRoot) var JSRoot = '/';


// Code originally from jQuery: http://jquery.com/
(OnReady = {
    initialize: function() {
        if (!NiceBrowser) return false;
        var browser = navigator.userAgent.toLowerCase()
        if ((/mozilla/.test(browser) && !/compatible/.test(browser)) ||
            /opera/.test(browser)) {
            document.addEventListener( "DOMContentLoaded", OnReady.fire, false );
        } else if (/msie/.test(browser) && !/opera/.test(browser)) {
            document.write("<scr" + "ipt id=__ie_init defer "+"src=https:///><\/script>");
            var script = document.getElementById("__ie_init");
            script.onreadystatechange = function() {
            if (OnReady.readyState == "complete")
                OnReady.fire();
            };
            script = null;
        } else if (/webkit/.test(browser)) {
            OnReady.safariTimer = setInterval(function() {
                if (document.readyState == "loaded" || document.readyState == "complete") {
                    clearInterval( jQuery.safariTimer );
                    OnReady.safariTimer = null;
                    OnReady.fire();
                }
            }, 10);
        }
        Event.observe(window, 'load', OnReady.fire);
    },

    isReady: false,
    readyList: [],

    register: function(func) {
        if (OnReady.isReady )
            func.apply( document );
        else
            OnReady.readyList.push(func);
        return this;
    },

    fire: function() {
        if (!OnReady.isReady) {
            OnReady.isReady = true;
            if (OnReady.readyList) {
                for (var i = 0, func; func = OnReady.readyList[i]; ++i)
                    func.apply(document);
                OnReady.readyList = null;
            }
        }
    }
}).initialize();

if (!NiceBrowser) 
    Event.observe=refalse;

function refalse()
{
  return false;
}

function GlobalKey(event)
{
    var evt = window.event ? window.event : event;

    var code = evt.keyCode ? evt.keyCode : evt.which ? evt.which : null;
    if (27 == code || 0x27 == code)
       window.CloseBox();
}

if (document.addEventListener)
    document.addEventListener('keydown', GlobalKey, false);
else
    document.attachEvent('onkeydown', GlobalKey);
    
var lightbox = Class.create();
var lightbox_ready = false;
var lightbox_height = 0;

lightbox.prototype = {
 callAfterLoad: null, 
 yPos : 0,
 xPos : 0,
 inner: "",

 initialize: function(ctrl, url, call_func) {
  if (!lightbox_ready) addLightboxMarkup();

  this.content = url || ctrl.href;
  if (ctrl)
  {
    Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
    ctrl.onclick = refalse;
  }

  if (null != call_func)
    this.callAfterLoad = call_func;
 },

 // Turn everything on - mainly the IE fixes
 activate: function(){
  this.displayLightbox("block");
 },

 // Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
 prepareIE: function(height, overflow){
  bod = document.getElementsByTagName('body')[0];
  bod.style.height = height;
  bod.style.overflow = overflow;
  if (!IEBrowserOld) bod.style.overflowY = (overflow=="hidden"?"scroll":"");


  htm = document.getElementsByTagName('html')[0];
  htm.style.height = height;
  htm.style.overflow = overflow;
 },

 // In IE, select elements hover on top of the lightbox
 hideSelects: function(visibility){
  selects = document.getElementsByTagName('select');
  for(var i = 0; i < selects.length; i++) {
   selects[i].style.visibility = visibility;
  }
 },

 // Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
 getScroll: function(){
  if (self.pageYOffset) {
   this.yPos = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop){
   this.yPos = document.documentElement.scrollTop;
  } else if (document.body) {
   this.yPos = document.body.scrollTop;
  }
 },

 setScroll: function(x, y){
  window.scrollTo(x, y);
 },

 displayLightbox: function(display){
    var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

   
  if(display != 'none'){
   this.loadInfo();
  }
  else
  {
    $('overlay').style.display = display;
    $('lightbox').style.display = display;
  }

  $('overlay').style.height = pageHeight+' px';

 },

 // Begin Ajax request based off of the href of the clicked linked
 loadInfo: function() {
   var myAjax = new Ajax.Request(
         this.content,
         {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
   );
 },

 // Display Ajax response
 processInfo: function(response){
  if (response.responseText=="") return false;
  if (IEBrowser){
   this.getScroll();
   this.prepareIE('100%', 'hidden');
   this.setScroll(0,0);
   this.hideSelects('hidden');
  }
  $('overlay').style.display = "block";
  $('lightbox').style.display = "block";

  this.inner=response.responseText;
  
  /*
  if ($('lbContent'))
  {
    //
    var myEffect = new fx.Height("lbContent" , {duration: 150, onComplete:
      this.processInfoFX.bindAsEventListener(this) }
     );
     myEffect.toggle();
  }
  else
  {
    this.processInfoFX();
  }
  */

  this.processInfoFX();
 },

 processInfoFX: function()
 {
  if ($('lbContent')) Element.remove($('lbContent'));
  var info = "<div id='lbContent'>" + this.inner + "</div>";

  new Insertion.Before($('lbLoadMessage'), info);
  this.actions();

  $('lightbox').className = "done";
  $('lightbox').style.height=$("lbContent").offsetHeight+"px";

  var clse=$("lbClose");

  if (clse)
  {
    Event.observe(clse, 'click', this.deactivate.bindAsEventListener(this), false);
    clse.onclick = refalse;

    Event.observe(document, "keypress", this.deactivateESC.bindAsEventListener(this), false);
  }

  var clse=document.getElementsByClassName("laClose");
  if (clse) for (var i in clse)
  {
    Event.observe(clse[i], 'click', this.deactivate.bindAsEventListener(this), false);
    clse[i].onclick = refalse;
  }

 },

 // Search through new links within the lightbox, and attach click event
 actions: function(){
  lbActions = document.getElementsByClassName('lbAction');

  for(var i = 0; i < lbActions.length; i++) {
   eval(lbActions[i].value);
   //Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
   //lbActions[i].onclick = function(){return false;};
  }

 },

 // Example of creating your own functionality once lightbox is initiated
 insert: function(e){
    link = Event.element(e).parentNode;
    Element.remove($('lbContent'));

    var myAjax = new Ajax.Request(
     link.href,
     {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
    );

 },

 // Example of creating your own functionality once lightbox is initiated
 deactivate: function(){
  var clse=$("lbClose");

  if (clse)
  {
    Event.stopObserving(clse, 'click', this.deactivate.bindAsEventListener(this), false);
    Event.stopObserving(document, 'keypress', this.deactivateESC.bindAsEventListener(this), false);
  }

  var clse=document.getElementsByClassName("laClose");
  if (clse) for (var i in clse)
  {
    Event.stopObserving(clse[i], 'click', this.deactivate.bindAsEventListener(this), false);
  }

  if ($('lbContent')) Element.remove($('lbContent'));

  if (IEBrowser){
   this.setScroll(0,this.yPos);
   this.prepareIE("", "");
   this.hideSelects("visible");
  }

  this.displayLightbox("none");
 },

 deactivateESC: function(e){
   if (e.keyCode==Event.KEY_ESC) this.deactivate();
 }

}

/*-----------------------------------------------------------------------------------------------*/

// Event.observe(window, 'load', initialize, false);

// Onload, make all links that need to trigger a lightbox active
function initialize(){
 addLightboxMarkup();
 lbox = document.getElementsByClassName('lbOn');
 for(var i = 0; i < lbox.length; i++) {
  valid = new lightbox(lbox[i]);
 }
}

// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
function addLightboxMarkup() {
 if (lightbox_ready) return;
 lightbox_ready = true;
 var bod        = document.getElementsByTagName('body')[0];
 var overlay    = document.createElement('div');
 overlay.id     = 'overlay';

 if (IEBrowser)
 {
   overlay.style.backgroundImage="none";
   overlay.style.backgroundColor="#000";
   overlay.style.filter="alpha(opacity=70)";
 }
 else if (MozBrowser)
 {
   overlay.style.backgroundImage="";
   overlay.style.backgroundColor="#000";
   overlay.style.MozOpacity="0.7";
 }
 else if (OperaBrowser && OperaVersion>8)
 {
   overlay.style.backgroundImage="";
   overlay.style.backgroundColor="#000";
   overlay.style.opacity="0.7";
 }

 if (!_v('lightbox'))
 {
     var lb = document.createElement('div');
     lb.id  = 'lightbox';
 }
 else
     var lb = _v('lightbox');

 lb.className= 'loading';
 lb.innerHTML= '<div id="lbLoadMessage"><p>&nbsp;</p></div>';
 bod.appendChild(overlay);
 bod.appendChild(lb);

 /*if (IEBrowserPNG)
 {
   document.styleSheets[0].addRule(".lb_top", "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='image', src='"+JSRoot+"lb_top_line.png');")
   document.styleSheets[0].addRule(".lb_head", "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='scale', src='"+JSRoot+"lb_top_body.png');");
   document.styleSheets[0].addRule(".lb_line", "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='image', src='"+JSRoot+"lb_line.png');");
   document.styleSheets[0].addRule(".lb_body", "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='scale', src='"+JSRoot+"lb_bottom_body.png');");
   document.styleSheets[0].addRule(".lb_bottom", "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='image', src='"+JSRoot+"lb_bottom_line.png');");
 }*/
}