/* a function which checks whether a date is valid */
function isDate(dtStr, strName, strID){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)

	var objField = document.getElementById(strID);

	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 : dd/mm/yyyy");
		objField.focus();
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month for the " + strName + " field");
		objField.focus();
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day for the " + strName + " field");
		objField.focus();
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear+ " for the " + strName + " field");
		objField.focus();
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date for the " + strName + " field");
		objField.focus();
		return false;
	}
	return true;
}
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
}





/* a function used to check whether a form field has a value */
function isEmpty(objField, strMsg) {
	if (objField) {
		if (objField.tagName == 'INPUT' || objField.tagName == 'TEXTAREA') {
			if (objField.value == '') {
				if (strMsg.length > 0) {
					alert(strMsg);
					if (objField.style.display == 'none') {
						showhide(objField.id);
					}
					objField.focus();
				}
				return true;
			}
		}
		else if (objField.tagName == 'SELECT') {
			if (objField.options[objField.selectedIndex].value == '') {
				if (strMsg.length > 0) {
					alert(strMsg);
					objField.focus();
				}
				return true;
			}
		}
		else {
			alert("Tag type " + objField.tagName + " is not yet supported by the isEmpty function");
			return false;
		}
	}
	return false;
}

/* a function used to check whether a form field contains a numeric value */
function isNumericField(objField, blnAllowCommas, strMsg) {
  var blnIsNumeric = true;
	var strChar;
	var i;

	if (!isNumeric(objField.value, blnAllowCommas)) {
		blnIsNumeric = false;
		if (strMsg.length > 0) {
			alert(strMsg);
			objField.focus();
		}
	}
	return blnIsNumeric;
}

/* a function used to check whether a string contains valid numeric data */
function isNumeric(strText, blnAllowCommas) {
  var blnIsNumeric = true;
	var strChar;
	var i;

	if (blnAllowCommas) {
		strText = stripCommas(strText);
	}

	for (i=0;i<strText.length; i++) {
		strChar = strText.charAt(i);
		if ("0123456789.%".indexOf(strChar) == -1) {
			blnIsNumeric = false;
			break;
		}
	}
	return blnIsNumeric;
}

/* a function used to remove commas from a string */
function stripCommas(strText) {
	var regExp = new RegExp(',', 'gi');
	return strText.replace(regExp, '');
}

/* formats a given input field with commas and decimal places */
m_tmp = true;
function formatNumericField(objField, blnDP) {
	if (isNumeric(objField.value, true)) {
		objField.value = formatNumber(objField.value, blnDP);
	}
	else {
		alert('Field must be numeric');
		objField.focus();
	}
}

/* formats a given input field with commas and decimal places before appending % */
function formatPercentField(objField, blnDP) {
	var strValue = objField.value.replace(new RegExp('%', 'gi'), '');

	if (strValue.length == 0) { // if zero length then field may contain just %, set to empty
		objField.value = '';
	}
	else {
		if (isNumeric(strValue, true)) {
			objField.value = formatNumber(strValue, blnDP) + '%';
		}
		else {
			alert('Field must be numeric');
			objField.focus();
		}
	}
}

/* formats a number with the specified decimal places */
function formatNumber(strDecimal, blnDP) {
	var i;
	var intDigitCount;
	var intStartPos;
	var strDP;
	var strInteger;

	//turn the decimal into a string
	strDecimal += '';

	strDecimal = stripCommas(strDecimal);

	// if there is a decimal point get the decimal places as a string
	intStartPos = strDecimal.indexOf('.');
	if(intStartPos > -1) {
		strInteger = strDecimal.substr(0,intStartPos);

		strDP = strDecimal.substring(intStartPos);

		// rounding the number helps eradicate strange values.  round to 3dp.
		strDP = Math.round(strDP*100)/100 + '000';

		// we now have decimal places as 0.xx00 unless DPs are zeroes when we have 000 or if DPs have been rounded to 1 when we have 100
		if (strDP.charAt(1) != '.') {
			// if we rounded up to zeroes, add one to the integer
			if (strDP.charAt(0) == '1') {
				strInteger = (parseInt(strInteger) + 1) + '';
			}

			// set decimal places to zeros
			strDP = '0.00';
		}

		strDP = strDP.substr(1, 3);
	}
	else { // if there is no decimal place start from the last character
		strDP = '.00';
		strInteger = strDecimal;
		intStartPos = strDecimal.length;
	}

	//move backwards along the string counting 3 digits and adding a comma
	intDigitCount = 0;
	for (i=intStartPos;i>0;i--) {
		if (intDigitCount == 3) {
			//add a comma
			strInteger = strInteger.substr(0, i) + ',' + strInteger.substr(i);
			intDigitCount = 0;
		}
		intDigitCount ++;
	}

	if (blnDP) {
		return strInteger + strDP;
	}
	return strInteger;
}

/* formats a commission rate based on its type */
function formatCommission(field, commissionFormatID) {
	if (commissionFormatID == 1) { //percentage
		formatPercentField(field, true);
	}
	else if(commissionFormatID == 2) { //currency
		var regExp = new RegExp('\u00A3', 'gi'); //replace the £
		field.value = field.value.replace(regExp, "");
		formatNumericField(field, true);
		if (isNumeric(field.value)) {
			field.value = "\u00A3" + field.value;
		}
	}
	else { //text
		//leave alone
	}
}

function validCommissionRate(field, commissionFormatID) {
	var val = field.value;

	if (commissionFormatID == 3) {//free text
		//valid
		return true;
	}
	else {
		//replace any %
		var regExp = new RegExp('%', 'gi');
		val = val.replace(regExp, "");

		//replace any £
		var regExp = new RegExp('\u00A3', 'gi');
		val = val.replace(regExp, "");

		//is the remaining value numeric?
		if (!isNumeric(val)) {
			field.focus();
			alert("Please enter a valid commission rate");
			return false;
		}
	}
	return true;
}

/* hide an element based on it's current display attribute */
function hide(strID) {
	var el;
	if (typeof strID == "string" || typeof strID == "number") {
		el = document.getElementById(strID);
	}
	else {
		//assume the parameter was the element itself
		el = strID;
	}
	el.style.display = "none";
}

/* show an element based on it's current display attribute */
function show(strID) {
	var el;
	if (typeof strID == "string" || typeof strID == "number") {
		el = document.getElementById(strID);
	}
	else {
		//assume the parameter was the element itself
		el = strID;
	}
	el.style.display = "block";
}

/* hide or show an element based on it's current display attribute */
function hideShow(strID) {
	var el = document.getElementById(strID);
	var s = document.getElementById(strID).style;

	//hide or show
	s.display = (s.display == "none") ? "block" : "none";
}

/* hide or show a tr element based on it's current display attribute */
function hideShowTR(strID) {
	var el = document.getElementById(strID);
	var s = document.getElementById(strID).style;
	
	s.display = (s.display == "none") ? "" : "none";
}


/* add an event handler in a cross browser way */
function addEventHandler(element, eventName, functionPointer) {
	//we use lowercase event names
	eventName = eventName.toLowerCase();

	//remove the on... prefix
	if (eventName.indexOf("on") > -1) {
		eventName = eventName.substring(2);
	}

	//the (un)load events belong to the window, not the body
	if (element == document.body && (eventName == "load" || eventName == "unload")) {
		element = window;
	}

/*
	if (eval) {
		if (element == document.body) {
			eval("document.body.on" + eventName + " = " + functionPointer);
		} else if (element == window) {
			eval("window.on" + eventName + " = " + functionPointer);
		} else {
			eval("document.getElementById(\"" + element.getAttribute("id") + "\").on" + eventName + " = " + functionPointer);
		}
	}
	else { // we want to use this but there are issues regarding return values in netscape and mozilla
*/
		//add the event listener
		if (element.addEventListener) {	//use addEventListener if possible
			element.addEventListener(eventName, functionPointer, false);
		}
		else if (element.attachEvent) { //try the ie attachEvent method
			element.attachEvent("on" + eventName, functionPointer);
		}
//	}
}

/* Add toCamelCase to the String object */
String.prototype.toCamelCase = function toCamelCase() {
	if (this.indexOf("-") == -1) {
		return this;
	}
	else {
		var strParts = this.split("-");
		var strCamel = "";
		var intParts = strParts.length;
		for (var i=0; i<intParts; i++) {
	    var strPart = strParts[i];
	    strCamel += (i==0) ? strPart : strPart.charAt(0).toUpperCase() + strPart.substring(1);
		}
	}
	return strCamel;
}

String.prototype.toPascalCase = function toPascalCase() {
	var strPascal = this.toCamelCase();
	return strPascal.charAt(0).toUpperCase() + strPascal.substring(1);
}

/* get the current style attribute of an element */
function getStyleAttribute(el, property) {
	if (el.currentStyle) {
		value = el.currentStyle[property.toCamelCase()];
	}
	else if(document.defaultView) {
		value = window.getComputedStyle(el, "").getPropertyValue(property.toCamelCase());
	}
	return value;
}

/* set the current style attribute of an element */
function setStyleAttribute(el, property, value) {
	el.style[property.toCamelCase()] = value;
	return value;
}