
var httpRequest;
function initHttpRequest() {
        httpRequest=null;
        if (typeof ActiveXObject != 'undefined') {
                httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
        }
        else if (typeof XMLHttpRequest != 'undefined') {
                httpRequest = new XMLHttpRequest();
        }
}
function showLoading(id){
	var obj=document.getElementById(id);
	if(obj){
		document.body.style.cursor='progress';
		
		//obj.innerHTML='<br><br<br>loading please wait....';
	}
}
function xmlSend(url,data,id){
	showLoading(id);
	initHttpRequest();
	if(httpRequest){
        	httpRequest.open('POST', url , true);
	        httpRequest.onreadystatechange = function() {xmlStatus(id, data);}
        	httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        	httpRequest.setRequestHeader('Referer',document.referrer);
        	httpRequest.send(data);        	
	}else{
		alert('Your browser does not support http Request');
	}

}

function checkReadyState(obj){
  	if(obj.readyState == 4){
    		if(obj.status == 200){
		        return true;
	    	}else{
        		if (obj.status == 404 ){
				alert('File not found');
        		}
        		if (obj.status == 500 ) {
				alert('Internal Server Error');
        		}
    		}
  	}
}

function xmlStatus(id, data) {
        if(checkReadyState(httpRequest)) {      
        
        	
        	document.body.style.cursor='default';        	
		var obj=document.getElementById(id);
		obj.innerHTML=httpRequest.responseText;			
				
        }
}


function NewWindow(link,myname,w,h,scroll,menubar,resize,toolbar,status){
        var win = null;
        if (resize=='') { var resize="no"; }
        var LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
        var TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
        var settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable='+resize+',menubar='+menubar+',toolbar='+toolbar+',status='+status;
        win = window.open(link,myname,settings)
}

function view_links(a){
	var obj=document.link_frm;
	NewWindow(a,'links',800,600,'yes','yes','yes','yes','yes');
	obj.target='links';
	obj.action=a;
	obj.submit();
	
}

function getElementsByTagNames(list,obj) {

	if (!obj) var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	return resultArray;
}

function getElementFields(fObj) {
	
	var myI='';

	if (typeof fObj == 'string') { 
		var obj = document.getElementById(fObj);
		if (!obj.elements) {
			myI = getElementsByTagNames('input,select,textarea',obj);
		} else {
			myI = obj.elements;
		}
	} else { 	
		if (!fObj.elements) {
			myI = getElementsByTagNames('input,select,textarea',fObj);
		} else { 
			myI = fObj.elements;
		}
	}
	return myI;
}


function getFormValues(fObj)
{
        var str = "";
	var myI = getElementFields(fObj);
	
	for (var i=0;i<myI.length;i++) {
		var objAtNode = myI[i];
		if (objAtNode.disabled) continue;
                switch(objAtNode.type)
	        {
	 		  case "checkbox":
					   if (objAtNode.checked) 
						str += objAtNode.name + "=" + escape(objAtNode.value) + "&";
				 	   break;
	   		  case "radio":
					   if (objAtNode.checked)
                                		str += objAtNode.name + "=" + escape(objAtNode.value) + "&";
                        		   break;
	   		  case "textarea":	
	   	          case "hidden":
           	          case "text":
	   	          case "password":
                			    str += objAtNode.name + "=" + escape(objAtNode.value) + "&";
                 			    break;
           		  case "select-one":
					   if (objAtNode.options.length && objAtNode.selectedIndex>-1) 
                				str += objAtNode.name + "=" + objAtNode.options[objAtNode.selectedIndex].value + "&";
					  
                			   break;
		}
       }
   

       str = str.replace(/\+/g,'%2B');
       str = str.substr(0,(str.length - 1));
       return str;
       alert(str);
}



function xValidate(obj) {

        var xmesg='';
	var objAtNode='';

	var myI = getElementFields(obj);
	var _i = 0;

        for (_i=0;_i<myI.length;_i++) {

                objAtNode = myI[_i];
                z=objAtNode.type;
               	var ztype=objAtNode.getAttribute('alt');
               	var zid=objAtNode.id;
               	var zv=trimAll(objAtNode.value);

		
		if ( ztype!='nonrequired' && !objAtNode.disabled ) {
	                if (z=='text' || z=='password' || z=='hidden' || z=='file') {
        	                if (ztype!='') {
                	                if (ztype=='string' && zv=='') {
                        	                xmesg=xmesg +zid+' is a required field.\n';
						if (z!='hidden') objAtNode.focus();
                                	}
	                                if (ztype=='date' && !is_Date34(zv)) {
        	                                xmesg=xmesg +zid+' field requires a valid date.\n';
						if (z!='hidden') objAtNode.focus();
                	                }
                        	        if (ztype=='integer' && !validateInteger(zv)) {
                                	        xmesg=xmesg +zid+' field requires a valid whole number.\n';
						if (z!='hidden') objAtNode.focus();
                                	}	
					if (ztype=='float' && !validateNumeric(zv)) {
						xmesg=xmesg +zid+' field requires a valid number.\n';
						if (z!='hidden') objAtNode.focus();
					}
					 if ( ( ztype=='time24' || ztype=='time12' || ztype=='time') && !validateTime(zv)) {
                                	        xmesg=xmesg +zid+' field requires a valid 24 hour time format.\n';
						if (z!='hidden') objAtNode.focus();
                                	}
                                	if (ztype=='email' && !validateEmail(zv)){
                                		xmesg=xmesg +zid+' field requires a valid email address format.\n';
                                		if (z!='hidden') objAtNode.focus();
                                	}
	                        }
        	        } 
			if (z=='textarea') {
				if (zid && zv=='') {
					xmesg=xmesg +zid+' is a required field.\n';
					if (z!='hidden') objAtNode.focus();
				}
			}
	                if (( z=='select-one' || z=='select-multiple' || z=='select')  ) {
                	        zselected=objAtNode.selectedIndex;
				//alert(z+' : '+zid+' : '+zselected);
                        	if (zid) {
                                	if (zselected==0 || zselected<0) {
                                        	xmesg=xmesg + 'Please select a '+zid + '\n';
						if (z!='hidden') objAtNode.focus();

	                                }
        	                }
               		 }

		}

        }

	 if (xmesg!='') {

			try {
	                        if (z!='hidden') objAtNode.focus();
        	                //xalert("Error",xmesg,objAtNode);
        	                alert('ERROR\n\n'+xmesg);
			
			}catch(e) {
				//xalert("Error", xmesg);
				alert('ERROR\n\n'+xmesg);
			}finally {
	                        return false;
			}
                }

        return true;
}


function trimAll( strValue ) {
    var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }
    
   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function  validateNumeric( strValue ) {
/******************************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/; 
 
  //check for numeric characters 
  return objRegExp.test(strValue);
}

function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only 
    valid integer number.
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  = /(^-?\d\d*$)/;
 
  //check for integer characters
  return objRegExp.test(strValue);
}

function validateNotEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }  
   return false;
}

function validateUSZip( strValue ) {
/************************************************
DESCRIPTION: Validates that a string a United
  States zip code in 5 digit format or zip+4
  format. 99999 or 99999-9999
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.

*************************************************/
var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
 
  //check for valid US Zipcode
  return objRegExp.test(strValue);
}

function validateUSDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only 
    valid dates with 2 digit month, 2 digit day, 
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and 
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy or mm.dd.yy
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
   
REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2,4}$/;
 
  //check to see if in correct format
  if(!objRegExp.test(strValue))
    return false; //doesn't match pattern, bad date
  else{
    var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
	var intDay = parseInt(arrayDate[1],10); 
	var intYear = parseInt(arrayDate[2],10);
    var intMonth = parseInt(arrayDate[0],10);
	
	//check for valid month
	if(intMonth > 12 || intMonth < 1) {
		return false;
	}
	
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}
  
    //check if month value and day value agree
    if(arrayLookup[arrayDate[0]] != null) {
      if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
        return true; //found in lookup table, good date
    }
		
    //check for February
	var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
    if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0)
      return true; //Feb. had valid number of days
  }
  return false; //any other values, bad date
}

function validateValue( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Validates that a string a matches
  a valid regular expression value.
    
PARAMETERS:
   strValue - String to be tested for validity
   strMatchPattern - String containing a valid
      regular expression match pattern.
      
RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp = new RegExp( strMatchPattern);
 
 //check if string matches pattern
 return objRegExp.test(strValue);
}


function rightTrim( strValue ) {
/************************************************
DESCRIPTION: Trims trailing whitespace chars.
    
PARAMETERS:
   strValue - String to be trimmed.  
      
RETURNS:
   Source string with right whitespaces removed.
*************************************************/
var objRegExp = /^([\w\W]*)(\b\s*)$/;
 
      if(objRegExp.test(strValue)) {
       //remove trailing a whitespace characters
       strValue = strValue.replace(objRegExp, '$1');
    }
  return strValue;
}

function leftTrim( strValue ) {
/************************************************
DESCRIPTION: Trims leading whitespace chars.
    
PARAMETERS:
   strValue - String to be trimmed
   
RETURNS:
   Source string with left whitespaces removed.
*************************************************/
var objRegExp = /^(\s*)(\b[\w\W]*)$/;
 
      if(objRegExp.test(strValue)) {
       //remove leading a whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}


function is_allDigits(a){
        regexp_allDigits = /^[0-9]*[0-9]$/;

        return(regexp_allDigits.test(a));
}


function is_Measure(a){
        var b=parseFloat(a);

        regexp_isMeasure = /^[0-9]*[.]?[0-9]?[0-9]?[0-9]?[0-9]$/;

        return(regexp_isMeasure.test(a) && b!=0);
}

function is_Date34(strValue){

	if( strValue == '00/00/0000' )
	{
		return false;
	}

        //regexp_isDate = /(0[1-9]|1[0-2])[(\x2F)-. ]((0[1-9])|(3[0-1])|([1-2][0-9]))[(\x2F)-. ][0-9]{4}/;
         
        regexp_isDate = /((0[1-9])|(3[0-1])|([1-2][0-9]))[(\x2F)-. ](0[1-9]|1[0-2])[(\x2F)-. ][0-9]{4}/;
        
        
        if(regexp_isDate.test(strValue) && strValue!='') {

                var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2,4}$/;

                //check to see if in correct format
                if(!objRegExp.test(strValue)){
                	alert('here');
                        return false; //doesn't match pattern, bad date
                }
                else{
                        var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
                        //var intDay = parseInt(arrayDate[1],10);
                        var intDay = parseInt(arrayDate[0],10);
                        var intYear = parseInt(arrayDate[2],10);
                        //var intMonth = parseInt(arrayDate[0],10);
                        var intMonth = parseInt(arrayDate[1],10);

                        //check for valid month
                        if(intMonth > 12 || intMonth < 1) {
                                //alert('Year Entered has an invalid month.');
                                return false;
                        }

                        //create a lookup for months not equal to Feb.
                        var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
                                        '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}

                        //check if month value and day value agree
                        if(arrayLookup[arrayDate[0]] != null) {                        
                                if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)                                
                                return true; //found in lookup table, good date
                       		else {
                               		//alert('Date is invalid.');
                               		return false;
                        	}
                        }

                        //check for February
                        var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
                        if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0)
                                return true; //Feb. had valid number of days
                        else {  //alert('Day in Febuary date is invalid.');
                                return false; //any other values, bad date
                        }
                }
        }
        //else alert('Date must be in MM/DD/YYYY format. Please check your date.');
        return false;
}


function validateEmail( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid email pattern. 
 PARAMETERS:
   strValue - String to be tested for validity
RETURNS:
   True if valid, otherwise false.
   
REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) and optionally,
  a valid country suffix.  Since email has many
  forms this expression only tests for near valid
  address.  Some additional validation may be
  required.
*************************************************/
var objRegExp  = /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,3}(\.[a-z]{2}){0,2})$/i;
  //check for valid email
  return objRegExp.test(strValue);
}

function validateTime ( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid 12 hour time format. Seconds are optional.
 PARAMETERS:
   strValue - String to be tested for validity
RETURNS:
   True if valid, otherwise false
REMARKS: Returns True for time formats such as:
  HH:MM or HH:MM:SS or HH:MM:SS.mmm (where the
  .mmm is milliseconds as used in SQL Server 
  datetime datatype.  Also, the .mmm portion will 
  accept 1 to 3 digits after the period)
*************************************************/
  //var objRegExp = /^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/;
  var objRegExp = /([0-9]|0[0-9]|1[0-2]|2[0-3]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/;

  return objRegExp.test( strValue );

}
