/*********************************************
** Javascript document for dw_PropMan_X1 	**
** Written by PBS@21052008					**
** libertylivingstone@yahoo.com				**
**********************************************/

var txt;
var temp;

function isEmpty(ctrl) {
	//Check for and report empty txtboxes
	txt = ctrl.value;
	return (txt == "");
}

function isNAN(ctrl) {
	//Check for and report non numeric values in controls
	txt = ctrl.value;
	return (isNaN(txt));
}

function isDisabled(ctrl){
	if (ctrl.disabled){
		return ctrl.disabled;
	}
	else{
		return false;
	}
}

function isValidFile(filename) {
	filename = filename.toLowerCase();
	var mime = filename.substr( filename.lastIndexOf(".") + 1 );
	return (mime == "jpg" || mime == "jpeg" || mime == "png");
}

function validLength(ctrl, len){
	//Check for a specific length of characters in a given control
	txt = ctrl.value;
	return (txt.length == len);
}

function selectField(field) {
	if (field) {
		field.focus();
		field.select();
	}
}

//if two strings are equal, returns true else false (Case Sensitive)
function equalStrings(str1, str2) {
	return (str1 == str2)? true : false;
}

//if two strings are equal, returns true else false (Case Insensitive)
function equalStringsCI(str1, str2) {
	return (str1.toLowerCase() == str2.toLowerCase())? true : false;
}

//Compares two dates and returns 0 for EQ, 1 for date1 > date2, -1 for date2 > date2, null for invalid dates
//TO DO -Check for invalid dates
function compareDates(date1_value, date2_value){
	//alert("In compareDates fn, dat1, dat2 == " + date1_value + " :: " + date2_value);
	if (!date1_value || !date2_value) { return null; }
	var date1 = new Date(date1_value).getTime();
	var date2 = new Date(date2_value).getTime();
	return (date1 === date2)? 0 : ((date1 > date2) ? 1 : -1);
}

function alertAndFocus(field, info, setFocus) {
	//give info and focus e.g. call frm.txt, 'fill this pls', true
	if (info) {
		alert(info);
		if (setFocus && field) {
			field.focus();
		}
	}
}

function _a(field, info, setFocus){
	//An alias kind of for alertandfocus
	alertAndFocus(field, info, setFocus);
}

function setCheck(ctrl, checked){
	//sets the checked state of checkable controls
	//alert("Seting: " + ctrl.name + " to : " + checked); 
	if (ctrl){
		ctrl.checked = checked;
	}
}

function toggleCheckboxGroup(frm, cbg_name, state) {
	if (frm){
		for (var i = 0; i < frm.elements.length; i++) {
			if (frm.elements[i].name == cbg_name && frm.elements[i].type == "checkbox"){
				frm.elements[i].checked = state;
			}
		}
	}
	//return true;
}

function noSelectableOptions(lbox, nsv){
	//This functions checks if there are options to select from a list box control.
	//nsv == nullselectionvalue, meaning an option whose selection means nothing to the listbox
	var nso = false;
	if (!nsv){
		nso = (lbox.options.length == 0);
	}
	else {
		nso = (lbox.options.length == 0) ? true : 
				((lbox.options.length == 1 && lbox.options[0].value == nsv) ? true : false);
	}
	return nso;
}

function isSelected(listbox){
	return (listbox.selectedIndex != -1);
}

//Part 2 of isSelected function. Gives room for NSVs
//NSV is a value which informs and not meant to be selected
function isSelected2(lbox, nsv){
	if (nsv){
		return (lbox.selectedIndex != -1 && lbox.value != nsv);
	}
	else{
		return (lbox.selectedIndex != -1);
	}
}

function optionvalueXist(listbox, optionval){
	if (listbox){
		for (i=0; i < listbox.options.length; i++){ 
			if (listbox.options[i].value == optionval){ return true; } 
		}
	}
	return false;
}

function urlHasParameters(url){
	return (url.indexOf("?") != -1) ? true : false;
}

function disableControl(ctrl, state){
	if (ctrl){
		ctrl.disabled = state;
	}
}

/***********NOT READY FOR USE YET PLEASE!**********/
function DisableControls(ctrl_array, state){
	//Sets all the controls in the array to a state, either true or false.
	var f;
	for (ctrl in ctrl_array){
		f = ctrl_array[ctrl];
		//alert (ctrl_array[ctrl].name + ' is actaully ' + ctrl_array[ctrl].disabled);
		alert (f.name + ' is actually ' + f.disabled);
		enableDisableControl(f, state);
	}
}
/*************************************************/

/************************************************
** This function trims the contents of all the **
** textboxes found in a form object passed in  **
** frm. Prince Blessing Sunday @ 2008.11.dw    **
************************************************/
function trimTextBoxContents(frm){
	//regexpression used :: str.replace(/^\s+|\s+$/g, '') ;
	//waiting for looping through controls js being searched from the net
}


/*************************************************
** The email validator function validates for 	**
** valid email addresses. PBS@21052008		 	**
** libertyivingstone@yahoo.com					**
**************************************************/

//Validate that email is valid, contain @ and no strange characters.
function ChkEmail(txt) {
	var i, atPos, periodPos, invalidChars, badChar;
	
    if (txt != "") {
   
		invalidChars = " /|\:,;-?!~^#$%*&()+=><[]{}";
       
		for (i=0; i<invalidChars.length; i++)	{
			badChar = invalidChars.charAt(i);
			//alert("Current Bad Character == " + badChar);
			if (txt.indexOf(badChar,0) != -1) {
				alert(txt + " - Invalid Characters in Email field");
				return false;
            }
		}

		if ( (txt.indexOf('@@',0)!=-1) || (txt.indexOf('..',0)!=-1)) {
		    alert(txt + " - Invalid Email Address");
			return false;             
		}
              
		atPos = txt.indexOf("@",1);
		if (atPos == -1) {
		    alert(txt + " - Invalid Email Address");
			return false;             
		}
       
		if (txt.indexOf("@",atPos+1) != -1) {
			alert(txt + " - Invalid Email Address, More Than one '@' found");
			return false;
        }
		
		periodPos = txt.indexOf(".",atPos);
		if (periodPos == -1) {
			alert(txt + " - Invalid Email Address");
			return false;
        }
                   
		if (periodPos+3 > txt.length) {
			alert(txt + " - Invalid Email Address");
			return false;
        }                                
	}
    return true;
}

//Calls ChkEmail to validate email addresses
function isValidEmail(txb) {
  txt = txb.value;
  
  if (ChkEmail(txt))
	return true;
  else {
	txb.focus();
	txb.select();
	return false;	
  }                    
}

//Version three, soon to replace two cos it returns the error for the caller
//to display as due! Test 4 blank return which means no errors
//Prince Blessing Sunday @ 19102008 libertylivingstone@yahoo.com
function ChkEmailIII(txt) {
	var i, atPos, periodPos, invalidChars, badChar;
	var einfo = ""; //Returns it blank when there are no errors
	
    if (txt != "") {
   
		invalidChars = " /|\:,;-?!~^#$%*&()+=><[]{}";
       
		for (i=0; i<invalidChars.length; i++)	{
			badChar = invalidChars.charAt(i);
			//alert("Current Bad Character == " + badChar);
			if (txt.indexOf(badChar,0) != -1) {
				einfo = "Invalid Characters in Email field";
				return einfo;
            }
		}

		if ( (txt.indexOf('@@',0)!=-1) || (txt.indexOf('..',0)!=-1)) {
		    einfo = "Invalid Email Address";
			return einfo;
		}
              
		atPos = txt.indexOf("@",1);
		if (atPos == -1) {
		    einfo = "Invalid Email Address";
			return einfo;
		}
       
		if (txt.indexOf("@",atPos+1) != -1) {
			einfo = "Invalid Email Address, More Than one '@' found";
			return einfo;
        }
		
		periodPos = txt.indexOf(".",atPos);
		if (periodPos == -1) {
			einfo = "Invalid Email Address";
			return einfo;
        }
                   
		if (periodPos+3 > txt.length) {
			einfo = "Invalid Email Address";
			return einfo;
        }                                
	}
    return einfo;
}

//Calls ChkEmailIII to validate email addresses
function isValidEmail3(txb) {
  txt = txb.value;
  return ChkEmailIII(txt);
}

//End of email validation function

/*****************************************************************************************************************
* This function chkboxSelected is the Part 2 of a similar function this one was specifically written because of  *
* the problem that PHP has in submitting an array of checkboxes with the same name but different values.         *
* Sometime, you want to do just this! Like some chckboxes for course with the name course but values different   *
* course ids. In PHP it must be named like this: name = course[] for them to be submitted when checked otherwise *
* only one gets submitted This doesn't happen in JAVA. The problem then is that controls with such names can't   *
* be validated in javascript because [] means array This function handles the validation very well and at the    *
* end tells you if any check box exist at all and if any has been selected. IT CAN ALSO BE USED FOR JAVA OR ANY  *
* OTHER LANGUAGE. The function gives the appropriate message so you do not need to give any message at all.      *
* Just call the function! Feel free to use this in your own page as far as this text remains there.              *
*     @@ Version2 for inline display instead of alerts. Prince Blessing Sunday. libertylivingstone@yahoo.com     *
*****************************************************************************************************************/

function chkboxSelected2(frmObject, cboxname, noSelectionInfo, noCboxInfo){
	var cboxes = new Array();
	var cbxExist = false;
	var chkboxselected = false;
	var einfo = "";
	
	cbxExist = cboxesExist(frmObject, cboxname);
	if (cbxExist) {
	   if (cboxes.length == 1){
		   //just one checkbox so process it
		   chkboxselected = cboxes[0].checked;
	   }
	   else {
		   //multiple existing checkboxes, handle them
		   for (var i = 0; i < cboxes.length; i++) {
			   if (cboxes[i].checked) {					
					chkboxselected = true;
					break;					
				}
		   }
	   }
	   //Inform the user as due
	   if (!chkboxselected) {
		   (noSelectionInfo != undefined && noSelectionInfo != "") ? 
		   		einfo = noSelectionInfo : einfo = "Please select one or more items first!";
	   }
	}
	else {
		(noCboxInfo != undefined && noCboxInfo != "") ? 
			einfo = noCboxInfo : einfo = "There are no items found on this page to select for this process!";
	}
	
	return einfo;
	
	//Helper function for the main function Embedded by 
	//Prince Blessing Sunday (libertylivingstone@yahoo.com)
	function cboxesExist(frmObject, cboxname) {
		for (var i = 0; i < frmObject.length; i++) {
			if (frmObject[i].type == "checkbox") {
				if (frmObject[i].name == cboxname) {
					cboxes[cboxes.length] = frmObject[i];
				}
			}
		}
		return (cboxes.length == 0)? false : true;
	}
	//End of embedded helper funtion
}

function isBlank(s) {
	// Check if string is blank
	var isBlank_re = /\S/;
	return String (s).search (isBlank_re) == -1
}

function isValidEmail(email) {
	var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
	return String(email).search (isEmail_re) != -1; // if it is == -1, it failed!
}

function isValidPhoneNumber(phone) {
	var isPhone_re = /^\d{6,}$/;
	return String(phone).search (isPhone_re) != -1; // if it is == -1, it failed!
}

function isValidQuantity(qty) {
	var isQty_re = /^\d{1,}$/;
	return String(qty).search (isQty_re) != -1; // if it is == -1, it failed!
}


/*****************************************************/
//Utilities for showing and hiding sections//

function showSectionByID(id, indisplay){
	//shows a hidden section indisplay == true, set it inline
	var section = document.getElementById(id);
	if (section) {
		section.style.display = (indisplay == true) ? "inline" : "block";
	}
}

function hideSectionByID(id){
	//hides a section
	var section = document.getElementById(id);
	if (section) {
		section.style.display="none";
	}
}

function showSectionByObject(obj, indisplay){
	//shows a hidden section indisplay == true, set it inline
	if (obj) {
		obj.style.display = (indisplay == true) ? "inline" : "block";
	}
}

function hideSectionByObject(obj){
	//hides a section
	if (obj) {
		obj.style.display="none";
	}
}

function toggleSectionVisibility(id){
	var section = document.getElementById(id);
	if (section) {
		var curV = section.style.display;
		(curV == '' || curV == 'none') ? showSectionByID(id) : hideSectionByID(id);
	}
}

function setSectionTEXT(id, info){
	//uses innerHTML to change the data in section (div for e.g.)
	var section = document.getElementById(id);
	if (section) {
		section.innerTEXT = info;
	}
}

function getSectionHTML(id){
	//returns the innerHTML in a section (div for e.g.)
	var section = document.getElementById(id);
	if (section) {
		return section.innerHTML;
	}
}

function setSectionHTML(id, info){
	//uses innerHTML to change the data in section (div for e.g.)
	var section = document.getElementById(id);
	if (section) {
		section.innerHTML = info;
	}
}

function setStyle(id, style, value){
	var section = document.getElementById(id);
	if (section) {		
		switch (style) {
			case "color":
				section.style.color=value;
				break;
			case "border":
				section.style.border=value;
				break;
			case "height":
			value += 'px';
				section.style.height=value; //parseInt(value);
			default:
				//nothing just return
		}
	}
}

function setCustomTimeout(myFunction, myTime){
	timeoutID = setTimeout(myFunction, myTime);
}
/**********************************************************/
