/**
* @ Modified By	 : Gargi Bakshi
* @ Modified On	 : 4th-Apr-04
* @ Modification	 :	Added trimAll() method that removes all the leading and trailing blanks of all the elements of the passed form.
*/
// Note: All developers are requested to either return true or false explicetly while adding a function to the file.



// this function fills a value into text box named fieldName from obj
/*
function fillTextBox(obj, fieldName) 
{ assignValueTo(obj, fieldName); 
}
function assignValueTo(obj, fieldName) 
{ 
	var destinationFormField = eval("document."+obj.form.name+"."+fieldName);
	destinationFormField.value = obj.options[obj.selectedIndex].value;
}
*/
// Usage in jsp/html file: 		if(!chkBlank(document.f1.Username,'User Name')) return false;
/* This function makes the field compulsary. */

function remesc(id)
{
str=id.value;
var filter=/[^a-z\d ]/i;
				if (filter.test(str))
				{
					alert("Plz enter correct value")
					id.value='';
					return false;
				}
			}	


function chkBlank(formelement,text)
{
	if (formelement.value=='')
	{
		alert('Please enter your '+text);
		formelement.focus();
		return false;
  }
	else
	{
		return true;
	}
}


function chkAllBlank(formelement,text)
{
	var msg='true';
	var a=formelement.value;
	if (a.indexOf(' ') >= 0) 
	{
			msg='Blank space are not allowed in '+text;
			alert(msg);
			formelement.focus();
			return false;
	}

	if (msg=='true')
	{
	return true;
	}

}



/* This function checks for non numeric numbers. */

function chkNaN(formelement,text)
{
	if (isNaN(formelement.value))
	{
		alert('Please enter a numeric value for '+text);
		formelement.value="";
		formelement.focus();
		return false;
  	}
	else
	{
		return true;
	}
}

/*Function to check if a float eg. 20.22 is in proper format.
parameters :
	formElementObject - Object of the form element
	displayText - Name of field (String)
	isRequired - true if this field should not be empty, false otherwise.(boolean)

	Note : More suitable for onBlur event
*/
function isDigit(formElementObject, displayText, isRequired) {
	var eleValue = trim(formElementObject.value);

	if(formElementObject == null || displayText == '') {
		alert('Incorrect use of function isDigit');
		return false;
	}
	if(eleValue == '' && isRequired == true) {
		alert('Please provide a value for '+displayText);
		formElementObject.focus();
		return false;
	}
	if(eleValue != '') {
		if(eleValue.indexOf('.') != -1) {
			var eleArr = eleValue.split('.');
			if(eleArr.length > 2) {
				alert('Please enter a valid ' + displayText+'. You may enter upto 2 digits after the decimal point.' );
				formElementObject.focus();
				return false;
			} else {
				if(isNaN(eleArr[0]) || isNaN(eleArr[1])) {
					alert(' Please enter a valid ' + displayText+' Please enter a numeric value.' );
					formElementObject.focus();
					return false;
				}
			}
		} else {
			if (isNaN(eleValue))
			{
				alert('Please enter a numeric value for '+displayText);
				formElementObject.focus();
				return false;
			}
			else
			{
				return true;
			}
		}
	}
	return true;
}

/*
function isEmail(theField){
	var pattern = ".+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)"
	var regex = new RegExp(pattern)
	if (regex.test(theField.value)) return true;
	else
		return warnInvalid (theField, "Incomplete or Invalid Email")
}
*/

/* This function checks for a valid email address. */

function CheckMail(id)
		{
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(id.value))
		{
		return (true)
		}
		else
		{
		alert("Invalid E-mail Address! Please re-enter.")
		id.value="";
		return (false)
		}
		}

/*
function chkEmail(formelement, text) {
	if(formelement.value != '') {
		//var pattern = ".+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)"
		//var pattern = "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
		
		regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ //new RegExp(pattern)
		if (!regex.test(formelement.value)){
			alert("Please enter a valid "+text+",\nfor example : \n     'yourname@domain.com'  OR\n     'yourid@yourdomain.co.in'  OR\n     'yourid.somname@domain.co.in' " );
			formelement.focus();
			return false;
		} else {
			return true;
		}
	}
}
8/
/* This function checks for the minimum characters. */

function chkLessLen(formelement,text,len)
{
	if(formelement.value.length<parseInt(len))
	{
		alert('The '+text+' should not have less than '+len+' characters');
		formelement.focus();
		return false;
	}
	else
	{
		return true;
	}
}

/* This function checks for the maximum characters. */

function chkGreaterLen(formelement,text,len)
{
	if(formelement.value.length>parseInt(len))
	{
		alert('The '+text+' should not have more than '+len+' characters');
		formelement.focus();
		return false;
	}
	else
	{
		return true;
	}
}


/**/
function chkCharacters(formelement, charList) { 
	var parsed = true;
	var elementValue = formelement.value;
	for (var i=0; i < elementValue.length; i++) {
		var letter = elementValue.charAt(i).toLowerCase();
		if (charList.indexOf(letter) != -1) continue;
		parsed = false;
		break;
	}
 	
	return parsed;
}


/* This function checks for special characters as per the user requirement. */

function chkSpecialCharCustom(formelement,text, cha)
{

	var msg='true';
	var a=formelement.value;
	var b=a.length;
	var ch=cha.length;
	var i,j;
	for(i=0;i<ch;i++)
	{
		var ch1=cha.substring(i,i+1);
		for(j=0;j<b;j++)
		{
			var a1=a.substring(j,j+1);
			if(a1==ch1)
			{
				msg='Characters like ' +cha+ ' are not allowed in '+text;
				alert(msg);
				formelement.focus();
				return false;
			}
		}
	}
	if (msg=='true')
	{
	return true;
	}

}

/* This function checks for special characters. */

function chkSpecialChar(formelement,text)
{
	var msg='true';
	var a=formelement.value;
	var b=a.length;
	var cha='`~!@#$%^&()+-[]{}/|;:,<>.?';
	var ch=cha.length;
	var i,j;
	for(i=0;i<ch;i++)
	{
		var ch1=cha.substring(i,i+1);
		for(j=0;j<b;j++)
		{
			var a1=a.substring(j,j+1);
			if(a1==ch1)
			{
				msg='Special Characters like ' +cha+ 'are not allowed in '+text;
				alert(msg);
				formelement.focus();
				return false;
			}
		}
	}
	if (msg=='true')
	{
	return true;
	}
}

/* This function checks for spaces in the field. */

function chkSpace(formelement,text)
{
	var msg='true';
	var a=formelement.value;
	var b=a.length;
	var i,j;
		for(j=0;j<b;j++)
		{
			var a1=a.substring(j,j+1);
			if(a1==' ')
			{
				msg='Blank spaces are not allowed in '+text;
				alert(msg);
				formelement.focus();
				return false;
			}
		}

	if (msg=='true')
	{
	return true;
	}
}

/* This function compels the user to enter number greater than 0. */

function chkLEZero(formelement,text)
{
	if (formelement.value <= 0)
	{
		alert('Please enter a value greater than 0 for '+text+'.');
		formelement.focus();
		return false;
	}
	else
	{
		return true;
	}
}

/* This function checks for identical passwords. */

function chkPassword(formelement1,formelement2)
{
	var password1=formelement1.value;
	var password2=formelement2.value;

	if (password1 != password2)
	{
		alert('Passwords do not match. Please reenter your passwords.');
		formelement1.focus();
		return false;
	}
	else
	{
		return true;
	}
}

/* This function compels the user to select a value in the list box. */

function chkListBlank(formelement,text)
{


	if (formelement.options[formelement.selectedIndex].value=='')
	{
		alert('Please select a '+text);
		formelement.focus();
		return false;
	}
	else
	{
		return true;
	}
}

/* This function compels the user to select atleast one radio button. */

function chkRadio(formelement,text)
{
	var flag='false';
	if(formelement.checked==true){
		flag='true';
	}
	else{
		for (var i =0;i<formelement.length;i++ ){
			if(formelement[i].checked==true){
				flag='true';
			}
		}
	}
	if (flag=='false')
	{
		alert('Please select a '+text);
		return false;
	}
	else
	{
		return true;
	}

}

/* This function is used to trim the leading and trailing spaces from given string.
   Useful to remove unwanted spaces before processing string value in JavaScript. */

function trim ( str )
{
    var k=0;
    var i=0;
    var j=0;
    k   =   str.length;
    while ( str.charAt (j) == ' ' )
       j++;

    i   =   k;
    while ( str.charAt (i-1) == ' ' )
        i   =   i-1;
    if ( j != k )
        trimstr = str.substring(j,i);
    else
        trimstr = '';
    return trimstr;
}

/* This function is used to check if the given string containes single quote chracter*/

function hasQuotes(str)
{
    var ch="'";
    if(str.indexOf(ch)==-1)
    return false;
    return true;
}

/* This function is used to open a new pop-up window. */
function OpenWin (link, windowName)
{
    loc =   link;
    win =   window.open (loc,windowName,'top=150,left=200,height=300,width=600,scrollbars=yes,status=no,toolbar=no,resizable=yes') ;
    win.focus();

}

/* Used for rounding off value. Deprecated. Insted use function round_decimals given below. */
function roundOff(value, precision)
{
        value = "" + value //convert value to string
        precision = parseInt(precision);

        var whole = "" + Math.round(value * Math.pow(10, precision));

        var decPoint = whole.length - precision;

        if(decPoint != 0)
        {
                result = whole.substring(0, decPoint);
                result += ".";
                result += whole.substring(decPoint, whole.length);
        }
        else
        {
                result = whole;
        }
        return result;
}

/* Used for rounding off decimal values to the correct decimal precision. */

function round_decimals(original_number, decimals)
{
 var result1 = original_number * Math.pow(10, decimals)
 var result2 = Math.round(result1)
 var result3 = result2 / Math.pow(10, decimals)
 return pad_with_zeros(result3, decimals)
}

/* Internally used by round_decimals function for padding amount with zeros while rounding off. */

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()

    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {

        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0

        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }

    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length

    if (pad_total > 0) {

        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++)
            value_string += "0"
        }
   // alert("deci :"+value_string);
    return value_string
}

	//use this function to disable form element
function disable(elem) { // elem: form element to be disabled
  elem.onfocus=elem.blur;
}
	//use this function to enable form element
function enable(elem) { // elem: form element to be reenabled
  elem.onfocus=null;
}

/*function to get the date after the given period
  currentYear - String giving current year in yyyy format
  currentMonth - String giving current month in mm format
  currentDay - String giving current day in dd format
  addDays - Integer showing no of days after the current date
  return next date as mm/dd/yyyy string
*/
function getNextDate(currentYear, currentMonth, currentDay, addDays) {
	var nextDate = '';
	
	var currDateObj = new Date(parseInt(currentYear),
				parseInt(currentMonth),
				parseInt(currentDay));
		
	currDateObj.setDate(parseInt(currentDay)+addDays);
	nextDate = currDateObj.getMonth()+'/'+currDateObj.getDate()+'/'+currDateObj.getYear();
	return nextDate;
}

/*
	this function iterates though the selection control
	and selects appropriate option as per the supplied argument
*/
function go2CurrentSelectedValue(sel,val)
{
		for(var i=0; i < sel.options.length; i++) {
						if(sel.options[i].value==val) {
								sel.options[i].selected = true;
						}
				}
}


function WinOpenCurrencyConvertor(a,b) {
	postwindow=window.open("/includes/wld_curconvert.jsp?amount="+a + "&cssfile=" + b, "xfdfd","status=no,resize=yes,scrollbars=yes,toolbar=no,dependent=yes,alwaysRaised=yes,resizable=no,width=520,height=430");
	window.status="done";
}


// to popup window of given size and with different names ----- 
	function WinOpen(url, height, width, winName) {	winPopUp(url, winName, width, height);	}
	function WinOpen(url, height, width) {	winPopUp(url, "defaultWin", width, height);	}
	
	function winPopUp(url, winName, width, height) {
		if (winName == null) winName = "defaultWin";
		if (width == null) width = "500";
		if (height == null) height = "600";
		var winProperties = "status=no,resize=no,scrollbars=yes,toolbar=no,dependent=yes,alwaysRaised=yes,maximize=no,resizable=no,width=" + width +",height=" + height + "";
		postwindow = window.open(url, winName, winProperties);
		window.status = "Done";
	}
// -------------------

// Removes all characters which appear in string bag from string s.
	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 getTyped(search,field) {
		var pattern 

		if (search.value == "") 	{
			field.options.selectedIndex = -1;
			return;
		}
		// "i" - not case-sensitive
		pattern = new RegExp("^" + search.value, "i");

		for(var x=0; x < field.options.length; x++) {
			if (pattern.test(field.options[x].text) == true) { // testing the value of text and the item in the list
				field.options[x].selected = true       //make the list box as selected 
				break;
			}
		}
	}



// Added by sachin 
// to check rdoButton to select atleast one .... here taken care of the number of buttons
// i.e. it will work with any number of radio buttons... dynamic radio buttons
	function checkRdoOptions(rdoElement) {
		var rdoLen = rdoElement.length == null ? 1 : eval(rdoElement.length);
		var firstRdoBtn;
		for (var i=0; i<rdoLen; i++) {
			tmpElement = rdoLen == 1 ? rdoElement : rdoElement[i];
			if (i==0) firstRdoBtn = tmpElement;
			if (tmpElement.checked) return true;	
		}
		firstRdoBtn.focus();
		return false;
	}
// ------------------------------------------------------------------------------------------------

/* This function removes all the leading and trailing blanks of all the elements of the passed form. */
	function trimAll(frm) { trimAllFomElementValues(frm); }
	function trimAllFomElementValues(frm) { 
		for (var i=0; i<frm.elements.length; i++) 
			frm.elements[i].value = (""+frm.elements[i].value).replace(/^\s*/,'').replace(/\s*$/, '');	
	}

// To check the valid phone numbers.....
	function validPhNum(obj) { 
		var ph = stripWhitespace(obj.value);
		obj.value = ph;
		var validChars = "1234567890-+()";

		for(var i = 0; i<ph.length; i++)
			if (validChars.indexOf(ph.charAt(i)) < 0) {
				alert("Please enter a valid telephone number.");
				obj.select(); 
				return false;
			}
		
		return true;
	}
	
// Removes all whitespace characters from s.
	function stripWhitespace (s) { 
		var whitespace = " \t\n\r"; // This variable defines which characters are considered whitespace.
		return stripCharsInBag (s, whitespace); 
	}
// ================================================

