/** 
 * A collection of client-side utility type functions
 */

// Make sure that HTML field is not blank 
function validField(field, errorMessage) {
	if (isblank(field.value)) {
    	alert(errorMessage);
		field.focus();
		field.blur();
		field.select();
		return false;
  	} else {
		return true;
	}
}

// A utility function that returns true if a string contains only
// whitespace characters or is null.
function isblank(s) {
    if (s == null) {
        return true;
    }
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

// Checks if the String contains a particular character
function containsChar(s, c) {
    if (s == null || c == null) {
        return false;
    }
    for (var i = 0; i < s.length; i++) {
        if (s.charAt(i) == c) {
            return true;
        }
    }
    return false;
}

// Generates a year is Y2K compliant
function y2k(number) {
	return (number < 1000) ? number + 1900 : number;
}

// Returns the current year 
function getCurrentYear(){
	mydate = new Date();
	myyear= y2k(mydate.getYear());
	year = parseInt(myyear);
	return year;
}

// Validate email address
function isEmail(str) {
    // 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 (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
    }
    var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
    var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
    return (!r1.test(str) && r2.test(str));
}

/**
 * Validates the time.
 * Checks if time is in HH:MM:SS AM/PM format.
 * The AM/PM are optional.
 */
function isValidTime(timeStr, secondsRequired) {

    var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

    var matchArray = timeStr.match(timePat);
    if (matchArray == null) {
        alert("Time is not in a valid format.");
        return false;
    }

    hour = matchArray[1];
    minute = matchArray[2];
    second = matchArray[4];
    ampm = matchArray[6];

    if (secondsRequired && second == "") {
        alert("You need to enter seconds values.");
        return false;
    }

    if (ampm=="") { ampm = null }

    if (hour < 0  || hour > 23) {
        alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
        return false;
    }

    //if (hour <= 12 && ampm == null) {
    //	if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
    //		alert("You must specify AM or PM.");
    //		return false;
    //      }
    //}

    //if  (hour > 12 && ampm != null) {
    //	alert("You can't specify AM or PM for military time.");
    //	return false;
    //}

    if (minute<0 || minute > 59) {
        alert ("Minute must be between 0 and 59.");
        return false;
    }

    if (second != null && (second < 0 || second > 59)) {
        alert ("Second must be between 0 and 59.");
        return false;
    }
    return true;
}

/**
 * Sorts the content of an paticular html table.
 */
function sortTable(tgtTable, onCol, hasHeading, asNumber, sortOrder, skipLastRow) {

    if (sortOrder == '0') {  // ascending
	descending = false;
    } else {
	descending = true;
    }

    tgtTable = document.getElementById(tgtTable);
    if(!onCol) onCol=0;
    if(skipLastRow) {
        skipLastRow = 1;
    } else {
        skipLastRow = 0;
    }
    var i=0;
    if(hasHeading) i=1;
    var nRows = tgtTable.rows.length;
    var t, ele1, ele2;
    for(; i < nRows-1-skipLastRow; i++) {
        t=i;
        for(var j=i+1; j < nRows-skipLastRow; j++) {
            ele1 = tgtTable.rows[j].cells[onCol].innerText;
            ele2 = tgtTable.rows[t].cells[onCol].innerText;
            if(asNumber) {
                ele1 = parseFloat(ele1);
                ele2 = parseFloat(ele2);
            }
            if(!descending  &&  ele1 < ele2) {
                t=j;
            } else if(descending  &&  ele1 > ele2) {
                t=j;
            }
        }
        tgtTable.tBodies[0].insertBefore(tgtTable.rows[t], tgtTable.rows[i]);
    }
}

// Set's the browser status bar message
function setStatusBar(msgStr) {
    self.status = msgStr;
}

// adjust the current date by N days
function addDayToCurrentDate(numOfDays) {
	var now = new Date();
	now.setTime(now.getTime() + numOfDays * 24 * 60 * 60 * 1000);
	return now;
}

// Checks if the passed String Text is a valid numeric value.
function isNumeric(sText, validStrList) {

	var validChars = "0123456789.";  // default valid numeric chars
	if (validStrList != null) {
		validChars = validStrList;	// use whatever was passed as valid chars
	}

	var isNumber = true;
	var tmpChar;
	for (i = 0; i < sText.length && isNumber == true; i++)  { 
		tmpChar = sText.charAt(i); 
		if (validChars.indexOf(tmpChar) == -1) {
			isNumber = false;
		}
	}
	return isNumber;
}

// Validates if the HTML Input object contains a valid year data.
// Sample usage -  onChange="isValidYear(this);"
function isValidYear(yearValue) {
	if (! isblank(yearValue) && isNumeric(yearValue) && (yearValue.length == 4) && (parseInt(yearValue) <= getCurrentYear())) {
		return true;
	} else {
		return false;
	}
}

// Sets the focus to the given field (Must be a valid html element of type = "input".) 
function setFieldFocus(field) {
	field.focus();
	field.blur();
	field.select();
}	

// Limits the file attachment allowed to filetypes provided in the extArray variable below.
function limitAttach(form, file) {
	allowSubmit = false;
	var extArray = new Array(".gif", ".jpg");  //file type to accept
	var fullFilename = file; 
	if (file == null || file == '') { 
		alert('Please select a file to upload.');
		return false;
	}	
	
	var ext = '';
	while (file.indexOf("\\") != -1) {
		file = file.slice(file.indexOf("\\") + 1);
		ext = file.slice(file.indexOf(".")).toLowerCase();
	}
	
	for (var i = 0; i < extArray.length; i++) {
		if (extArray[i] == ext) { 
			allowSubmit = true; 
			break; 
		}
	}
	
	if (allowSubmit) {		
		return true;
	} else {
		alert("Please only upload files that end in types:  " 
			+ (extArray.join("  ")) + "\nPlease select a new "
			+ "file to upload and submit again.");
		return false;
	}
}


/**
 * DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
 
// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

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++){   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}
