// Lemon (Asia) Ltd

/*******************************************************
 * This file contains some general form elements
 * related functions, for both input and output usages.
 *******************************************************/

function isDigit(c) { return c >= '0' && c <= '9'; }
function isLetter(c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }

// pre-select options according to the variables passed
function selectedOptions()
{
	var i, j;
	var args = selectedOptions.arguments;
	var frm_name = (document.all != null ? "document.all." : "document.") + args[0];
	for (i=1; i<args.length-1; i+=2)
	{
		var obj = eval(frm_name + "." + args[i]);
		var t = obj.type

		if (t == 'select-one' || t == 'select-multiple')
		{
			for (j=0; j<obj.options.length; j++)
			{
				if (obj.options[j].value == args[i+1])
				{
					obj.options[j].selected = true;
					break;
				}
			}
		}
		else if (t == 'checkbox')
		{
			obj.checked = obj.value == args[i+1];
		}
		else if (obj[0] != null && obj[0].type != null && (obj[0].type == 'radio' || obj[0].type == 'checkbox'))
		{
			for (j=0; j<obj.length; j++)
			{
				if (obj[j].value == args[i+1])
				{
					obj[j].checked = true;
				}
			}
		}
		else
			obj.value = args[i+1]
	}
}

function selectedOptions2(f,n,v,i) {
	var frm = (document.all != null ? "document.all." : "document.")
	var obj = i != 0 ? eval(frm + f + "." + n + "["+i+"]") : eval(frm + f + "." + n)
	if (obj.type == 'select-one'){
		for (j=obj.options.length; --j>=0; )
			if (obj.options[j].value == v)
				obj.options[j].selected = 1
	}
}

// used to retrieve the select value off a group of radio buttons
function radioButtonValue(o)
{
	for (i=o.length;--i>=0;)
		if (o[i].checked) return o[i].value
}

function valueOf(o)
{
	return o.type == 'select-one' ? o.options[o.selectedIndex].value : radioButtonValue(o)
}

function validateAddress(objValue) {
	if(objValue == "") return true;
	var pattern = /[~`!#$%^&*()+|\\=,<>?:;'"{}\[\]]/;
	var result = objValue.split(/\s*,\s*/);
	for (var i = 0; i < result.length; i++) {
		if(result[i].match(pattern)) {
			alert("Invalid email address with unacceptable character(s). Please enter again");
			return false;
		}
		var occur = /@[^@]*@/;
		if(result[i].match(occur)) {
			alert("Invalid email address with more than one '@' symbol. Please enter again");
			return false;
		}
		if(-1 == result[i].indexOf("@")) {
			alert("Invalid email address not containing an '@' symbol. Please enter again");
			return false;
		}
		if(0 == result[i].indexOf("@")) {
			alert("Invalid email address with an '@' symbol at a start. Please enter again");
			return false;
		}
		if(-1 != result[i].indexOf(" ")) {
			alert("Invalid email address containing a space between characters/ numbers. Please enter again" );
			return false;
		}
		if(result[i].length == (result[i].indexOf("@")+1) ) {
			alert("Invalid email address not containing a domain name after the '@' symbol. Please enter again");
			return false;
		}
	}
	return true;
}

// check if the string is an email
function isEmail(s, o, m)
{
	// are regular expressions supported?
	var supported = 0;
	if (window.RegExp) {
		var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr)) supported = 1;
	}

	if (!supported)
		return s.indexOf(".") > 2 && s.indexOf("@") > 0 ? 1 : alertErr(o, m)

	var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)")
	var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$")
	return (!r1.test(s) && r2.test(s)) ? true : alertErr(o, m)
}

// check if the string is a valid variable-syntaxed string
function isSimpleWord(s, o, m)
{
	for (i=0, c=s.charAt(0); i<s.length; c=s.charAt(++i))
	if (!isDigit(c) && !isLetter(c) && c != '_') return alertErr(o, m)
	return 1
}

// used to alert messages
function alertErr(o, m)
{
	if (m) alert(m)
	if (o) o.focus()
	return false
}

// check if object is an integer
function isInteger(s, o, m)
{
	for (i=0, c=s.charAt(0); i<s.length; c=s.charAt(++i))
	{
		if (c == '+' || c == '-') { if (i!=0) return alertErr(o, m); }
		else if (!isDigit(c)) return alertErr(o, m)
	}
	return true;
}

function isNumber(s, o, m)
{
	for (i=0, c=s.charAt(0); i<s.length; c=s.charAt(++i))
	{
		if (!isDigit(c)) return alertErr(o, m);
	}
	return true;
}

// check if object is a float
function isFloat(s, o, m)
{
	var dot=0;
	for (i=0, c=s.charAt(0); i<s.length; c=s.charAt(++i))
	{
		if (c == '.') { if (dot) return alertErr(o, m); else dot=1; }
		else if (c == '+' || c == '-') { if (i!=0) return alertErr(o, m); }
		else if (!isDigit(c)) return alertErr(o, m)
	}
	return true
}

var _dim  = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

// check if date is leap year
function isLeap(yr) {
 return yr % 400 == 0 || (yr % 4 == 0 && yr % 100 != 0);
}

// return the day of week of a given day+month+year combo
function DayOfWeek(d,m,y)
{
 if (m < 3)
 {
	 m += 13;
	 y--;
 }
 else m++;
 return Math.floor((d + 26 * m / 10 + y + y / 4 - y / 100 + y / 400 + 5) % 7) + 1;
}

// returns the number of days in a given month and year
function daysInMonth(mm, yr)
{
 return _dim[mm-1] + (mm==2 ? isLeap(yr) : 0);
}

// set the number of days in a month
function setDaysInMonth(obj)
{
 var frm = obj.form;
 var name = obj.name.substring(3);
 var d = frm["DD_" + name];
 var m = frm["MM_" + name];
 var y = frm["YY_" + name];
 __setDaysInMonth(d,m,y);
}

// hard core function
function __setDaysInMonth(d,m,y)
{
 var mm = m.options[m.selectedIndex].value;
 var dd = d.options[d.selectedIndex].value;
 var yy = y.options[y.selectedIndex].value;

 var _dim = daysInMonth(mm, yy);
 if (dd > _dim) d.selectedIndex = _dim-1;

 while (d.options.length != _dim)
 {
	if (d.options.length > _dim)
	 d.options[d.options.length-1] = null;
	else
	 d.options[d.options.length] = new Option(d.options.length+1,d.options.length+1);
 }
}

// set today's date
function setToday(frm, name, mask)
{
 var t = new Date();
 var today = t.getFullYear()+"-"+a0(t.getMonth()+1)+"-"+a0(t.getDate())+" "+a0(t.getHours())+":"+a0(t.getMinutes())+":"+a0(t.getSeconds())+".0"
 setDate(frm, name, today, mask);
}

// add leading zero to single digits
function a0(v) {
 return v>9 ? v : "0"+v;
}

// set the date to a field in a form
function setDate(frm, name, date, mask) {
 if (!date) return;
 if (!mask) mask = "DD MM YY";
 var ss = mask.indexOf("SS") == -1 ? null : frm["SS_" + name];
 var hh = mask.indexOf("HH") == -1 ? null : frm["HH_" + name];
 var mi = mask.indexOf("MI") == -1 ? null : frm["MI_" + name];
 var d  = mask.indexOf("DD") == -1 ? null : frm["DD_" + name];
 var m  = mask.indexOf("MM") == -1 ? null : frm["MM_" + name];
 var y  = mask.indexOf("YY") == -1 ? null : frm["YY_" + name];
 var yy = y.options[0].value;
 // 2000-04-06 00:05:15.0
 if (y)  y.selectedIndex = date.substring(0,4) - yy;
 if (m)  m.selectedIndex = date.substring(5,7)-1;
 if (d)  d.selectedIndex = date.substring(8,10)-1;
 if (hh) hh.value = date.substring(11,13);
 if (mi) mi.value = date.substring(14,16);
 if (ss) ss.value = date.substring(17,19);
 if (d && m && y) __setDaysInMonth(d,m,y);
}

// convert string months to numeric month
function convertMonth2Num(mon) {
 var m = mon.toUpperCase();
 if (m == "JAN")
	return 0;
 else if (m == "FEB")
	return 1;
 else if (m == "MAR")
	return 2;
 else if (m == "APR")
	return 3;
 else if (m == "MAY")
	return 4;
 else if (m == "JUN")
	return 5;
 else if (m == "JUL")
	return 6;
 else if (m == "APR")
	return 7;
 else if (m == "SEP")
	return 8;
 else if (m == "OCT")
	return 9;
 else if (m == "NOV")
	return 10;
 else if (m == "DEC")
	return 11;
}

// generate a list of years and input to a select list
function generateYear(currentSel,cnt,backTo) {
 var theYear = new Date().getFullYear()-(backTo||0);
 if (!cnt) cnt = 10;
 for (var i = 0; i < cnt; i++)
	currentSel[i] = new Option(theYear + i, theYear + i);

 for (var i = 0; i < currentSel.options.length - 1; i++) {
	if (currentSel.options[i].value != "") {
	 currentSel.options[i].selected = true;
	 break;
	}
 }
}

// check if the string is a space
function isSpace(c)
{
	return c==' ' || c=='\t' || c=='\n' || c=='\r'
}

// trim spaces
function trim(s)
{
	j=s.length
	for (var i=j; --i>=0&&isSpace(s.charAt(i)); --j);
	for (var i=0; i<j&&isSpace(s.charAt(i)); i++);
	return s.substring(i, j)
}

function trimDecimalPlaces(n){
	var dotIndex = n.indexOf(".");
	if(dotIndex == -1) return n;

	return n.substring(0, dotIndex);
}

function convertHtmlSymbols(str) {
	if(str=="") return str;
	
	str = str.replace(/&/g, "&amp;");	// this has to be ahead the remaining to avoid over-replacing.
	str = str.replace(/\"/g, "&quot;");
	str = str.replace(/</g, "&lt;");
	str = str.replace(/>/g, "&gt;");
	return str;
}

function insertNewLines(str) {
	if(str=="") return str;
	
	str = str.replace(/\n/g, "<BR>\n");
	str = str.replace(/\r\n/g, "<BR>\r\n");
	return str;
}

function isPhoneNumber(str) {
	return !str.match(/[^0-9 \(\)\-+]/);	// returns false if finds any characters other than 0-9 ( ) - +
}

function disableIt(obj)
{
	obj.disabled = !(obj.disabled);
	var z = (obj.disabled) ? 'disabled' : 'enabled';
}

function extracheck(obj)
{
	return !obj.disabled;
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}
