function chkall(obj_frm,obj) {
 for(i=0;i<obj_frm.elements.length;i++) {
  if(obj_frm.elements[i].type == "checkbox"){ 
  obj_frm.elements[i].checked = obj.checked;
  }
 }
}

function unCheck(objform,checkObjName,unCheckObjName) {
 var uncheckFlag=0;
 var selectAll = 1;
 for(i=0;i<objform.length;i++) 
 {
	  if(objform.elements[i].type == "checkbox" && objform.elements[i].name==checkObjName.name)
	  { 
			if(objform.elements[i].checked)
			{
				uncheckFlag=1;
			}
			else
			{
				selectAll = 0;	
			}
	  }
 }
	 if(!uncheckFlag)//if no one is checked 
	 {
		 unCheckObjName.checked = false;
	 }
	 if(selectAll)
	 {
		 unCheckObjName.checked = true;
	 }
}

function chkallonlink(obj_frm) {
 for(i=0;i<obj_frm.elements.length;i++) {
  if(obj_frm.elements[i].type == "checkbox"){ 
  obj_frm.elements[i].checked = 1;  
  }
 }
}
function unchkallonlink(obj_frm) {
 for(i=0;i<obj_frm.elements.length;i++) {
  if(obj_frm.elements[i].type == "checkbox"){ 
  obj_frm.elements[i].checked = 0;
  }
 }
}
 
function  del_prompt(obj_frm,val,act) 
{

  if(confirm("Are you sure, you want to "+ val + " this record(s)")) 
  {
   if(act!="") 
   { 	  
	    obj_frm.action = act;
	    obj_frm.what.value=val; 
	    obj_frm.submit(); 
   }  
  }
  else
  {     
   return false;
  }
}

function acceptForm(val)  // by akash for accepting form at enquiry counter
{

  if(confirm("Are you sure, you want to accept this " + val + " ?")) 
	{
		//alert("Yes");
		//return false;
	}
  else
	{     
		//alert("No");
		return false;
	}
}


function checkSelection(frm,objVal,phpName)
{ 
 var check=false; 
 for(i=0;i<frm.elements.length;i++)
 {
  if(frm.elements[i].type=='checkbox')
  {
   if(frm.elements[i].checked==true)
   {
    check=true;
    break;
   }
  }
  
 }
	 if(check) 
	  del_prompt(frm,objVal,phpName);
	 else 
	  alert('Please select any checkbox');  
 return false;
}


function checkActivitySelection(frm,objVal,phpName)
{ 
 var check=false; 
 for(i=0;i<frm.elements.length;i++)
 {
  if(frm.elements[i].name=='del[]')
  {
   if(frm.elements[i].checked==true)
   {
    check=true;
    break;
   }
  }
  
 }
	 if(check) 
	  del_prompt(frm,objVal,phpName);
	 else 
	  alert('Please select atleast one activity!!');  
	 return false;
}
function ReceiveCorrespondense(frm)
{ 
 var check=false; 
 for(i=0;i<frm.elements.length;i++)
 {
  if(frm.elements[i].name=='correspondenseRequestId[]')
  {
   if(frm.elements[i].checked==true)
   {
    check=true;
    break;
   }
  }
  
 }
	 if(check)
	 {
	  var con = confirm("Are you sure to receive this correspondense?");
		  if(con)
		  {
			  frm.hidden.value="ReceiveCorrespondense";
			  frm.submit();
		  }
	 }
	 else 
	 {
	  alert('Please select atleast one correspondence to receive!!');  
	 }
	 return false;
}


function CheckValidation(string,bag){
for(q=0; q<string.length; q++){
var charval = string.charAt(q);
if(bag.indexOf(charval) == -1)
return (false);
}
return (true);
}

function MM_validateForm() 
{  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
 j=0;
 // /^([-a-zA-Z0-9._]+@[-a-zA-Z0-9.]+(\.[-a-zA-Z0-9]+)+)$/;
 var regEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; 
 var regBlank = /[^\s]/;   
 var regAlphaNum = /^([a-zA-Z0-9 .()\/\-_]+)$/; 
 var regDate = /^([0-9_]+-[0-9][0-9]+-[0-9][0-9]+)$/;
 //alert (MM_validateForm.arguments[1].name);
 //alert("sss--->"+document.forms[""+args[0]].elements[""+args[0]].value); 
 for (i=1; i<(args.length-2); i+=3) 
 { 
  mesg=args[i+1];
  test=args[i+2]; 
  val=document.forms[""+args[0]].elements[""+args[i]];
      if (val)  
  { nm=mesg; 
   
   val = val.value;
   //if ((val=val.value)!="") 
   if(regBlank.test(val))
   {
    if(test.indexOf('isEqual')!=-1)
    {
     result = trim(val);
    if(result.length==0){
    errors +='- Please enter your '+nm+ '.\n'; 
    }else{
     equal_obj_val = test.substring(8,test.indexOf(":"));
     mesg_string =test.substring((test.indexOf(":")+1));
     if(val != document.forms[""+args[0]].elements[""+equal_obj_val].value) 
     {
      errors+='- '+nm+' and '+mesg_string+' are not same.\n';
     }
    }
    }
    else if(test.indexOf('isAlphaNum')!=-1)
    {
    result = trim(val);
    if(result.length==0){
    errors += '- '+nm+' is required.\n'; 
    }else{
     if(!regAlphaNum.test(val))
     {
      errors+='- '+nm+': Only Alpha Numeric and "_" Chars Allowed.\n';
     }
    }
    }
    else if (test.indexOf('isDate')!=-1) 
    { 
     p=val.indexOf('-');
           
     if (p != 4 )
     {
      errors+='- '+nm+' must contain Valid Date YYYY-MM-DD.\n';
  
     }
     else if(!regDate.test(val))
     {
      errors+='- '+nm+' must contain Valid Date YYYY-MM-DD.\n'; 
     }
        }
    else if (test.indexOf('isEmail')!=-1) 
    { 
     p=val.indexOf('@');
     s=val.indexOf('.');
           if (p<1 || p==(val.length-1))
     {
      errors+='- Please enter a valid '+nm+' address.\n';
  
     }
     //else if(s<p || s==(val.length-1))
     else if(!regEmail.test(val))
     {
      errors+='-Please enter a valid '+nm+' address.\n'; 
     }
        }
    else if (test.indexOf('isUrl')!=-1) 
    { 
     p=val.indexOf('http://');
     s=val.indexOf('.');
           if (p<0 || p==(val.length-1))
     {
      errors+='- '+nm+' must be valid URL e.g. http://www.abc.com\n';
  
     }
     else if(s<p || s==(val.length-1))
     {
      errors+='- '+nm+' must be valid URL e.g. http://www.abc.com\n' ;
     }
        }else if (test.indexOf('isChar')!=-1) 
     { 
     var first_char;
     first_char= val.charAt(0);
     if(first_char==0||first_char==1||first_char==2||first_char==3||first_char==4||first_char==5||first_char==6||first_char==7||first_char==8||first_char==9){ 
      errors+='- '+nm+' must starts with  a char.\n';
     }
        }
        else if (test!='R') 
     {
     result = trim(val);
     if(result.length==0){
     errors +='- '+nm+' is required.\n'; 
     }
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
     if (test.indexOf('inRange') != -1) 
     { num = parseFloat(val);
      p=test.indexOf(':');
      min=test.substring(4,p); 
      max=test.substring(p+1);
      if (num<min || max<num) 
      errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
     } 
     if (val.indexOf('-') != -1) 
     { 
      errors+='- '+nm+' must contain a number without dashes sign.\n'; 
     } 
     if (val.indexOf('+') != -1) 
     { 
      errors+='- '+nm+' must contain a number without plus sign.\n';
     }
     
    }else if (test.charAt(0)=='R')
    {
    result = trim(val); 
    if(result.length==0){
    errors += '- Please enter your '+nm+' .\n'; 
    }
    } 
   }
   else if (test.charAt(0) == 'R'){
    errors += '- Please enter your '+nm+'.\n'; 
   }
  }
  if(errors !="") 
  { if(j<=0)
   {
    
    focusitem = document.forms[""+args[0]].elements[""+args[i]];
    j++;
   } 
   
  }
 } 
 
//return errors;
  
  if (errors)
  {
 alert('Sorry, we cannot complete your request.\nKindly provide us the missing or incorrect information enclosed below.\n\n'+errors);
 
 focusitem.focus();
 return false;
   }
   else
 return true;

//  document.MM_returnValue = (errors == '');
 
}

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

//CODE FOR RECURRENCE STUFF
function valid_orderform(formname)
{ if(MM_validateForm(formname,'lender_company','Lender Company','RisNaN','lender_contact_name','Lender Contact Name','R','lender_phone','Lender Phone','R','leander_email','Leander Email','R','property_number','Property Number','R','property_street_name','Property Street Name','R','property_city','Property City','R','property_state','Property State','R','property_zip_code','Property Zip Code','R','prime_seller_fname','Seller First Name','R','prime_seller_address','Seller Address','R','prime_buyer_fname','Buyer First Name','R','prime_buyer_address','Buyer Buyer Address','R','ordering_party','Ordering Party','R','applicant_company','Applicant Company or Name','R','applicant_attn','Applicant Attn','R','applicant_address','Applicant address','R','applicant_phone','Applicant Phone','R','applicant_fax','Applicant Fax','R','applicant_email','Applicant Email','RisEmail')) 
 {return true;}
 else
 {return false;}
}

function checkMenuMaster(formname)
{ if(MM_validateForm(formname,'menuName','Menu Name','RisAlphaNum','parentName','Parent Name','R','pageURL','Page URL','R')) 
 {return true;}
 else
  {return false;}
}

function check_ParameterForm(formname) 
{ if(MM_validateForm(formname,'parameterName','Parameter Name','R')) 
 {
		 return true;
 }
 else
 {return false;}
}

function check_userRights(formname) 
{ 
if(MM_validateForm(formname,'userType','User Type','R','userId','User Id','R')) 
	 {return true;}
 else
 {return false;}
}

function md5Auth(seed)
	{
	  var password = document.forms[0].password.value;
	  var hash = MD5(password);
	  var hash = hash+seed;
	  document.forms[0].password.value='';
	  document.forms[0].pwd.value=hash;
	  //alert("data sent = "+document.forms[0].pwd.value);
	  return true;
	}
function ValidateData(f)
	{
        if (f.loginId.value==""){
			alert("Please enter User Name!");
			f.loginId.focus();
			return false;
        }
         if (f.password.value==""){
			alert("Please enter Password!");
			f.password.focus();
			return false;
        }
        var x;
   		x= md5Auth(f.ids.value);
		if (x==true)
			f.ids.value='';
		return x;
	}
 
function openNewWindow(theURL,winName,features) { //v2.0 
var featuresadd = features +',top=0,left=0';
  window.open(theURL,winName,featuresadd);
}
function openSameWindow(theURL) { //v2.0 
  location.replace(theURL);
}

function CompareDate(strDate1,strDate2)
{
	var firstIndex = 0 + strDate1.indexOf ('-');
	var lastIndex = 0 + strDate1.lastIndexOf ('-');
	var date1 = strDate1.substring (0, firstIndex);
	var month1 = strDate1.substring (firstIndex+1, lastIndex);
	var year1 = strDate1.substring (lastIndex+1, strDate1.length);

	var date2 = strDate2.substring (0, firstIndex);
	var month2 = strDate2.substring (firstIndex+1, lastIndex);
	var year2 = strDate2.substring (lastIndex+1, strDate2.length);

	var enteredDate1 = new Date(year1,month1,date1); //
	var enteredDate2 = new Date(year2,month2,date2); //
	//alert("date-->"+enteredDate+"-->"+enteredDate.getTime()+"----CurrentDate--->"+currentDate+"--->"+currentDate.getTime());
	if (enteredDate1.getTime() >= enteredDate2.getTime())
	{
		return true;
	}
	else
	{
		return false;
	}
}


/*function checkDate(){
var validformat=/^\d{4}\/\d{2}\/\d{2}$/ //Basic check for format validity
var returnval=false
	// if both the values are not given
	if(!document.frm_reportGeneration.dateOfSample.value )
	return false;
	
	if (!validformat.test(document.frm_reportGeneration.dateOfSample.value))
		alert("Invalid Date Format. Please correct and submit again.")
	else{ //Detailed check for valid date ranges
		var monthfield1=document.frm_reportGeneration.dateOfSample.value.split("/")[1]
		var dayfield1=document.frm_reportGeneration.dateOfSample.value.split("/")[2]
		var yearfield1=document.frm_reportGeneration.dateOfSample.value.split("/")[0]
		var yearfield2 = Date('Y');
		var monthfield2 = Date('m');

			if (yearfield2 < yearfield1 ){
				alert("Year should be less than current year!")
				document.frm_reportGeneration.dateOfSample.value=""
				}
			else if (monthfield1>monthfield2){
				alert("date of sample month should be than with current month!")
				document.frm_reportGeneration.dateOfSample.value=""			
				}	

				}
			else
				{
					returnval=true 
				}			

		/*var dayobj = new Date(yearfield, monthfield-1, dayfield)
			if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
				alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
			else
				returnval=true*/
/*
}
return returnval
}

*/
// -------------------------------------------------------------------
// autoComplete (text_input, select_input, ["text"|"value"], [true|false])
//   Use this function when you have a SELECT box of values and a text
//   input box with a fill-in value. Often, onChange of the SELECT box
//   will fill in the selected value into the text input (working like
//   a Windows combo box). Using this function, typing into the text
//   box will auto-select the best match in the SELECT box and do
//   auto-complete in supported browsers.
//   Arguments:
//      field = text input field object
//      select = select list object containing valid values
//      property = either "text" or "value". This chooses which of the
//                 SELECT properties gets filled into the text box -
//                 the 'value' or 'text' of the selected option
//      forcematch = true or false. Set to 'true' to not allow any text
//                 in the text box that does not match an option. Only
//                 supported in IE (possible future Netscape).
// -------------------------------------------------------------------
function autoComplete (field, select, property, forcematch) {
	var found = false;
	for (var i = 0; i < select.options.length; i++) {
	if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
		found=true; break;
		}
	}
	if (found) { select.selectedIndex = i; }
	else { select.selectedIndex = -1; }
	if (field.createTextRange) {
		if (forcematch && !found) {
			field.value=field.value.substring(0,field.value.length-1); 
			return;
			}
		var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
		if (cursorKeys.indexOf(event.keyCode+";") == -1) {
			var r1 = field.createTextRange();
			var oldValue = r1.text;
			var newValue = found ? select.options[i][property] : oldValue;
			if (newValue != field.value) {
				field.value = newValue;
				var rNew = field.createTextRange();
				rNew.moveStart('character', oldValue.length) ;
				rNew.select();
				}
			}
		}
	}



/**********************************************************************************/
// date function
/*********************************************************************************/
var dtCh= "-";
var minYear=1900;
var maxYear=2100;

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
}

/**********************************************************************************/
// date function
/*********************************************************************************/


function validDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=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 : dd-mm-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 triminput(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
