	var mSelectedDate	//Date selected in the picker, should be null if no date selected
	var mQuestionId     //QuestionId currently filling
	var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
    var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    var dayInitials = new Array("S","M","T","W","T","F","S"); 
    var displayMonth	//Month currently displayed
	var displayYear		//Year currently displayed
	var dowStart=0;
	var dateLong = new Array();
	var dateUtc = new Array();

//General date functions
    function getDaysInMonth(month, year) {
		// Test for leap year when February is selected.
		if (1 == month)
			return ((0 == year % 4) && (0 != (year % 100))) || (0 == year % 400) ? 29 : 28;
		else
			return daysInMonth[month];
    }

	function getDOW(day, month, year)
	{
		var date = new Date(year, month, day);
		return (date.getDay()+(7-dowStart))%7;
	}

	function IsValidDate(year, month, day) {
		if (isNaN(parseInt(year)) || isNaN(parseInt(month)) || isNaN(parseInt(day)))
			return false;
		else {
			var dte = new Date(year, month, day);
			//make sure that the date is the one represented by what was entered, not automatically changed
			if (parseInt(month)==dte.getMonth() && parseInt(day)==dte.getDate()) {
				return true;
			} 
			else {
				return false;
			}
		}			
	}
		
	function DateStringFromComponents(year, month, day) {
		var dte = new Date(year, month, day);
		return '' + dte.getFullYear() + '-' + (dte.getMonth() + 1) + '-' + dte.getDate();
	}
	
	function DateUTCFromComponents(year, month, day) {
		var dte = new Date(year, month, day);
		var m=''
		//acount for single digit minutes
		if (dte.getUtcMinutes() < 10) {
			m='0'+dte.getUtcMinutes();
		} else {
			m='0'+dte.getUtcMinutes();
		}
		return '' + dte.getUTCFullYear() + '-' + (dte.getUTCMonth() + 1) + '-' + dte.getUTCDate() + ' ' + dte.getUTCHours() + ':' + m;
	}
		
	function getDateLocalSql(SqlDate)
	{
		return getShortDate(getLocalTimeFromUtcSqlTime(SqlDate));	
	}
	function getDateTimeLocalSql(SqlDate)
	{
		return getDateTime(getLocalTimeFromUtcSqlTime(SqlDate));	
	}
	function getLocalTimeFromUtcSqlTime(sDate)
	{
	//converts the sql UTC date string into local time
		var dte = new Date(Date.UTC(sDate.substr(0,4),sDate.substr(5,2)-1,sDate.substr(8,2), sDate.substr(11,2), sDate.substr(14,2)));
		return dte;
	}
	function getDateLocal(Year, Month, Day, Hour, Minute, Second)
	{
	//converts the sql UTC date string into local time then formats it to a date
		return getShortDate(getLocalFromUtc(Year, Month, Day, Hour, Minute, Second));
	}
			
	function getDateTimeLocal(Year, Month, Day, Hour, Minute, Second)
	{
	//converts the sql UTC date string into local time then formats it dd MMM YYYY HH:nn
		return getDateTime(getLocalFromUtc(Year, Month, Day, Hour, Minute, Second));
	}
		
	function getLocalFromUtc(Year, Month, Day, Hour, Minute, Second)
	{
	//converts the sql UTC date string into local time
		var dte = new Date(Date.UTC(Year, Month, Day, Hour, Minute, Second));
		return dte;
	}

	function getShortDate(date)
	{
		return date.getDate() + " " + months[date.getMonth()] + " " + date.getFullYear();
	}	
	
	function getDateTime(date)
	{
		var x = date.getMinutes()
		//add leading zero to minutes if needed
		if (Math.abs(parseInt(x)) < 10){ x = "0"+ Math.abs(x); };
		return getShortDate(date) + " " + date.getHours() + ":" + x;
	}

//Drop down picker functions	
	//either returns the style object for the div, or the layer, both of which have a visiblity property 
	function getDivStyle() {
		if (document.getElementById || document.all) { 
			return getSingleElement('calDropDown').style; 
		} else {
			return  document.layers['calDropDown'];
		}
	}
	function setInnerHtml() {
		var startDay = new Date(displayYear ,displayMonth, 1);
		var dayOfWeek=getDOW(1,displayMonth ,displayYear);
        var intDaysInMonth = getDaysInMonth(displayMonth , displayYear);
	    var daysGrid = '<table class="cal"><tr><td>';
	    var today=new Date();
	    var isTodayMonth=(displayMonth==today.getMonth()) && (displayYear==today.getFullYear());
	    var isSelectedMonth=(mSelectedDate && (displayMonth==mSelectedDate.getMonth()) && (displayYear==mSelectedDate.getFullYear()));
	    //header with pickers in it
	    daysGrid += '<table class="calHead" border="0" cellpadding="0" cellspacing="1" height="20" align="center"><tr>';
	    //month picker
	    daysGrid += '<td width="16px"><a href="#" onclick="incMonth(-1);return false;"><img alt="Show previous month" src="/img/calendar/prev.gif" /></a></td>';
	    daysGrid += '<td>&nbsp;' + months[displayMonth] + '&nbsp;</td>';
	    daysGrid += '<td width="16px"><a href="#" onclick="incMonth(1);return false;"><img alt="Show next month" src="/img/calendar/next.gif" /></a></td>';
	    //year picker
   	    daysGrid += '<td width="16px"><a href="#" onclick="incYear(-1);return false;"><img alt="Show previous year" src="/img/calendar/prev.gif" /></a></td>';
	    daysGrid += '<td>&nbsp;' + displayYear + '&nbsp;</td>';
	    daysGrid += '<td width="16px"><a href="#" onclick="incYear(1);return false;"><img alt="Show next year" src="/img/calendar/next.gif" /></a></td>';
		//end pickers
		daysGrid += '</tr></table>';
		
		//Calander body
		daysGrid += '<table class="calBody">';
		//days of the week
		daysGrid += '<tr>';
		for(var i=0; i<=6; i++) {
			daysGrid += '<th>' + dayInitials[(i + (7-dowStart))%7] + '</th>';
		}
		daysGrid += '</tr>';
		// spacing before first actual date, need some spacing first, unless the 1st of the month is in the 1st column
		if (dayOfWeek!=0) {
			daysGrid += '<tr>';
			for(var i=0; i<dayOfWeek; i++) {
				daysGrid += '<td>&nbsp;</td>';
			}
		}
		//actual dates ie calander body, often need some spacing first, unless the 1st of the month is in the 1st column
		for(var dayOfMonth=1; dayOfMonth<=intDaysInMonth; dayOfMonth++) {
			dayOfWeek=getDOW(dayOfMonth ,displayMonth, displayYear);
			//new line for start of week
			if (dayOfWeek==0) daysGrid += '<tr>';
			var className='';
			//Highlight today
			if (isTodayMonth && (dayOfMonth==today.getDate())) { 
				className='calToday';
			}
			//Highlight selected date
			if (isSelectedMonth && (dayOfMonth==mSelectedDate.getDate())) {
				if (className.length > 0) 
					className += ' ';
				className += 'calSel'
			} 
			if (className.length > 0) {
				daysGrid += '<td class="' + className + '">';
			} else {
				daysGrid += '<td>';
			}
			daysGrid += '<a href="#" onclick="SetDate(' + dayOfMonth + ', ' + displayMonth + ', ' + displayYear + ');return false;">' + dayOfMonth + '</a></td>';
			if (dayOfWeek==6) daysGrid += '</tr>';
		}
		//need to complete table if not at end of row
		if (dayOfWeek!=6) {
			for(var i=dayOfWeek+1; i<=6; i++) {
				daysGrid += '<td>&nbsp;</td>';
			}
			daysGrid += '</tr>';
		}
		//close calbody
		daysGrid += '</table>';
		//Cancel and today
		daysGrid += '<table class="calFooter" align="center"><tr>';
		daysGrid += '<td onclick="SetDate(' + today.getDate() + ', ' + today.getMonth() + ', ' + today.getFullYear() + ');return false;"><a href="#" >Today</a></td>';
		daysGrid += '<td onclick="hideCalendar();return false;"><a href="#" onclick="hideCalendar();return false;">Cancel</a></td>';		
		daysGrid += '</table>';
		//close outer table
		daysGrid + '</td></tr></table>';
		
		//now stick it into the document
	    if (document.getElementById || document.all) {
			getSingleElement('calDropDown').innerHTML = daysGrid;
	    } else {
	       var elt = document.layers[eltName].document;
	       elt.open();
	       elt.write(daysGrid);
	       elt.close();
	    }
	 }

	 function incMonth(delta) {
	   displayMonth += delta;
	   if (displayMonth >= 12) {
	     displayMonth = 0;
	     incYear(1);
	   } else if (displayMonth <= -1) {
	     displayMonth = 11;
	     incYear(-1);
	   } else {
	     setInnerHtml();
	   }
	 }

	 function incYear(delta) {
	   displayYear = parseInt(displayYear + '') + delta;
	   setInnerHtml();
	 }	 

//Visible date component functions
    function dateAnswerWrite(id, day, monthx, year) {
		var DateHolder=getSingleElement('dh' + id);
		dateLong[id]=true;
		DateHolder.innerHTML +=	dateAnswerWriteDays(id);
		DateHolder.innerHTML +=	dateAnswerWriteMonths(id, false);
		DateHolder.innerHTML +=	dateAnswerWriteYears(id);
		DateHolder.innerHTML +=	dateAnswerWriteHidden(id);
		DateHolder.innerHTML +=	dateAnswerWriteCal(id);
		DateHolder.innerHTML +=	dateAnswerWriteIcon(id,true);
		dateAnswerValuesSet(id, day, monthx-1, year);
	}

    function dateAnswerWriteShort(id, day, month, year) {
		var DateHolder=getSingleElement('dh' + id);
		dateLong[id]=false;
		if (day==0) month=0;
		DateHolder.innerHTML +=	dateAnswerWriteHiddenDays(id);
		DateHolder.innerHTML +=	dateAnswerWriteMonths(id, true);
		DateHolder.innerHTML +=	dateAnswerWriteYears(id);
		DateHolder.innerHTML +=	dateAnswerWriteHidden(id);
		//DateHolder.innerHTML +=	dateAnswerWriteCal(id);
		//never display icon
		DateHolder.innerHTML +=	dateAnswerWriteIcon(id,false);
		dateAnswerValuesSet(id, day, month-1, year);
	}	
	
	function dateAnswerWriteUTC(id, day, month, year) {
		dateUtc[id]=true;		
		dateAnswerWrite(id, day, month, year); 
	}	
	
	function dateAnswerWriteIcon(id, display) {
		var s='<img id="qwi' + id + '" name="qwi' + id + '" src="/img/icon-warning-orange.gif" height="15px" width="15px" border="0" alt="Invalid Date" style="visibility:hidden;margin-right:3px;';
		if (!display) s+= 'display:none;';
		return s + '" />';
	}
	
	function dateAnswerWriteDays(id) {
		var s='';
		s+='<select onchange="dateAnswerIsSet(' + id + ');changed();" id="qadd' + id + '" name="qadd' + id + '" class="calDay">';
		s+='<option value="0">Not Set</option>';
		for (var i=1;i<=31;i++) {
			s+='<option value="' + i + '">' + i + '</option>';
		}
		s+='</select>';
		return s;
	}
	
	function dateAnswerWriteHiddenDays(id) {
		return '<input type="hidden" value="0" id="qadd' + id + '" name="qadd' + id + '">';
	}	
	
	function dateAnswerWriteMonths(id, NotSetRow) {
		var s='';
		s+='<select onchange="dateAnswerIsSet(' + id + ');changed();" id="qadm' + id + '" qadm="qadm' + id + '" class="calMonth">';
		if (NotSetRow) s+='<option value="-1">Not Set</option>';
		for (var i=0;i<=11;i++) {
			s+='<option value="' + (i) + '">' + months[i] + '</option>';
		}
		s+='</select>';
		return s;
	}
   
	function dateAnswerWriteYears(id) {
		return '<input id="qady' + id + '" name="qady' + id + '" type="text" maxlength="4" onchange="dateAnswerIsSet(' + id + ');changed();" onkeypress="return integerKeys(event.which);" class="calYears" />';
	}
	
	function dateAnswerWriteHidden(id) {
		return '<input type="hidden" id="q' + id + '" name="q' + id + '" />'; 
	}
	
	function dateAnswerWriteCal(id) {
		if (navigator.userAgent.indexOf("Opera") == -1) {
			return '<a href="#" onclick="PopUpCalendar(' + id + ');event.cancelBubble=true;return false;" class="NonAural"><img alt="View calendar to select a date" border="0" hspace="1" id="dateAnswerCalImg' + id + '" name="dateAnswerCalImg' + id + '" src="/img/calendar/calendar.gif" style="top: 3px; left: -1px; position: relative;"/></a>';
		} else {
			return '<img border="0" id="dateAnswerCalImg' + id + '" name="dateAnswerCalImg' + id + '" src="/img/spacer.gif" />';
		}
	}		
	
	function dateAnswerIsSet(id) {
		//disables other fields id date set to not set
		var disabled
		if (dateLong[id]) {
			var sd=getSingleElement('qadd' + id);
			disabled=sd.value==0;
			getSingleElement('qadm' + id).disabled=disabled;	
		} else {
			//short date
			var sm=getSingleElement('qadm' + id);
			var sd=getSingleElement('qadd' + id);
			disabled=sm.value==-1;
			if (disabled) {
				sd.value=0;
			} else {
				sd.value=15;
			}
		}
		getSingleElement('qady' + id).disabled=disabled;
		dateAnswerIconShow(id, disabled);
		dateAnswerChanged(id);
	}
	
	function dateAnswerIconShow(id, disabled) {
		var ico=getSingleElement('qwi' + id);	
		if (disabled || IsValidDateAnswer(id))
			ico.style.visibility='hidden';
		else
			ico.style.visibility='visible';
	}	
	
	function dateAnswerValuesSet(id, day, month, year) {
		var sd=getSingleElement('qadd' + id);
		var sm=getSingleElement('qadm' + id);
		var sy=getSingleElement('qady' + id);
		if (dateLong[id]) {
			//long date format
			//sd.value=day;
			sd.options[day].selected=true;
			//sm.value=month;
			sm.options[month].selected=true;
		} else {
			//short date format
			
			if (month!=-1) {
				//sm.value=month
				sm.options[month+1].selected=true;
			} else {
				//sm.value=-1
				sm.options[0].selected=true;
			}
		}
		sy.value=year;		
		dateAnswerIsSet(id);
	}
		
	function SetDate(day, month, year)
	{
		//This is where the value from the calendar is placed into the controls
		dateAnswerValuesSet(mQuestionId, day, month, year);
		if (dateLong[mQuestionId]) getSingleElement('qadd' + mQuestionId).focus();
		hideCalendar();
		changed();
	}

	function dateAnswerChanged(id) {
		var xt=getSingleElement('q' + id);
		var sd=getSingleElement('qadd' + id);
		var sm=getSingleElement('qadm' + id);
		var sy=getSingleElement('qady' + id);
		if (IsValidDate(sy.value, sm.value, sd.value)) {
			if (dateUtc[id]) {
				//if value in this array is true then have to save the utc date and time instead
				xt.value=DateUTCFromComponents(sy.value, sm.value, sd.value);
			} else {
				xt.value=DateStringFromComponents(sy.value, sm.value, sd.value);
			}
		}
		else xt.value="";
	}
		
	function IsValidDateAnswer(id) {
		var sd=getSingleElement('qadd' + id);
		var sm=getSingleElement('qadm' + id);
		var sy=getSingleElement('qady' + id);
		return IsValidDate(sy.value, sm.value, sd.value);		
	}
		
	function DateFromId(QuestionId) {
		var sd=getSingleElement('qadd' + QuestionId);
		var sm=getSingleElement('qadm' + QuestionId);
		var sy=getSingleElement('qady' + QuestionId);
		return new Date(sy.value, sm.value, sd.value);	
	}
	
//popup calender	
	function PositionCalendar(QuestionId) {
		var dateImage=getSingleElement('dateAnswerCalImg' + QuestionId);
		var cal=getDivStyle();
		var calShims=getSingleElement('calShim').style;
		//OK, so try doing it without the visibility first
		//cal.visibility='visible';
		if (document.getElementById) {	//only do this check if has dom, otherwise just stick underneath
			var calO=getSingleElement('calDropDown');

            //18-May-2006 Andrew Shearer (Gemini 1966) - Units Added.
            //The W3C DOM states that style.left is a string containing the length followed by the unit.
            cal.left = getAbsX(dateImage) - calO.offsetWidth + dateImage.width + "px";

			if(getAbsY(dateImage) + calO.offsetHeight + dateImage.height >= document.body.scrollTop + document.body.clientHeight) {
                //show above if have to
                //18-May-2006 Andrew Shearer (Gemini 1966) - Units Added.
                //The W3C DOM states that style.left is a string containing the length followed by the unit.
                cal.top=getAbsY(dateImage)-calO.offsetHeight + "px";
			}
			else {
                //18-May-2006 Andrew Shearer (Gemini 1966) - Units Added.
                //The W3C DOM states that style.left is a string containing the length followed by the unit.
                cal.top=getAbsY(dateImage)+ dateImage.height + "px";
			}
			calShims.left=cal.left;
			calShims.top=cal.top;
			calShims.width='180px';
			calShims.height=calO.offsetHeight; 
		} else {
			//just put it under the day dropdown if full date, under the month if short date
			if (dateLong[QuestionId])	
				cal.left=getAbsX(getSingleElement('qadd' + QuestionId));
			else cal.left=getAbsX(getSingleElement('qadm' + QuestionId));
			cal.top=getAbsY(dateImage)+dateImage.height;
		}
	}
	
	function hideCalendar() {
		getSingleElement('calShim').style.display='none';
		getDivStyle().visibility = 'hidden';
		mQuestionId=null;
	}
			
	function PopUpCalendar(QuestionId) {
		var s = getDivStyle();
		//If displayed then hide, use visiblity for layers
		if (mQuestionId && mQuestionId != QuestionId) {s.visibility="visible";}
		mQuestionId=QuestionId;		
		//If displayed then hide, use visiblity for layers
		if (s.visibility=="visible") {
			hideCalendar();
		} 
		else
		{
			if (IsValidDateAnswer(QuestionId)) {
				//Set selected date
				mSelectedDate=DateFromId(QuestionId);
				displayMonth=mSelectedDate.getMonth();
				displayYear=mSelectedDate.getFullYear()
				setInnerHtml();
			}
			else {
				//No selected date
				selectedDate=null;
				var today=new Date()
				displayMonth=today.getMonth();
				displayYear=today.getFullYear()				
				setInnerHtml();
			}
			
			//position calender
			PositionCalendar(QuestionId);
			
			//Show
			s.visibility="visible";
			getSingleElement('calShim').style.display='block';
		}
	}