/*
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/
*/

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

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

//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 = "Netscape Navigator"
		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', initialize);//, false);//Runs the initialize function when the window loads
Event.observe(window, 'load', getBrowserInfo);//, false);
/*http://www.prototypejs.org/api/event/unloadCache/*/
//Event.observe(window, 'unload', Event.unloadCache);//, false);

var lightbox = Class.create();
var gallerybox = Class.create();
var bInitDone = false;

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
		this.oldClass = null;
		this.content = ctrl.href + '&lb=' + ctrl.getAttribute("rev");//Add the module to load in link
		this.lbClass = ctrl.getAttribute("rel");//Get the classname which the lightbox should have		
		this.lightboxContent = null;//Set so it will only be filled by the right function, when needed
		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.displayLightbox("block");
	},
	
	//Activate the lightbox upon reload of the page, to allow for displaying the desired content, mostly forms with some error in the post
	activateReload: function(url,lbStyle){
		this.content = url;
		this.lbClass = lbStyle;
		this.activate();
	},
	
	//Activate the lightbox when upload button has been pressed
	activateUpload: function(lbContent){
		this.lightboxContent = lbContent;
		this.lbClass = 'lbInfo';
		this.activate();
	},
	
	
	//Function activates the lightbox and displays the error caused during a file download
	activateDownloadError: function(lbContent){
		/*this.content = url;*/
		this.lbClass = 'lbAlert';
		this.lightboxContent = lbContent;
		this.activate();
	},
	
	//Load the alert error
	activateCheckError: function(lbContent){
		this.activateDownloadError(lbContent);
	},
	
	// 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;
		}
	},
	
	// 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){
		$('overlay').style.display = display;
		$('lightbox').style.display = display;
		if(display != 'none'){
			Event.observe('overlay', 'click', this.deactivate.bindAsEventListener(this), false);
			this.loadInfo();
		}
	},
	
	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
		
		if(this.lightboxContent != null){
			this.processInfo(null);
			return;
		}		

		var myAjax = new Ajax.Request(
        this.content,
        {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
		);
		
	},
	
	
	// Display Ajax response
	processInfo: function(response){
		
		//FS20080824 Remove any previously displayed content from the box
		//if there is a document displayed, close it
		if(document.getElementById('lbContent')){
			Element.remove($('lbContent'));
		}
		
		info  = '<div id="lbContent">';
		info += '<div class="lbHead">';
		info += '<a href="javascript:;" onclick="lightbox.prototype.deactivate();"><img src="http://www.tansarc.nl/image/manage/Overlay-close.png" alt="Close" title="Close"/></a>';
		info += '</div>'
		info += '<div class="lbMain">';
		info += response.responseText;
		info += '</div>';		
		info += '</div>';		
		
		new Insertion.Before($('lbLoadMessage'), info);
		
		//When loading the image preview
		// if browser is IE6, default display all delete fields, otherwise it refuses to execute any hover related actions
		if(browser == "Internet Explorer" && version == 6){
			del = $('lbContent').select('.img_delete');//document.getElementsByClassName('img_delete',document.getElementById('lbContent'));//Will be depricated in future version!!1
			//Initialize lightBox
			for(i = 0; i < del.length; i++) {
				del[i].style.display = 'block';
			}
		}	
		
		//Give the lightbox a class depending on the content requested
		//The rel attribute in the anchor holds the classname
		if(this.lbClass){
			$('lightbox').className = this.lbClass;
		}
		else{
			$('lightbox').className = "done";
		}
		this.actions();
		this.addLightBox();//Search through links in box the load new content into the box
		
		//Reset the old class
		if(this.oldClass != null){
			this.lbClass  = this.oldClass;
			this.oldClass = null;
		}
	},
	
	// Search through new links within the lightbox, and attach click event
	actions: function(){
	
		//Add action handlers
		lbActions = $$('.lbAction');//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;};
		}
		
		//Add datePicker fields
		aDatePickers = $$('.datepicker');//document.getElementsByClassName('datepicker');
		for(i=0;i<aDatePickers.length; i++) {
			aDatePickers[i].id = 'datePicker-' + i;
			var picker = new Control.DatePicker('datePicker-' + i, {icon: 'http://www.tansarc.nl/image/manage/calendar.png', locale:'en_GB', loadInLightbox: true});
		}
		//Add timePicker fields
		aTimePickers = $$('.timepicker');//document.getElementsByClassName('timepicker');
		for(i=0;i<aTimePickers.length; i++) {
			aTimePickers[i].id = 'timePicker-' + i;
			var picker = new Control.DatePicker('timePicker-' + i, {icon: 'http://www.tansarc.nl/image/manage/clock.png', locale:'en_GB', use24hrs: true, datePicker: false, timePicker: true, timePickerAdjacent: true, loadInLightbox: true});
		}
		//Add dateTimePicker fields
		aDateTimePickers = $$('.datetimepicker');//document.getElementsByClassName('datetimepicker');
		for(i=0;i<aDateTimePickers.length; i++) {
			aDateTimePickers[i].id = 'dateTimePicker-' + i;
			var picker = new Control.DatePicker('dateTimePicker-' + i, {icon: 'http://www.tansarc.nl/image/manage/calendar.png', locale:'en_GB', use24hrs: true, timePicker: true, timePickerAdjacent: true, loadInLightbox: true});
		}
	},
	
	// 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)}
	   );
	},
	
	insertConfirm: function(e){
		this.oldClass = this.lbClass;	
		this.lbClass = 'lbConfirm';		
		this.insert(e);		
	},
	
	//Function that reloads when a select element is changed
	changeType: function(selectOption){
	   
	   //Store the old display class
	   this.lbClass = $('lightbox').className;
	   
	   //Show the loading message
	   $('lightbox').className = "loading";
	   
	   //Remove the old content, make AJAX request and process info afterwards
	   Element.remove($('lbContent'));
	   var myAjax = new Ajax.Request(
			  selectOption[selectOption.selectedIndex].value,
			  {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
	   );
	   //Restore the original display class
	   $('lightbox').className = this.lbClass;
	},
	
	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		if(document.getElementById('lbContent')){
			Element.remove($('lbContent'));
		}
		
		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		
		this.displayLightbox("none");
		$('lightbox').className = "loading";
	},	
		
	// Add lightboxes to the newly loaded item
	addLightBox: function(){
		lbox = $('lightbox').select('.lbOn');//document.getElementsByClassName('lbOn',document.getElementById('lightbox'));//Will be depricated in future version!!1
		//Initialize lightBox
		for(i = 0; i < lbox.length; i++) {
			valid = new lightbox(lbox[i]);
		}
	}
}

gallerybox.prototype = {

	yPos : 0,
	xPos : 0,
	width : 0,
	height : 0,
	content : '',

	initialize: function(ctrl) {
		this.content = ctrl.href;// + '&lb=' + ctrl.getAttribute("rev");//Add the module to load in link
		this.width = ctrl.getAttribute("rev");//Get the classname which the lightbox should have		
		this.height = ctrl.getAttribute("rel");//Get the classname which the lightbox should have		
		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.displayLightbox("block");
	},
	
	//Activate the lightbox upon reload of the page, to allow for displaying the desired content, mostly forms with some error in the post
	activateReload: function(url,lbStyle){
		this.content = url;
		//this.lbClass = lbStyle;
		this.activate();
	},
	
	
	// 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;
		}
	},
	
	// 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){
		$('overlay').style.display = display;
		$('lightbox').style.display = display;
		if(display != 'none'){
			Event.observe('overlay', 'click', this.deactivate.bindAsEventListener(this), false);
			this.loadInfo();
		}
	},
	
	loadInfo: function() {
		this.processInfo();		
	},
	
	
	processInfo: function(){
		
		//FS20080824 Remove any previously displayed content from the box
		//if there is a document displayed, close it
		if(document.getElementById('lbContent')){
			Element.remove($('lbContent'));
		}
		
		info  = '<div id="lbContent">';
		info += '<div class="lbGalleryHead">';
		info += '<a href="javascript:;" onclick="lightbox.prototype.deactivate();"><img src="/shared/image/gallery/close-lightbox.png" alt="Close" title="Close"/></a>';
		info += '</div>'
		info += '<div class="lbMain">';
		info += '<img src="'+this.content+'" />';
		info += '</div>';		
		info += '</div>';		
		
		new Insertion.Before($('lbLoadMessage'), info);

		var viewportheight = 0;
		// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
		if (typeof window.innerWidth != 'undefined'){
		      viewportheight = window.innerHeight;
		}
		// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		else if (typeof document.documentElement != 'undefined'
				 && typeof document.documentElement.clientWidth !=
		     	 'undefined' && document.documentElement.clientWidth != 0){
		       viewportheight = document.documentElement.clientHeight;
		}
		marginTop = -1*(this.height/2) - (viewportheight-this.height)/4;

		$('lightbox').style.width = this.width+'px';
		$('lightbox').style.height = this.height+'px';
		$('lightbox').style.marginLeft = -1*(this.width/2)+'px';
		$('lightbox').style.marginTop = marginTop+'px';
		$('lightbox').className = "lbGallery";
	},
	
	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		if(document.getElementById('lbContent')){
			Element.remove($('lbContent'));
		}
		
		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		
		$('lightbox').style.width = '';
		$('lightbox').style.height = '';
		$('lightbox').style.marginLeft = '';
		$('lightbox').style.marginTop = '';
		
		
		this.displayLightbox("none");
		$('lightbox').className = "loading";
	}
}

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

// Onload, make all links that need to trigger a lightbox active
function initialize(){

	//Initialize lightBox
	lbox = $$('.lbOn');//document.getElementsByClassName('lbOn',document.getElementById('lightbox'));//Will be depricated in future version!!1
	for(i = 0; i < lbox.length; i++) {
		valid = new lightbox(lbox[i]);
	}
	//Initialize lightBox
	lbox = $$('.lbGalleryOn');
	for(i = 0; i < lbox.length; i++) {
		valid = new gallerybox(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() {
	//Body is replaced because markup is included in html head
	return;
}
