
function validateField(frm , cond , fObj , errmsg){
	if(cond){
		alert(errmsg);
		fObj.focus();
		return false;
	}
	
	return true;
	
}


/*
 * getFormObject : function to get a Form object by it's name.
 *                 handy when inputs have funny names. such as array variables xxx[]
 *
 *                 getflast will cache the last form object found. this is handy because in large forms it can be time consuming
 *
 *                 if not found after getflast>0; we reset and search again
 */



var getflast = 0;

function getFormObject( frm , name) {

    // are we starting from scratch?
    var begining = (getflast == 0)? true : false;
	
    for (; getflast<frm.length; getflast++) {
      if ( (frm.elements[getflast].name == name) ) {
	      var returnobj = frm.elements[getflast];
	      getflast = getflast - (getflast>0?1:0); // just go back 1 for next run
	      return returnobj;
	      
      }
    }
    
    // if didn't start at the begining then let's go back at the start
    if(!begining){
	    //alert('not found so going back');
	    getflast = 0;
	    return getFormObject( frm , name);
    }
    
    return null;
  
}




function updateFormObjectValue( frm , name , value) {

	//alert(value);
	
    var obj = getFormObject(frm , name);
    
    if(obj != null)
	    obj.value=value;
    
    return;
  
}





// get all form's elements and make up query string
function get_form_inputs(frm){
	
	var ret = "";
	
    for (i=0; i<frm.length; i++) {
      if (
           (frm.elements[i].type == "button") 
	  	) {

			
        continue;
      }
	  
	  ret += ( "&" + frm.elements[i].name + "=" + frm.elements[i].value) ;
	  
    }
	
	return ret;
	
}


// make sure minimum of minChecked has been selected on cObj
function boxChecked(frm , objName , minChecked){

	var count = 0;

	    for (var i=0; i<frm.length; i++) {
	      if ( (frm.elements[i].name == objName) ) {
		if(frm.elements[i].checked) count++;
	      }
	    }
	
	//alert(cObj.name + " " + cObj.type + " " + cObj.length + " " + minChecked + " " + count);

	if (count >= minChecked){
		//alert("It is greater>=");
		return true;	
	}

	return false;
	
}





function validatedate2(strDate){
	var strDateArray = strDate.split('-');
	if (strDateArray.length != 3)
		return false;
	strDate = strDateArray[2] + '/' + strDateArray[1] + '/' + strDateArray[0];
	//alert(strDate);
	
	return validatedate(strDate);
}

function validatedate(strDate){
	
var strDatestyle = "AU"; //United States date style
//var strDatestyle = "EU";  //European date style
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
//var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = "Jan";
strMonthArray[1] = "Feb";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Apr";
strMonthArray[4] = "May";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Aug";
strMonthArray[8] = "Sep";
strMonthArray[9] = "Oct";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dec";
//strDate = datefield.value;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
   }
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
   }
}
if (strYear.length <4) {
return false;
}
// US style
//if (strDatestyle == "US") {
///strTemp = strDay;
//strDay = strMonth;
//strMonth = strTemp;
//}
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
   }
}
if (isNaN(intMonth)) {
err = 3;
return false;
   }
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
}
}
else {
if (intday > 28) {
err = 10;
return false;
}
}
}
return true;
}


function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) { return true; }
	}	
	return false;	
}





function validatetime(t){
	if(t == "")
		return true;
	//alert('function entered');
	if(t.length < 4)
		return false;
	if(t.length > 5)
		return false;

	//alert('length checked');	
	var colon = t.indexOf(":");
	if(colon < 0 )
		return false;
	//alert('colon exists');
	var hour = t.substring(0 , colon );
	var minute = t.substring(colon+1  , t.length );
	/*if ( (parseInt(hour) + "") != hour)
		return false;
	//alert('hour matches ' + hour);
	//alert('minute is ' + minute);
	if ( (parseInt(minute) + "") != minute)
		return false;*/
	//alert('minute matches ' + minute);
	if(minute.length < 2)
		return false;
	if(parseInt(hour) > 24)
		return false;
	if(parseInt(hour) <0)
		return false;
	if(parseInt(minute) <0)
		return false;
	if(parseInt(minute) >60)
		return false;
	
	return true;
}


function validateint(i){
	if(i == "")
		return true;
	if ( (parseInt(i) + "") != i)
		return false;
	return true;	
}


function validatenumber(i){
	if(i == "")
		return true;
	if ( (parseFloat(i) + "") != i)
		return false;
	return true;	
}



function popupWindow(url) {
  window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=auto,resizable=yes,copyhistory=no,width=100,height=100,screenX=150,screenY=150,top=150,left=150')
}


function popupWindow2(url, width , height) {
  window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=auto,resizable=yes,copyhistory=no,width=' + width + ',height=' + height + ',screenX=180,screenY=100,top=180,left=100')
}


function popupWindowHelp(url) {
  window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=auto,resizable=yes,copyhistory=no,width=300,height=300,screenX=150,screenY=150,top=150,left=150')
}

function SetFocus() {
  if (document.forms.length > 0) {
    var field = document.forms[0];
    for (i=0; i<field.length; i++) {
      if ( (field.elements[i].type != "image") && 
           (field.elements[i].type != "hidden") && 
           (field.elements[i].type != "button") && 
           (field.elements[i].type != "reset") && 
           (field.elements[i].type != "submit") ) {

        document.forms[0].elements[i].focus();

        if ( (field.elements[i].type == "text") || 
             (field.elements[i].type == "password") )
          document.forms[0].elements[i].select();
        
        break;
      }
    }
  }
}

// farr is a array of common pair
function ListCopy(farr , tbox , selectIndex){
	//alert('current length ' + tbox.length);
	var i = 0;
	
	//alert('from length ' + farr.length);
	for(i=0 ; i < farr.length ; i++){
		var e = new Option();
		e.value = farr[i].x;
		e.text  = farr[i].y;
		tbox[i] = e;
	}
	tbox.length = farr.length;
	if(farr.length > 0)
		tbox[selectIndex].selected = true;
	//alert('actual length ' + tbox.length);
	return;
}



function ListMove(fbox, tbox) {
var arrFbox = new Array();
var arrTbox = new Array();
var arrLookup = new Array();
var i;
for (i = 0; i < tbox.options.length; i++) {
arrLookup[tbox.options[i].text] = tbox.options[i].value;
arrTbox[i] = tbox.options[i].text;
}
var fLength = 0;
var tLength = arrTbox.length;
for(i = 0; i < fbox.options.length; i++) {
arrLookup[fbox.options[i].text] = fbox.options[i].value;
if (fbox.options[i].selected && fbox.options[i].value != "") {
arrTbox[tLength] = fbox.options[i].text;
tLength++;
}
else {
arrFbox[fLength] = fbox.options[i].text;
fLength++;
   }
}
//arrFbox.sort();
//arrTbox.sort();
fbox.length = 0;
tbox.length = 0;
var c;
for(c = 0; c < arrFbox.length; c++) {
var no = new Option();
no.value = arrLookup[arrFbox[c]];
no.text = arrFbox[c];
fbox[c] = no;
}
for(c = 0; c < arrTbox.length; c++) {
var no = new Option();
no.value = arrLookup[arrTbox[c]];
no.text = arrTbox[c];
tbox[c] = no;
   }
}






function ListSelected(lObj , val){
	
	for(var i=0; i< lObj.options.length ; i++){
		if(lObj.options[i].value == val){
			lObj.options[i].selected = true;
			return;
		}
	}
	return;
}


// dbug : dump object properties
function dumpProps(obj, parent) {
	for (var i in obj) {
		if (parent) { msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
		if (!confirm(msg)) { return; }
		if (typeof obj[i] == "object") { 
			if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
		}
	}
}


function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-')  + num + '.' + cents);
}













	function isDigit(c) {
		
		return ((c=='0')||(c=='1')||(c=='2')||(c=='3')||(c=='4')||(c=='5')||(c=='6')||(c=='7')||(c=='8')||(c=='9'))
	}

	function isNumeric(n) {
		
		num = parseInt(n,10);

		return !isNaN(num);
	}

	function padZero(n) {
		v="";
		if (n<10){ 
			return ('0'+n);
		}
		else
		{
			return n;
		}
	}

	function fixTimeFeild(ctl) {

		t=ctl.value.toLowerCase();
		t=t.replace(" ","");
		t=t.replace(".",":");
		t=t.replace("-","");

		if ((isNumeric(t))&&(t.length==4))
		{
			t=t.charAt(0)+t.charAt(1)+":"+t.charAt(2)+t.charAt(3);
		}

		var t=new String(t);
		tl=t.length;

		if (tl==1 ) {
			if (isDigit(t)) {
				ctl.value="0" + t+":00";
			}
			else {
				return false;
			}
		}
		else if (tl==2) {
			if (isNumeric(t)) {
					if (t.charAt(1)!=":") {
						ctl.value= t + ':00';
					} 
					else {
						ctl.value= t + '00';
					}
			}
			else
   		    {
				if ((t.charAt(0)==":")&&(isDigit(t.charAt(1)))) {
					ctl.value = "00:" + padZero(parseInt(t.charAt(1),10)) + "";
				}
				else {
					return false;
				}
			}
		}
		else if (tl>=3) {

			var arr = t.split(":");
			if (t.indexOf(":") > 0)
			{
				hr=parseInt(arr[0],10);
				mn=parseInt(arr[1],10);


				if (isNaN(hr)) {
					hr=0;
				} 
			
				if (isNaN(mn)) {
					mn=0;
				}
				else {
					if (mn>60) {
						mn=mn%60;
						hr+=1;
					}
				}
			} else {

				hr=parseInt(arr[0],10);

				if (isNaN(hr)) {
					hr=0;
				} else {
					if (hr>24) {
						return false;
					}
				}

				mn = 0;
			}
			
			if (hr==24) {
				hr=0;
			}
			ctl.value=padZero(hr)+":"+padZero(mn);
		}
	}



















function getXMLObj(url) {
       var req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
        try {
                        req = new XMLHttpRequest();
        } catch(e) {
                        req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
        try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
                try {
                        req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                        req = false;
                }
                }
    }
    
    req.open("POST" , url  , true);
    req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    return req;
}



function span_text_update(id , text){
	
	var obj = document.getElementById(id);
	
	if(!obj)
		alert('Object not found : ' + id);
	
	obj.innerHTML = text;
	
	
}




function span_class_update(id , classname){
	
	var obj = document.getElementById(id);
	
	if(!obj)
		alert('Object not found : ' + id);
	
	obj.className = classname;
	
	
}







// get javascript code dynamically from server...
// ruturnfunc is executed once the code arrives..
function get_dyn_js(url , params , returnfunc) {
	var obj = getXMLObj(url);
	obj.onreadystatechange = function()
	{
		if (obj.readyState != 4)
			return;
		
		if (obj.status==200)
		{
				eval(obj.responseText);
				eval(returnfunc);
				//var xml = obj.responseXML.documentElement;
				//alert(response.getElementsByTagName('method')[0].firstChild.data);
		}
	}
	obj.send(params);
	
//    return req;
}






// add an item to a list if it is not already in the list
// NOTE :: Item key and value must be the same
function select_other(thelist){
	
	return;
}




// Select all items in the given list.
function selectAllInList(list){
	changeSelectionAllInList(list,true);
}
// Select all items in the given list.
function deselectAllInList(list){
	list.options.selectedIndex=-1;
}	

// Select all items in the given list.
function changeSelectionAllInList(list, selected){
	for(var i = 0; i < list.options.length;i++) {
		list.options[i].selected = selected;
	}
}


function isEnterPressed() {
    var evt = event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
        ((evt.which) ? evt.which : 0));
    return (charCode == 13);
}




/*
 * puts an element at the end of an array
 */
function common_array_put(arr , item){
	arr[arr.length] = item;
	return arr;
}


/*
 * copy exisitng array and return a copy
 */
function common_array_copy(arr1 , arr2){
	arr2 = new Array();
	for(i=0; i < arr1.length ; i++)
		arr2[i] = arr1[i];
	return arr2;
}

/*
 * remove an element from array
 */
function common_array_del(arr , indx){

	size = arr.length;

	if((indx > size) || ( indx < 0))
		return arr;

	for(var i = indx ; i < size ; i++)
		arr[i] = arr[i+1]
	
	arr.length = size-1;
	return arr;
}



/*
 * search an array and returns the index of the found element - starting at given index
 */
function common_array_search(arr , item , startindex){
	var i = 0 , len = arr.length;
	for(i = startindex ; i < len ; i++)
		if(arr[i] == item)
			return i;
	return -1;
}


/*
 * search an array of objects for attribute
 */
function common_array_obj_search(arr , attribstr , item){
	var len = arr.length;
	for(var i =0; i < len ; i++){
		if((arr[i]!= null) && (arr[i] != 0) && ((typeof arr[i]) == "object"))
		if(eval("arr[" + i + "]." + attribstr) == item)
			return i;
	}
	return -1;
}



/*
 * Current Browser, version, platform
 */
function common_browser_check() {
	this.browser = navigator.appName
	this.platform = navigator.platform
	this.version = parseInt(navigator.appVersion)
	this.ns = (this.browser=="Netscape" && this.version>=4)
	this.ns4 = (this.ns && this.version==4)
	this.ns5 = (this.ns && this.version==5)
	this.ns6 = (this.ns && this.version==6)

	this.ie4 = (navigator.appVersion.indexOf('MSIE 4')>0)
	this.ie5 = (navigator.appVersion.indexOf('MSIE 5')>0)
	this.ie6 = (navigator.appVersion.indexOf('MSIE 6')>0)
	this.ie = this.ie4 || this.ie5 || this.ie6;

	this.min = (this.ns||this.ie)

	return this;
}
var common_browser = new common_browser_check()


/*
 * a two variable object - useful for keeping pairs
 */
function common_pair(x , y){
	this.x = x;
	this.y = y;
	return this;
}


/*
 * a three variable object - useful for keeping triples
 *
 */
function common_triple(x , y , z){
	this.x = x;
	this.y = y;
	this.z = z;
	return this;
}






/*
 * Java like vector object
 */
function common_vector(){
	this.elements = new Array();
	
	this.add = function(item){
		this.elements[this.elements.length] = item;
	}

	this.size = function(){
		return this.elements.length;
	}

	this.get = function(ind){
		if(ind < 0 || ind > this.elements.length)
			return null;

		return this.elements[ind];
	}

	this.getbyparam = function(paramstr , val){
		
		var ind = common_array_obj_search( this.elements , paramstr , val);
		if(ind == -1)
			return null;

		return this.elements[ind];
	}


	this.addAt = function(item , ind){
		this.elements[ind] = item;
	}

}




/*
 * common_strstr : returns true if the search string is found inside the target string - case insensitive
 */
function common_strstr( target, search){
	var slower = search.toLowerCase();
	var tlower = target.toLowerCase();
	if(tlower.indexOf(slower,0) >=0)
		return true;

	return false;
}




/*
 * Stripper : Strips a string like "var1:val1;var2:val2" into an array of pairs
 */
function common_strip(str){
	var arr_breaks = str.split(';');
	var arr = new Array();
	var temp;
	for(var i = 0; i < arr_breaks.length ; i++){
		temp = arr_breaks[i].split(':');
		if(temp.length > 1){
			arr[arr.length] = new common_pair(temp[0] , temp[1]);
		}
	}
}





// if the number is less than 0 then return 0 , or else return the number
function common_non_negate( num){
	if(num<0)
		return 0;
	return num;
}


// a substutite function which replaces all occurance for a string with another
function common_substitute(target,oldTerm,newTerm,caseSens,wordOnly) {

	var work = target;
	var ind = 0;
	var next = 0;

	if (!caseSens) {
		oldTerm = oldTerm.toLowerCase();
		work = target.toLowerCase();
	}

	while ((ind = work.indexOf(oldTerm,next)) >= 0) {
		if (wordOnly) {
			var before = ind - 1;
			var after = ind + oldTerm.length; 
			if (!(space(work.charAt(before)) && space(work.charAt(after)))) {
				next = ind + oldTerm.length; 
				continue;
			}
		}
		target = target.substring(0,ind) + newTerm + 
		target.substring(ind+oldTerm.length,target.length); 
		work = work.substring(0,ind) + newTerm + 
		work.substring(ind+oldTerm.length,work.length); 
		next = ind + newTerm.length;
		if (next >= work.length) { break; } 
	}

	return target;

}



// parseInt but take all integers into count
function common_parseInt(str){
	var res1 = "";
	var res2 = "";
	for(i=0; i < str.length ; i++){
		ch = str.substr(i , 1);
		if((ch >= "0") && (ch <= "9"))
			res1 += ch;
	}
	// remove all leading zeros
	var zerofound = true;
	for(i=0; i < res1.length ; i++){
		ch = res1.substr(i , 1);
		if((ch == "0") && zerofound){
			res2 += "";
		}else{
			res2 += ch;
			zerofound = false;
		}	
			
	}
	if(res2 == "")
		return 0;
	//alert(' stripped ints ' + res2);
	res3 = parseInt(res2);
	return res3;
		
	
}







/*
==================================================================
LTrim(string) : Returns a copy of a string without leading spaces.
==================================================================
*/
function common_ltrim(str)
/*
   PURPOSE: Remove leading blanks from our string.
   IN: str - the string we want to LTrim
*/
{
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...

      var j=0, i = s.length;

      // Iterate from the far left of string until we
      // don't have any more whitespace...
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;

      // Get the substring from the first non-whitespace
      // character to the end of the string...
      s = s.substring(j, i);
   }
   return s;
}

/*
==================================================================
RTrim(string) : Returns a copy of a string without trailing spaces.
==================================================================
*/
function common_rtrim(str)
/*
   PURPOSE: Remove trailing blanks from our string.
   IN: str - the string we want to RTrim

*/
{
   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc.  Add anything else you want to
   // "trim" here in Whitespace
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      // We have a string with trailing blank(s)...

      var i = s.length - 1;       // Get length of string

      // Iterate from the far right of string until we
      // don't have any more whitespace...
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;


      // Get the substring from the front of the string to
      // where the last non-whitespace character is...
      s = s.substring(0, i+1);
   }

   return s;
}

/*
=============================================================
Trim(string) : Returns a copy of a string without leading or trailing spaces
=============================================================
*/
function common_trim(str)
/*
   PURPOSE: Remove trailing and leading blanks from our string.
   IN: str - the string we want to Trim

   RETVAL: A Trimmed string!
*/
{
   return common_rtrim(common_ltrim(str));
}











function cNotation(t , sep){
        tH = Math.floor(t/100) ;
	tM =  t%100;
	tM = Math.floor((tM / 25))* 15;
	if(tH == 0)
		tH = '00' ;   
	else if(tH < 10)
		tH = '0' + tH;   

	if(tM == 0)
		tM = '00' ;   
	else if(tM < 10)
		tM = '0' + tM;  		
	return tH + sep + tM;
}



// From HH:MM returns HHHH (i.e. mintes in decimal of hours)
function clock2int(str){
	//alert(str);
	var t = common_parseInt(str);
	//alert(t);
        var tH = Math.floor(t/100) ;
	var tM =  t%100;
	tM = Math.floor((tM / 15))* 25;
	var result = ((tH*100) + tM);
	//alert(result);
	return result;
	
	
}


// From HH:MM returns HHHH (i.e. mintes in decimal of hours) - this one does it in every minute block
function clock2int2(str){
	//alert(str);
	var t = common_parseInt(str);
	//alert(t);
        var tH = Math.floor(t/100) ;
	var tM =  t%100;
	tM = Math.floor((tM / 60)* 100);
	var result = ((tH*100) + tM);
	//alert(result);
	return result;
	
	
}



// alert('common');

function ourParseInt(str)
{
	var r = parseInt(str);
	
	// There is a bug with parseInt(): '08' and '09' get parsed to 0?!?
	// This is why we check for a '0' before the parsing
	//
	if (str.length == 2)
	{
		if (str.charAt(0) == '0')
		{
			r = parseInt(str.charAt(1));
		}
	}

	return r;
}
