/* 
############################################################################
  JavaScript Validation Functions
  Author: Mithun @ Unosoft Technologies
  Last Modified: 07/05/2008 by Kumar Bhogaraju
############################################################################
*/

/*
------------------------------------------------------------------------------
    FUNCTION NAME: validateField
	DESCRIPTION: This function validates the field based on the value in the ALT tag. It
				 expects following values in the ALT tag. If a field needs to have multiple
				 validations, seperate the values with a hypen between them like NUMBER-ALPHABET:
				 
				 1. EMAIL 				- Indicates that the field needs to be validated for correct Email format
				 2. DATE  				- Checks to see if the date is valid. If it is valid, reformats the date to DD-MM-YYYY.
				 3. NUMBER  			- Checks to see if there are any characters other than numbers. +, -, . are allowed.
				 4. ALPHABET 			- Checks to see that characters entered are only alphabets. Spaces are allowed.
				 5. ALPHANUMERIC 		- Checks to see that the characters are either numbers or alphabets. Spaces are allowed.
				 6. FORMATCURRENCY		- Formats currency.
				 7. REQUIRED			- Need user input.
				 8. UPPER				- Converts the field value to Upper Case 
				 9. DIGITS				- Takes only numbers (will not accept +, - and .)
				10. PAN					- PAN Validation
				11. ANYSTART			- Start Date cannot be lesser than 01-01-1900
				12. FYSTARTSTART			- Financial start date - >= 01-04-YYYY (current year).
				13. TODAY				- Verifies if the date entered is the current date or not.
				14. TODAYEND			-- Date before today
				15. FYENDSTART			-- After the financial year end... >= 01-04-YYYY
				16. FYENDEND				-- Before the financial year end... < 01-04-YYYY
				17. TODAYSTART			-- Greater than or equal to today
    INPUT PARAMETER: 
			formField - Form Field object.
	RETURNS: true if validation is successful
			 false if validation fails
-------------------------------------------------------------------------------
*/

function validateField(formField) { 

    // This function expects the formField passed in to have ALT tag. If it does not exist, skip validation.
    if (!formField.getAttribute('alt')) {
         return true;
    }
        
    // Set the retVal to true initially. If the validations fails, return false.
    var retVal = true;
    var mesg = "";
    
   // Reset old messages. 
   if (trim(formField.value).length == 0) {
       setMessage(formField,"");
       return true;
    }

	// Get the event that fired us.
    var e = window.event;  		
     if (!e)
        e = validateField.caller.arguments[0];
   
   // The ALT tag of the INPUT tag tells us the datatype. 
   // If we need to validate the field for more than one function, they are separated with a hyphen (-).
   

   	valList = formField.alt.split("-");    
    

    for (var j = 0; j< valList.length; j++) {
		switch (valList[j]) {
		  case "ALPHABET": 
			  if (!isAlphabetic(formField.value)) {
			    mesg = "Only alphabets are allowed in this field.";
			    retVal = false;
			  }
			  break;
		  case "NUMBER": 
			  if (!validateNumber(formField)) {
			    mesg = "Only numbers are allowed in this field.";
			    retVal = false;
			  }			 
			  break;
		  case "ALPHANUMERIC": 
			  if (!isAlphaNumeric(formField.value)) {
			    mesg = "Only alphabets and numbers are allowed in this field.";
			    retVal = false;
			  }	 
			  break;
		  case "EMAIL": 
			  if (!isValidEmail(formField.value)) {
			    mesg = "The email address you entered does not appear to be a valid address.";
			    retVal = false;
			  }
			  break;	 
		  case "DIGITS":
		      if (trim(formField.value) != "") {
			  	  var reExp = /[^0-9]/
			  	  if (reExp.test(formField.value)) {
			  	    mesg = "Only numbers are allowed in this field";
			  	    retVal = false;
			  	  }
		  	  }
		  	  break;
		  case "DATE": 

				   // Check Required Field validations only on Submit and blur...not on Key events.
				   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {
				  			mesg = isDate(formField);
					  	    if ( mesg != "true") 
						      retVal = false;
					        else 
					  	      mesg = "";
	   			  	       	
	  				 } else {
	  				 
	  				   mesg = onKeyValidateDate(formField);
	  				 //  alert("Message is " + mesg);
	  				   if ( mesg != "true") 
						      retVal = false;
					        else 
					  	      mesg = "";
					 }
			  break;
		  case "FORMATMONTHNUM": 
		        var reExp = /^-/;
		        if (reExp.test(formField.value)) {
		          mesg = "Only positive numbers are allowed."; 
		          retVal = false;
		        }
		        else {
		          mesg = "";
                  if (!formatCurrency(formField)) {
                      mesg = "Invalid month";
                      retVal = false;
    		          }
    		      else {
    		      	// remove commas in the field
				    var cleanedNumber = formField.value.replace(/,/g,"");
				    if (cleanedNumber > 12.00) {
				       mesg = "Number cannot exceed 12.00";
				       retVal = false;
				    }
    		      }
    		   }
			  break;

		  case "FORMATSTOCKMFNUM": 
		        var reExp = /^-/;
		        if (reExp.test(formField.value)) {
		          mesg = "Only positive numbers are allowed."; 
		          retVal = false;
		        }
		        else {
		          mesg = "";
                  if (!formatCurrency(formField)) {
                      mesg = "Invalid number";
                      retVal = false;
    		          }
    		      else {
    		      	// remove commas in the field
				    var cleanedNumber = formField.value.replace(/,/g,"");
				    if (cleanedNumber > 99999.99) {
				       mesg = "Number cannot exceed 99999.99";
				       retVal = false;
				    }
    		      }
    		   }
			  break;

		  case "FORMATCURRENCY": 
                   if (!formatCurrency(formField)) {
                      mesg = "Invalid currency format";
                      retVal = false;
                   } else {
    		      	// remove commas in the field
				    var cleanedNumber = formField.value.replace(/,/g,"");
				    if ((cleanedNumber > 99999999.99) || (cleanedNumber < -99999999.99)) {
				       mesg = "Number should be between -99999999.99  and +99999999.99";
				       retVal = false;
				    }
    		      }                     
			  break;
		  case "FORMATPOSCURRENCY": 
		        var reExp = /^-/;
		        if (reExp.test(formField.value)) {
		          mesg = "Only positive numbers are allowed."; 
		          retVal = false;
		        }
		        else {
		          mesg = "";
                  if (!formatCurrency(formField)) {
                      mesg = "Invalid currency format";
                      retVal = false;
    		          }
    		      else {
    		      	// remove commas in the field
				    var cleanedNumber = formField.value.replace(/,/g,"");
				    if (cleanedNumber > 99999999.99) {
				       mesg = "Number cannot exceed 99999999.99";
				       retVal = false;
				    }
    		      }
    		   }
			  break;
		  case "FORMATNEGCURRENCY": 
			  break;
		  case "PAN":
				   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {

		      if (trim(formField.value) != "") {
		  
		  		var reExp = /^[A-Z]{5}[0-9]{4}[A-Z]$/;
		  		if (!reExp.test(formField.value)) {
		  		   mesg = "Invalid PAN.";
		  		   retVal = false;
		  		}
		  	   }}
		  		break;
		  case "TAN":

				   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {

		    if (trim(formField.value) != "") {
		  		var reExp = /^[A-Z]{4}[0-9]{5}[A-Z0]{1}$/;
		  		if (!reExp.test(formField.value)) {
		  		   mesg = "Invalid TAN.";
		  		   retVal = false;
		  		}
		  	}}
		  		break;

		  case "REQUIRED":
   
				   // Check Required Field validations only on Submit and blur...not on Key events.
				   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {

				  		if (formField.value == "") {
				  			// The following line is hanging IE 6
				  		   // formField.focus();
				  		   retVal = false;
				  		   mesg = "User input required. This is a mandatory field.";
				  		}
   				   }
		  		   break;   
		  case "UPPER":
			
		    var code;
		    if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
	
			var character = String.fromCharCode(code);
			// Convert to upper only if the value entered is alphanumeric. This takes care of the arrow key issue.
			 if (isAlphabetic(character)) 
		  		upperCase(formField);				
		  		break;

		  case "ANYSTART":
		   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {

 		      if (trim(formField.value) != "") {
 		      
 		          mesg = checkDateBounds(formField.value,"01-01-1900","");
 		          if (mesg != "true") 
		  			retVal = false;
		  		else
		  			mesg = "";
			   }
              }             
		  		break;
		  case "FYSTARTSTART":
		   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {
 		      if (trim(formField.value) != "") {		  
		  		var d = new Date();
		  		// Try to figure Final Year Start.
		  		var year = d.getFullYear();
		  		
				if ((d.getMonth()	> 2) && (d.getMonth() <= 12))
					year--;
				else 
					year = year - 2;
	  		   	         
 		  		date = "01-04-";
 		  		year = getAYFrmCookie();
 		  		start_yr = parseInt(year);
 		  		start_yr -=1;
			  	fyStart = date.concat(start_yr.toString());
		  		
		  		mesg = checkDateBounds(formField.value,fyStart,"");		  		
		  		if (mesg != "true") 
		  			retVal = false;
		  		else
		  			mesg = "";
			   }
             }
		  		break;
		  case "FYENDEND":
				   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {

		     if (trim(formField.value) != "") {
		  		var d = new Date();
		  		
		  	// Try to figure Final Year End.
		  		var year = d.getFullYear();

				if ((d.getMonth()	> 2) && (d.getMonth() <= 12))
					year;
				else 
					year = year - 1;
		  		
 		  		date = "31-03-";
 		  		year = getAYFrmCookie();
			  	fyEnd = date.concat(year);

		  		mesg = checkDateBounds(formField.value,"",fyEnd);		  		
		  		if (mesg != "true") 
		  			retVal = false;
		  		else
		  			mesg = "";
			  }
              }
		  		break;
		  case "FYENDSTART":
				   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {

		     if (trim(formField.value) != "") {
		  		var d = new Date();
		  		
		  	// Try to figure Final Year End.
		  		var year = d.getFullYear();

				if ((d.getMonth()	> 2) && (d.getMonth() <= 12))
					year;
				else 
					year = year - 1;
		  		
 		  		date = "01-04-";
 		  		year = getAYFrmCookie();
			  	fyEnd = date.concat(year);

		  		mesg = checkDateBounds(formField.value,fyEnd, "");		  		
		  		if (mesg != "true") 
		  			retVal = false;
		  		else
		  			mesg = "";
			  }
              }
		  		break;
		  case "TODAYEND":
				   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {

		   	if (trim(formField.value) != "") {
		   		//var d = new Date();
                //d.setTime(0)

				var today = today_date; //d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getYear();

		  		mesg = checkDateBounds(formField.value,"", today);		  		
		  		if (mesg != "true") {
		  			retVal = false;
		  		}
		  		else {
		  			mesg = "";
				}
			}
            }           
		  		break;
		  case "TODAYSTART":
				   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {

		   	if (trim(formField.value) != "") {
                var today = today_date;
		   		//var d = new Date();

				//var today = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear();

		  		mesg = checkDateBounds(formField.value,today,"");		  		
		  		if (mesg != "true") {
		  			retVal = false;
		  		}
		  		else {
		  			mesg = "";
				}
			}
            }           
		  		break;
		  case "TODAY":
		if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {

		   	if (trim(formField.value) != "") {
                var today = today_date;
		   		//var d = new Date();
				//var today = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear();

		  		mesg = checkDateBounds(formField.value,today, today);		  		
		  		if (mesg != "true") {
		  			retVal = false;
		  		}
		  		else {
		  			mesg = "";
				}
			}
            }           
		  		break;
	
		  default: 
		  		break;	 
      	} // End of Switch block
      	
   
      	if (!retVal) {
      		setMessage(formField,mesg);
      		return retVal;
      	}
      	
      	if (retVal) {
      		setMessage(formField,"");
      	}
    }  	// End of loop
    return retVal;
  
 } //End of Function

function getAYFrmCookie() {
    var name = "taxspanner_cookie";
    var nameEQ = name + "=";
    var year_arr=new Array('2008','2009','2010','2011','2012','2013','2014','2015');
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0){ 
            var cookie_val = c.substring(nameEQ.length,c.length);
            for (var j=0; j<year_arr.length;j++) {
                if (cookie_val.search(year_arr[j]) != -1) {
                    return year_arr[j];}
            }
        }
    }
    return '0000';
}


/*
------------------------------------------------------------------------------
    FUNCTION NAME: validateForm
	DESCRIPTION: This is the master level Form validation function. It dynamically
				 loops through all the fields in a given form and checks validation. 
    INPUT PARAMETER: 
			formName - Useful if there are more than one form in the document.
	RETURNS: true if validation is successful
			 false if validation fails
	DEPENDENCIES: validateField()
-------------------------------------------------------------------------------
*/

function validateForm(formName) 
{
  // Reset the DIV tag first.
  
   var divObject = document.getElementById("errorpanel");

  // If the form does not have a DIV object with ErrorPanel, move on.
  if (!divObject) {
    return;
  } else {
    divObject.innerHTML = "";
    divObject.visible = "hidden";
  }


   var f = document.forms[formName];
   var formField, valList;
   
   // Set the return value of the validation to true initially.
   var retVal = true; 
   
   for (var i = 0; i < f.elements.length; i++) {
       formField = f.elements[i];
       // If the field valiation fails, set retVal to false.
	   if (!validateField(formField)) {
	   	 retVal = false;
	   } 
    }   	  
    
    if (!retVal)
       alert("There are some errors in the data. Please correct before proceeding.");
     
    return retVal; 
}

/*
-----------------------------------------------------------------------------------------
    FUNCTION NAME: setMessage
	DESCRIPTION: This function is used to set error messages in the next, adjacent SPAN tag. 
    INPUT PARAMETER: 
			formField - Form Field Object.
			mesg	  - Message to be displayed in the span tag.
	RETURNS: None
	DEPENDENCIES: None
-----------------------------------------------------------------------------------------
*/
function setMessage(formField,mesg) {
  
  var divObject = document.getElementById("errorpanel");
  
  if (mesg != "") formField.style.background = "red";
  
  // If the form does not have a DIV object with ErrorPanel, move on.
  if (!divObject) {
    return;
  }
  defbgcolor = "#BEDCFF"; /* #eBEFE7"; */

	// Get the event that fired us.
    var e = window.event;  		
     if (!e)
        e = validateField.caller.arguments[0];
 
	     if ((e.type == "submit") ||( e.type == undefined)) {
	       defbgcolor = "white";
		   if (divObject.innerHTML != "") {
		     return ;
		   }
		 }

 // Get the Form Field coordinates
  var fieldCoords = findPos(formField);
 
 // Get the errorpanel coordinates       
  var divCoords = findPos(divObject);
 
    if (mesg != "") {
       divObject.innerHTML = mesg;
       divObject.style.visibility = "visible";
       // unhighlightInput(formField.getAttribute('id'));
       formField.style.background = "red";
       divObject.style.left = fieldCoords[0] + "px";
       divObject.style.top = fieldCoords[1] + + 20 + "px";
    } else {
      // Message is null.
	    if ((divCoords[0] == fieldCoords[0]) && (divCoords[1] == (fieldCoords[1] + 20))) {      
	    	divObject.innerHTML = "";
	    	divObject.style.visibility = "hidden";
			formField.style.background = defbgcolor;	  	  
	    } 
    
    }
}

  
/*
-----------------------------------------------------------------------------------------
    FUNCTION NAME: getNextSibling
	DESCRIPTION: This function returns the next sibling ELEMENT_NODE
    INPUT PARAMETER: 
			formField - Form Field Object.
	RETURNS: None
	DEPENDENCIES: None
-----------------------------------------------------------------------------------------
*/
  
function getNextSibling(startElement){
   endElement = startElement.nextSibling;
   // makes sure that the element exists and it is an ELEMENT_NODE.
  while(endElement) {
    if (endElement.nodeType != 1){
     endElement = endElement.nextSibling;
     break;
    }
  }
  return endElement;
}

/*
------------------------------------------------------------------------------
    FUNCTION NAME: isValidEmail
	DESCRIPTION: Checks if the passed in String is in valid email "format" or not.
				 Note that this function does NOT validate if the email or its domain
				 really exists or not.
    INPUT PARAMETER: 
		addr - Email Address passed in
	RETURNS: true if the string passed in is in correct format.
			 false if the string is either empty or in invalid format.
	DEPENDENCIES:
			emailCheck();
			validateOnKeyEmail();
-------------------------------------------------------------------------------
*/
function isValidEmail(addr) 
{
 
   if (addr == "")
     return true;
    
   var reEmail;
   
   // Assume user is using IE
   var e = window.event;
   
   // bad assumption, user is not using IE
   if (!e) 
     e = validateField.caller.arguments[0];
    
   // Check the type of event that fired.
   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {
     return emailCheck (addr);
   }

    return validateOnKeyEmail(addr);
    
}
/*
------------------------------------------------------------------------------
    FUNCTION NAME: rTrim
	DESCRIPTION: Trims space, Tab, New Line Char and CR on the RHS of the string passed in.
    INPUT PARAMETER: 
		str - String passed in.
	RETURNS: rtrimmed string
-------------------------------------------------------------------------------
*/
function rTrim(str)
{
  var whitespace = new String(" \t\n\r");

  var s = new String(str);

  if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
    var i = s.length - 1;  
    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
	{
      i--;
      s = s.substring(0, i+1);
	}
  }
  return s;
}
/*
------------------------------------------------------------------------------
    FUNCTION NAME: trim
	DESCRIPTION: Trims space, Tab, New Line Char and CR on both LHS and RHS of the string passed in.
    INPUT PARAMETER: 
		str - String passed in.
	RETURNS: trimmed string
	DEPENDENCIES: none
-------------------------------------------------------------------------------
*/
function trim(str)
{
      var reTrim = /^(\s*)(.*?)(\s*?)$/;
    
	  if (reTrim.test(str)) 
       	  return RegExp.$2;
      else 
       	return str;
}

/*
-------------------------------------------------------------------------------
	FUNCTION NAME: validateNumber
	DESCRIPTION:   Checks whether the parameter passed in is a valid number or not.
	INPUT PARAMETER: 
		val - Input entered by user
	RETURNS: true if its a number (float, int etc); Else, returns false.
-------------------------------------------------------------------------------
*/

function validateNumber(formField)
{
     
  if (formField.value == "")
    return true;
   
  var reExp = /\s/;    
  if (reExp.test(formField.value))
    return false;
   
   
	// Assume user is using IE
	  	var e = window.event;  
		// bad assumption, user is not using IE
		if (!e) 
		     e = validateField.caller.arguments[0];

		   // Check the type of event that fired.
		   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {
		     if (isNaN(Math.abs(formField.value)))
			    return false;
  		     else  {
  		        // formField.value = Math.abs(formField.value);  		           
     		    return true;
 			 }
		   }
    
		  // On Key Events...ignore if the only char is .
		 if ((formField.value == ".")||(formField.value == "-")||(formField.value == "+"))
	       return true;
   
		  if (isNaN(Math.abs(formField.value)))
			    return false;
  		  else {
     		    return true;
     		   }
     		       
}


/*
----------------------------------------------------------------------------						

	FUNCTION NAME: upperCase
    DESCRIPTION:  Takes field name has input and changes the text within the field to upper case.
 	INPUT PARAMETER:  
		Comp - Input field name
	RETURNS: NONE
----------------------------------------------------------------------------							
*/

function upperCase(formField)
{
	str = formField.value;
	formField.value = str.toUpperCase();
}

/*
--------------------------------------------------------------------------
	FUNCTION NAME: isAlphaNumeric
	DESCRIPTION:   Checks if the field contains only AlphaNumeric chars or not.
	INPUT PARAMETERS:
			addr - Input text.

--------------------------------------------------------------------------
*/

function isAlphaNumeric(addr)
{
    if (addr == "") 
       return true;
       
	var noalpha = /^[a-zA-Z0-9]*$/;
	
	if (!noalpha.test(addr)) 
		return false;
	else
		return true;
}
/*
--------------------------------------------------------------------------
	FUNCTION NAME: formatCurrency
	DESCRIPTION:   Formats the currency field.
	INPUT PARAMETERS:
			addr - Input text.
	DEPENDENCIES:
		checkRepeatingSpecChars()
		formatCurrencyOB();

--------------------------------------------------------------------------
*/


function formatCurrency (formField) {
   var decPart = "";
   if (formField.value == "")
     return true;
   
   var reExp = /\s/;
   if (reExp.test(formField.value))
     return false;  
     
   // Assume user is using IE
   var e = window.event;
   
   // bad assumption, user is not using IE
   if (!e) 
     e = validateField.caller.arguments[0];

   // Not onBlur...must be onKey events...just validate user input.
    if (checkRepeatingSpecChars(formField.value)) 
      return false;

     if ((formField.value).indexOf(".") > 0) {    
	  //Get the decimal part
	  decPart = (formField.value).substr((formField.value).indexOf("."));
	} 

	if (decPart.length > 3) {
	  return false;
	}
	
      
   // Check the type of event that fired.
   if ((e.type == "submit") ||( e.type == undefined) ||(e.type == "blur")) {
   
     if (formatCurrencyOB (formField.value) == "")
       return false;
         
     formField.value = formatCurrencyOB (formField.value);
     return true;
   }
   
   if ((formField.value == ".")||(formField.value == "-")||(formField.value == "+"))
     return true;
   
   // Remove any commas that user entered.
	var cleanedNumber = formField.value.replace(/,/g,"");

   // Take care of exponential issues 10e2 should not become 1000.
    var reExp = /e/;
    
    if (reExp.test(cleanedNumber))
      return false;
      
    if (isNaN(Math.abs(cleanedNumber)))
      return false;
    else
      return true;
}
/*
--------------------------------------------------------------------------
	FUNCTION NAME: formatCurrencyOB
	DESCRIPTION:   Formats the parameter passed in to NN,NN, NNNN.NN format. This
				   function should be called only after user completes typing (onBlur).
	INPUT PARAMETERS:
			num - Number to be formatted.
--------------------------------------------------------------------------
*/

function formatCurrencyOB(num)
{

   // Nothing to do, if the string is either null or just has blank spaces.
	if (trim(num) == "") {
		return "";
	}
	
	// Remove any commas that user entered.
	var cleanedNumber = num.replace(/,/g,"");

 // Take care of exponential issues 10e2 should not become 1000.
    var reExp = /e/;
    
    if (reExp.test(cleanedNumber))
      return "";

	var negNumber = false;

	// parseFloat removes invalid chars...so just check with ABS.
	if (isNaN(Math.abs(cleanedNumber)))
	  return ""; 
	   	
  
	// Check if we can convert it into Float.
	cleanedNumber = parseFloat(cleanedNumber);
	
	// Round the number
	cleanedNumber = cleanedNumber.toFixed(2);
	
   
    if (cleanedNumber < 0) {
      negNumber = true;
      cleanedNumber = Math.abs(cleanedNumber);
      cleanedNumber = cleanedNumber.toString();
    }

	var decPart = ".00";
	
	if (cleanedNumber.indexOf(".") > 0) {    
	  //Get the decimal part
	  decPart = cleanedNumber.substr(cleanedNumber.indexOf("."));
	}
		
	var intPart = (parseInt(cleanedNumber)).toString();
	
	
	// String that will be returned
	var retStr = intPart;
	 
	  
	if (intPart.length <= 3) {
	  if (negNumber) {
	    intPart = "-" + intPart.toString();
	  }
	  return intPart + decPart;
	}
	
	// This variable indicates the number of times looped
	var j = 0;
	
	// Process from the end of the number and start appending , as necessary
	for(var i=0; i < intPart.length; i++)
	{			
			if ((i%2) && (i > 1))
			{
				lStr = retStr.substr(retStr.length - i -j);				
				retStr = intPart.substr(0, intPart.length -i) + "," + lStr;
				j++;
			}
	 }

	 if (retStr.length > 3) {
		 retStr = retStr + decPart;
	 }
	else 
	 {
	   retStr = "0" + decPart;
   }

   
    if (negNumber) {
      retStr = "-" + retStr;
    }
    	   
	return retStr;	 
}
/*
--------------------------------------------------------------------------
	FUNCTION NAME: isAlphabetic
	DESCRIPTION:   Checks that the field has only alphabets.
	INPUT PARAMETERS:
			val - String passed in
	RETURNS: true or false.
--------------------------------------------------------------------------
*/

function isAlphabetic(val)
{
   if (val.length == 0) return true;
   
	var noalpha = /^[a-z ]*$/i;
	if (!noalpha.test(val)) 
	{
		return false;
	} else
	   return trim(val);
}

/*
--------------------------------------------------------------------------
	FUNCTION NAME: isNum
	DESCRIPTION:   Checks that the field has only numbers and decimal digit.
	INPUT PARAMETERS:
			val - number passed in
	RETURNS: true or false.
--------------------------------------------------------------------------
*/

function isNum(val)
{
   var validChars = /[^0-9.]/;
   
   if (validChars.test(val)) {
   	return false;
   	}
   else {
     var s = /[^.{0,1}]/g;
     if (s.test(val)) {
     	return true;
     	}
       else return false;
   }

}
/*
--------------------------------------------------------------------------
	FUNCTION NAME: isDate
	DESCRIPTION:   Checks if the field has a valid date or not.
	INPUT PARAMETERS:
			formField - Form Field Object.
	RETURNS:
			true - if the value is valid date, else - return false.
	DEPENDENCIES: None
--------------------------------------------------------------------------
*/
function isDate(formField) {

	var strDate = formField.value;
	if (strDate == "")
	   return "true";
	
	// Array to split the date string and store day, month and year separately.
	var strDateArray;
	
	// Parse and store the date string in String format.
	var strDay, strMonth, strYear;
	
	// Parse and store day, month and year in Integer objects.
	var intday, intMonth, intYear;
	
	var booFound = false;
	
	// Possible seperators in a date string.
	var strSeparatorArray = new Array("-"," ","/",".");
	
	var intElementNr;
	
	var errMessage = "SUCCESS";
	
	// Array of Months.
	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";
	
	// Check if user entered any value or not.
	if (strDate.length == 0) {
	   return "true";
	}
	
	// Check if user entered date using the separators mentioned in strSeparatorArray.
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) {
				return "Invalid Date Format. Please enter the date in DD-MM-YYYY format.";
			}
			else {
				strDay =    strDateArray[0];
				strMonth =  strDateArray[1];
				strYear =   strDateArray[2];
			}
		booFound = true;
	   }
	} // for loop
	
	// User probably did not mention separators
	if (booFound == false) {
	   return "Invalid date format. Please enter the date in DD-MM-YYYY format.";
	}
	
	// Check if we have a 2 digit year.
	
	var regExp = /\d*/g;
	
	if (strYear == null)
	   return "Invalid Year";
	   	
	if (!regExp.test(strYear)) 
	    return "Invalid Year";

/*
	if (strYear.length == 2) {      
		if (Math.abs(strYear) >= 50) {
		  strYear = '19' + strYear;
		} else {
		    strYear = "20" + strYear;
		 }
	}
*/
	if (strYear.length != 4)
	  return "Invalid Year. Please enter date in DD-MM-YYYY format";
	intday = Math.abs(strDay);
	
	if (isNaN(intday)) {
		return "Invalid Date. Date is not a valid number";
	}

	intMonth = Math.abs(strMonth);

    // Check if user used Month in strings		
	 if (isNaN(intMonth)) {
		return "Invalid Month.";
	   }
	
	intYear = Math.abs(strYear);
	
	if (isNaN(intYear)) {
		return "Invalid Year";
	}
	
	if (intMonth>12 || intMonth<1) {
	   return "Invalid Month. Month should be between 1 and 12.";
	}
	
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
        return "Incorrect number of days in a month."; 
	}
	
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
        return "Incorrect number of days in a month."; 
	}
	
	// Check for the Feb!
	if (intMonth == 2) {
		if (intday < 1) {
          return "Incorrect number of days in a month."; 
		}
	
		if (LeapYear(intYear) == true) {
			if (intday > 29) {
		        return "Incorrect number of days in a month."; 
			}
		}
		else {
			if (intday > 28) {
		        return "Incorrect number of days in a month."; 
			}
		}
	}
	
	if (intday < 10) 
	  strDay = "0" + intday;
	else
	  strDay = intday;
	
	if (intMonth < 10) 
	   strMonth = "0" + intMonth;
	else
	   strMonth = intMonth;
	
	if (intYear < 100) 
		return "Invalid Year. Year should be greater than 1900.";
		   
	formField.value = strDay + "-" + strMonth + "-" + strYear;
	
	return "true";
	}
/*
--------------------------------------------------------------------------
	FUNCTION NAME: LeapYear
	DESCRIPTION:   Checks if the year passed in is a Leap year or not. Makes sure that the year
				   is in YYYY format.
	INPUT PARAMETERS:
			str - year passed in.
	RETURNS:
			true - if leap year
			false - if not a leap year.
	DEPENDENCIES: None
--------------------------------------------------------------------------
*/
	function LeapYear(intYear) {
	
	var strYear = intYear.toString();
	strYear = strYear.substr(2,2);
	
	if ((parseInt(strYear) % 4) == 0)
	  return true;
  
	return false;
}

/*
--------------------------------------------------------------------------
	FUNCTION NAME: emailCheck
	DESCRIPTION:   Called from onBlur of an email field. Validates the email format.
	INPUT PARAMETERS:
			addr - Email Address passed in.
	RETURNS:
			true - if email passes validation.
			false - if validation fails.
	DEPENDENCIES: None
--------------------------------------------------------------------------
*/

function emailCheck (emailStr) {

		/* The following variable tells the rest of the function whether or not
		to verify that the address ends in a two-letter country or well-known
		TLD.  1 means check it, 0 means don't. */
		
		var checkTLD=1;
		
		/* The following is the list of known TLDs that an e-mail address must end with. */
		
		var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
		
		/* The following pattern is used to check if the entered e-mail address
		fits the user@domain format.  It also is used to separate the username
		from the domain. */
		
		var emailPat=/^(.+)@(.+)$/;
		
		/* The following string represents the pattern for matching all special
		characters.  We don't want to allow special characters in the address. 
		These characters include ( ) < > @ , ; : \ " . [ ] */
		
		var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
		
		/* The following string represents the range of characters allowed in a 
		username or domainname.  It really states which chars aren't allowed.*/
		
		var validChars="\[^\\s" + specialChars + "\]";
		
		/* The following pattern applies if the "user" is a quoted string (in
		which case, there are no rules about which characters are allowed
		and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
		is a legal e-mail address. */
		
		var quotedUser="(\"[^\"]*\")";
		
		/* The following pattern applies for domains that are IP addresses,
		rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
		e-mail address. NOTE: The square brackets are required. */
		
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
		
		/* The following string represents an atom (basically a series of non-special characters.) */
		
		var atom=validChars + '+';
		
		/* The following string represents one word in the typical username.
		For example, in john.doe@somewhere.com, john and doe are words.
		Basically, a word is either an atom or quoted string. */
		
		var word="(" + atom + "|" + quotedUser + ")";
		
		// The following pattern describes the structure of the user
		
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
		
		/* The following pattern describes the structure of a normal symbolic
		domain, as opposed to ipDomainPat, shown above. */
		
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
		
		/* Finally, let's start trying to figure out if the supplied address is valid. */
		
		/* Begin with the coarse pattern to simply break up user@domain into
		different pieces that are easy to analyze. */
		
		var matchArray=emailStr.match(emailPat);
		
		if (matchArray==null) {
		
		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */
		
// 		alert("Email address seems incorrect (check @ and .'s)");
		return false;
		}
		var user=matchArray[1];
		var domain=matchArray[2];
		
		// Start by checking that only basic ASCII characters are in the strings (0-127).
		
		for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
//		alert("Ths username contains invalid characters.");
		return false;
		   }
		}
		for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
//		alert("Ths domain name contains invalid characters.");
		return false;
		   }
		}
		
		// See if "user" is valid 
		
		if (user.match(userPat)==null) {
		
		// user is not valid
		
//		alert("The username doesn't seem to be valid.");
		return false;
		}
		
		/* if the e-mail address is at an IP address (as opposed to a symbolic
		host name) make sure the IP address is valid. */
		
		var IPArray=domain.match(ipDomainPat);
		if (IPArray!=null) {
		
		// this is an IP address
		
		for (var i=1;i<=4;i++) {
		if (IPArray[i]>255) {
//		alert("Destination IP address is invalid!");
		return false;
		   }
		}
		return true;
		}
		
		// Domain is symbolic name.  Check if it's valid.
		 
		var atomPat=new RegExp("^" + atom + "$");
		var domArr=domain.split(".");
		var len=domArr.length;
		for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
//		alert("The domain name does not seem to be valid.");
		return false;
		   }
		}
		
		/* domain name seems valid, but now make sure that it ends in a
		known top-level domain (like com, edu, gov) or a two-letter word,
		representing country (uk, nl), and that there's a hostname preceding 
		the domain or country. */
		
		if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
//		  alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
		}
		
		// Make sure there's a host name preceding the domain.
		
		if (len<2) {
//		alert("This address is missing a hostname!");
		return false;
		}
		
		// If we've gotten this far, everything's valid!
		return true;
}

/*
--------------------------------------------------------------------------
	FUNCTION NAME: checkUserPortionEmail
	DESCRIPTION:   Makes sure that certain special chars do not repeat in the email.
	INPUT PARAMETERS:
			addr - Email Address passed in.
	RETURNS:
			true - if email passes validation.
			false - if validation fails.
	DEPENDENCIES: None
--------------------------------------------------------------------------
*/

function checkUserPortionEmail(addr) {

	// Special chars not allowed in an email.	
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	
	// Valid Chars - saying all chars minus special chars.
	var validChars="\[^\\s" + specialChars + "\]";
	
    // Quotes around user name implies....no rules...free to use whatever.	
	var quotedUser="(\"[^\"]*\")";
	
	// The following string represents an atom (basically a series of non-special characters.)	
	var atom=validChars + '+';
	
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	
	var word="(" + atom + "|" + quotedUser + ")";
	
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	
 	return userPat.test(addr);
}

/*
--------------------------------------------------------------------------
	FUNCTION NAME: checkRepeatingSpecChars
	DESCRIPTION:   Makes sure that certain special chars do not repeat in the email.
	INPUT PARAMETERS:
			str - String passed in
	RETURNS:
			true - if there are repeating chars
			false - if there are no repeating chars.
	DEPENDENCIES: None
--------------------------------------------------------------------------
*/

 function checkRepeatingSpecChars(str) {

    var specialChars = [",","@","\"","\\."];
    var retVal = true;
    for (var i = 0; i < specialChars.length;i++) {
       reExp = new RegExp(specialChars[i] + specialChars[i]);
	   retVal = reExp.test(str);
	   if (retVal)
	     return true;
    }
    return false;
  }
/*
--------------------------------------------------------------------------
	FUNCTION NAME: validateOnKeyEmail
	DESCRIPTION:   Called on OnKey event. Validates the email as user types.
	INPUT PARAMETERS:
			addr - Email Address passed in.
	RETURNS:
			true - if email passes validation.
			false - if validation fails.
	DEPENDENCIES:
			checkRepeatingSpecChars
			checkUserPortionEmail
--------------------------------------------------------------------------
*/

function validateOnKeyEmail(addr) {

   if ((addr == "")||(addr == "\""))
      return true;

   var reExp = /^[.\@\\,]/;

   if (reExp.test(addr))
     return false;
       

	var atSymbol = /@/;
	
	var reExp;
	if (!atSymbol.test(addr)) {
  	     // Validate User Portion 
  	     
  	     // Do not do validation on key triggers, if the first char is " and last char is not.
  	     reExp = /^[\"].*[^\"]$/;
	     if (reExp.test(addr)) {
	       return true;
	     } 
		 
		 // Don't check for repeating chars if the first and last chars are "
   		var reExp = /^[\"].*[\"]$/;
	     if (reExp.test(addr)) 
	         return true;
	     else {
			 if (checkRepeatingSpecChars(addr))
			   return false;
		      } 
         
	     // Do not do the validation on key triggers, if the last char is .
		  reExp = /\.$/;   
	     if (reExp.test(addr)) 
	       return true;
	  return checkUserPortionEmail(addr);
	}  // End On Key User Portion Validation
	else {
	
	 // Validating Domain.
	 
	 // Check if @ is the last char, so far typed.
	 reExp = /@$/;
	 
	 if (reExp.test(addr)) {
   	   if (!checkUserPortionEmail(addr.replace("@",""))) 
	     return false;
	 }
	 	  
	  	 // Check if the following sequences occurs in the string.
	 reExp = /(@@)|(\.\.)|(\.@)|(@\.)|(,@)|(@,)/;
	 if (reExp.test(addr))  {
	   return false;
     }

     return true;
	} // End OnKey Domain Portion validation
}
/*
--------------------------------------------------------------------------
	FUNCTION NAME: onKeyValidateDate
	DESCRIPTION:   Called on OnKey event. Validates the date field as user types.
	INPUT PARAMETERS:
			addr - Date field passed in
	RETURNS:
			true - If the field passes validation.
			error message - if the validation fails.
	DEPENDENCIES: none
--------------------------------------------------------------------------
*/
function onKeyValidateDate(formField) {

  if (formField.value == "") 
     return "true";
     
  if (formField.value.length > 10)
    return "Invalid date format. Please enter date in DD-MM-YYYY format";
    
   // Permissible chars in a date field.
   var reExp = /[^-/\.\d]/;
   
   if (reExp.test(formField.value))
     return "Invalid character in the date field.";
     
	   // On Key Events.	
	var strDate = formField.value;
	
	// Array to split the date string and store day, month and year separately.
	var strDateArray;
	
	// Parse and store the date string in String format.
	var strDay, strMonth, strYear;
	
	// Parse and store day, month and year in Integer objects.
	var intday, intMonth, intYear;
	
	var booFound = false;
	
	// Possible seperators in a date string.
	var strSeparatorArray = new Array("-"," ","/",".");
	
	var intElementNr;
	
	var errMessage = "SUCCESS";
	
	
	// Check if user entered any value or not.
	if (strDate.length == 0) {
	   return "true";
	}
	
	// Check if user entered date using the separators mentioned in strSeparatorArray.
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {

		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {

			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			
            switch (strDateArray.length) 
            {
	            case 2:
	            	// We come here, when we have only one separator in the field.
					strDay =    strDateArray[0];
					
					if (strDay.length > 2)
					   return "Invalid date format. Please enter date in DD-MM-YYYY format";
					
					// parseInt seems to have a bug when the string is either 08 or 09.
					
				    intDay = Math.abs(strDay);									
				    
				    if ((strDay.length == 1) && intDay == 0)
				       return "true";
				       
					if ((intDay > 31) || (intDay <= 0))
					   return "Invalid number of days in a month";
					   
				    strMonth = strDateArray[1];
					if (strMonth == "")
					   return "true";
					
					if ((strMonth.length == 1) && (strMonth == "0"))
					   return "true";
					   
				    intMonth = Math.abs(strMonth);				
					break;
	            case 3:
	            	// We come here, when we have only two separators in the field.
					strDay =    strDateArray[0];
				    intDay = Math.abs(strDay);									
  				    
  				    strMonth =  strDateArray[1];
  				    
  				    strYear = strDateArray[2];
  				    
   					if (strMonth.length > 2)
					   return "Invalid date format. Please enter date in DD-MM-YYYY format";

					if (strYear.length > 4)
						return "Invalid year. Please enter date in DD-MM-YYYY format";
						
				    intMonth = Math.abs(strMonth);				
  				    
		        	break;
	            default:
					   return "Invalid date format. Please enter date in DD-MM-YYYY format";
	                 break;
	      } // Switch condition
	      		booFound = true;
	   } // IF condition.
	} // for loop

	
	// User did not mention separators yet.
	if (booFound == false) {
	   	
	   	strDay =    strDate;
	   	
	   	if (strDay.length > 2) 
	   	   return "Invalid date format. Please enter the date in DD-MM-YYYY format.";
	   	   
	   	intDay = Math.abs(strDay);									
		
		if (strDay == "0")
			   return "true";

		if ((intDay > 31) || (intDay <= 0))
		   return "Invalid number of days in a month";
		
		return "true";
    }
				
    	if (intMonth>12 || intMonth<1) {
		   return "Invalid Month. Month should be between 1 and 12.";
		}
		
		if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intDay > 31 || intDay < 1)) {
	        return "Incorrect number of days in a month."; 
		}
		
		if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30 || intDay < 1)) {
	        return "Incorrect number of days in a month."; 
		}
		
		// Check for the Feb!
		if (intMonth == 2) {
			if ((intDay > 29) || (intDay <= 0))
	          return "Incorrect number of days in a month."; 
		}

	return "true";
	}
/*
--------------------------------------------------------------------------
	FUNCTION NAME: checkDateBounds
	DESCRIPTION:   Checks whether a given date falls between the given Start and End Dates.
	INPUT PARAMETERS:
			pDate	  in DD-MM-YYYY format
			pStartDate in DD-MM-YYYY format.
			pEndDate	  in DD-MM-YYYY format
	RETURNS:
			"true" - If the field value is between the Start and End Dates.
			error message - if the validation fails.
			
			If upperbound is not needed, pass "" for pStartDate.
			If lowerbound is not needed, pass "" for pEndDate.
			
	DEPENDENCIES: none
--------------------------------------------------------------------------
*/

function checkDateBounds(pDate, pStartDate, pEndDate) {
	
	  var dateSeparator = "-";
	  var givenDate = new Date();
      givenDate.setTime(0);	  
	  
	  var strDateArray = pDate.split(dateSeparator);
			
	  //Month array starts from zero.
	  givenDate.setFullYear(strDateArray[2], strDateArray[1] - 1, strDateArray[0]);
	
	  if (pStartDate != "") {
	  	var startDate = new Date();
        startDate.setTime(0);

	    strDateArray = pStartDate.split(dateSeparator);

   	    //Month array starts from zero.
	    startDate.setFullYear(strDateArray[2], strDateArray[1] - 1, strDateArray[0]);
	    
	    //startDate.setDate(strDateArray[0]);
	    //startDate.setMonth(strDateArray[1] - 1);
	    //startDate.setYear(strDateArray[2]);

		if (givenDate.getTime() < startDate.getTime()) {
		  return "Date cannot be less than " + pStartDate;
		}	
	  }
	  
	  
	  if (pEndDate != "") {
	  	var endDate = new Date();
        endDate.setTime(0);	  

	    strDateArray = pEndDate.split(dateSeparator);
	    
   	    //Month array starts from zero.
	    endDate.setFullYear(strDateArray[2], strDateArray[1] - 1, strDateArray[0]);
	    //endDate.setDate(strDateArray[0]);
	    //endDate.setMonth(strDateArray[1] - 1 );
	    //endDate.setYear(strDateArray[2]);
	
		if (givenDate.getTime() > endDate.getTime()) {
		  return "Date cannot be greater than " + pEndDate;
		}
	  }
	  return "true";
	}
	
/*
--------------------------------------------------------------------------
	FUNCTION NAME: findPos
	DESCRIPTION:   Given a formfield, returns its absolute Left and Top positions.
	INPUT PARAMETERS:
		obj - Formfield object
	RETURNS:
		an array {LEFTPOSITION, TOPPOSITION];			
	DEPENDENCIES: none
--------------------------------------------------------------------------
*/
function findPos(obj) {
	var curleft = curtop = curheight = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}

	return [curleft,curtop];
}

function CmdCalculate_onclick(document) {

    var a,b,c,d,e
    a=document.formpage.txtHra.value
    b=(document.formpage.txtActual.value-(document.formpage.txtSal.value*10)/100)
    c=document.formpage.txtSal.value*document.formpage.cmbCity.value


    if ((a<=b)&& (b<=c)) {
        document.formpage.txtHraEx.value=a

        }
    if ((b<=a) && (b<=c)) {
        if (b>0) {
            document.formpage.txtHraEx.value=b
            }
        if(b<0) {
            document.formpage.txtHraEx.value=0
            }
        }
    if ((c<=a) && (c<=b)) {
        document.formpage.txtHraEx.value=c
        }
    document.formpage.txtMaxRent.value=(Number(document.formpage.txtHra.value)+(Number(document.formpage.txtSal.value*10)/100))
    d=Number(document.formpage.txtMaxRent.value)
        if((a<=c) && (a<=d)) {
        document.formpage.txtHraExBase.value=a
        }
        if ((d<=c) && (d<=a)) {
        document.formpage.txtHraExBase.value=d
        }
        if ((c<=a) && (c<=d)) {
        document.formpage.txtHraExBase.value=c
        }
   return
}

function CmdRest1_onclick(document) {
    document.formpage.txtActual.value=""
    document.formpage.txtHra.value=""
    document.formpage.txtSal.value=""
    document.formpage.txtHraEx.value=""
    document.formpage.txtHraExBase.value=""
    document.formpage.txtMaxRent.value=""
}

var ids=new Array('f16_part1','f16_part2','f16_part3','f16_part4');

function switchid(id){
    hideallids();
    showdiv(id);
}

function hideallids(){
    //loop through the array and hide each element by id
    for (var i=0;i<ids.length;i++){
        hidediv(ids[i]);
    }
}

function hidediv(id) {
    //safe function to hide an element with a specified id
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(id).style.display = 'none';
    }
    else {
        if (document.layers) { // Netscape 4
            document.id.display = 'none';
        }
        else { // IE 4
            document.all.id.style.display = 'none';
        }
    }
}

function hidediv(id) {
    //safe function to hide an element with a specified id
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(id).style.display = 'none';
    }
    else {
        if (document.layers) { // Netscape 4
            document.id.display = 'none';
        }
        else { // IE 4
            document.all.id.style.display = 'none';
        }
    }
}

function showdiv(id) {
    //safe function to show an element with a specified id

    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(id).style.display = 'block';
    }
    else {
        if (document.layers) { // Netscape 4
            document.id.display = 'block';
        }
        else { // IE 4
            document.all.id.style.display = 'block';
        }
    }
}


function doMenu(id)
{
    obj=document.getElementById(id);
    col=document.getElementById("x" + id);

    if (obj.style.display=='none')
    {
        obj.style.display='block';
        col.innerHTML="<img src='/it_media/v4/n/images/minus2.gif'/>";
    }
    else
    {
        obj.style.display='none';
        col.innerHTML="<img src='/it_media/v4/n/images/plus2.gif'/>";
    } 
}
function show(id)
{
    document.getElementById(id).style.display = 'block';
}

function hide(id)
{
    document.getElementById(id).style.display = 'none';
}


function checkConfirmEmail() {
emailadd = document.formpage.email.value;
conemail = document.formpage.email1.value;
if (conemail != emailadd) {
alert ("Email addresses do not match - please re-enter!");
document.formpage.email.value = "";
document.formpage.email1.value = "";
document.formpage.email.focus();
}
}


function checkForm(id)
{
 if(document.getElementById("father_name").value == "")
 {
 alert("Father Name is a required field");
 document.getElementById("father_name").focus();
 return false;
 }
 if(!document.getElementById("gender_M").checked && !document.getElementById("gender_F").checked)
 {
 alert("Gender is a required field");
 return false;
 }
 if(document.getElementById("dateofbirth").value == "")
 {
 alert("Date of Birth is a required field");
 document.getElementById("dateofbirth").focus();
 return false;
 }
 /*if(document.getElementById("email").value == "")
 {
 alert("Email-Id is a required field");
 document.getElementById("email").focus();
 return false;
 }
 if(document.getElementById("email1").value == "")
 {
 alert("Confirm Email-Id is a required field");
 document.getElementById("email1").focus();
 return false;
 }*/
 if(document.getElementById("res_addr_flat").value == "")
 {
 alert("Flat/Door/Block No is a required field");
 document.getElementById("res_addr_flat").focus();
 return false;
 }
 if(document.getElementById("res_addr_road").value == "")
 {
 alert("Road/Street/Post Office No is a required field");
 document.getElementById("res_addr_road").focus();
 return false;
 }
 if(document.getElementById("res_addr_area").value == "")
 {
 alert("Area/Locality is a required field");
 document.getElementById("res_addr_area").focus();
 return false;
 }
 if(document.getElementById("res_city").value == "")
 {
 alert("Town/City/District is a required field");
 document.getElementById("res_city").focus();
 return false;
 }
 if(document.getElementById("res_state_ut").value == "none")
 {
 alert("State is a required field");
 document.getElementById("res_state_ut").focus();
 return false;
 }
 if(document.getElementById("res_pin_code").value == "")
 {
 alert("PIN Code is a required field");
 document.getElementById("res_pin_code").focus();
 return false;
 }
 SendEmail(id);
}

