/*
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/

Modified to ensure it won't upset Media River's "Grab It" Flash controls.
Content in the lightbox is hidden rather than destroyed when the user closes it.
*/

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;
var lightboxIsInitialized = false;

/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Mozilla"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/*-----------------------------------------------------------------------------------------------*/

Event.observe(window, 'load', initLightbox, false);
//Event.observe(window, 'load', getBrowserInfo, false);  // do this the first time lightbox is initialized
//Event.observe(window, 'load', addLightboxMarkup, false);  // do this the first time lightbox is initialized

// Event.unloadCache is no longer available in prototype 1.6
if (Event.unloadCache) {
	Event.observe(window, 'unload', Event.unloadCache, false);
}

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
		if(!lightboxIsInitialized){
			addLightboxMarkup();
			getBrowserInfo();			
			lightboxIsInitialized = true;
		}
		this.content = ctrl.href;
		Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
		ctrl.onclick = function(){return false;};
	},

	// Turn everything on - mainly the IE fixes
	activate: function(){
		if (browser == 'Internet Explorer'){
			this.getScroll();
			this.prepareIE('100%', "hidden");
			this.setScroll(0,0);
			this.hideSelects("hidden");
		}
		this.hideObjects("hidden");
		this.hideEmbeds("hidden");
			
		this.displayLightbox("block");
			
		//Bug in Firefox/Mac will hide Flash content if there is ANY opacity set on lightbox.
		if(OS == "Mac" && browser == "Mozilla") {
			$('lbOverlay').style.opacity = 1.0;
		}
	},

	// 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;

		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(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},
	
	// Same for objects i.e. Flash
	hideObjects: function(visibility){
		objects = document.getElementsByTagName('object');
		for(i = 0; i < objects.length; i++) {
			objects[i].style.visibility = visibility;
		}
	},

	// Same for embeds
	hideEmbeds: function(visibility){
		embeds = document.getElementsByTagName('embed');
		for(i = 0; i < embeds.length; i++) {
			embeds[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){
		$('lbOverlay').style.display = display;
		$('lightbox').style.display = display;
		if(display != 'none') {
			this.loadInfo();
		}
	},

	// 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){
		Element.hide('systemWorking');
		
		// check for existing content DIV - if it's there, delete it now
		if($('lbContent') != null)		
		{
		   Element.remove($('lbContent'));
		   
		   // alternate approach
		   // if removing the element continues to prove problematic,
		   // assign inner text and unhide the existing DIV
		   // comment out Element.remove above if using this approach.
		   
		   //$('lbContent').innerHTML = response.responseText;
		   //$('lbContent').style.visibility = "visible";
		   //$('lbContent').style.display = "block";
		}
		
		// The below two lines become an "else" clause to the above if using
		// the alternate approach
		
		// else {
	   info = "<div id='lbContent'>" + response.responseText + "</div>";
	   new Insertion.Before($('lbLoadMessage'), info);
		// }
		
		$('lightbox').className = "done";
		this.actions();

		// reposition lightbox to match loaded content
		var lbContent = $("lbContent");
		var lightbox = lbContent.parentNode;
		
		if (lightbox.style.display != "none") {
			// grab a bunch-o-numbers
			var vp = viewportSize();
			var ps = pageSize();
			var lb = lbContent.getDimensions();
			var center = {x : vp.width / 2, y : vp.height / 2};

			// position horizontally
			var left = (vp.width > lb.width) ? center.x - lb.width / 2 : 0;

			// position vertically, adjustedHeight lets tweak the vertical position
			var adjustedHeight = lb.height * 1.05;
			var top = (vp.height > adjustedHeight) ? center.y - adjustedHeight / 2 : 0;
			lightbox.style.left = left + "px";
			lightbox.style.top = top + "px";
			
			/* set overlay to the size of capsWrapper to prevent
			 things peaking out of the overlay */
			// get capsWrapper width for actual caps width. getWidth doesn't work with this RC
			var capsWidth = $("capsWrapper").getDimensions().width;
			capsWidth = capsWidth + 10; //Pad it a little to cover some body padding
			// get body height to overlay whole document
			var bodyHeight = $$("body")[0].getHeight();
			//set overlay to body height
			$("lbOverlay").style.height = bodyHeight + "px";
			// set height to either pagesize width or capsWidth
			$("lbOverlay").style.width = (ps.width > capsWidth) ? ps.width + "px" : capsWidth + "px";
		}
	},

	// Search through new links within the lightbox, and attach click event
	actions: function(){
		lbActions = document.getElementsByClassName('lbAction');

		for(i = 0; i < lbActions.length; i++) {
			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(){
	
	   // Determine if a Clicksurge widget is in the lightbox
	   var lbContentDIV = $('lbContent');
	   var blnShouldRemoveLBContent = true;
	   if(lbContentDIV != null)
	   {
	      var objectsInContentDIV = lbContentDIV.getElementsByTagName("object");
	      if(objectsInContentDIV != null)
	      {
	         for(var i=0; i<objectsInContentDIV.length; i++)
	         {
	            var objTest = objectsInContentDIV[i];
	            var dataAttr = objTest.getAttribute("altHtml");
	            if(dataAttr != null && dataAttr.indexOf("clearspring") != -1)
	            {
	               // found a Clicksurge widget - do not destroy content
	               blnShouldRemoveLBContent = false;
	            }
	         }
	      }
      }
      	      
	   // If it isn't, call Element.remove as usual
      if(blnShouldRemoveLBContent == true)
      {      	      
		   Element.remove($('lbContent'));
      }		   
      // If it is, don't remove it, just hide it
      else
      {
	      $('lbContent').style.display = "none";
	      $('lbContent').style.visibility = "hidden";
      }

		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		this.hideObjects("visible");
		this.hideEmbeds("visible");

		this.displayLightbox("none");		
	},

	openMultistockPick:function()
	{
		Element.remove($('lbContent'));

		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}

		this.displayLightbox("none");
		var stockPickWin = window.open('MultiTickerEntry.aspx?ticker= ', 'PickStocks','scrollbars=yes,width=700,height=500,status=1').focus();
	}
}

/*-----------------------------------------------------------------------------------------------*/


// Onload, make all links that need to trigger a lightbox active
function initLightbox(){
	// addLightboxMarkup(); // do this the first time lightbox is initialized
	lbox = document.getElementsByClassName('lbOn');
	for(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() {
	var bod 			= document.getElementsByTagName('body')[0];
	
	var overlay 	= document.createElement('div');
	overlay.id		= 'lbOverlay';
	
	var lb				= document.createElement('div');
	lb.id					= 'lightbox';
	lb.className 	= 'loading';
	lb.innerHTML	= '<div id="lbLoadMessage">' +
										'<div id="systemWorking">Loading...</div>' +
									'</div>';
						  
	bod.appendChild(overlay);
	bod.appendChild(lb);
}


// http://www.quirksmode.org/viewport/compatibility.html
function viewportSize() {
	var w,h;
	if (self.innerHeight) {
		// all except Explorer
		w = self.innerWidth;
		h = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		// Explorer 6 Strict Mode
		w = document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	} else if (document.body) {
		// other Explorers
		w = document.body.clientWidth;
		h = document.body.clientHeight;
	}
	return {height:h, width:w}
}


// http://www.quirksmode.org/viewport/compatibility.html
function scrollOffset () {
	var x,y;
	if (self.pageYOffset) {
		// all except Explorer
		x = self.pageXOffset;
		y = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		// Explorer 6 Strict
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	} else if (document.body) {
		// all other Explorers
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}
	return {top:y, left:x};
}

// http://www.quirksmode.org/viewport/compatibility.html
function pageSize() {
	var x,y;
	var test1 = document.body.scrollHeight;
	var test2 = document.body.offsetHeight
	if (test1 > test2) {
		// all but Explorer Mac
		x = document.body.scrollWidth;
		y = document.body.scrollHeight;
	} else {
		// Explorer Mac - would also work in Explorer 6 Strict, Mozilla and Safari
		x = document.body.offsetWidth;
		y = document.body.offsetHeight;
	}
	return {height:y, width:x};
}
