/*
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);
Event.observe(window, 'load', getBrowserInfo, false);
//Event.observe(window, 'unload', Event.unloadCache, false); //no need for this with prototype 1.6

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
		addLightboxMarkup(); //NP - moved from initialize() function (below) to fix IE issue
		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");

		//DA: don't drag lightboxes... 
		//if (browser != 'Internet Explorer')	new Draggable('lightbox',{revert:false});
	},

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

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

	// In IE, select elements hover on top of the lightbox
	//NP 31/01/2008 - fix IE issue with hidden selects being displayed when LB turned off 
	hideSelects: function(visibility){
		var selects = $$('select');
		for(i = 0; i < selects.length; i++) {
			var curVis=selects[i].getStyle('visibility');
			var selectAncestors=selects[i].ancestors();
			var changeVis=true;
			/*Only change visibility of elements that are currently visible on page
			(ie. none of their ancestors are hidden)*/
			selectAncestors.each(function(item){
				if ((item.getStyle('display')=="none")||(item.getStyle('visibility')=="hidden")){
					changeVis=false;
					throw $break;
				}
			});
			//Check visibility status before deciding whether to change
			switch(curVis) {
				case "inherit":
					if ((visibility=='hidden') && changeVis){ //Hide
						selects[i].style.visibility = visibility;
						//Use 'zoom' to mark this item so we can revert to 'inherit'
						selects[i].style.zoom="100%";
					} 
					break;
				case "visible":
					if ((visibility=='hidden') && changeVis){ //Hide
						selects[i].style.visibility = visibility;
					} 
					break;
				case "hidden":
					if (visibility=='visible'){ //Show
						if (changeVis){
							if(selects[i].style.zoom=="100%"){
								//Revert to 'inherit'
								selects[i].style.visibility = "inherit";
								//Clear 'zoom' marker
								selects[i].style.zoom="normal";
							}else{
								selects[i].style.visibility = visibility;
							}
						}
					} 
					break;
			}
		}
	},

	// 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){
	//	alert("lightbox: " + typeof($('lightbox')));
			$('overlay').style.display = display;
			$('lightbox').style.display = display;
			if (display!="none")
			{
				var myWidth=getQueryVariable("width",this.content);
				var myHeight=getQueryVariable("height",this.content);
				$('lightbox').style.width =myWidth+"px";
				$('lightbox').style.height =myHeight+"px";
				$('lightbox').style.marginLeft = (myWidth/2)*(-1) +"px";
				$('lightbox').style.marginTop = (myHeight/2)*(-1) +"px";
				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){
		info = "<div id='lbContent'>" + response.responseText + "</div>";
		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++) {
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		}

	},

	// timetable_dates (if error don't close window)
	checkDates: function(){
		if ($F('lbError')=='0')
		{
			var url = 'ajaxFunctions.asp';
			var pars =Form.serialize("frmAddTimetable")+'&'+Form.serialize("frmTimetableDates")+'&page=timetable_adddates';

			new Ajax.Request(url, {method: 'get',parameters:pars,
				onComplete: function() {
						GetSessionsDates($F('mode'));
						$('chkTDatesAll').checked=false;
				}
			});

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

			if (browser == "Internet Explorer"){
				this.setScroll(0,this.yPos);
				this.prepareIE("auto", "auto");
				this.hideSelects("visible");
			}

			this.displayLightbox("none");
		}
	},

	// timetable_dates save time changes (if error don't close window)
	saveTimes: function(){
		if ($F('lbError')=='0')
		{
			var url = 'ajaxFunctions.asp';
			var tid = Form.serializeElements($('frmTimetableDates').getInputs('hidden','tid'));
			var gid = Form.serializeElements($('frmTimetableDates').getInputs('hidden','gid'));
			var ay = Form.serializeElements($('frmTimetableDates').getInputs('hidden','ay_id'));
			var pars =tid+'&'+gid+'&'+ay+'&'+Form.serialize("frmEditTimes")+'&page=timetable_changetimes';
		
			new Ajax.Request(url, {method: 'get',parameters:pars,
				onSuccess: function(t) {
						if (t.responseText=='0')
						{
							$('chkTDatesAll').checked=false;
							checkUncheckAll($('chkTDatesAll'),'TDates','all');
							GetSessionsDates($F('mode'));
						} else {
							dynamicLightBox('Some values for the changed times are duplicated in the same sesion','',300,100);
							return false;
						}
						lightbox.prototype.deactivate();
				}
			});
		}
	},
	SaveCommentEntry: function (){
		var url = 'ajaxFunctions.asp';
		var pars = Form.serialize("frmAddComment4Entry");
		var isError = false;

		if ($('comment_subject').value=='')
		{			
			$('msgwblb_box').innerHTML='Please enter a subject';
		    $('wblb_overlay').show();
		    CenterElement('wblb_message');
			isError=true;

		}

		if (($('comment_text').value=='') && !isError) {			
			$('msgwblb_box').innerHTML='Please enter a comment';
		    $('wblb_overlay').show();
		    CenterElement('wblb_message');
			isError=true;
		}

		if (!isError) {
			$('lightbox').setStyle({overflow:'hidden'});
			$('saving').show();
			new Ajax.Request(url, {method: 'get',parameters:pars,
				onComplete: function(t) {
					var arrResponse=eval(t.responseText);
					if (arrResponse[0]!='Error'){
						if ($('pagefrom').value=='view') {
							//view entry, refresh list of comments
							getCommentsEntry();
							lightbox.prototype.deactivate();
						} else {
							// list entries update number comments
							$('counterComments'+arrResponse[1]).update("("+arrResponse[2]+" comments)");
							lightbox.prototype.deactivate();
							if (browser == "Internet Explorer") $('entry_'+arrResponse[1]).scrollTo();
							new Effect.Highlight('counterComments'+arrResponse[1], {startcolor:'#F9FF00', endcolor:'#ffffff'});
						}
					} else {
						$('saving').hide();
					}
				}
			});
		}
	},
	UpdateOrderHeadings: function(){
		var url = 'ajaxResources.asp';

		var pars=Form.serialize("frmEditHeadings")
		pars+='&type=updateorderheadings';

		new Ajax.Request(url, {method: 'get',parameters:pars,
			onComplete: function() {
					initHeadings();
			}
		});
	},
	// resources functionality
	addupdateresource: function(){

		if ($('main_title').getValue()=="") {
			alert('You must enter a title for this resource. If you are uploading more than one resource, then the title will be appended with an incremental number, which you can later change if you wish.');
			return false;
		}

		//NP 07/01/2008 hide 'saving' layer for file uploads to display progress bars
		if($('resource_type').getValue()!="file") $('saving').toggle();

		switch($('resource_type').getValue()){
		case "file" :

			/* Check a value in the form to find out when the process is finished
			 * to update the resources list and hide the lightbox
			 */
			new Form.Element.Observer('finished',0.8,
			  function(el, value){
				if ($('finished').value!='')
				{
					$('finished').value='';
					$('orderby').value='date_order'+' '+'desc';
					ResourcesList($('isSearch').value);
					lightbox.prototype.deactivate();
				}
			  }
			);

			if ($F('isEdit')!='-1'){ //add files
				var url='/ajaxResources.asp?type=addupdate';
				manualStartFileUploadResources(url);
			} else {
				var url = "/ajaxResources.asp";
				var pars = "type=addupdate&"+Form.serialize("frmEditResources");

				new Ajax.Request(url, {method: 'get',parameters:pars,
					onComplete: function() {
						$('finished').value='';
						$('orderby').value='date_order'+' '+'desc';
						ResourcesList($('isSearch').value);
						lightbox.prototype.deactivate();
					}
				});
			}
			break;
		case "template" :
			var url = "/ajaxResources.asp";
			var pars = "type=addupdate&"+Form.serialize("frmEditResources");
			var isEdit = 0
			if (exists('isEdit')) {
				pars+="&isEdit="+$F('isEdit');
				isEdit=$F('isEdit');
			}

			new Ajax.Request(url, {method: 'get',parameters:pars,
				onComplete: function(t) {
					$('finished').value='';
					lightbox.prototype.deactivate();
					$('orderby').value='date_order'+' '+'desc';
					ResourcesList($('isSearch').value);
					TemplateScreen(2,t.responseText);
				}
			});
			break;				
		case "boarditem" :
			var url = "/ajaxResources.asp";
			var pars = "type=addupdate&"+Form.serialize("frmEditResources");
			new Ajax.Request(url, {method: 'get',parameters:pars,
				onComplete: function() {
					$('finished').value='';
					lightbox.prototype.deactivate();
					$('orderby').value='date_order'+' '+'desc';
					ResourcesList($('isSearch').value);
					//tinyMCE.remove();
					tinyMCE.execCommand('mceRemoveControl', false, 'main_html');
					tinyMCE.destroy();
					
				}
			});
			break;				
		case "rss" :
		case "link":
			var url = "/ajaxResources.asp";
			var pars = "type=addupdate&"+Form.serialize("frmEditResources");

			new Ajax.Request(url, {method: 'get',parameters:pars,
				onComplete: function() {
					$('finished').value='';
					$('orderby').value='date_order'+' '+'desc';
					ResourcesList($('isSearch').value);
					lightbox.prototype.deactivate();
				}
			});
			break;				
		}
	},
	// select users pop up functionality
	selectusers_pop: function(){
		var strSelectedUsers="No records";
		var pageName=getPageName();
		if (exists('SelectedDiv')) strSelectedUsers=$('SelectedDiv').innerHTML;
		if (strSelectedUsers.startsWith('No records') || strSelectedUsers.startsWith('0 records')) {
			lightbox.prototype.deactivate();
		} else {
			var url = '/ajaxUsersPopup.asp';
			var pars='type=send_selectedusers&pagefrom='+pageName+'&name='+$('selected_popup').value;
			if (exists('record_id')) pars+='&record_id='+$('record_id').value;
			new Ajax.Request(url, {method: 'get',parameters:pars,
				onComplete: function(t) {
					switch(pageName) {
						case "folder_system":
							var objFolder='editNode'+$('record_id').value;
							var oldText=$(objFolder).innerHTML;
							$(objFolder).update(oldText+' ('+t.responseText+')');
							new Effect.Highlight(objFolder, {startcolor:'#F9FF00', 
								endcolor:'#ffffff',
								duration: 2.5,
								afterFinish: function() {
									$(objFolder).update(oldText);
								}
							});
							break;
						case "resource_library":
							ResourcesList($('isSearch').value,1);
							break;
						case "groups_view":
							GroupsList();
							break;
						default:
							lightbox.prototype.deactivate();
					}
					$('lstSelectedUsersPopUp'+$('selected_popup').value).value=t.responseText;
				}
			});
		}
	},
	saveAddFolder: function(){
		var url = 'ajaxSubFolderView.asp';

		var pars=Form.serialize("formAddSubFolder")
		pars+='&type=saveSubFolder';

		new Ajax.Request(url, {method: 'get',parameters:pars,
			onLoading: function() {$('lightbox').setStyle({overflow:'hidden'});$('saving').show();},
			onComplete: function(t) {
				var arrResponse=t.responseText.split(",");
				var fid=arrResponse[0];
				var user_ilp=arrResponse[1];
				new Ajax.Updater('region1Right', '/ajaxSubFolderView.asp', {parameters:{fid: fid,student_ilp: user_ilp},method: 'get',evalScripts: true,onComplete:function(){lightbox.prototype.deactivate();}});
			}
		});
	},
	// 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(){
		Element.remove($('lbContent'));

		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}

		this.displayLightbox("none");
	}
}

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

// Onload, make all links that need to trigger a lightbox active
function initialize(){
//	addLightboxMarkup();	//NP - moved to lightbox.initialize function (above) to fix IE issue
	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" style="height:100%;width:100%;vertical-align:middle;text-align:center;">' +
						  '<img style="top:50%;position:relative;" src="/web_common/images/loadingAnimation.gif"/>' +
						  '</div>';
	bod.appendChild(overlay);
	bod.appendChild(lb);
}


// Added by David & Nick!
function dynamicLightBox(strMessage,strHelpContentPath,strWidth,strHeight)
{
	if (exists('tempLink')){
		//Remove old lightbox link (cached by IE)
		Element.remove($('tempLink'));
	}
	getContentScript = "dynamicLightBox_content.asp";	

	// Create a hidden link via DOM, then fire it off...
	var html_doc = document.getElementsByTagName('body').item(0);
    var link = document.createElement('a');
    link.setAttribute('id', 'tempLink');
    link.setAttribute('href', getContentScript+'?strMessage='+strMessage+'&strHelpContentPath='+strHelpContentPath+'&width='+strWidth+'&height='+strHeight);
    link.setAttribute('class', 'lbOn');
    link.setAttribute('style', 'display:none');
    html_doc.appendChild(link);
	
    tempLightbox = new lightbox($("tempLink"));

	tempLightbox.activate();
}

