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

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl,isSearch) {
		addLightboxMarkup(isSearch); //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){
		if($('lbLoadMessage')) {
			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;};
		}

	},
	// upload files functionality
	addupdatefile: function(){

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

		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
			 */
			if ($F('isEdit')!="True"){ //add files
				var url='/ajaxFiles.asp?type=addupdate';
				manualStartFileUploadFiles(url);
			} else {
				var url = "/ajaxFiles.asp";
				var pars = "type=addupdate&"+Form.serialize("frmEditFiles");

				new Ajax.Request(url, {method: 'get',parameters:pars,
					onComplete: function() {
						GetDocuments($('curpage').value);
						lightbox.prototype.deactivate();
					}
				});
			}
			break;
		}
	},
	// send course enquiry
	sendCourseEnquiry: function(){
		var errMsg="";
		if ($('txtName').getValue()=="") errMsg+="Please include your name.\r\n";
		if ($('txtEmail').getValue()=="") errMsg+="Please include your email address.\r\n";
		if ($('txtConfEmail').getValue()=="") errMsg+="Please confirm your email address.\r\n";
		if ($('txtQuestion').getValue()=="") errMsg+="Please include your enquiry.\r\n";

		if (($('txtConfEmail').present() && $('txtEmail').present()) && ($('txtConfEmail').getValue() != $('txtEmail').getValue())) {
				errMsg+="The email adresses you entered do not match. Please re-enter.\r\n";
		} else if (($('txtConfEmail').present() && $('txtEmail').present()) && ($('txtConfEmail').getValue() == $('txtEmail').getValue())) {
			if (!isEmail($('txtEmail').getValue())) errMsg+="The email address entered is not valid. Please re-enter.\r\n";
		}


		if (errMsg!="") alert(errMsg);
		else {
			var url = "/AjaxSearch.asp";
			var pars = "type=sendenquiry&"+Form.serialize("frmEnquiry");

			new Ajax.Request(url, {method: 'get',parameters:pars,
				onLoading: function() {
					$('statusLightbox').innerHTML='Sending your enquiry...';
					$('sendingMessage').show();
				},
				onComplete: function(t) {
					if (t.responseText.length!=0)
					{
						$('statusLightbox').innerHTML=t.responseText;
						//$('statusLightbox').toggleClassName('statusMessage');
						$('statusLightbox').show();
						new PeriodicalExecuter(function(pe) {
							if ($('lightbox')) {
								$('statusLightbox').hide();
								//$('statusMessage').toggleClassName('waiting');
								$('sendingMessage').hide();
								lightbox.prototype.deactivate();
							}
							pe.stop();
						}, 4);
					}
					//GetDocuments($('curpage').value);
				}
			});
		}
	},
	// send a provider enquiry
	sendProviderEnquiry: function(){
		var errMsg="";
		if ($('txtName').getValue()=="") errMsg+="Please include your name.\r\n";
		if ($('txtEmail').getValue()=="") errMsg+="Please include your email address.\r\n";
		if ($('radReplyPhone')) {
			if ($('radReplyPhone').checked && !($('txtPhone').present())) errMsg+="Please include your phone number.\r\n";
		}
		if ($('txtSubject')) {
			if ($('txtSubject').getValue()=="") errMsg+="Please include the subject of your enquiry.\r\n";
		}
		if ($('txtEnquiry').getValue()=="") errMsg+="Please include your enquiry.\r\n";

		if ($('txtEmail').present() && !isEmail($('txtEmail').getValue())) errMsg+="The email address entered is not valid. Please re-enter.\r\n";

		if (errMsg!="") alert(errMsg);
		else {
			var url = "/AjaxProviders.asp";
			var pars = "type=sendProviderEnquiry&"+Form.serialize("frmEnquiry");

			new Ajax.Request(url, {method: 'get',parameters:pars,
				onLoading: function() {
					$('statusLightbox').innerHTML='Sending your enquiry...';
					$('sendingMessage').show();
				},
				onComplete: function(t) {
					if (t.responseText.length!=0)
					{
						$('statusLightbox').innerHTML=t.responseText;
						//$('statusLightbox').toggleClassName('statusMessage');
						$('statusLightbox').show();
						new PeriodicalExecuter(function(pe) {
							if ($('lightbox')) {
								$('statusLightbox').hide();
								//$('statusMessage').toggleClassName('waiting');
								$('sendingMessage').hide();
								lightbox.prototype.deactivate();
							}
							pe.stop();
						}, 4);
					}
					//GetDocuments($('curpage').value);
				}
			});
		}
	},
	saveCommPref: function(){
		var errMsg="";
		$('process').value="";
		if (!$('txtEnquiries').present()) errMsg+="Please include at least one email address to receive enquiries.\r\n";
		if (!checkMail($F('txtEnquiries')));

		if (!$('txtAlerts').present()) errMsg+="Please include at least one email address to receive administrative messages.\r\n";
		if (!checkMail($F('txtAlerts')));

		if (errMsg!="") alert(errMsg);
		else {
			$('process').value="1";
			var url = "/AjaxProviders.asp";
			var alerts=$F('txtAlerts').split("\n");
			var emailAlerts="";
			var emailAlertsHTML="";
			for (var i=0;i<alerts.length;i++) {
				emailAlerts+=alerts[i]+",";
				emailAlertsHTML+=alerts[i]+"<br/>";
			}
			$("alertsHidden").value=emailAlerts;

			var enquiries=$F('txtEnquiries').split("\n");
			var emailEnquiries="";
			var emailEnquiriesHTML="";
			for (var i=0;i<enquiries.length;i++) {
				emailEnquiries+=enquiries[i]+",";
				emailEnquiriesHTML+=enquiries[i]+"<br/>";
			}
			$("enquiriesHidden").value=emailEnquiries;

			$("enquiries"+$("sid").value).innerHTML=emailEnquiriesHTML;
			$("alerts"+$("sid").value).innerHTML=emailAlertsHTML;

			var objEffect="school"+$("sid").value;
			var pars = "type=saveCommPref&"+Form.serialize("frmComm");
			new Ajax.Request(url, {method: 'get',parameters:pars,
				onComplete: function() {
					lightbox.prototype.deactivate();
					if (Prototype.Browser.IE) $(objEffect).scrollTo();
					new Effect.Highlight($(objEffect));
				}
			});
		}
	},
	// 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(){
		//NP - 10/06/2008 Fix issue when closing lightbox with no content in IE
		//Element.remove($('lbContent'));
		if($('lbContent')) 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
	$$('.lbOn').each(function(item){
		new lightbox(item);
	});
}

// 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 strHTML				='';
	bod 					= document.getElementsByTagName('body')[0];
	overlay 				= document.createElement('div');
	overlay.id				= 'overlay';
	lb						= document.createElement('div');
	lb.id					= 'lightbox';
	lb.className 			= 'loading';
	var thePage=getPageName();
	if (arguments[0]==true) { //isSearch lightbox
		strHTML					= '<div style="height:80px;overflow:hidden;z-index:9999;">';
		strHTML					= strHTML+'<div class="popupContent" style="overflow:hidden;width:200px;height:80px;vertical-align:middle;text-align:center;">';
		strHTML					= strHTML+'<div align="center"><p><img src="/web_common/img/loading_search.gif"></p><p><font class="maintext"><b>Searching...</b></font></p></div>';
		strHTML					= strHTML+'</div>';
		strHTML					= strHTML+'</div>';
		lb.innerHTML			= strHTML;
		bod.appendChild(overlay);
		bod.appendChild(lb);
		$('lightbox').setStyle({border:'0px solid black'});
	} else {
		lb.innerHTML		= '<div id="lbLoadMessage" style="background-color:White;height:100%;width:100%;vertical-align:middle;text-align:center;background-image:url(/web_common/img/loading_search.gif);background-position:50% 50%;	background-repeat:no-repeat;"></div>';
		bod.appendChild(overlay);
		bod.appendChild(lb);
		$('lightbox').setStyle({border:'1px solid black'});
	}
}

function getPageName() {
	var sPath = window.location.href;
	var sPage=sPath.substring(0,sPath.lastIndexOf('.asp'));
	sPage = sPage.substring(sPage.lastIndexOf('/') + 1);
	return sPage;
}

function fixLightbox(state){
	if($('lightbox')&&Prototype.Browser.Gecko) {
		if(state==1){
			$('lightbox').style.position = "fixed";
		}else{
			//Adjust offsets for 'position:absolute' to keep lightbox in same visual location on page
			$('lightbox').setStyle({
				marginTop: '0px',
				top: (parseInt((getFrameSize()[1]-$('lightbox').offsetHeight)/2)+getScrollXY()[1])+'px',
				position: 'absolute'
			});
		}
	}
}

//Get screen width / height
function getFrameSize(){
	if (self.innerWidth){
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
		return Array(frameWidth,frameHeight);
	} else if (document.documentElement && document.documentElement.clientWidth){
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	} else if (document.body){
		frameWidth = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
	} else {
		return;
	}
	return Array(frameWidth,frameHeight);
}


//Get scrolling offsets
function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
	//window.alert( 'Horizontal scrolling = ' + scrOfX + '\nVertical scrolling = ' + scrOfY );
}

function getQueryVariable(variable,queryURL) {
  if (queryURL!=undefined)
  {
	  var query=queryURL.substr(queryURL.indexOf("?")+1);
  } else {
	  var query = window.location.search.substring(1);
  }
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  return false;
  //alert('Query Variable ' + variable + ' not found');
}

// Added by David & Nick!
function dynamicLightBox(strMessage,strHelpContentPath,strWidth,strHeight)
{
	if ($('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();
}
