
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;


function validateFloat(str){


      //str = strip(' \n\r\t',str);
      

      //remove leading zeros, if any
      while(str.length > 1 && str.substring(0,1) == '0'){
         str = str.substring(1,str.length);
      }
      var val = parseFloat(str);
      if(isNaN(val))
         return false;
      else
         return true;
   }

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++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

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){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	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 : mm/dd/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("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 true
}



function closeIt(e)
{



  if (document.forms.length > 0 )
  {
  
    if ( document.forms[0].elements['saveclicked'].value == 'off' )
     return;
	
  
	
  if ( document.forms[0].elements['saveclicked'].value != 'true' )
  {
  

	
	
     if ( document.forms[0].elements['dirty'].value =='true' )
     {
	
		
       event.returnValue = "Your changes will be lost.";
     
       
     }

  }
 }
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function






function validate(formname,skip)
{
	var errMsg = '';
	var i =0;
	var sReqID;
	var validatefield=true;
	
	
	try
	{
	if ( document.forms[0].elements["submitonce"].value = document.forms[0].elements["submitonce"].value > 1 )
	{
	alert("This appears to be a duplicate submission due to multiple clicks. Please wait for a system response before retrying.");
	window.event.returnValue = false;
	return false;
	
	}
	}
	catch (e)
	{
	}
	
	
	
	
	
	
	
	if ( skip == 1 )
	{
		try {
		document.forms[formname].elements["submitonce"].value = document.forms[0].elements["submitonce"].value + 1;
		}
		catch (e) {}
		return document.forms[formname].submit();
		
	
	
	}
	

	
	
	
	
	for (i=0;i<document.forms[formname].elements.length;i++)
	{
		//alert(document.forms[formname].elements[i].name	 + ":" + document.forms[formname].elements[i].type 	);
		 sReqID = new String(document.forms[formname].elements[i].id ); 

		 if ( document.forms[formname].elements[i].getAttribute("req") == "FW_REQ" )
		 {
		 
		 //check if table element and row for modified before validating
		 if ( document.forms[formname].elements[i].getAttribute("tabid") != '' && document.forms[formname].elements[i].getAttribute("tabid") != null)  //field part of some table.
		 {
		 
		 
			if (document.forms[formname].elements[document.forms[formname].elements[i].getAttribute("tabid")].value == 1) 
			{
			validatefield = true;
			}
			else
			{
			validatefield=false;
		  
			}
		}
		else
		{
		validatefield = true;
		 }
		 
		 
		 
		 
		 if ( validatefield  ) 
		 {
		 
			
			if (trim(document.forms[formname].elements[i].value) == '' ) 
			{
			alert("All the indicated required fields must be entered");
			document.forms[formname].elements[i].className="v_error";
			document.forms[formname].elements[i].focus();
			window.event.returnValue = false;
			
			return false;
			break;
			}
			else
			{
			
		 if (document.forms[formname].elements[i].type == 'text')
		 {
			switch ( document.forms[formname].elements[i].getAttribute("dttyp"))
			{
			case "MONEY":
					{
					
					
					if ( isNaN (removeCurrency(document.forms[formname].elements[i].value)) )
					{
						alert(document.forms[formname].elements[i].name + " must be a number!");
						document.forms[formname].elements[i].className="v_error";
						document.forms[formname].elements[i].focus();						
						window.event.returnValue = false;
			
						return false;
											
					}
					}
					break;
			case "NUMBER":
					{
					
					 
						if (validateFloat(document.forms[formname].elements[i].value)==false)
						{
	
						alert("Please Enter a Valid Number (do not include %, $");
						document.forms[formname].elements[i].className="v_error";
						document.forms[formname].elements[i].focus();						
						window.event.returnValue = false;
			
						return false;
											
						}
						
					}
					break;					
				
					
			case "PHONE":
					{
						if (checkInternationalPhone(document.forms[formname].elements[i].value)==false)
						{

						alert("Please Enter a Valid Phone Number");
						document.forms[formname].elements[i].className="v_error";
						document.forms[formname].elements[i].focus();						
						window.event.returnValue = false;
			
						return false;
											
						}
						
					}
					break;
			case "ZIP":
					{
						if (validateUSZip(document.forms[formname].elements[i].value)==false)
						{

						alert("Please Enter a Valid US Zipcode");
						document.forms[formname].elements[i].className="v_error";
						document.forms[formname].elements[i].focus();						
						window.event.returnValue = false;
			
						return false;
											
						}
					}
					break;					
				
			case "DATE":	
					{

						/*
						try
						{
						var sErrMsg = validateDate(document.forfsms[formname].elements[i].value,  "Date", new Array("MM/DD/YYYY"), false);
						}
						catch(e)
						{
							alert("ERROR CALLING FUNCION");
							alert(e.description);
						}
						
						alert(sErrMsg);
						*/

						
						if ( !isDate(document.forms[formname].elements[i].value))
						{
							document.forms[formname].elements[i].className="v_error";
							document.forms[formname].elements[i].focus();
							//alert(document.forms[formname].elements[i].value);
							window.event.returnValue = false;
			
							return false;
						}


						}
		
						break;	
			case "EMAIL":
				{

			var emailRe = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/
			phoneRe = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;

				 /*if (!(/^[\w\.]+@[\-|a-z|A-Z|0-9\.]+$/.test(document.forms[formname].elements[i].value)))*/
				if (!emailRe.test(document.forms[formname].elements[i].value))
					{
			 				alert(document.forms[formname].elements[i].name + " must be a valid email!");
			 				document.forms[formname].elements[i].className="v_error";
			 				document.forms[formname].elements[i].focus();
							window.event.returnValue = false;
							return false;
				
					}
				}
					break;
					

			} 			
			}
		 }
		 }
		 

		 }
		 
		 

	}
	
	
	if (errMsg != '')
	{
		alert (errMsg);
		return false;
	}
	try
	{
	//alert("here");
	var fnBaseValidate=new Function("sForm","return BaseValidate(sForm)");
	
	return fnBaseValidate(formname);
	
	}
	catch(e)
	{

	
	}
	
	try
	{
	document.forms[formname].elements["submitonce"].value = document.forms[formname].elements["submitonce"].value + 1;
	}
	catch (e)
	{}
	

	
	return document.forms[formname].submit();
	
}

function NewRecord(formname)
{
	var errMsg = '';
	var i;
	for (i=0;i<document.forms[formname].elements.length;i++)
	{
	//alert(document.frmMaintenance.elements[i].type);
	
	
	
	if ( document.forms[formname].elements[i].fix != 'y')  //*** for fields which have this attribute set to y, do not clear since
	{
		
	 if (document.forms[formname].elements[i].type == 'text' || document.forms[formname].elements[i].type =='hidden' )
	 {
		document.forms[formname].elements[i].value = '';
	 }
	 if (document.forms[formname].elements[i].type == 'textarea')
	 {
		document.forms[formname].elements[i].innerText = "";
	 }
	 if (document.forms[formname].elements[i].type == 'checkbox')
	 {
		document.forms[formname].elements[i].checked =0;
	 }
	}
	}

	return true;
}


function Keydetect()
{


 if ( document.forms.length > 0 )
	{
  
   if (!window.event.shiftKey && !window.event.ctrlKey && !window.event.altKey )
   {
     document.forms[0].elements['dirty'].value='true';
   }
 }
}





	function ProcessChange(val, e) 
	{
		//alert(val);
		//alert(document.forms(0).elements(val).value);
		
		document.forms[0].elements[val].value=1;
		document.forms[0].elements["dirty"].value = 'true';
		
		
		   var myevent = e ? e : window.event;  // to handle both NS and IE events
			var target = myevent.target ? myevent.target : myevent.srcElement;
		
		

		
		//alert(e.target.name);
		try 
		{
		
	
		
				if (target.name != ("chk_" +val) ) //if user clicked the check box itself, then do not change the check status via code.
				{
				document.forms[0].elements["chk_"+val].checked="1";
				}
				else
				{
					//alert(document.forms[0].elements["chk_"+val].checked);
				  if ( document.forms[0].elements["chk_"+val].checked == "0" )  //if user change some text field but unchecked sel check box, then mark row not changed.
				  {
				  document.forms[0].elements[val].value=0;
				  }
				}

		}
		catch(e)
		{
		//ignore
		}
		
		//alert("here");
		
	}
	
	
// Title: Tigra Calendar
// URL: http://www.softcomplex.com/products/tigra_calendar/
// Version: 3.2 (American date format)
// Date: 10/14/2002 (mm/dd/yyyy)
// Feedback: feedback@softcomplex.com (specify product title in the subject)
// Note: Permission given to use this script in ANY kind of applications if
//    header lines are left unchanged.
// Note: Script consists of two files: calendar?.js and calendar.html
// About us: Our company provides offshore IT consulting services.
//    Contact us at sales@softcomplex.com if you have any programming task you
//    want to be handled by professionals. Our typical hourly rate is $20.

// if two digit year input dates after this year considered 20 century.
var NUM_CENTYEAR = 30;
// is time input control required by default
var BUL_TIMECOMPONENT = false;
// are year scrolling buttons required by default
var BUL_YEARSCROLL = true;

var calendars = [];
var RE_NUM = /^\-?\d+$/;

function calendar2(obj_target) {

	// assing methods
	
	this.gen_date = cal_gen_date2;
	this.gen_time = cal_gen_time2;
	this.gen_tsmp = cal_gen_tsmp2;
	this.prs_date = cal_prs_date2;
	this.prs_time = cal_prs_time2;
	this.prs_tsmp = cal_prs_tsmp2;
	this.popup    = cal_popup2;

	// validate input parameters
	if (!obj_target)
		return cal_error("Error calling the calendar: no target control specified");
	if (obj_target.value == null)
		return cal_error("Error calling the calendar: parameter specified is not valid tardet control");
	this.target = obj_target;
	this.time_comp = BUL_TIMECOMPONENT;
	this.year_scroll = BUL_YEARSCROLL;
	
	// register in global collections
	this.id = calendars.length;
	calendars[this.id] = this;
}

function cal_popup2 (str_datetime) {
	this.dt_current = this.prs_tsmp(str_datetime ? str_datetime : this.target.value);
	if (!this.dt_current) return;
	


	var obj_calwindow = window.open(
		'../include/calendar.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id,
		'Calendar', 'width=200,height='+(this.time_comp ? 215 : 190)+
		',status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes'
	);
	obj_calwindow.opener = window;
	obj_calwindow.focus();
}

// timestamp generating function
function cal_gen_tsmp2 (dt_datetime) {
	return(this.gen_date(dt_datetime) + ' ' + this.gen_time(dt_datetime));
}

// date generating function
function cal_gen_date2 (dt_datetime) {
	return (
		(dt_datetime.getMonth() < 9 ? '0' : '') + (dt_datetime.getMonth() + 1) + "/"
		+ (dt_datetime.getDate() < 10 ? '0' : '') + dt_datetime.getDate() + "/"
		+ dt_datetime.getFullYear()
	);
}
// time generating function
function cal_gen_time2 (dt_datetime) {
	return (
		(dt_datetime.getHours() < 10 ? '0' : '') + dt_datetime.getHours() + ":"
		+ (dt_datetime.getMinutes() < 10 ? '0' : '') + (dt_datetime.getMinutes()) + ":"
		+ (dt_datetime.getSeconds() < 10 ? '0' : '') + (dt_datetime.getSeconds())
	);
}

// timestamp parsing function
function cal_prs_tsmp2 (str_datetime) {
	// if no parameter specified return current timestamp
	if (!str_datetime)
		return (new Date());

	// if positive integer treat as milliseconds from epoch
	if (RE_NUM.exec(str_datetime))
		return new Date(str_datetime);
		
	// else treat as date in string format
	var arr_datetime = str_datetime.split(' ');
	return this.prs_time(arr_datetime[1], this.prs_date(arr_datetime[0]));
}

// date parsing function
function cal_prs_date2 (str_date) {

	var arr_date = str_date.split('/');

	if (arr_date.length != 3) return alert ("Invalid date format: '" + str_date + "'.\nFormat accepted is dd-mm-yyyy.");
	if (!arr_date[1]) return alert ("Invalid date format: '" + str_date + "'.\nNo day of month value can be found.");
	if (!RE_NUM.exec(arr_date[1])) return alert ("Invalid day of month value: '" + arr_date[1] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[0]) return alert ("Invalid date format: '" + str_date + "'.\nNo month value can be found.");
	if (!RE_NUM.exec(arr_date[0])) return alert ("Invalid month value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
	if (!arr_date[2]) return alert ("Invalid date format: '" + str_date + "'.\nNo year value can be found.");
	if (!RE_NUM.exec(arr_date[2])) return alert ("Invalid year value: '" + arr_date[2] + "'.\nAllowed values are unsigned integers.");

	var dt_date = new Date();
	dt_date.setDate(1);

	if (arr_date[0] < 1 || arr_date[0] > 12) return alert ("Invalid month value: '" + arr_date[0] + "'.\nAllowed range is 01-12.");
	dt_date.setMonth(arr_date[0]-1);
	 
	if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
	dt_date.setFullYear(arr_date[2]);

	var dt_numdays = new Date(arr_date[2], arr_date[0], 0);
	dt_date.setDate(arr_date[1]);
	if (dt_date.getMonth() != (arr_date[0]-1)) return alert ("Invalid day of month value: '" + arr_date[1] + "'.\nAllowed range is 01-"+dt_numdays.getDate()+".");

	return (dt_date)
}

// time parsing function
function cal_prs_time2 (str_time, dt_date) {

	if (!dt_date) return null;
	var arr_time = String(str_time ? str_time : '').split(':');

	if (!arr_time[0]) dt_date.setHours(0);
	else if (RE_NUM.exec(arr_time[0])) 
		if (arr_time[0] < 24) dt_date.setHours(arr_time[0]);
		else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed range is 00-23.");
	else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed values are unsigned integers.");
	
	if (!arr_time[1]) dt_date.setMinutes(0);
	else if (RE_NUM.exec(arr_time[1]))
		if (arr_time[1] < 60) dt_date.setMinutes(arr_time[1]);
		else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed range is 00-59.");
	else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed values are unsigned integers.");

	if (!arr_time[2]) dt_date.setSeconds(0);
	else if (RE_NUM.exec(arr_time[2]))
		if (arr_time[2] < 60) dt_date.setSeconds(arr_time[2]);
		else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed range is 00-59.");
	else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed values are unsigned integers.");

	dt_date.setMilliseconds(0);
	return dt_date;
}

function cal_error (str_message) {
	alert (str_message);
	return null;
}


/**
 * 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);
}

function cent(amount) {
// returns the amount in the .99 format 
    amount -= 0;
    amount = (Math.round(amount*100))/100;
    return (amount == Math.floor(amount)) ? amount + '.00' : (  (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount);
}

	
function removeCurrency( strValue )
{
/************************************************
DESCRIPTION: Removes currency formatting from
  source string.

PARAMETERS:
  strValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /\(/;
  var strMinus = '';
    //check if negative
  if(objRegExp.test(strValue)){
    strMinus = '-';
  }
  objRegExp = /\)|\(|[,]/g;
  strValue = strValue.replace(objRegExp,'');
    if(strValue.indexOf('$')>= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;




}

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 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 checkall(e)
{
   //alert(window.event.srcElement.tabid);
   //alert(window.event.srcElement.chkname);
   
   //alert(window.event.srcElement.checked);
   
   var myevent = e ? e : window.event;  // to handle both NS and IE events
   var target = myevent.target ? myevent.target : myevent.srcElement;
   
   //alert(target.id);
   
   
 //alert(document.getElementById(target.getAttribute("chkname"));
 //alert(window.event.srcElement.chkname);
   
   var i=1;
   var chknm;
   var tablerowcount=0;
   // //chknm = window.event.srcElement.chkname;
   chknm = target.getAttribute("chkname");
   //alert(chknm);
   
   // //tablerowcount = document.forms[0].elements[window.event.srcElement.tabid + "ROWCount"].value;
   tablerowcount = document.forms[0].elements[target.getAttribute("tabid") + "ROWCount"].value;
   //alert(tablerowcount);
   
   
   while ( i <= tablerowcount )
   {
	try {
	document.forms[0].elements[chknm + i].checked = target.checked;
	}
	catch (e)
	{
	// do nothing on error.
	}
	
	i++;
   }
   
   
   
}


function validateEmail(val)
{
	if (!(/^[\w\.]+@[\-|a-z|A-Z|0-9\.]+$/.test(val))) 
	{
		alert(document.forms[formname].elements[i].name + " must be a valid email!");
		return false;
				
	}
	return true;
}


