//----------------------------------------------------
// Javascript library

// validate text control (0 value)
function isZero(control){
	var the_value = parseFloat(trimSpaces(control.value));
	if (the_value == 0){
		control.focus();
		control.select();
		return true;
	}
	return false;
}

// validate text control (valid numeric value)
function isNotNumeric(control){
	if (isNaN(trimSpaces(control.value))){
		control.focus();
		control.select();
		return true;
	}
	return false;
}

// validate text control
function isEmpty(control){
	if (trimSpaces(control.value) == "" ){
		control.focus();
		control.select();
		return true;
	}
	return false;
}

// remove leading and tailing a string
function trimSpaces(inputStr){
	var len=inputStr.length;
	var i=0;
	while(i<len && inputStr.charAt(i)==" ") i++;
	var j=len-1;
	while(j>=0 && inputStr.charAt(j)==" ") j--;
	if (i<=j) // not empty
		return inputStr.substring(i,j+1);
	else
		return "";
}

// validate the email
function emailCheck (emailStr) {
 var emailPat=/^(.+)@(.+)$/
 var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
 var validChars="\[^\\s" + specialChars + "\]"
 var quotedUser="(\"[^\"]*\")"
 var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
 var atom=validChars + '+'
 var word="(" + atom + "|" + quotedUser + ")"
 var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
 var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
 var matchArray=emailStr.match(emailPat)

	if (emailStr=="") {
	 	alert("Please provide a contact Email Address")
		return false;
	}

	if (matchArray==null) {
	 	alert("Your Email Address seems incorrect.\nPlease make sure the formatting is correct (@ and .)")
		return false;
	}
	var user=matchArray[1]
	if (user.match(userPat)==null) {
	    alert("The email username does not seem to be valid.")
	    return false;
	}

	return true;
}

// check the dropdown selection
function checkDropDown(control,input){
	if (control[control.selectedIndex].value==input){
		control.focus();
		return false;
	}
	return true;
}

// check the radio selection
function checkRadioButton(control){
	var i;
	for (i=0;i<control.length;i++) {
		if (control[i].checked)
			return true;
	}
	control[0].focus();
	return false;
}

// validate the date of birth to fix the leap year,
// different in number of day for each month
function validateDOB(dob_day, dob_month, dob_year){

	// get the current selected month and year
	var dayIndex=dob_day.selectedIndex;
	var theMonth=parseInt(dob_month[dob_month.selectedIndex].value,10);
	var theYear=parseInt(dob_year[dob_year.selectedIndex].value,10);
	if (theMonth==0 || theYear==0){
		return;
	}
	//alert(theMonth+"--"+theYear);
	// JavaScript uses month index from 0-11, while the list is 1-12
	theMonth--;

	// remove old day list
	var k;
	for(k=dob_day.length-1;k>0;k--){
		dob_day.options[k]=null;
	}

	// add new options for the day list
	k=1;
	var theDay=1;
	var dob_date;
	var currMonth=theMonth;
	while(theDay<=31){
		dob_date=new Date(theYear,theMonth,theDay);
		//alert(dob_date);
		theMonth=dob_date.getMonth();
		if (currMonth==theMonth){
			if (theDay<10){
				dob_day.options[k]=new Option(" 0"+theDay+" ","0"+theDay, 0, 0);
			}
			else{
				dob_day.options[k]=new Option(" "+theDay+" ", theDay, 0, 0);
			}
		}
		else{
			break;
		}
		theDay++;
		k++;
	}

	// keep the current selected day
	//alert(dayIndex +"--"+theDay);
	if (dayIndex<theDay){
		dob_day.selectedIndex = dayIndex;
	}
	else{
		// select the last item in th list
		dob_day.selectedIndex = dob_day.length-1;
	}
}

// open help window
function openHelp(vLink, vHeight, vWidth, vScrollbar)
{
	var sLink = (typeof(vLink.href) == 'undefined') ? vLink : vLink.href;
	
	if (sLink == '')
	{
		return false;
	}

	winDef = 'status=no,resizable=yes,toolbar=no,location=no,fullscreen=no,titlebar=yes,height='.concat(vHeight).concat(',').concat('width=').concat(vWidth).concat(',').concat('scrollbars=').concat(vScrollbar).concat(',');
	winDef = winDef.concat('top=').concat((screen.height - vHeight)/2).concat(',');
	winDef = winDef.concat('left=').concat((screen.width - vWidth)/2);
	newwin = open('', '_blank', winDef);
	newwin.location.href = sLink;

	if (typeof(vLink.href) != 'undefined')
	{
		return false;
	}
}

// limit number of chars in the textarea
// check when the key is pressed
// textObj: textarea control name
// maxChar: max number of chars allowed
function checkKeypress(textObj,maxChar){
	var result = true;
	var charTyped = textObj.value.length;
	if (charTyped >= maxChar){
		result = false;
	}
	if (window.event) window.event.returnValue = result;

	return result;
}

// limit number of chars in the textarea
// check when the key is up
// textObj: textarea control name
// counterObj: textbox name that shows the number of chars left
// maxChar: max number of chars allowed
function checkKeyup(textObj, counterObj,maxChar){
	var charTyped = textObj.value.length;
	var charLeft = maxChar - charTyped;
	if (charLeft < 0){
		var diff = charTyped - maxChar;
		var validText = textObj.value.substr(0, charTyped-diff);
		textObj.value = validText;
		charLeft = 0;
	}
	counterObj.value = charLeft;
}

// pre-select an item in the list
function selectDefaultItem(optionList, defaultItem){
	var length = optionList.length;
	var ii;
	if (new String(defaultItem)!=""){
		for(ii=0;ii<length;ii++){
			if (optionList[ii].value == defaultItem){
				optionList.selectedIndex = ii;
				break;
			}
		}
	}
}

// pre-select an item in a list if no item is selected
function selectOptionList(optionList, empty_value, new_value){
	if (optionList[optionList.selectedIndex].value == empty_value){
		selectDefaultItem(optionList, new_value);
	}
}

// time range validation: end point - start point >= required period (in months)
// input: option list  controls
// return true if valid period, false if else
function timePeriodValidate(start_month, start_year, end_month, end_year, month_period){
	var start_month_val = parseInt(start_month[start_month.selectedIndex].value,10);
	var start_year_val = parseInt(start_year[start_year.selectedIndex].value,10);
	var end_month_val = parseInt(end_month[end_month.selectedIndex].value,10);
	var end_year_val = parseInt(end_year[end_year.selectedIndex].value,10);
	var return_val = false;
	var max_month = 12, min_month = 1;
	var study_month;
	
	// check the values
	if (start_year_val>0 && end_year_val>0){
		if (start_month_val>=min_month && start_month_val<=max_month){
			if (end_month_val>=min_month && end_month_val<=max_month){
				// get the actual time period in months
				study_month = (end_year_val - start_year_val)*12 + end_month_val - start_month_val + 1;
				if (study_month >= month_period){
					return_val = true;
				}
			}
		}
	}
	
	return return_val;
}

// time conversion
// input: local country, time in local country, date required, country in which time is required
// returns time in target country equivalent to given time in local country
function convertTime(local_country, local_time, local_date, target_country)
{
	var local_zone, target_zone, zone_difference, target_hour;

	// get time zone for local country
	switch (local_country)
	{
		case "AU":
			local_zone = getMelbourneTimeZone(local_date);
			break;
		case "CA":
			local_zone = getTorontoTimeZone(local_date);
			break;
		case "GB":
			local_zone = getLondonTimeZone(local_date);
			break;
		case "LK":
			local_zone = getColomboTimeZone(local_date);
			break;
		default:
			local_zone = 0;
	}

	// get time zone for target country
	switch (target_country)
	{
		case "AU":
			target_zone = getMelbourneTimeZone(local_date);
			break;
		case "CA":
			target_zone = getTorontoTimeZone(local_date);
			break;
		case "GB":
			target_zone = getLondonTimeZone(local_date);
			break;
		case "LK":
			target_zone = getColomboTimeZone(local_date);
			break;
		default:
			target_zone = 0;
	}

	// get time difference between two countries
	if (target_zone > local_zone)
	{
		zone_difference = target_zone - local_zone;
	}
	else
	{
		zone_difference = local_zone - target_zone;
	}
	target_hour = local_time - zone_difference;

	// add 24 (one day) if target time is negative
	if (target_hour < 0)
	{
		target_hour+= 24;
	}

	// return converted time
	return target_hour;
}

/*************************************************************
/ Melbourne Time Zone Library
/ Get the current time zone (inc saving time)
/************************************************************/
// get the time zone of Melbourne
// time saving start at 2:00:00 AM of the last Sunday in Oct
// and end at 3:00:00 AM of the last Sunday of March
function getMelbourneTimeZone(today)
{
	var start_month = 3;
	var end_month = 10;
	var the_year;
	var time_zone;
	var start_standard, end_standard;
	time_zone = 11;
	today = new Date(today);
	the_year = today.getYear();

	// start and end of the standard time
	start_standard = new Date(getLastSunday(start_month, the_year));
	end_standard = new Date(getLastSunday(end_month, the_year));

	// if in standard time, the time zone is 10
	if ((today>=start_standard) && (today<end_standard))
	{
		time_zone = time_zone - 1;
	}

	// return value
	return time_zone;
}

//-------------------------------------------------------------
// get the time zone of Toronto
// time saving start at 2:00:00 AM of the first Sunday in April
// and end at 2:00:00 AM of the last Sunday of October
function getTorontoTimeZone(today)
{
	var start_month = 4;
	var end_month = 10;
	var the_year;
	var time_zone;
	var start_standard, end_standard;
	time_zone = -5;
	today = new Date(today);
	the_year = today.getFullYear();

	// start and end of the saving time
	start_standard = new Date(getLastSunday(start_month, the_year));
	end_standard = new Date(getLastSunday(end_month, the_year));

	// if in standard time, the time zone is -4
	if ((today>=start_standard) && (today<end_standard))
	{
		time_zone = time_zone + 1;
	}

	// return value
	return time_zone;
}

//-------------------------------------------------------------
// get the time zone of Colombo
function getColomboTimeZone(today)
{
	return 6;
}

//-------------------------------------------------------------
// get the time zone of London
// time saving start at 1:00:00 AM of the last Sunday in March
// and end at 2:00:00 AM of the last Sunday of October
function getLondonTimeZone(today)
{
	var start_month = 3;
	var end_month = 10;
	var the_year;
	var time_zone;
	var start_standard, end_standard;
	time_zone = 0;
	today = new Date(today);
	the_year = today.getFullYear();

	// start and end of the saving time
	start_standard = new Date(getLastSunday(start_month, the_year));
	end_standard = new Date(getLastSunday(end_month, the_year));

	// if in standard time, the time zone is -4
	if ((today>=start_standard) && (today<end_standard))
	{
		time_zone = time_zone + 1;
	}

	// return value
	return time_zone;
}

// get the last Sunday of a month
function getLastSunday(the_month, the_year)
{
	var last_sunday, last_date, last_day;
	the_month = parseInt(the_month);
	the_year = parseInt(the_year);

	// find the end of the month
	switch (the_month)
	{
		case 1, 3, 5, 7, 8, 10, 12:
			last_date = 31;
			break;
		case 4, 6, 9, 11:
			last_date = 30;
			break;
		case 2:
			last_date = 28;
			break;
		default:
			last_date = 0;
	}
	last_sunday = new Date(the_year, the_month, last_date);

	// find the last Sunday
	last_day = last_sunday.getDate();
	last_sunday = last_sunday.setDate(last_date-last_day);

	// return the date	
	return last_sunday;
}
