﻿/*
Unity global JavaScript

Included on all pages within the console
*/

//------------------------------------------------------------------
// Unity 3 Linking and Form Submission Functions

var linkProcessing = 0;//set to 1 when page links and form subissions occour.
var unityFormInitiated = false;//set to true if a unity form on page
var unityAmp = "&"; //used to escape ampersands for js inside xsl's

function unityPrintPage()
{
	//For "print" button on printer friendly page. Win IE and NS6
	//compatible. MacIE not supported so they get the alert()
	if(self.print)
	{
		self.print();
	}
	else
	{
		alert('Sorry but your browser does not support this in page print button. To print, select the print option from your browser\'s toolbar or pulldown menus.');
	}
}

function informLinkProcessing()
{
	/*Shows generic message that link is processing to user. Called
	/from page link functions that use linkProcessing var.*/

	alert("Processing. Please wait for a response.");
}

function submitUnityForm(formName)
{
	if (!linkProcessing)
	{
		linkProcessing = 1;
		eval("document."+formName+".submit()");
	}
	else
	{
		informLinkProcessing();
		return false;
	}
}

// Unity 3 Linking and Form Submission Functions
//------------------------------------------------------------------



//------------------------------------------------------------------
// Kill links in content view

/*When viewing content, nulls all links.*/

function unityLinkUnavailable()
{
	alert("Links are disabled while viewing in this mode.");
}

function unityKillLinks(container)
{
	/*Redirects links and onclicks for all children of container.*/

	var container = document.getElementById(container);
	
	//Handle hrefs
	var linkArray = container.getElementsByTagName("A");
	var numLinks = linkArray.length;
	
	for (i=0; i<numLinks; i++)
	{
		linkArray[i].target = "_self";
		linkArray[i].href = "javascript:unityLinkUnavailable()";
	}
	
	//Handle any onclicks
	var str = container.innerHTML;
	var reg = /onclick="[^"]+"/g;
	var repl= 'onclick="unityLinkUnavailable()"';
	if(str.search(reg) != -1)
	{
		str = str.replace(reg,repl);
		container.innerHTML = str;
	}	
	
	//Handle other possible links
	var linkArray = document.getElementsByTagName("INPUT");
	var numLinks = linkArray.length;
	for (i=0; i<numLinks; i++)
	{
		if (linkArray[i].type == "image" || linkArray[i].type == "button" || linkArray[i].type == "submit")
		{
			linkArray[i].onclick = unityLinkUnavailable;
		}
	}
}


// Form info show/hide
//------------------------------------------------------------------




//------------------------------------------------------------------
// Form info show/hide

function unityFormDetailMore(show,formName)
{
	/*Toggles display of form detail block.*/
	
	var moreBtn = document.getElementById("formDetail"+formName+"More");
	var formDetail = document.getElementById("formDetail"+formName);

	if(show==1)
	{
		moreBtn.style.display="none";
		formDetail.style.display="block";
	}
	else
	{
		moreBtn.style.display="block";
		formDetail.style.display="none";
	}
	
}

// Form info show/hide
//------------------------------------------------------------------




//------------------------------------------------------------------
// Form reset handler

function unityFormReset(formName)
{
	/*Special handling for DHTML form fields. Typically called with
	/form reset (which handles reset of the normal fields).*/
	
	//reset all dhtml elements
	var dhtmlFields = eval('unity'+formName+'DHTMLFields');

	for(i in dhtmlFields)
		eval(dhtmlFields[i]+'.reset()');
	
}

// Form reset handler
//------------------------------------------------------------------




//------------------------------------------------------------------
// Auto form focus

function unityFormFocusObj()
{
	/*Sets up focus target and method.*/
	
	this.target = null;
	if(document.forms[0])
	{
		if(document.forms[0].elements[0])
		{
			//Only apply to certain elements
			var el = document.forms[0].elements[0];
			if(el.tagName.toUpperCase()=="INPUT")
			{
				if(el.type.toUpperCase() == "TEXT" || el.type.toUpperCase()=="RADIO" || el.type.toUpperCase()=="CHECKBOX")
				{
					this.target=document.forms[0].elements[0];
				}
			}
		}
	}

	this.focus = unityFormFocusAction;
}

function unityFormFocusAction()
{	
	/*Focuses first element of first form.*/

	try
	{
		this.target.focus();
		this.target.select();
	}
	catch(e)
	{
		/*do nothing*/
	}
}

// Auto form focus
//------------------------------------------------------------------




//------------------------------------------------------------------
// Default button actions
function unitySendForm(formName)
{
	/*Note form submitUnityForm() in global.js*/
	
	//Check file fields before sending
	if(unityFileFieldCheck(formName))
		submitUnityForm(formName);
}

function unityCancelForm(targetURL)
{
	/*Note form gotoUnityPage() in global.js*/
	gotoUnityPage(targetURL);
}

// Default button actions
//------------------------------------------------------------------




//------------------------------------------------------------------
// Textarea Tab Handling

/*Currently IE only function. With Moz/Gecko etc. there are problems
/with focus() with tab when using selectionStart etc.*/

function unityStoreCaret(textareaRef)
{
	/*Stores cursor pos for a textarea*/
	if (textareaRef.createTextRange)
	{	
		unityStoreCaretFormat = 'range';
		textareaRef.caretPos = document.selection.createRange().duplicate();
	}
}

function unityInsertTab(textareaRef)
{
	/*Inserts tab for a textarea at the caretPos*/
	
	if(textareaRef.caretPos &&textareaRef.createTextRange)//IE
	{
		var caretPos = textareaRef.caretPos;
		caretPos.text = caretPos.text + "\t";
		textareaRef.focus();
	}
}

// Textarea Tab Handling
//------------------------------------------------------------------



//------------------------------------------------------------------
//	Radio buttons

function unityCheckedRadio(formName,radioGroupName,returnType)
{
	/*Returns the value or index (specified in returnType) of the
	/currently checked radio.*/
	
	var radioGroup = document.forms[formName].elements[radioGroupName];
	
	for(i=0;i<radioGroup.length;i++)
	{
        if(radioGroup[i].checked)
		{
			if(returnType == 'value')
				return radioGroup[i].value;
			else //if 'index'
				return i;
		}		
    }
}

//	Radio buttons
//------------------------------------------------------------------



//------------------------------------------------------------------
// Date and time fields COMMON

function unityGetDateParts(initDate)
{
	/*Returns date parts (yyyy,mm etc.) from initDate as array.*/
	
	//Check date, make new if required
	var regx = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/;
	if(initDate.search(regx) != -1)
	{
		var year = initDate.substring(0,4);
			year = parseInt(year);
		var month = initDate.substring(initDate.indexOf("-")+1,initDate.lastIndexOf("-"));
			month = parseFloat(month) - 1;//-1 to sync with js month array
		var day = initDate.substring(initDate.lastIndexOf("-")+1,initDate.length);
			day = parseFloat(day);
	}
	else
	{
		//no date, set up today as a start point
		var date = new Date();
		var year = date.getFullYear();
		var month = date.getMonth();
		var day = 0;//0 so this start point won't be set as date
	}
	
	return new Array(year,month,day);
}

function unityGetTimeParts(initTime)
{
	/*Returns time parts (hh,mm etc.) from initTime as array.*/

	var hours	= initTime.substring(0,2);
	var minutes = initTime.substring(3,5);
	var seconds = initTime.substring(6,9);
	
	return new Array(hours,minutes,seconds);
}

function unityGetTimePicker(formRef,fieldRef,elRef,initHours,initMinutes)
{
	/*Returns selects for hours and minutes (with selected options
	/for initHours and initMinutes.*/

	var hoursSel = '<select id="unity'+formRef+'SetTime'+fieldRef+'Hours" onchange="'+elRef+'.set();">';
	for(i=0;i<24;i++)
	{
		var displayHours = (i<10)? "0"+i:i;
		var selected = (displayHours == initHours)? ' selected="selected"':"";
		hoursSel = hoursSel + '<option value="'+displayHours+'"'+selected+'>'+displayHours+'</option>';
	}
	hoursSel = hoursSel + "</select>";
	
	//Make minutes select
	var minsSel = '<select id="unity'+formRef+'SetTime'+fieldRef+'Minutes" onchange="'+elRef+'.set();">';
	for(i=0;i<60;i++)
	{
		var displayMins = (i<10)? "0"+i:i;
		var selected = (displayMins == initMinutes)? ' selected="selected"':"";
		minsSel = minsSel + '<option value="'+displayMins+'"'+selected+'>'+displayMins+'</option>';
	}
	minsSel = minsSel + "</select>";
	
	var output = '<span class="formSetTimePickerSelects"><span>'+hoursSel+' Hours<\/span><span>'+minsSel+' Minutes<\/span>';

	return output;
}

function unityGetCalHTML(elRef,calId)
{
	/*Returns the calendar HTML framework (outer parts). Called from
	/here because used for plain calendar and for date-time
	/calendar. The later writes in an extra row for the time select*/

	var calHTML = '<table class="formDatePicker"><tr><th class="formDatePicker"><img src="../graphics/forms/date_picker_arrow_next.gif" class="formDPArrowNext" alt="Next month" onclick="'+elRef+'.addMonth(1)" /><img src="../graphics/forms/date_picker_arrow_prev.gif" class="formDPArrowPrev" alt="Previous month" onclick="'+elRef+'.addMonth(-1)" /><span id="'+elRef+'Title"><\/span><\/th><th class="formDatePickerJump"></th><th class="formDatePickerJump"><img src="../graphics/forms/date_picker_close.gif" class="formDatePickerClose" alt="Close calendar" onclick="'+elRef+'.close()" /></th></tr><tr><td class="formDatePickerCal" id="'+calId+'">';
	calHTML = calHTML + '<\/td><td class="formDatePickerJump"><div><span onclick="'+elRef+'.addMonth(6)"><img src="../graphics/forms/date_picker_plus.gif" alt="Add" class="formDPBtnPlus" />6&nbsp;Months<\/span><span onclick="'+elRef+'.addMonth(-6)"><img src="../graphics/forms/date_picker_minus.gif" alt="Minus" class="formDPBtnMinus" />6&nbsp;Months<\/span><\/div><div><span onclick="'+elRef+'.addYear(1)"><img src="../graphics/forms/date_picker_plus.gif" alt="Add" class="formDPBtnPlus" />1 Year<\/span><span onclick="'+elRef+'.addYear(-1)"><img src="../graphics/forms/date_picker_minus.gif" alt="Minus" class="formDPBtnMinus" />1 Year<\/span><\/div><div><span onclick="'+elRef+'.addYear(5)"><img src="../graphics/forms/date_picker_plus.gif" alt="Add" class="formDPBtnPlus" />5 Years<\/span><span onclick="'+elRef+'.addYear(-5)"><img src="../graphics/forms/date_picker_minus.gif" alt="Minus" class="formDPBtnMinus" />5 Years<\/span><\/div><\/td><td class="formDatePickerJump"><div class="formDatePickerJump"><span onclick="'+elRef+'.today()"><img src="../graphics/forms/date_picker_today.gif" alt="Jump to today" class="formDPBtnToday" />Today<\/span><\/div><div class="formDatePickerJump"><span onclick="'+elRef+'.reset()"><img src="../graphics/forms/date_picker_reset.gif" alt="Reset" class="formDPBtnReset" />Reset<\/span><\/div><\/td><\/tr>';

	return calHTML;
}

function unityGetHours(formRef,fieldRef)
{
	/*Returns current hours from hours select.*/

	var hours = document.getElementById('unity'+formRef+'SetTime'+fieldRef+'Hours');
	return hours.options[hours.selectedIndex].value;
}

function unityGetMinutes(formRef,fieldRef)
{
	/*Returns current minutes from minutes select.*/

	var minutes = document.getElementById('unity'+formRef+'SetTime'+fieldRef+'Minutes');
	return minutes.options[minutes.selectedIndex].value;//minutes displayed as 00,01 etc, unlike var hoursDisplay
}
// Date and time fields COMMON
//------------------------------------------------------------------




//------------------------------------------------------------------
// Date Picker (also used for Date-Time Picker)

/*Note: shares functions with date-time picker.*/

unityDatePickerMonths = new Array('January','February','March','April','May','June','July','August','September','October','November','December');

function unityDatePicker(formRef,dpRef)
{
	/*Sets up a new date picker calendar element.*/

	var initDate = document.forms[formRef].elements[dpRef].value;

	var dateParts = unityGetDateParts(initDate);
	
	//Create new calendar object and render picker
	eval('unity' + formRef + 'DP' + dpRef + ' = new unityDatePickerCalObj(formRef,dpRef,dateParts[0],dateParts[1],dateParts[2])');
	eval('unity' + formRef + 'DP' + dpRef + '.renderInit()');
}

function unityDatePickerCalObj(formRef,fieldRef,year,month,day,type)
{
	/*Date picker calendar object.*/
	
	//Properties
		//Start date - doesn't change while scrolling calendar
		this.initYear 	= year;
		this.initMonth 	= month;
		this.initDay 	= day;
		
		//The date that changes as user scrolls calendar
		this.varYear	= year;
		this.varMonth	= month;
		
		//The date the user clicks on, writes to hidden field on close
		//of calendar
		this.setYear 	= year;
		this.setMonth	= month;
		this.setDay 	= day;
	
		this.ref 		= 'unity' + formRef + 'DP' + fieldRef;
		this.pickerId 	= 'unity' + formRef + 'DP' + fieldRef + 'Picker';
		this.calId 		= 'unity' + formRef + 'DP' + fieldRef + 'PickerCal';
		this.displayId 	= 'unity' + formRef + 'DP' + fieldRef + 'Display';
		this.btnId 		= 'unity' + formRef + 'DP' + fieldRef + 'Btn';
		this.title 		= '';
		this.formRef 	= formRef;
		this.fieldRef	= fieldRef;
	
	//Methods
	this.renderInit = unityDatePickerCalRenderInit;
	this.render 	= unityDatePickerCalRender;
	this.addYear 	= unityDatePickerAddYear;
	this.addMonth 	= unityDatePickerAddMonth;
	this.setDate 	= unityDatePickerSetDate;
	this.close 		= unityDatePickerClose;
	this.reset 		= unityDatePickerReset;
	this.today 		= unityDatePickerToday;
	this.clear 		= unityDatePickerClear;
	this.show 		= unityDatePickerShow;
	this.hilite 	= unityDatePickerHighlightCurrentDate;
	this.writeDate	= unityDatePickerWriteDate;
}

function unityDatePickerCalRenderInit()
{
	/*Starts a new calendar render. Renders static border elements,
	/calls unityDatePickerCalRender() to render scrolling
	/calendar inside all of this.*/
	
	var calHTML = unityGetCalHTML(this.ref,this.calId) + "<\/table>";

	//Show calendar
	document.getElementById(this.pickerId).innerHTML = calHTML;
	this.render();
}

function unityDatePickerCalRender()
{
	/*Renders a calendar based on calendar object's current
	/variables.*/
	
	var stDay = unityDatePickerGetStartDay(this.varYear,this.varMonth);
	var prevMonthDays = unityDatePickerGetMonthDays(this.varYear,this.varMonth -1);
	var nextMonthDays = unityDatePickerGetMonthDays(this.varYear,this.varMonth +1);
	var monthDays = unityDatePickerGetMonthDays(this.varYear,this.varMonth);

	var calHTML = '<table class="formDatePickerCal"><tr><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th><th>S</th></tr>';

	//Row 1
	calHTML = calHTML + '<tr>';
	if(stDay ==1)//All first row all previous month
	{
		for(i=6;i>-1;i--)
		{
			var date = prevMonthDays-i;
			var classRef = (i<2)? 'formDPWeN':'formDPWN';//weekend:weekday of neighbouring month
			classRef = this.hilite(-1,date,classRef);
			var onclick = this.ref+'.setDate('+date+',-1)';
			calHTML = calHTML + '<td onclick="'+onclick+'" class="' + classRef + '">'+date+'<\/td>';
		}
		date = 0;//for start of new row
	}
	else//Rirst row partly previous month
	{
		for(i=1;i<8;i++)
		{
			if(i < stDay)
			{
				var date = prevMonthDays-((stDay - i)-1);
				var classRef = (i>5)? 'formDPWeN':'formDPWN';//weekend:weekday of neighbouring month
				classRef = this.hilite(-1,date,classRef);
				var onclick = this.ref+'.setDate('+date+',-1)';
			}
			else
			{
				var date = i - stDay + 1;
				var classRef = (i>5)? 'formDPWeT':'formDPWT';//weekend:weekday of this month
				classRef = this.hilite(0,date,classRef);
				var onclick = this.ref+'.setDate('+date+',0)';
			}
			calHTML = calHTML + '<td onclick="'+ onclick +'" class="' + classRef + '">'+date+'<\/td>';
		}
	}
	calHTML = calHTML + '<\/tr>';
	
	//Rows 2,3,4,5,6
	for(row=2;row<7;row++)
	{
		calHTML = calHTML + '<tr>';
		for(col=1;col<8;col++)
		{	
			date++;
			if(date > monthDays)//if into next month
			{
				var dateDisplay = (date % monthDays);
				var classRef = (col>5)? 'formDPWeN':'formDPWN';
				classRef = this.hilite(1,dateDisplay,classRef);
				var onclick = this.ref+'.setDate('+dateDisplay+',1)';
				calHTML = calHTML + '<td onclick="'+onclick+'" class="' + classRef + '">'+dateDisplay+'<\/td>';
			}
			else //still in same month
			{
				var dateDisplay = date;
				var classRef = (col>5)? 'formDPWeT':'formDPWT';
				classRef = this.hilite(0,dateDisplay,classRef);
				var onclick = this.ref+'.setDate('+dateDisplay+',0)';
				calHTML = calHTML + '<td onclick="'+onclick+'" class="' + classRef + '">'+dateDisplay+'<\/td>';
			}
			//calHTML = calHTML + '<td onclick="'+onclick+'" class="' + classRef + '">'+dateDisplay+'<\/td>';
			
		}
		calHTML = calHTML + '<\/tr>';
	}
	calHTML = calHTML + '<\/table>';
	
	document.getElementById(this.calId).innerHTML = calHTML;
	document.getElementById(this.ref+'Title').innerHTML = unityDatePickerMonths[this.varMonth] + ' ' + this.varYear;
}

function unityDatePickerAddYear(n)
{
	/*Adds years to date, including negatives.*/

	var yearInc = this.varYear + n;

	if(yearInc > 1900 && yearInc < 2300)
		this.varYear = yearInc;
	else
		alert("Sorry but you've reached the end of the calendar's range.\nThe range is between the years 1900 and 2300.");

	this.render();
}

function unityDatePickerAddMonth(n)
{
	/*Adds months to date and increments years as required. Handles
	/negatives too.*/
	
	var monthInc = this.varMonth + n;
	var monthYearTrim = monthInc % 11;
	
	//Sort years
	if(monthInc > 11 || monthInc < -11)
	{
		var years = (monthInc - monthYearTrim)/11;
		this.varYear = this.varYear + years;
	}
	else if(monthInc < 0 && monthInc > -11)
		this.varYear = this.varYear - 1;
	
	//Sort months
	if(monthInc > 11)
		this.varMonth = monthYearTrim - 1;
	else if(monthInc < 0)
		this.varMonth = n + 12;
	else
		this.varMonth = monthInc;

	this.render();
}

function unityDatePickerSetDate(date,month)
{
	/*Sets the picked date. Permits previous and next months date
	/picks too because these dates are also displayed on a current
	/month's view.*/

	this.setDay = date;
	switch(month)
	{
		case -1:
		{
			if(this.varMonth == 0)
			{
				this.setYear = this.varYear - 1;
				this.setMonth = 11;
			}
			else
			{
				this.setYear = this.varYear;
				this.setMonth = this.varMonth - 1;
			}
		}
		break;
		case 0:
		{
			this.setYear = this.varYear;
			this.setMonth = this.varMonth;
		}
		break;
		case 1:
		{
			if(this.varMonth == 11)
			{
				this.setYear = this.varYear + 1;
				this.setMonth = 0;
			}
			else
			{
				this.setYear = this.varYear;
				this.setMonth = this.varMonth + 1;
			}
		}
		break;
	}
	
	this.writeDate();

	//Refresh to show current selection
	this.render();
}

function unityDatePickerReset()
{
	/*Resets calendar to init date.*/
	
	if(this.initDay == 0)//case for init with blank value
		this.clear();
	else
	{
		this.setYear = this.initYear;
		this.setMonth = this.initMonth;
		this.setDay = this.initDay;
	
		this.varYear = this.initYear;
		this.varMonth = this.initMonth;
		
		this.writeDate();
		this.render();
	}
}

function unityDatePickerToday()
{
	/*Sets today's date as current pick in calendar.*/
	
	var today = new Date();
	this.setYear = today.getFullYear();
	this.setMonth = today.getMonth();
	this.setDay = today.getDate();
	
	this.varYear = this.setYear;
	this.varMonth = this.setMonth;
	
	this.writeDate();
	this.render();
}

function unityDatePickerClear()
{
	this.setDay = 0;
	this.render();
	this.close();
	
	var hiddenField = document.forms[this.formRef].elements[this.fieldRef];
	hiddenField.value='';
	
	document.getElementById(this.displayId).innerHTML = '--';
}

function unityDatePickerShow()
{
	//Show calendar
	document.getElementById(this.pickerId).style.display = 'inline';

	//Hide button
	document.getElementById(this.btnId).style.display = 'none';
	
	if(this.setDay == 0)
		this.today();
}

function unityDatePickerClose()
{
	//Hide calendar
	document.getElementById(this.pickerId).style.display = 'none';

	//Show button
	document.getElementById(this.btnId).style.display = 'inline';
}

function unityDatePickerWriteDate()
{
	/*Sets hidden form field and display SPAN to the currently
	/picked date  (this.setDay etc).*/
	
	//Convert JavaScript month index to calendar value
	var month=this.setMonth + 1;
	
	//Handle zeros
	month =(month < 10)? "0".concat(month):month;
	var day =(this.setDay < 10)? "0".concat(this.setDay):this.setDay;

	//Output new data
	var hiddenField = document.forms[this.formRef].elements[this.fieldRef];
	hiddenField.value = this.setYear+'-'+month+'-'+day;

	document.getElementById(this.displayId).innerHTML = day+'-'+month+'-'+this.setYear;
}

function unityDatePickerHighlightCurrentDate(monthRelative,date,classRef)
{
	/*Checks current date being rendered, if matches set date,
	/returns highlight CSS class. Else returns current CSS class.*/
	
	if(this.setDay == date)
	{
		switch(monthRelative)
		{
			case -1:
			{
				if(this.varMonth == 0)
				{
					var year = this.varYear - 1;
					var month = 11;
				}
				else
				{
					var year = this.varYear;
					var month = this.varMonth - 1;
				}
			}
			break;
			case 0:
			{
				var year = this.varYear;
				var month = this.varMonth;
			}
			break;
			case 1:
			{
				if(this.varMonth == 11)
				{
					var year = this.varYear + 1;
					var month = 0;
				}
				else
				{
					var year = this.varYear;
					var month = this.varMonth + 1;
				}
			}
			break; 
		}

		if(this.setMonth == month && this.setYear == year)
			return 'formDPSel';
	}
	
	return classRef;
}

function unityDatePickerGetStartDay(year,month)
{
	/*Returns start day of month as 1 for Monday,..., 7 for Sunday.
	/Normally 0 is Sunday but this calendar starts with Monday as
	/column one.*/

	var date = new Date(year,month,1);
	var stDay = date.getDay();
		stDay = (stDay == 0)? 7:stDay;

	return stDay;
}

function unityDatePickerGetMonthDays(year,month)
{
	/*Returns days in month.*/

	//This if/else is for special handling for next/prev month calls
	//to this function
	if(month == 12)
	{
		month = 0;
		year++;
	}
	else if(month == -1)
	{
		month = 11
		year--;
	}

	var days = new Array(31, ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

	return days[month];
}

// Date Picker (also used for Date-Time Picker)
//------------------------------------------------------------------




//------------------------------------------------------------------
// Time Picker

/*Note: shares functions with date-time picker.*/

function unitySetTime(formRef,fieldRef)
{
	/*Sets up a new set-time element*/
	
	var initTime = document.forms[formRef].elements[fieldRef].value;
	
	var timeParts = unityGetTimeParts(initTime);
	
	//Create new time picker object
	eval('unity' + formRef + 'SetTime' + fieldRef + ' = new unitySetTimeObj(formRef,fieldRef,timeParts[0],timeParts[1],timeParts[2])');
	eval('unity' + formRef + 'SetTime' + fieldRef + '.renderInit()');
}

function unitySetTimeObj(formRef,fieldRef,hours,minutes,seconds)
{
	/*SetTime object*/	
	
	this.initHours 	 = hours;
	this.initMinutes = minutes;
	this.initSeconds = seconds;
	
	//Properties
	this.ref 	   = 'unity' + formRef + 'SetTime' + fieldRef;
	this.pickerId  = 'unity' + formRef + 'SetTime' + fieldRef + 'Picker';
	this.btnId     = 'unity' + formRef + 'SetTime' + fieldRef + 'Btn';
	this.displayId = 'unity' + formRef + 'SetTime' + fieldRef + 'Display';
	this.formRef   = formRef;
	this.fieldRef  = fieldRef;

	//Methods
	this.reset 		= unitySetTimeReset;
	this.set   		= unitySetTimeSet;
	this.writeTime  = unitySetTimeWriteTime;
	this.renderInit = unitySetTimeRenderInit;
	this.show 		= untiySetTimeShow;
	this.close 		= untiySetTimeClose;
	this.clear 		= untiySetTimeClear;
}

function untiySetTimeClear()
{
	this.close();
	
	var timeDisplay = document.getElementById(this.displayId);
	timeDisplay.innerHTML = '--';
	
	var hiddenField = document.forms[this.formRef].elements[this.fieldRef];
	hiddenField.value = '';
}

function untiySetTimeShow()
{
	//If blank, set to now
	var time= new Date();
	var hours = document.getElementById('unity'+this.formRef+'SetTime'+this.fieldRef+'Hours');
	hours.selectedIndex = time.getHours();
	var minutes = document.getElementById('unity'+this.formRef+'SetTime'+this.fieldRef+'Minutes');
	minutes.selectedIndex = time.getMinutes();

	//Show picker
	document.getElementById(this.pickerId).style.display = 'inline';

	//Hide button
	document.getElementById(this.btnId).style.display = 'none';
	
	//Set time
	this.set();
}

function untiySetTimeClose()
{
	//Hide picker
	document.getElementById(this.pickerId).style.display = 'none';
	//Show button
	document.getElementById(this.btnId).style.display = 'inline';
}

function unitySetTimeRenderInit()
{
	//Make hours select
	var timePicker = unityGetTimePicker(this.formRef,this.fieldRef,this.ref,this.initHours,this.initMinutes);
	
	var output = timePicker + '<img src="../graphics/forms/date_picker_close.gif" class="formSetTimeClose" alt="Close" onclick="'+this.ref+'.close()" />';
	
	document.getElementById(this.pickerId).innerHTML = output;
}

function unitySetTimeReset()
{
	/*Resets the time to the state at first page load*/
	
	if(this.initHours == '')//case for init with blank value
		this.clear();
	else
	{
		this.writeTime(this.initHours,this.initMinutes);
		this.close();
	}
}

function unitySetTimeSet()
{
	/*Sets sets the time to the current selection (in the form
	/selects).*/
	
	var hours = unityGetHours(this.formRef,this.fieldRef);
	var minutes = unityGetMinutes(this.formRef,this.fieldRef);
	
	this.writeTime(hours,minutes);
}

function unitySetTimeWriteTime(hours,minutes)
{
	/*Writes out the time into the hidden data input and into user
	/display (which is an AM/PM version of the 24hr time)*/
	
	//Sort hours display
	var hoursDisplay = parseFloat(hours);
	var amPm = (hoursDisplay < 12)? 'AM':'PM';
	hoursDisplay = hoursDisplay % 12;
	hoursDisplay = (hoursDisplay == 0)? 12:hoursDisplay;
	
	//Sort seconds
	var secs = (this.initSeconds=='')? "00":this.initSeconds;

	//Output display of set time
	var timeDisplay = document.getElementById(this.displayId);
	timeDisplay.innerHTML = hoursDisplay + ":" + minutes + " " + amPm;
	
	//Write set time to input
	var hiddenField = document.forms[this.formRef].elements[this.fieldRef];
	hiddenField.value = hours + ":" + minutes + ":" + secs;
}

// Time Picker
//------------------------------------------------------------------




//------------------------------------------------------------------
// Date-time picker

/*Note: calls functions from date and time elements.*/

function unityDateTimePicker(formRef,fieldRef)
{
	/*Sets up a new date-time picker element*/
	
	var initDateTime = document.forms[formRef].elements[fieldRef].value;
	
	var dateParts = unityGetDateParts(  initDateTime.substring(0,initDateTime.indexOf("T"))  );
	var timeParts = unityGetTimeParts(  initDateTime.substring(initDateTime.indexOf("T")+1,initDateTime.length)  );
	
	//Create new time picker object
	eval('unity' + formRef + 'DateTime' + fieldRef + ' = new unityDateTimeObj(formRef,fieldRef,dateParts[0],dateParts[1],dateParts[2],timeParts[0],timeParts[1],timeParts[2])');
	eval('unity' + formRef + 'DateTime' + fieldRef + '.renderInit()');
}

function unityDateTimeObj(formRef,fieldRef,year,month,day,hours,minutes,seconds)
{
	/*Date-time picker object*/
	
	//Properties
		//Date
			//Start date - doesn't change while scrolling calendar
			this.initYear 	= year;
			this.initMonth 	= month;
			this.initDay 	= day;
			
			//The date that changes as user scrolls calendar
			this.varYear	= year;
			this.varMonth	= month;
			
			//The date the user clicks on, writes to hidden field on close
			//of calendar
			this.setYear 	= year;
			this.setMonth	= month;
			this.setDay 	= day;
	
		//Time
			this.initHours 	 = hours;
			this.initMinutes = minutes;
			this.initSeconds = seconds;
	
		this.ref 	   = 'unity' + formRef + 'DateTime' + fieldRef;
		this.pickerId  = 'unity' + formRef + 'DateTime' + fieldRef + 'Picker';
		this.calId 	   = 'unity' + formRef + 'DateTime' + fieldRef + 'PickerCal';
		this.displayId = 'unity' + formRef + 'DateTime' + fieldRef + 'Display';
		this.btnId     = 'unity' + formRef + 'DateTime' + fieldRef + 'Btn';
		this.title 		= '';
		this.formRef   = formRef;
		this.fieldRef  = fieldRef;

	//Methods
		//from datePicker
		this.render 	= unityDatePickerCalRender;
		this.hilite 	= unityDatePickerHighlightCurrentDate;
		this.addYear 	= unityDatePickerAddYear;
		this.addMonth 	= unityDatePickerAddMonth;
		this.setDate 	= unityDatePickerSetDate;
		
		this.close 		= unityDatePickerClose;
		this.today 		= unityDatePickerToday;
		this.dateReset	= unityDatePickerReset;
		this.clear 		= unityDatePickerClear;

	this.renderInit = unityDateTimeRenderInit;
	this.reset 		= unityDateTimeReset;
	this.set   		= unityDateTimeWrite;
	this.writeDate  = unityDateTimeWrite;
	this.show 		= unityDateTimeWriteShow;
}

function unityDateTimeRenderInit()
{
	/*Create HTML for new dateTime picker and insert into page.*/

	var dateTimeHTML = unityGetCalHTML(this.ref,this.calId);
	dateTimeHTML = dateTimeHTML + '<tr><td colspan="3" class="formDateTimeTimeRow">' + unityGetTimePicker(this.formRef,this.fieldRef,this.ref,this.initHours,this.initMinutes) + "<\/td><\/tr>";
	dateTimeHTML = dateTimeHTML + "<\/table>";

	document.getElementById(this.pickerId).innerHTML = dateTimeHTML;
	
	this.render();
}

function unityDateTimeWrite()
{
	//Resolve date
	var month=this.setMonth + 1;//+1 to convert back from js array index
		month =(month < 10)? "0".concat(month):month;
	var day =(this.setDay < 10)? "0".concat(this.setDay):this.setDay;
	var dateDisplay = day+'-'+month+'-'+this.setYear;
	var dateData 	= this.setYear+'-'+month+'-'+day;

	//Resolve time
	var hours  = unityGetHours(this.formRef,this.fieldRef);
	var minutes = unityGetMinutes(this.formRef,this.fieldRef);
	var hoursDisplay = parseFloat(hours);
	var amPm = (hoursDisplay < 12)? 'AM':'PM';
	hoursDisplay = ((hoursDisplay % 12) == 0)? 12:hoursDisplay;
	var timeDisplay = hoursDisplay + ":" + minutes + " " + amPm;
	var secs = (this.initSeconds=='')? "00":this.initSeconds;
	var timeData = hours + ":" + minutes + ":" + secs;
	
	//Display new data
	document.getElementById(this.displayId).innerHTML = dateDisplay + ', ' + timeDisplay;

	//Output new data
	var hiddenField = document.forms[this.formRef].elements[this.fieldRef];
	hiddenField.value = dateData + "T" + timeData;
}

function unityDateTimeReset()
{
	//Reset time (before date)
	var hours = document.getElementById('unity'+this.formRef+'SetTime'+this.fieldRef+'Hours');
	hours.selectedIndex = this.initHours;

	var minutes = document.getElementById('unity'+this.formRef+'SetTime'+this.fieldRef+'Minutes');
	minutes.selectedIndex = this.initMinutes;

	//Reset date
	this.dateReset();
}

function unityDateTimeWriteShow()
{
	//Show calendar
	document.getElementById(this.pickerId).style.display = 'inline';

	//Hide button
	document.getElementById(this.btnId).style.display = 'none';
	
	if(this.setDay == 0)
	{
		var time= new Date();
		var hours = document.getElementById('unity'+this.formRef+'SetTime'+this.fieldRef+'Hours');
		hours.selectedIndex = time.getHours();
	
		var minutes = document.getElementById('unity'+this.formRef+'SetTime'+this.fieldRef+'Minutes');
		minutes.selectedIndex = time.getMinutes();

		this.today();
	}
}

// Date-time picker
//------------------------------------------------------------------





// File fields
//------------------------------------------------------------------
//Date Selector
function unityDateSelectorRenderDays(dayFieldName, monthFieldName, yearFieldName){
	var daySelect = document.getElementsByName(dayFieldName).item(0);
	var monthSelect = document.getElementsByName(monthFieldName).item(0);
	var yearSelect = document.getElementsByName(yearFieldName).item(0);
	
	var monthDayNum = null;
	var optionObj = null;
	
	if(daySelect != null){
		if(yearSelect != null){
			monthDayNum = unityGetMonthDays(yearSelect.value, monthSelect.value);
			
			if((daySelect.options.length - 1) < monthDayNum){
				
				for(var i = daySelect.options.length; i <= monthDayNum; i++){
					optionObj = document.createElement("option");
					optionObj.value = i;
					optionObj.text = i;
					optionObj.innerText = i;
					
					daySelect.appendChild(optionObj);
				}
			}else if((daySelect.options.length - 1) > monthDayNum){
				while((daySelect.options.length - 1) > monthDayNum){
					daySelect.removeChild(daySelect.options[daySelect.options.length - 1]);
				}
			}
		}
	}
}

function unityGetMonthDays(year,month)
{
	var today = new Date();
	
	if(isNaN(month) || month < 1 || month > 12)
	{
		month = 1;
	}
	
	var febDayNum = 28;
	
	if(isNaN(year) || year == 0){
		//do nothing
	}else if(year % 400 == 0){
		febDayNum = 29;
		
	}else if(year % 4 == 0){
		
		if(year % 100 != 0){
			febDayNum = 29;
		}
	} 
	
	var days = new Array(31, febDayNum, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

	return days[month -1];
}
//------------------------------------------------------------------


// Javascript object used to create an html Flash OBJECT
// Uses unityObject object with suitable defaults, and adds default parameters
// Flash version defaults to 8,0,0,0 and need not be supplied
// Example usage:
//	obj = new unityFlashObject('test', 'VIDEO.SWF', 400, 200);
//  obj.Write(); or obj.Insert();
function unityFlashObject(id, movie, width, height, flashVersion) {
	//Default Flash version
	if (typeof(flashVersion) == 'undefined') {
		flashVersion = '8,0,0,0';
	}

	//Create object
	var obj = new unityObject(id, 
		'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000', 
		location.protocol + '//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + flashVersion, 
		width, height, 
		'application/x-shockwave-flash', 
		location.protocol + '//www.macromedia.com/go/getflashplayer'
		);

	//Get default BASE from movie URL	
	var base = movie.substring(0, movie.lastIndexOf('/') + 1);
	
	//Add default parameters
	obj.AddParam('movie', movie, true, false); //not used in EMBED
	obj.AddParam('BASE', base);
	obj.AddParam('quality', 'high');
	obj.AddParam('allowScriptAccess', 'sameDomain');
	obj.AddParam('bgcolor', '#ffffff');
	obj.AddParam('wmode', 'transparent');
	// for embedding
	obj.AddParam('src', movie, false);
	obj.AddParam('swliveconnect', 'true', false);

	return obj;
}

// Basic javascript object used to create an html OBJECT
function unityObject(id, classid, codebase, width, height, type, pluginspage) {
	var obj = this;
	
	//Set properties
	obj.id = id;
	obj.width = width;
	obj.height = height;
	obj.classid = classid;
	obj.codebase = codebase; 
	obj.type = type; //used for EMBED tag
	obj.pluginspage = pluginspage; //used for EMBED tag

	//Attach methods
	obj.AddAttribute = unityObjectAddAttribute;
	obj.DeleteAttribute = unityObjectDeleteAttribute;
	obj.AddParam = unityObjectAddParam;
	obj.DeleteParam = unityObjectDeleteParam;
	obj.GenerateHtml = unityObjectGenerateHtml;
	obj.Write = unityObjectWrite;
	obj.Insert = unityObjectInsert;
	
	return obj;
}

// Generate the Html to be inserted
function unityObjectGenerateHtml() {
	var obj = this;

	var attrs = '';
	var embedAttrs = '';
	var params = '';
	var embedParams = '';
	
	for (prop in obj) {
		var p = obj[prop];
		
		if (typeof(p) != 'undefined' && p != null) {
			var index = prop.indexOf('_');
			var type = prop.substring(0, index);
				
			switch (type) {
				case 'attribute':
					if (p.useInEmbed) {
						attrs += ' ' + prop.substring(10) + '="' + p.value +'"';
					}
					if (p.useInObject) {
						embedAttrs += ' ' + prop.substring(10) + '="' + p.value +'"';
					}
					break;
					
				case 'param':
					if (p.useInEmbed) {
						embedParams += ' ' + prop.substring(6) + '="' + p.value +'"';
					}
					if (p.useInObject) {
						params += '<param name="' + prop.substring(6) + '" value="' + p.value + '" />\n';
					}
					break;
			}
		}
	}
	
	//Build EMBED tag. Note: all params will be output as attributes
	var embedHtml = 
		'<embed'
		+ ' name="' + obj.id + '"'
		+ ' type="' + obj.type + '"'
		+ ((typeof(obj.width) != 'undefined') ? ' width="' + obj.width + '"' : '')
		+ ((typeof(obj.height) != 'undefined') ? ' height="' + obj.height + '"' : '')
		+ ((typeof(obj.pluginspage) != 'undefined') ? ' pluginspage="' + obj.pluginspage + '"' : '')
		+ embedAttrs
		+ embedParams
		+ '></embed>\n';
	
	//Build OBJECT tag, including EMBED tag from above
	var objectHtml = 
		'<object'
		+ ' id="' + obj.id + '"'
		+ ' classid="' + obj.classid + '"'
		+ ((typeof(obj.codebase) != 'undefined') ? ' codebase="' + obj.codebase + '"' : '')
		+ ((typeof(obj.width) != 'undefined') ? ' width="' + obj.width + '"' : '')
		+ ((typeof(obj.height) != 'undefined') ? ' height="' + obj.height + '"' : '')
		+ attrs
		+ '>\n'
		+ params
		+ embedHtml
		+ '</object>';

	//Save generated HTML
	obj.generatedHtml = objectHtml;
	
	return objectHtml;
}

// Insert HTML into document under given element id
// The restyleHost parameter defaults to true and need not be supplied
function unityObjectInsert(hostId, restyleHost) {
	var obj = this;
	
	//Default replacing behaviour
	if (typeof(restyleHost) == 'undefined') {
		restyleHost = true;
	}
	
	var hostElement = document.getElementById(hostId);
	
	//Save host element
	obj.hostElement = hostElement;
	
	if (hostElement) {
		//Build output Html
		var objectHtml = obj.GenerateHtml();
		
		//Insert html into document at host element 
		hostElement.innerHTML = objectHtml;

		//Resize host element to fit
		if (restyleHost) {
			hostElement.style.width = obj.width + 'px';
			hostElement.style.height = obj.height + 'px';
		}
	}
}

// Insert HTML into document under given element id
// The restyleHost parameter defaults to true and need not be supplied
function unityObjectWrite() {
	var obj = this;
	
	//Build output Html
	var objectHtml = obj.GenerateHtml();
	
	//Insert html into document
	document.write(objectHtml);
}

// Add attribute method
// The useInObject and useInEmbed parameters both default to true and need not be supplied
function unityObjectAddAttribute(name, value, useInObject, useInEmbed) {
	if (typeof(useInEmbed) == 'undefined') {
		useInEmbed = true;
	}
	if (typeof(useInObject) == 'undefined') {
		useInObject = true;
	}
	
	this['attribute_' + name] = {
		value: value, 
		useInEmbed: useInEmbed, 
		useInObject: useInObject
		};
}

// Delete attribute method
function unityObjectDeleteAttribute(name) {
	delete this['attribute_' + name];	
}

// Add param method
// The useInObject and useInEmbed parameters both default to true and need not be supplied
function unityObjectAddParam(name, value, useInObject, useInEmbed) {
	if (typeof(useInEmbed) == 'undefined') {
		useInEmbed = true;
	}
	if (typeof(useInObject) == 'undefined') {
		useInObject = true;
	}

	this['param_' + name] = {
		value: value, 
		useInEmbed: useInEmbed, 
		useInObject: useInObject
		};
}

// Delete param method
function unityObjectDeleteParam(name) {
	delete this['param_' + name];	
}


//-------------------------------------------------------------------------------------
// New flash insertion technique

function unityEmbeddedMedia_NameValueCollection() 
{
	this.params = new Object();
	this.AddParam = unityEmbeddedMedia_AddParam;	
	return this;
}
function unityEmbeddedMedia_AddParam(paramName, paramValue)
{
	unityEmbeddedMediaParams.params[paramName] = paramValue;
}

//Param list to hold user defined params
var unityEmbeddedMediaParams = new unityEmbeddedMedia_NameValueCollection();
//Default value for wmode
unityEmbeddedMediaParams.AddParam("WMode", "Opaque");

//Insert flash
function unityEmbeddedMedia_Flash(mediaBoxId, mediaUrl, mediaWidth, mediaHeight, mediaId, name) 
{
	var classid = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000';
	var flashVersion = "8,0,0,0";
	var codebase = location.protocol + '//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + flashVersion;
	
	var paramHtml = "";
	var embedHtml = "";
	for(elem in unityEmbeddedMediaParams.params)
	{
		paramHtml += '<param name="' + elem + '" value="' + unityEmbeddedMediaParams.params[elem] + '" />\n';
		if (!document.all)
		{
			embedHtml += ' ' + elem + '="' + unityEmbeddedMediaParams.params[elem] + '" ';
		}
	}
	
	var nestedObj = "";
	if (!document.all)
	{
		nestedObj = '<object type="application/x-shockwave-flash" data="' + mediaUrl + '"'
							+ ' width="' + mediaWidth + '" height="' + mediaHeight + '" ' + embedHtml + '>\n'
							+ '</object>';
	}
	
	var objectHtml = 
		'<object'
		+ ' id="' + mediaId + '"'
		+ ' classid="' + classid + '"'
		+ ' codebase="' + codebase + '"'
		+ ' width="' + mediaWidth + '"'
		+ ' height="' + mediaHeight + '">'
		+ '<param name="movie" value="' + mediaUrl + '" />\n'
		+ paramHtml
		+ nestedObj
		+ '</object>';
	
	document.getElementById(mediaBoxId).innerHTML = objectHtml;
	
	//Clear the params obj
	unityEmbeddedMediaParams.params = new Object();
}
//-------------------------------------------------------------------------------------


//-------------------------------------------------------------------------------------
//Unity onload function handler
function unityOnloadHandler() 
{
	this.onloadFunctions = new Array();
	
	this.addOnloadFunction = function(fnName)
	{
		this.onloadFunctions.push(fnName);
	}
	
	this.processPageLoad = function()
	{
		for(var i in this.onloadFunctions)
		{
			eval(this.onloadFunctions[i] + "()");
		}
	}
}
//This exists because you cannot assign "unityPageLoadHandler.processPageLoad" to the onload event
function unityPageLoad()
{
	unityPageLoadHandler.processPageLoad();
}

//Run this when the page loads
var unityPageLoadHandler = new unityOnloadHandler();
window.onload = unityPageLoad;
//-------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------
//Unity onunload function handler
function unityOnunloadHandler() 
{
	this.onunloadFunctions = new Array();
	
	this.addOnunloadFunction = function(fnName)
	{
		this.onunloadFunctions.push(fnName);
	}
	
	this.processPageUnload = function()
	{
		for(var i in this.onunloadFunctions)
		{
			eval(this.onunloadFunctions[i] + "()");
		}
	}
}
//This exists because you cannot assign "unityPageLoadHandler.processPageLoad" to the onload event
function unityPageUnload()
{
	unityPageUnloadHandler.processPageUnload();
}

//Run this when the page loads
var unityPageUnloadHandler = new unityOnunloadHandler();
window.onunload = unityPageUnload;
//-------------------------------------------------------------------------------------