/** common function javascript by joanne **/
var numberChars = "0123456789";
var lowerChars = "abcdefghijklmnopqrstuvwxyz";
var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var otherChars = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/? ";


/** constant values  **/
//class Param{
	 var INPUT_ERR_COLOR = 0xFFDDDD; 
	 var EOL = "\n";
	 var PHONE_STR = "0123456789";	

	var WHOLE_NUM_STR = "0123456789";	
	//"0123456789 +-/()";
	/**
	var INPUT_ERR_COLOR 		= "#FFDDDD";
	**/
//};

 var FG_SAVE					= "FG_SAVE";
 var FG_PRINT				= "FG_PRINT";

//class MARKET_OPT {
	 var VAL_MKT_SEPARATOR 		= "|";
	 var VAL_MKT_WHOLESALE		= "mkt_wholesale"+VAL_MKT_SEPARATOR;
	 var VAL_MKT_GOVERNMENT		= "mkt_government"+VAL_MKT_SEPARATOR;
	 var VAL_MKT_EDUCATION		= "mkt_education"+VAL_MKT_SEPARATOR;
	 var VAL_MKT_RETAIL			= "mkt_retail"+VAL_MKT_SEPARATOR;
	 var VAL_MKT_CORPORATE		= "mkt_corporate"+VAL_MKT_SEPARATOR;
	 var VAL_MKT_OTHER_PREFIX	= "mkt_other:";
	/**
	var VAL_MKT_SEPARATOR 		= "|";
	var VAL_COMP_TYPE_SEPARATOR = VAL_MKT_SEPARATOR;
	var VAL_MKT_WHOLESALE		= "mkt_wholesale"+VAL_MKT_SEPARATOR;
	var VAL_MKT_GOVERNMENT		= "mkt_government"+VAL_MKT_SEPARATOR;
	var VAL_MKT_EDUCATION		= "mkt_education"+VAL_MKT_SEPARATOR;
	var VAL_MKT_RETAIL			= "mkt_retail"+VAL_MKT_SEPARATOR;
	var VAL_MKT_CORPORATE		= "mkt_corporate"+VAL_MKT_SEPARATOR;
	var VAL_MKT_OTHER_PREFIX	= "mkt_other:";
	**/
//}



//class COMPANY_OPT {
/** Change company types 
var VAL_COMP_COMPANY 		= "company";
var VAL_COMP_OTHER 		= "other";
**/
	 var VAL_COMP_TYPE_SEPARATOR = VAL_MKT_SEPARATOR;	
	 var VAL_COMP_COPRIVATE 	= "co_private";
	 var VAL_COMP_COPUBLIC		= "co_public";
	 var VAL_COMP_PARTNERSHIP	= "partnership";
	 var VAL_COMP_TRADER 		= "sole_trade";
	 var VAL_COMP_ARRAY			= new Array(
		VAL_COMP_COPRIVATE,VAL_COMP_COPUBLIC,VAL_COMP_PARTNERSHIP,VAL_COMP_TRADER);
//}							  



var ALERT_MSG_PHONE_NUMBER_INV
	= "Valid formats: 6 or 7 digits (e.g. 132610 or 1312888), 10 digits (e.g 1300361000, 1800800099, 0404144244 or 0292800880)"+EOL;
var ALERT_MSG_DIGIT_INV
 	= "Invalid format, must be a digit"+EOL;
var ALERT_MSG_DATE_INV
	= "Dates must be entered as dd-mm-yyyy"+EOL;
var ALERT_MSG_ABN_INV
	= "ABN must be a minimum of 11 digits without spaces"+EOL;	
var ALERT_MSG_ACN_INV
	= "ACN must be a minimum of 9 digits without spaces"+EOL;	
var ALERT_MSG_PASSWD_INV
 	= "Your password must be a minimum of 4 characters (12 maximum)"+EOL;

var ALERT_MSG_NOT_NULL
	= "cannot be blank"+EOL;
var ALERT_MSG_TOCOMPANY_NOT_NULL 
	="Please specify your type of your Company"+EOL;
var ALERT_MSG_YOUR_MKT_CHKED_OTHERS_INV 
	="If you checked others for your market, please specify it in the textbox."+EOL;
var ALERT_MSG_TRADE_REF_FIRST_NULL
	="Please fill in all the boxes for the 1st Trade Reference"+EOL;
var ALERT_MSG_TRADE_REF_SECOND_NULL
	="Please fill in all the boxes for the 2nd Trade Reference"+EOL;
var ALERT_MSG_TRADE_REF_THIRD_NULL
	="Please fill in all the boxes for the 3rd Trade Reference"+EOL;
var ALERT_MSG_TRADE_REF_FIRST_ANULL
	="Please fill in at least one Trade Reference"+EOL;
var ALERT_MSG_COMPANY_ID_NULL
	="Please contact the adminstrator with the quote 'co_id is null'"+EOL;
var ALERT_MSG_CO_LVL_NULL
	="Please contact the adminstrator with the quote 'co_level is null'"+EOL;
var ALERT_MSG_ROLE_ID_NULL
	="Please contact the adminstrator with the quote 'rolde_id is null'"+EOL;
var ALERT_MSG_USER_NULL
	="Please contact the adminstrator with the quote 'rolde_id is null'"+EOL;
var MSG_RECORD_NOT_FOUND
	="Record Not Found";
var undefined;



/** common functions **/
function isUndefined(property) {
  return (typeof property == 'undefined');
}

// Array Extensions  v1.0.6
// Array.concat() - Join two arrays
if (isUndefined(Array.prototype.concat) == true) {
  Array.prototype.concat = function (secondArray) {
     var firstArray = this.copy();
     for (var i = 0; i < secondArray.length; i++) {
        firstArray[firstArray.length] = secondArray[i];
     }
     return firstArray;
  };
}

// Array.copy() - Copy an array
if (isUndefined(Array.prototype.copy) == true) {
  Array.prototype.copy = function() {
     var copy = new Array();
     for (var i = 0; i < this.length; i++) {
        copy[i] = this[i].clone();
     }
     return copy;
  };
}

// Array.pop() - Remove the last element of an array and return it
if (isUndefined(Array.prototype.pop) == true) {
  Array.prototype.pop = function() {
     var lastItem = undefined;
    if ( this.length > 0 ) {
        lastItem = this[this.length - 1];
        this.length--;
    }
    return lastItem;
  };
}

// Array.push() - Add an element to the end of an array
if (isUndefined(Array.prototype.push) == true) {
  Array.prototype.push = function() {
     var currentLength = this.length;
     for (var i = 0; i < arguments.length; i++) {
        this[currentLength + i] = arguments[i];
     }
     return this.length;
  };
}

// Array.shift() - Remove the first element of an array and return it
if (isUndefined(Array.prototype.shift) == true) {
  Array.prototype.shift = function() {
     var firstItem = this[0];
     for (var i = 0; i < this.length - 1; i++) {
        this[i] = this[i + 1];
     }
     this.length--;
     return firstItem;
  };
}

// Array.slice() - Copy several elements of an array and return them
if (isUndefined(Array.prototype.slice) == true) {
  Array.prototype.slice = function(start, end) {
     var temp;
     
     if (end == null || end == '') end = this.length;
     
     // negative arguments measure from the end of the array
     else if (end < 0) end = this.length + end;
     if (start < 0) start = this.length + start;
     
     // swap limits if they are backwards
     if (end < start) {
        temp  = end;
        end   = start;
        start = temp;
     }
     
     // copy elements from array to a new array and return the new array
     var newArray = new Array();
     for (var i = 0; i < end - start; i++) {
        newArray[i] = this[start + i];
     }
     return newArray;
  };
}

// Array.splice() - Splice out and / or replace several elements of an array and return any deleted elements
if (isUndefined(Array.prototype.splice) == true) {
  Array.prototype.splice = function(start, deleteCount) {
     if (deleteCount == null || deleteCount == '') deleteCount = this.length - start;
     
     // create a temporary copy of the array
     var tempArray = this.copy();
     
     // Copy new elements into array (over-writing old entries)
     for (var i = start; i < start + arguments.length - 2; i++) {
        this[i] = arguments[i - start + 2];
     }
     
     // Copy old entries after the end of the splice back into array and return
     for (var i = start + arguments.length - 2; i < this.length - deleteCount + arguments.length - 2; i++) {
        this[i] = tempArray[i + deleteCount - arguments.length + 2];
     }
     this.length = this.length - deleteCount + (arguments.length - 2);
     return tempArray.slice(start, start + deleteCount);
  };
}

// Array.unshift - Add an element to the beginning of an array
if (isUndefined(Array.prototype.unshift) == true) {
  Array.prototype.unshift = function(the_item) {
     for (loop = this.length-1 ; loop >= 0; loop--) {
        this[loop+1] = this[loop];
     }
     this[0] = the_item;
     return this.length;
  };
}

function isNotFilled(a)
{
	return (isNull(a) || isEmptyString(a));
}

function isFilled(a)
{
	return (!isNotFilled(a));	
}
function apostraphesEncode(mystr){
	mystr = mystr.split("'").join("\'");
	return mystr;
}
function apostraphesDecode(mystr){
	mystr = mystr.split("\'").join("'");
	return mystr;
}
function isEmptyString(a)
{
		return trim(a) == "";
}

function isAlien(a) 
{
   return isObject(a) && typeof a.constructor != 'function';
}

function isArray(a) 
{
    return isObject(a) && a.constructor == Array;
}

function isBoolean(a) 
{
    return typeof a == 'boolean';
}

function isEmpty(o) 
{
    var i, v;
    if (isObject(o)) 
    {
        for (i in o) 
        {
            v = o[i];
            if (isUndefined(v) && isFunction(v)) 
            {
                return false;
            }
        }
    }
    return true;
}

function isFunction(a) 
{
    return typeof a == 'function';
}

function isNull(a) 
{
    return typeof a == 'object' && !a;
}

function isNumber(a) 
{
    return typeof a == 'number' && isFinite(a);
}

function isObject(a) 
{
    return (a && typeof a == 'object') || isFunction(a);
}

function isString(a) 
{
    return typeof a == 'string';
}

function isUndefined(a) 
{
    return typeof a == 'undefined';
} 

function isInt(a){
	var temp = parseInt(a, 10);
	return !isNaN(temp);
}

function isWholeNumber(s)
{   
	
	if (isNull(s) || s=="")
	{ 
		return false;
	}
   for (i = 0; i < s.length; i++)
   {   
        // Check that current character is number.
        if (WHOLE_NUM_STR.indexOf(s.charAt(i)) == -1)
        {
        	return false;
        }
    }
    // All characters are numbers or valid char.
    return true;
}

/*

String.method('entityify', function () {
    return this.replace(/&/g, "&amp;").replace(/</g,
        "&lt;").replace(/>/g, "&gt;");
});
String.method('quote', (isThisNetscape4) ? function () {
    return '"' + this.replace(/(["\\])/g, function (s) {
        return '\\' + s;
    }) + '"';
} : function () {
    return '"' + this.replace(/(["\\])/g, '\\$1') + '"';
});
String.method('supplant', function (o) {
    var i, j, s = this, v;
    for (;;) {
        i = s.lastIndexOf('{');
        if (i < 0) {
            break;
        }
        j = s.indexOf('}', i);
        if (i + 1 >= j) {
            break;
        }
        v = o[s.substring(i + 1, j)];
        if (!isString(v) && !isNumber(v)) {
            break;
        }
        s = s.substring(0, i) + v + s.substring(j + 1);
    }
    return s;
});
String.method('trim', function () {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
}); 

*/

function emailCheck (emailStr) 
{
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	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);
	var msg = "";
	
	if (matchArray==null) 
	{
		msg+=("Email address seems incorrect (check @ and .'s)");
		return msg;
		//return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) 
	{
		if (user.charCodeAt(i)>127) 
		{
			msg+=("Ths username contains invalid characters.");
			return msg;
			//return false;
		}
	}
	for (i=0; i<domain.length; i++) 
	{
		if (domain.charCodeAt(i)>127) 
		{
			msg+=("Ths domain name contains invalid characters.");
			return msg;
			//return false;
		}
	}
	if (user.match(userPat)==null) 
	{
		msg+=("The username doesn't seem to be valid.");
		return msg;
		//return false;
	}

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) 
	{
		for (var i=1;i<=4;i++) 
		{
			if (IPArray[i]>255) 
			{
				msg+=("Destination IP address is invalid!");
				return msg;
				//return false;
			}
		}
		return msg;
		//return true;
	}

	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) 
	{
		if (domArr[i].search(atomPat)==-1) 
		{
			msg+=("The domain name does not seem to be valid.");
			return msg;
			//return false;
   		}
	}
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) 
	{
		msg+=("The address must end in a well-known domain or two letter " + "country.");
		return msg;
		//return false;
	}


	if (len<2) 
	{
		msg+=("This address is missing a hostname!");
		return msg;
		//return msg;
	}

	return msg;
}

function trim(inputString) 
{
	
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   
	if (typeof inputString != "string") 
	{
		return inputString; 
	}
	
	var retValue = inputString;
	var ch = retValue.substring(0, 1);
	
	while (ch == " ") { // Check for spaces at the beginning of the string
		retValue = retValue.substring(1, retValue.length);
		ch = retValue.substring(0, 1);
	}
	
	ch = retValue.substring(retValue.length-1, retValue.length);
	
	while (ch == " ") 
	{ // Check for spaces at the end of the string
		retValue = retValue.substring(0, retValue.length-1);
		ch = retValue.substring(retValue.length-1, retValue.length);
   	}
   	
   	while (retValue.indexOf("  ") != -1) 
   	{ // Note that there are two spaces in the string - look for multiple spaces within the string
		retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   	}
   	
	return retValue; // Return the trimmed string back to the user
} 
// Ends the "trim" function


function dateValid(dateValue) {
	
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	strDate = dateValue;
			
	if (strDate.length < 1) 
	{
		
		return true;
	}
	
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) 
	{
		
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) 
		{
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) 
			{
				err = 1;
				return false;
			}else {
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];

			}
			
			booFound = true;
			
		}
	}
	if (booFound == false) 
	{
		
		
		err = 12;
		return false
		
//		if (strDate.length>5) 
//		{
//			strDay = strDate.substr(0, 2);
//			strMonth = strDate.substr(2, 2);
//			strYear = strDate.substr(4);
//		}
		
	}
	//Adjustment for short years entered
	if (strYear.length != 4) 
	{
		err = 11;
		return false;
		
	}
	
	//strTemp = strDay;
	//strDay = strMonth;
	//strMonth = strTemp;
	
	intday = parseInt(strDay, 10);
	
	if (isNaN(intday)) 
	{
		err = 2;
		return false;
	}
	
	intMonth = parseInt(strMonth, 10);
	
	if (isNaN(intMonth)) 
	{
		err = 3;
		return false;
	}
	
	intYear = parseInt(strYear, 10);
	
	if (isNaN(intYear)) 
	{
		err = 4;
		return false;
	}
	
	if (intMonth>12 || intMonth<1) 
	{
		err = 5;
		return false;
	}
	
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 
		|| intMonth == 7 || intMonth == 8 || intMonth == 10 
		|| intMonth == 12) && (intday > 31 || intday < 1)) 
	{
		err = 6;
		return false;
	}
	else if ((intMonth == 4 || intMonth == 6 || intMonth == 9 
		|| intMonth == 11) && (intday > 30 
		|| intday < 1)) 
	{
		err = 7;
		return false;
	}
	else if (intMonth == 2) 
	{
		if (intday < 1) 
		{
			err = 8;
			return false;
		}
		if (leapYear(intYear) == true) 
		{
			if (intday > 29) 
			{
				err = 9;
				return false;
			}
		}
		else 
		{
			if (intday > 28) 
			{
				err = 10;
				return false;
				
			}
			
		}
		
	}
	//alert(err);
	return true;
}

function leapYear(intYear) 
{
	if (intYear % 100 == 0) 
	{
		if (intYear % 400 == 0) 
		{
			return true; 
		}
	}
	else 
	{
		if ((intYear % 4) == 0) 
		{ 
			return true; 
		}
	}
	return false;
}


function isIntO(obj, isMandatory){
	var s = obj.value;
	if (isMandatory  && isNotFilled(s+"")){
		obj.style.backgroundColor=INPUT_ERR_COLOR;
		return false;
	}else if( !isMandatory && isNotFilled(s+"")){
		return true;
	}
	if (!isInt(s)){
		obj.style.backgroundColor=INPUT_ERR_COLOR;
		return false;
	}
	return true;

}
function isDigit(obj, isMandatory){
	if (isMandatory  && isNotFilled(s)){
		obj.style.backgroundColor=INPUT_ERR_COLOR;
		return false;
	}else if( !isMandatory && isNotFilled(s)){
		return true;
	}
	var s = obj.value;
	for (i = 0; i <s.length; i++){
		if (numberChars.indexOf(s.charAt(i)) <0){
			obj.style.backgroundColor=INPUT_ERR_COLOR;
			return false;
		}
	}
	return true;
}
function isDate(obj,isMandatory){
	var s = obj.value;
	if (isMandatory  && isNotFilled(s)){
		obj.style.backgroundColor=INPUT_ERR_COLOR;
		return false;
	}else if( !isMandatory && isNotFilled(s)){
		return true;
	}
	if (!dateValid(s)){
		obj.style.backgroundColor=INPUT_ERR_COLOR;
		return false;
	}
	return true;
}
function isEmailO(obj, isMandatory){
	var s = obj.value;
	if (isMandatory  && isNotFilled(s)){
		obj.style.backgroundColor=INPUT_ERR_COLOR;
		return false;
	}else if( !isMandatory && isNotFilled(s)){
		return true;
	}
	if (trim(emailCheck(s)) != ""){
		obj.style.backgroundColor=INPUT_ERR_COLOR;
		alert(emailCheck(s));
		return false;
	}
	return true;
}
		
function isPhoneNumber(s)
{   
	if (isNull(s)){ 
		return false;
	}
	var i;
	var numLength = s.length;
	var is13Number = (s.substring(0,2) == "13");
	
	if (is13Number && !(numLength==6 || numLength==7|| numLength==10)){
		return false;
	}else if((!is13Number) && numLength != 10){
		return false;
	}
	
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        if (PHONE_STR.indexOf(s.charAt(i)) == -1)
        {
        	return false;
        }
    }
    // All characters are numbers or valid char.
    return true;
}

function isPhoneNumberO(obj, isMandatory){
	var s = obj.value + "";
	//alert("isP#:"+s);
	if (isMandatory  && isNotFilled(s)){
		obj.style.backgroundColor=INPUT_ERR_COLOR;
		return false;
	}else if( !isMandatory && isNotFilled(s)){
		return true;
	}
	
	if (!isPhoneNumber(s)){
		obj.style.backgroundColor=INPUT_ERR_COLOR;
		return false;
	}
	return true;
}

function constructErrorMsg(field, msg, obj){
	obj.style.backgroundColor=INPUT_ERR_COLOR;
	return field+": "+msg;	
}


/** Password generator **/
function getRandomNum(lbound, ubound) {
	return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
}

function getRandomChar(number, lower, upper, other, extra) {
	var charSet = extra;
	if (number == true)	charSet += numberChars;
	if (lower == true)	charSet += lowerChars;
	if (upper == true)	charSet += upperChars;
	if (other == true)	charSet += otherChars;
	return charSet.charAt(getRandomNum(0, charSet.length));
}

function getPassword(length, extraChars, firstNumber, firstLower, firstUpper, 
			firstOther, latterNumber, latterLower, latterUpper, latterOther) 
{
	var rc = "";
	if (length > 0)
	{
		rc = rc + getRandomChar(firstNumber, firstLower, 
								firstUpper, firstOther, extraChars);
	}
	for (var idx = 1; idx < length; ++idx) 
	{
		rc = rc + getRandomChar(latterNumber, latterLower, latterUpper, latterOther, 
		extraChars);
	}
	return rc;
}
/** password generator end **/


function poptastic(url,wname)
{
	var newwindow;
	newwindow=window.open(url,wname,'height=400,width=600,toolbar=no,menubar=no,location=no');
	if (window.focus) 
	{
		newwindow.focus();
	}
}

// super init() for child to overwrite
function init(){}