/**
 * DHTML date validation script for dd/mm/yyyy. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1901;
var maxYear=2037;

//see initialzetimer
var secs
var timerID = null
var timerRunning = false
var delay = 1000


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 chkNumeric(myField){
	if (!isNumeric(myField.value)){
		alert("This is not a number")
		myField.focus()
		myField.select()
		return false
	}
	return true
}
function chkInteger(myField){
	
	if (!isInteger(myField.value)){
		alert("This is not a whole number")
		myField.focus()
		myField.select()
		return false
	}
	return true
}
	
function isNumeric(s){
	var i;
	var dot = 0;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number or a dot, only 1 dot allowed.
        var c = s.charAt(i);
		if (c == "."){
			dot++
			if (dot > 1){
				return false
			}
		} else {
			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 isValidStr(myField,shorter) {
	var string = myField.value
	var allowed = ' 0123456789.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!&*()[]?-@'; // define valid characters
	if (shorter == 'Y'){
		allowed = ' 0123456789.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\\_-:';   // take out things dont want in things like file names
	}
	if (shorter == 'P'){
		allowed = ' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';   // take out things dont want in things like user names and passwords
	}
    for (var i = 0; i < string.length; i++) {
		if (allowed.indexOf(string.charAt(i)) == -1) {
	   		alert("You have entered a character into the text which is not allowed. (" + string.charAt(i) + ").")
			myField.focus()
        	return false 
		}
	}
	return true
}
function findCharInString(s,char){
	var i;
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (char.indexOf(c) != -1) return true;
    }
    return false
}

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
}

function isDate(dtStr,myField){

	if (dtStr.substring(2,3) == "-") {
		dtCh = "-"
	} else {
		dtCh = "/"
		dateBits = dtStr.split('/')
		if (dateBits.length == 3){
			dtStr = String(dateBits[0]) + '-' + String(dateBits[1]) + '-' + String(dateBits[2])
			dtCh = '-'
//			alert("date " + dtStr)
		}
	}
	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)
	if (strYear.length == 2){
		dateBits = dtStr.split('-')
		if (parseInt(strYear,10) < 10){
			strYear = String(parseInt(2000) + parseInt(strYear,10))
		} else {
			strYear = String(parseInt(1900) + parseInt(strYear,10))
		}
		dtStr = String(dateBits[0]) + '-' + String(dateBits[1]) + '-' + strYear
//		alert("date " + dtStr)
	}
	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 or dd-mm-yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Year entered was - " + year + ". Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return dtStr
}

function ValidateDate(myField,Blank){ <!--   Blank - means a null date is allowed //-->
	var dt=myField
	var BlankOK=Blank
	if (dt.value.length == 6){
		var dStr = dt.value.toString();
		var dt1 = dStr.substring(0,2).toString() + "-" + dStr.substring(2,4).toString() + "-" + dStr.substring(4).toString();
		dt.value = dt1;
	}
	if (dt.value == "00/00/0000" || dt.value == "00-00-0000" || dt.value == "000000" || dt.value == "") {
		if (BlankOK == "Y" ){
			return true
		} else {
			alert("You cannot enter a blank date")
			dt.focus()
			return false
		}
	}
	var newDate = isDate(dt.value,myField)
	if (newDate==false){
		dt.focus()
		return false
	} else {
		myField.value = newDate
	}
    return true
 }


function validateTime(myField,blank){ // works on 24 hr clock passes back 4 digits with a : in between
	var tm = myField
	var blankOK=blank
	if (blankOK == "Y" && (tm.value == "00:00" || tm.value == "")) {
		return true
	}		
	var tmArr = myField.value.split(":")
	var noArr = tmArr.length
	var tstr = ""
	for (i=0;i<noArr;i++){
		tstr = tstr + tmArr[i]
	}
	if (!isInteger(tstr)|| tstr.length != 4 ){
		alert("You must enter 4 digits or 4 digits with a ':' in the middle, using a 24 hour clock")
		tm.focus()
		tm.select()
		return false
	}
	var hrs = tstr.substring(0,2)
	var mins = tstr.substring(2)
	if (hrs < 0 || hrs > 23){
		alert("Hours must be between 0 and 23")
		tm.focus()
		return false
	}
	if (mins < 0 || mins > 59){
		alert("Minutes must be between 0 and 59")
		tm.focus()
		return false
	}
	tm.value = hrs + ":" + mins
	return true
}
	
function timeToMins(tm) { // assumes correctly formatted time 00:00
	var tmArr = tm.split(":")
	var tstr = tmArr[0] + tmArr[1]
	var totMins = (parseInt(tstr.substring(0,2),10) * 60) + parseInt(tstr.substring(2),10) // makes sure its an integer number
	return totMins;
}
	
function minsToTime(mins) { // calculates a time from minutes
	var htime = parseInt((mins/60),10)
	mtime = String(mins - (htime * 60))
	if (mtime.length < 2){
		mtime = "0" + mtime
	}
	htime = String(htime)
	if (htime.length < 2){
		htime = "0" + htime
	}
	tmStr = htime + ":" + mtime
	return tmStr;
}


function calcDuration(stfield,endfield,durfield,entno){ // stfield is the start time, endfield is the end time field and durfield is the duration field. entno shows which of these is being entered this time


	var flds = 0
	var sttime = stfield.value
	var endtime = endfield.value
	var dur = durfield.value
	if (!isInteger(dur)){
		alert("You must enter a number as the duration")
		durfield.focus()
		return false
	}
	if (dur > 0){
		flds++
	}
	st = false
	if (sttime != "" ){
		flds++
		st = true
	}
	if (endtime != ""){
		flds++
	}
	if  (flds < 2){  //  have to have at least 2 fields
		return true
	}
	if (entno == 3 ||( entno == 2 && !st)){ // the duration field, or we have the duration and the end but no start
		if (st){ // there is a start time so work from there
		
			if (timeToMins(sttime) +  parseInt(durfield.value,10) > 1439) {
				alert("This duration takes the end time into the next day - it must be on the same day. If necessary, make a new entry for the next day")
				durfield.focus()
				return false
			}
			var endtime = minsToTime(timeToMins(sttime) + parseInt(durfield.value,10))
			endfield.value = endtime
		} else { // there must be an end time 
			if (timeToMins(endtime) - parseInt(durfield.value,10) < 0) {
				alert("This duration takes the start time into the previous day - it must be on the same day. If necessary, make a new entry for the previous day")
				durfield.focus()
				return false
			}
			var sttime = minsToTime(timeToMins(endtime) - parseInt(durfield.value,10))
			stfield.value = sttime
		}
	} else { // one of the times was entered so work out the duration
		tm1 = timeToMins(sttime)
		tm2 = timeToMins(endtime)
		dur = tm2 - tm1
		if (dur < 0){
			alert("You have entered a negative time difference")
			endfield.focus()
			return false
		}
		durfield.value = dur
	}
	return true
}

function roundNumber(theValue,rlength) {

	var numberField = theValue;
	var rlength = rlength; // The number of decimal places to round to
	var newnumber = Math.round(numberField*Math.pow(10,rlength))/Math.pow(10,rlength);
	return(newnumber);
}
function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}
function formatField(myField){
	myField.value = formatAsMoney(roundNumber(myField.value,2))
	return(true)
}

function testIsValidObject(objToTest) {
	if (null == objToTest) {
		return false;
	}
	if ("undefined" == typeof(objToTest) ) {
		return false;
	}
	return true;

}



/* This script is Copyright (c) Paul McFedries and 
Logophilia Limited (http://www.mcfedries.com/).
Permission is granted to use this script as long as 
this Copyright notice remains in place.*/

function roundDecimals(original_number, decimals) {
	var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function format5Places(myField){
	myField.value = roundDecimals(myField.value,5)
	return(true)
}
function format3Places(myField){
	myField.value = roundDecimals(myField.value,3)
	return(true)
}
function format2Places(myField){
	myField.value = roundDecimals(myField.value,2)
	return(true)
}
function pad_with_zeros(rounded_value, decimal_places) {

    var value_string = rounded_value.toString()
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")
    // Is there a decimal point?
    if (decimal_location == -1) {
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {
        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

function doInitials() {
	if (orgs.org_initials.value == "" && orgs.org_christian_name.value != "") {
		var nameArr = orgs.org_christian_name.value.split(" ")
		var init1 = ''
		for( i=0 ; i < nameArr.length ; i++){
			init1 += leftStr(nameArr[i],1) + ' '
		}
		orgs.org_initials.value = trim(init1)
		orgs.org_initials.value = orgs.org_initials.value.toUpperCase()
	}
}

function leftStr(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}
function ValidateBlank(myField){
	if (trim(myField.value) == "") {
		alert("You must enter something in this location")
		myField.focus()
		myField.select()		
		return false
	}
    return true
 }
 
function validEmail(email,warn) {
	
	re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/
	if (email.value == "" || re.test(email.value)) {
		return true
	}
	if (warn == "Y") {
		alert("Warning - Invalid email address")
		return true
	} else {
		alert("Invalid email address")
		email.focus()
		email.select()
		return false
	}
	
}



function ucPostcode(postcode){
	postcode.value = postcode.value.toUpperCase()
	return true
}
	
								 
								 
								 
								 
function toCalendar(){
	toCal = true
	return 
}	
function offDate(){
	toCal = false
	return 
}
function toCalendarLU(){
	if(event.keyCode=='13'){toCal = true;} 
}	
	
	
function unloadMess(){

	mess = "You have unsaved data which will be lost."
	if (changesMade == true && isSubmit == false && event.ctrlKey == false && toCal == false) event.returnValue = mess;
}

function disableForm(theform) {
if (document.all || document.getElementById) {
for (i = 0; i < theform.length; i++) {
var tempobj = theform.elements[i];
if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")
tempobj.disabled = true;
}
return true;
}
else {
alert("The form has been submitted.  But, since you're not using IE 4+ or NS 6, the submit button was not disabled on form submission.");
return false;
   }
}


function closeit(){
	alert("You do not have access to this option");
	window.close();
}

function isChanged(){
	changesMade = true;
	offDate();  <!--   used to make sure toCal is false, so that onbeforeunload works //-->
}	


function sfocus(TextBox) 
{ 
	var object = document.getElementById(TextBox);
	if (object && document.getElementById(TextBox).type != 'hidden') {
		document.getElementById(TextBox).focus(); 
		if (document.getElementById(TextBox).type != 'select-one' && document.getElementById(TextBox).type != 'select-multiple'){
			document.getElementById(TextBox).select(); 
		} 
	} 
}




function InitializeTimer()
{
    // Set the length of the timer, in seconds
    secs = 3600 // the time set by session.gc_maxlifetime is 3640. The browser timeout (session.cookie_lifetime is set to 0 - which keeps it going until the browser closes
    StopTheClock()
    StartTheTimer()
}

function StopTheClock()
{
    if(timerRunning)
        clearTimeout(timerID)
    timerRunning = false
}

function StartTheTimer()
{
	if (secs < 1){
		StopTheClock()
		alert("You are likely to have timed out - please log in again")
	} else {
	
		if (secs==60) {
		   // 
			StopTheClock()
			alert("You have less than a minute left until the page times out.")
			
			//InitializeTimer()
		}
		self.status = 'Expected timeout in ' + parseInt(secs/ 60) + ' minutes and ' + (secs - (parseInt(secs/60)*60)) + ' seconds'
		secs = secs - 1
		timerRunning = true
		timerID = self.setTimeout("StartTheTimer()", delay)
	}
}
function checkInArray(arrValue,arrName){
	var i;  
	for (i=0; i < arrName.length; i++) {    
//		alert("value "+arrValue + " array " + arrName[i])
		if (trim(arrName[i]) == trim(arrValue)) {
			return true;
		}
	}
	return false;
}
function takeOffEndPipes(pipeField){

	pipeField = trim(pipeField)
	if (pipeField == ""){
		pipeField = '0'
	} else {
		if (pipeField.substring(0,1) == '|'){
			pipeField = pipeField.substring(1,pipeField.length)
		}
		if (pipeField.substring(pipeField.length-1,pipeField.length) == '|'){
			pipeField = pipeField.substring(0,pipeField.length-1)
		}
	}
	return pipeField
}

function popUpHelp(event,objectID) {
	objPopTrig = document.getElementById(event);
	objPopUp = document.getElementById(objectID);
	objPopUp.style.visibility = 'visible';
}

function popHideHelp() {
	objPopUp.style.visibility = 'hidden';
	objPopUp = null;
}
function clScreenSize(){

	loginform.windowDepth.value = 1;
	return true;
}

function chkFilledIn(fieldName,allowBlank,enterWhat){
	
	if (document.getElementById(fieldName).value == '' && allowBlank != 'Y'){
		alert("You must enter " + enterWhat);
//		document.getElementById(fieldName).focus()
		return false;
	}
	return true;
}

