//----------------------------------------------------
// 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;
}



//--------------------------------------------------------------------------------------------
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		//alert("Please enter a valid 4 digit year between")
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}

function checkDateDiff(theForm)
	{
		
	var from_day, from_month, from_year, to_day, to_month, to_year;
	var char_day, current_day;
	char_day = theForm.from_date.value;
	from_day = parseInt(char_day.substring(0,2));
	from_month = parseInt(char_day.substring(3,6));
	from_year = parseInt(char_day.substring(6,10));
	current_day = new Date();
	to_day = current_day.getDate();
	to_month = current_day.getMonth()+1;
	to_year = current_day.getFullYear();
	var date_of_edu, month_of_edu, day_of_edu;
	//alert("to_year =" +to_year+",to_month="+to_month+",to_day="+to_day+",from_year="+from_year+",from_month="+from_month+",from_day="+from_day);
	var curd = new Date(to_year,to_month-1,to_day);
	var cald = new Date(from_year,from_month-1,from_day);
	
	var dife = datediff(curd,cald);
	date_of_edu = dife[0];
	month_of_edu = dife[1];
	day_of_edu = dife[2];
	//alert("date_of_edu=" + date_of_edu);
	if (date_of_edu < 0)
	{
		return false;
	}
	else
	{
		return true;
	}
}
function DaysInMonthNew(Y, M) {
    with (new Date(Y, M, 1, 12)) {
        setDate(0);
        return getDate();
    }
}
function datediff(date1, date2) {
var y1 = date1.getFullYear(), m1 = date1.getMonth(), d1 = date1.getDate(),
	 y2 = date2.getFullYear(), m2 = date2.getMonth(), d2 = date2.getDate();
	//alert("y1 =" +y1+",m1="+m1+",d1="+d1+",y2="+y2+",m2="+m2+",d2="+d2);
    if (d1 < d2) {
        m1--;
        d1 += DaysInMonthNew(y2, m2);
    }
    if (m1 < m2) {
        y1--;
        m1 += 12;
    }
    return [y1 - y2, m1 - m2, d1 - d2];
}

 //-------------------------------------------------------------------------------------------------------------------