/*
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";
	//alert('browser = ' +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);
Event.observe(window, 'load', getBrowserInfo, false);
Event.observe(window, 'unload', Event.unloadCache, false);

var lightbox = Class.create();

lightbox.prototype = {
	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
		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.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;
		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') this.loadInfo();
		//if ( display == 'block' ) { $('lightbox').focus(); }
	},
	
	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
		var myAjax = new Ajax.Request(
        this.content,
        {method: 'get', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
		);
	},
	
	// Display Ajax response
	processInfo: function(response){
		info = "<div id='lbContent'>" + response.responseText + "</div>";
		//alert (info);
		new Insertion.Before($('lbLoadMessage'), info)
		$('lightbox').className = "done";	
		this.actions();			
	},
	
	// Search through new links within the lightbox, and attach click event
	actions: function(){
		lbActions = document.getElementsByClassName('lbAction');
		for(i = 0; i < lbActions.length; i++) {
			//alert ('lbAction=' + lbActions[i].rel);
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		}
	},
	
	// insert new editor interface via embedded link from existing
	insert: function(e){
	   var link = Event.element(e).parentNode;
	   Element.remove($('lbContent'));
	   var myAjax = new Ajax.Request(
			  link.href,
			  {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
	   );
	},
	
	// insert new editor interface via embedded link from existing
	_replaceForm: function(url){
		//alert('url=' + url);
	   Element.remove($('lbContent'));
	   var myAjax = new Ajax.Request(
			  url,
			  {method: 'get', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
	   );
	},
	
	// close editor window
	deactivate: function(){
		Element.remove($('lbContent'));
		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		
		this.displayLightbox("none");
	},

	// pass data to login page
	register: function(){
		document.loginForm.email.value = document.userForm.email.value;
		this.deactivate();
	},
	
	// pass form data to server
	submit: function(e){
		var link = Event.element(e).parentNode;
		//alert('submit:');
		var form = $('editform');
		var formData = this._compileData(form);
		var header = new Array ("enctype", "multipart/form-data");
		//alert('submit: link.href =' + link.href);
		//alert('submit: formData =' + formData);
		//var myAjax = new Ajax.Request('',{method: 'post', postBody: formData, onComplete: this._respond.bindAsEventListener(this), onFailure: this._failure.bindAsEventListener(this)});
		//alert('myAjax =' + myAjax);
		var myAjax = new Ajax.Request(link.href,{method: 'post', requestHeaders: header, postBody: formData, onComplete: this._respond.bindAsEventListener(this), onFailure: this._failure.bindAsEventListener(this)});
		//var response = new Ajax.Request('',{method: 'post', postBody: formData, onFailure: this._failure.bindAsEventListener(this)});
		//var response = new Ajax.Request('',{method: 'post', postBody: formData, onComplete: this._respond.bindAsEventListener(this)});
	},

	// respond to unsuccessful ajax return
	_failure: function(response) {
		alert('_failure: ');
	},

	// respond to successful ajax return
	_respond: function(response) {
		//alert('_respond: ');
		//alert('response.responseText = ' + response.responseText);
		try {
			var data = eval( "(" + response.responseText + ")" );
		}
		catch (exception) {
			alert ('_respond: exception: ' + exception.name + ' = ' + exception.message+ ' & responseText= ' + response.responseText);
		}
		//alert('_respond: data[success] = ' + data['success']);
		if (data['success'] == 1) {
			if (data['messages'] != null) {
				this._displayMesssage(data['messages']);
			}
			this._updatePage();		
		} else {
			if (data['redirect'] != null && data['redirect'].length > 0) {
				//alert('redirect=' + data['redirect']);
				this._displayMesssage(data['messages']);
				this._replaceForm(data['redirect']);
			} else {
				this._updateForm(response);
			}
		}
	},
	
	// compile form data into POST format
	_compileData: function(form){
		var data = '';
		for(var i = 0; i < form.length; i++) {
			if(form[i].type == "checkbox" || form[i].type == "radio") {
				if(form[i].checked == true) {
					data += form[i].name + '=' + escape(form[i].value) + '&';
					//data += form[i].name + '=' + form[i].checked + '&';
				}
			} else {
				data += form[i].name + '=' + escape(form[i].value) + '&';
			}
		}
		//alert ('lightbox._compileData: ' + data);
		return data;
	},

	// update form with server response content
	_updateForm: function(response){
		//alert('_updateForm:');
		var form = $('editform');
		//var message = $('editMessage');
		var data = eval( "(" + response.responseText + ")" );
		//var data = eval(response.responseText);
		this._displayMesssage(data['messages']);
		// update form fields
		for(var i = 0; i < form.length; i++) {
			//alert('_updateForm: i=' + i + ' & form[i].name=' + form[i].name);
			if (data[form[i].name]) {
				form[i].value = data[form[i].name];
			}
		}
	},

	// update page with original URL & close lightbox
	_updatePage: function(){
		location.reload(true);
		this.deactivate();
	},

	// display response message
	_displayMesssage: function(messages){
		// display messages from list
		var msg = '';
		for (var i = 0; i < messages.length; i++) {
			msg += messages[i] + "\n";
		}
		alert (msg);
	}
}

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

// Onload, make all links that need to trigger a lightbox active
function initialize(){
	//alert ('initializing");
	addLightboxMarkup();
	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() {
	bod 				= document.getElementsByTagName('body')[0];
	overlay 			= document.createElement('div');
	overlay.id		= 'overlay';
	lb					= document.createElement('div');
	lb.id				= 'lightbox';
	lb.className 	= 'loading';
	lb.innerHTML	= '<div id="lbLoadMessage">' +
						  '<p>Loading</p>' +
						  '</div>';
	bod.appendChild(overlay);
	bod.appendChild(lb);
}
