<!--
// // // // // // // // // // // // // //
// Filename: javascript\lib.js
// Author:	 Paco Bahamonde [paco@sharmannetworks.com]
// Purpose:	 A javascript functions library featuring
//			 date validation and general form validation.
//
// debug:	 alert('Welcome to the javascript library');

function roundOff(value, precision)
{
        if(eval(value) == 0){
			return '0.00';
		}

		value = "" + value; //convert value to string
        precision = parseInt(precision);

		//alert ('value: ' + value);
		//alert ('precision: ' + precision);

		if(value.substring(0,1) == '.'){
			value = '0' + value;
		}
		
		if( (value.substring(0,1) == '0') ){
			extra = '0';
			if(value.substring(2,3) == '0'){
				extra = extra + '0';
			}
		}else{
			extra = '';
		}
		
		var whole = extra + Math.round(value * Math.pow(10, precision));

		//alert ('whole: '+ whole);
		
		if(whole.substring(0,1) == '0' && whole.length > 3){
			whole = whole.substring(1,whole.length);
		}

        var decPoint = whole.length - precision;
		
		if(decPoint != 0)
        {
                result = whole.substring(0, decPoint);
                result += ".";
                result += whole.substring(decPoint, whole.length);
        }
        else
        {
                result = whole;
        }
        return result;
}

function isInt(value){
	//alert('function isInt(var)')
	if(value == parseInt(value)){
		return true;
	}else{
		return false;
	}
}

function isFloat(value){
	//alert('function isFloat(var)')
	if(value == parseFloat(value)){
		return true;
	}else{
		return false;
	}
}

function isBlank(s) {
  var len=s.length;
  var i;
  for(i=0;i<len;++i) {
    if(s.charAt(i)!=" ") return false
  }
  return true
}


function isEmail(fvalue){
	if (fvalue.indexOf("@") == -1 || fvalue.indexOf(".") == -1){
		return false;
	}else{
		return true;
	}
}

function isNum(passedVal){
	if(passedVal.indexOf(' ') != -1){
		return false;
	}
	return true;
}

function hasValidChars(passedVal){
	//passedVal is a string and not an array,
	//You cannot access each Char by passedVal[i]
	//Only by passedVal.charAt(i)
	for (i=0; i < passedVal.length; i++){
		//alert( passedVal.charAt(i) );
		if(/\w/.test( passedVal.charAt(i) ) == false){
			return false;
		}
	}
	return true;
}

function hasSpaces(passedVal){
	if(passedVal.indexOf(' ') == -1){
		return false;
	}else{
		return true;
	}
}

function isLowerCase(inputVal){
	if(inputVal != inputVal.toLowerCase()){
		return false;
	}else{
		return true;
	}
}
/*
fillTextBox(object1, object2){}

Assigns the value of one Input object to
another.
*/


function fillTextBox(fillvalue, obj2){
	obj2.value = fillvalue;
}

/*
function isNum(passedVal) {
	if(passedVal.length == 0){
		return false;
	}else{
		if(passedVal.indexOf(' ') == -1){
			//A '-1' means that it hasn't found it.
			for (i=0; i<passedVal.length; i++) {
				//alert(passedVal.charAt(i));
				total = 0;
				if(isInt(passedVal.charAt(i)) == false){
					total = 1; 
				}
			}
			alert('total: ' + total);
			if(total == 1){
				return false;
			}
		}else{
			//alert('got spaces');
			return false;
		}
	}

	return true;
}
*/

function validateForm(form, valArray1){

	//alert('function validateForm(form)');
	//The maximum length that an error message should be is given in the example below
	//'| 1. Please enter an integer value for the field \'testfield\'.'
	errorMsg = new Array();
	//Input objects that caused errors.
	errorObjs = new Array();
	
	for(i = 0; i < valArray1.length; i++){
	
	len = errorMsg.length;
	fvalue = form.elements[valArray1[i][0]].value;

		//alert(form.elements[valArray1[0][0]].value);
		if(( valArray1[i][3] == 'notnull' && isBlank(fvalue) ) || !isBlank(fvalue)){		
			
			aboveMaxLength = fvalue.length > valArray1[i][4];
			belowMinLength = fvalue.length < valArray1[i][5];
			
			if(valArray1[i][2] == 'varchar'){
				if(isBlank(fvalue) == true || belowMinLength){
				// You cannot do errorMsg[] = '..' in javascript, you must explicitly 
				// write the index down.
					errorMsg[len] = eval(errorMsg.length + 1) + '. Please enter a value for the field \'' + valArray1[i][1] + '\', \n    with a minimum length of \'' + valArray1[i][5] + '\'.';
					errorObjs[len] = valArray1[i][0];
				}
			}
			
			if(valArray1[i][2] == 'int'){
				if(isInt(fvalue) == false || aboveMaxLength){
				// You cannot do errorMsg[] = '..' in javascript, you must explicitly 
				// write the index down.
					errorMsg[len] = eval(errorMsg.length + 1) + '. Please enter an integer value for the field \'' + valArray1[i][1] + '\'.';
					errorObjs[len] = valArray1[i][0];
				}
			}

			if(valArray1[i][2] == 'float'){
				if(isFloat(fvalue) == false || aboveMaxLength){
				// You cannot do errorMsg[] = '..' in javascript, you must explicitly 
				// write the index down.
					errorMsg[len] = eval(errorMsg.length + 1) + '. Please enter a numerical value for the field \'' + valArray1[i][1] + '\'.';
					errorObjs[len] = valArray1[i][0];
				}
			}

			if(valArray1[i][2] == 'email'){
				if(isEmail(fvalue) == false || aboveMaxLength){
				// You cannot do errorMsg[] = '..' in javascript, you must explicitly 
				// write the index down.
					errorMsg[len] = eval(errorMsg.length + 1) + '. Please enter a valid email for the field \'' + valArray1[i][1] + '\'.';
					errorObjs[len] = valArray1[i][0];
				}
			}
			
			if(valArray1[i][2] == 'phone'){
				if(isBlank(fvalue) == true || aboveMaxLength){
					errorMsg[len] = eval(errorMsg.length + 1) + '. Please enter a valid Phone Number for the field \'' + valArray1[i][1] + '\'.';
					errorObjs[len] = valArray1[i][0];
				}
			}

			if(valArray1[i][2] == 'select'){
				if(fvalue == ''){
				// You cannot do errorMsg[] = '..' in javascript, you must explicitly 
				// write the index down.
					errorMsg[len] = eval(errorMsg.length + 1) + '. Please select an option for the field \'' + valArray1[i][1] + '\'.';
					errorObjs[len] = valArray1[i][0];
				}
			}
		}
	}
	
	if(errorMsg.length > 0){
		
		//alert(errorMsg.length);
		vReport = 'Form Validation Report\n\n';
		
		//Put the focus on the input object that caused the first error.
		form.elements[errorObjs[0]].focus();

		for(i=0; i < errorMsg.length; i++){
			vReport += errorMsg[i] + '\n\n';
		}

		vReport += 'Thankyou.\n\n';
		alert(vReport);
		return false;
	}else{
		return true;
	}
	
}

// Check Date functions
//
// for text fields (if day and year are select fields they
// are not needed.

function day_check(field)
{
if (field.value != "")
{
 //does it have a leading Zero if so it is ok.
 str = new String(field.value);
 
 if(str.indexOf('0') == 0){
	field_value = str.substring(1,str.length);
 }else{
	field_value = field.value;
 }
 
 var val = parseInt(field_value);
 var newval = ""+val;  
  if (newval != field_value) 
  {
    alert("You must give numeric value for the day!");
    field.focus();
    field.select();
   }
  else
  {
   if ((val <=0) || (val >= 32))
   {
    alert("Day " + val + " never exsists in a month!");
    field.focus();
    field.select();
   }
  }
}
}

function year_check(field)
{
if (field.value != "")
{
 var val = parseInt(field.value);
 var newval = ""+val;  
  if (newval != field.value) 
  {
    alert("You must give numeric value for the year!");
    field.focus();
    field.select();
   }
  else
  {
   if (val <=0)
   {
    alert("Have you ever met Jesus?");
    field.focus();
    field.select();
   }
  }
}
}

function checkDate(day,month,year,field_name)
{
  errorMsg = '';
 if (day.value == "")
 {
   //alert("Please fill in a day!");
   day.focus();
   //return false;
   errorMsg += 'Please fill in the \'' + field_name + '\' day,';
 }
  if (year.value == "")
 {
   //alert("Please fill in a year!");
   day.focus();
   
   //return false;
   errorMsg += 'Please fill in the \'' + field_name + '\' year,';
 }
  var var_date = new Date(year.value,month.value,day.value); 
  if (var_date.getDate() != day.value)
  {
    //alert("The month "+ month.options[month.selectedIndex].text +" has no " + day.value +"th day");
    //return false
	errorMsg += 'The month ...\'' + field_name + '\'';
  } 
 //return true;
	return errorMsg;
}

function assignCurrentDate(dayObj,monthObj,yearObj){
	var now_date  = new Date();
	dayObj.value  = now_date.getDate();
	monthObj.options[now_date.getMonth()].selected = true;
	yearObj.value = now_date.getYear();
}

function isInArray(arrayObj, val){
	
	if(arrayObj.length > 0){
		for(i = 0; i < arrayObj.length; i++){
			if (arrayObj[i] == val){
				return true;
			}
		}
	}
	return false;
}

/* function validHtmlTags(string htmlString, Array validTags)
 * Purpose: It is fed a string and checks if there are
 *			valid HTML tags (the tags in validTags Array). 
 *          Returns true if all <tags> are valid.
 */
function validHtmlTags(htmlString, validTags){
	
	var regexp = /<.[^(><.)]*>/ig;
	var input = htmlString;
	
	var tags = input.match(regexp);
	
	var invalidTags = new String();

	if(tags != null){
		//alert(tags.length);

		for(i=0; i < tags.length; i++){
			str = new String(tags[i]);
			//(\w*[^\s])(\s)(\w*)
			str = str.replace(/(<)(\/?)(\w*)(\s?)(.*)(>)/,'$3'); 
			
			if(validTags[str] != 1){
				invalidTags += tags[i];
				invalidTags += ', ';
			}
		}
	}
	if(invalidTags != ''){
		alert('You have entered the following INVALID html tags:\n\n' + invalidTags.substring(0,invalidTags.length - 2) + '\nPlease delete the above tags before you Save. Thankyou.\n\nThe Only VALID html tags for textarea\'s are:\n\n<b>, </b>, <i>, </i>, <em>, </em>, <strong>, </strong>,\n<a href="">, </a>, <u>, </u>, <ul>, </ul> , <ol>, </ol>, <li>, </li>.\n\nPlease note the above tags can also be entered in uppercase.');
		return false;
	}

	return true;
}

function validDocumentName(obj,docNameArray){
	
	errorMsg = new Array();
	
	len = errorMsg.length

	if( isLowerCase(obj.value) == false ||  hasSpaces(obj.value) == true || hasValidChars(obj.value) == false ){ 
		errorMsg[len]  = '\n         - Only Characters of type a-z, 0-9, _ (underscore)\n         - All lowercase characters\n         - No spaces';
	}
	
	
	if( isInArray(docNameArray, obj.value) == true ){
		errorMsg[len] = '\n         - Unique within its level. i.e. Two child pages of the same\n           parent cannot have the same document name.\n\nThere already exists a page in this level called \'' + obj.value + '\'.';
	}

	if(errorMsg.length > 0){
		errorReport = 'The \'Document Name\' field  must be:\n';

		for(i=0; i < errorMsg.length; i++){
			errorReport += errorMsg[i];
		}

		errorReport += '\n\nThankyou.';
		
		alert(errorReport);

		obj.focus();
	}
}

// Given a select box reference, returns the current value
function getSelectValue(selectBox) {
	return eval ('document.' + selectBox + '.options[document.' + selectBox + '.selectedIndex].value');
}

function check_date(form, date_name) {
	day     = getSelectValue(form + '.day_' + date_name);
	month   = getSelectValue(form + '.month_' + date_name);
	year    = getSelectValue(form + '.year_' + date_name);
	if (month == 2) {
		if (day == 29) {
			// if not leap year
			if (((year % 4) != 0) || ( ((year % 100) == 0) && ((year % 400) != 0))) {
				alert (year + " is not a leap year, there is no " + day + "th of Feburary (for "+date_name+").");
				eval('document.' + form + '.day_' + date_name + '.focus()');
				return 0;
			}
		}
		else if (day > 29) {
			alert ("There is no " + day + "th of Feburary (for "+date_name+").");
			eval('document.' + form + '.day_' + date_name + '.focus()');
			return 0;
		}
	}
	if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) {
		alert ("There is no " + day + "st of " + getSelectText(form + '.month_' + date_name) + " (for" +date_name+").");
		eval('document.' + form + '.day_' + date_name + '.focus()');
		return 0;
	}
	if(day<=0 || month<=0 || year<=0) {

		if(!(day==0 && month==0 && year==0)) {
			alert("This is not a valid date. Please select all dashes(-) if you wish to set a blank date.");
			if(day!=0) {
				eval('document.' + form + '.day_' + date_name + '.focus()');
			}
			else if(month!=0) {
				eval('document.' + form + '.month_' + date_name + '.focus()');
			}
			else {
				eval('document.' + form + '.year_' + date_name + '.focus()');
			}
			return 0;
		}
	}
	date_string = year + '-' + month + '-' + day;
	eval('document.' + form + '.' + date_name + '.value = date_string');
	return 1;
}

//-->