//   utilities.js
//
// This is a file of common JavaScript form validation 
// utilities which can be reused between various modules.
//
//  Created by: M.K
//  Created on: 07/23/2004
//
var onloads = new Array();


_editor_url = "./includes/htmlarea/htmlarea/";                     // URL to htmlarea files
var win_ie_ver = parseFloat(navigator.appVersion.split("MSIE")[1]);
if (navigator.userAgent.indexOf('Mac')        >= 0) { win_ie_ver = 0; }
if (navigator.userAgent.indexOf('Windows CE') >= 0) { win_ie_ver = 0; }
if (navigator.userAgent.indexOf('Opera')      >= 0) { win_ie_ver = 0; }
if (win_ie_ver >= 5.5) {
  document.write('<scr' + 'ipt src="' +_editor_url+ 'editor.js"');
  document.write(' language="Javascript1.2"></scr' + 'ipt>');  
} else { document.write('<scr'+'ipt>function editor_generate() { return false; }</scr'+'ipt>'); }


//trim a string by removing all external spaces
function trim(str) { 
    str.replace(/^\s*/, '').replace(/\s*$/, ''); 

   return str;
} 


// Declaring valid date character, minimum year and maximum year
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
}

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
}

//check if a field exists on a given form
function fieldExists(dform,fieldName)
    {
    for(i=0;i<dform.elements.length;i++)
        {
            if (dform.elements[i].name==fieldName)
                {
                return true;
                }
        }

    return false;
    }

//check if a form by given name exists
function formExists(formName)
    {
    for(i=0;i<document.forms.length;i++)
        {
            if (document.forms[i].name==formName)
                {
                return true;
                }
        }

    return false;
    }

//validate all required fields on a form
// (requires ASP function AddInputValidators called to set the list of required fields)
function validateRequiredFields(dform)
    {
   // alert("here");

    if (fieldExists(dform,'donotvalidate'))
        {
        if (dform.donotvalidate.value=="1")
            {
            return true;
            }
        }
    
    
    if (fieldExists(dform,'RequiredTitles'))
       {
       titleArray=dform.RequiredTitles.value.split('##');
       fieldArray=dform.RequiredFields.value.split('##');

       for(i=1;i<fieldArray.length;i++)
          {
            if (titleArray[i]!="")
                {
				    var fldVal;

                    fldVal=getFieldValue(dform,fieldArray[i]);


                    if (trim(fldVal)=="" || trim(fldVal)=="-1" )
                        {
                        alert(titleArray[i]+" is a required field! Please complete.");
                        dform.elements[fieldArray[i]].focus();
                        return false;
                        }
                }
           }
        }

    return true;
    }


function getFieldValue(dform,fieldName)
     {
     var val="";
	 var it=0;

     myObj=document.getElementsByName(fieldName);

     if (myObj)
     {
     
     for (it=0;it<myObj.length;it++)
		 {
		 el=myObj[it];

		 if (el.form)
		 {
             if (el.form.name==dform.name)
             {
             val=val+getOneElementValue(el);
             }
		 }
         
		 }
	 }
	 

     return val;       
     }
  
function getOneElementValue(elm)
{
var val1="";
//alert("one element "+elm.name);
//alert(elm.name+" is "+elm.type);
if(elm.type=="hidden")
	{
	return "";
	}

if (elm.type=="radio" || elm.type=="checkbox")
    {

    if (elm.checked==true)
      {
	  //alert(elm.name+" is checked and is checkbox/radio");
      val1=trim(elm.value);
      }
    }
else
    val1=trim(elm.value);

return val1;
}



function ValidateNumber(fld,title)
    {
    if(isNaN(fld.value.replace("$",""))) 
        {
        alert(title+' is a numeric field! Please enter a number');
        fld.focus();
        return false;
        }

    return true;
    }

function ValidateDate(fld,Title)
    {
       if (trim(fld.value)!="" && !isDate(fld.value) )
          {
          //alert(Title+" is not a valid date! Please correct.");
          fld.focus();
          return false;
          }

    return true;
    }



function tpopup(s)
{
msg=window.open(s, "rblPopup", "scrollbars=yes,status=no,toolbar=no,directories=no,menubar=no,location=no,resizable=yes,width=400,height=400");
}

function cpopup(s,wdth,hght)
{
msg=window.open(s, "rblPopup", "scrollbars=yes,status=no,toolbar=no,directories=no,menubar=no,location=no,resizable=yes,width="+wdth+",height="+hght);
}

function DateAdd(startDate, numDays, numMonths, numYears)
{
	var returnDate = new Date(startDate.getTime());
	var yearsToAdd = numYears;
	
	var month = returnDate.getMonth()	+ numMonths;
	if (month > 11)
	{
		yearsToAdd = Math.floor((month+1)/12);
		month -= 12*yearsToAdd;
		yearsToAdd += numYears;
	}
	returnDate.setMonth(month);
	returnDate.setFullYear(returnDate.getFullYear()	+ yearsToAdd);
	
	returnDate.setTime(returnDate.getTime()+60000*60*24*numDays);
	
	return returnDate;

}

function YearAdd(startDate, numYears)
{
		return DateAdd(startDate,0,0,numYears);
}

function MonthAdd(startDate, numMonths)
{
		return DateAdd(startDate,0,numMonths,0);
}

function DayAdd(startDate, numDays)
{
		return DateAdd(startDate,numDays,0,0);
}

function disallowDate(date) {
  // date is a JS Date object
  //if ( date<DayAdd(new Date(),4) ) {
  //  return true; // disable everything prior to today
  //}
  return false; // enable other dates
}

function UploadFile(FormName,FieldName,Path)
    {
    window.open('car_upload.asp?formname='+FormName+'&fieldname='+FieldName+'&path='+Path,'upload_window','resizable=0,location=0,left=0,top=0,height=600,width=600,scrollbars=1');
    }
  
function HTMLEdit(FieldTitle,FieldName)
    {
    fld=document.getElementById(FieldName)
 
    
    FormName=escape(fld.form.name);
    FieldName=escape(FieldName);
    FieldTitle=escape(FieldTitle);
    FieldValue=escape(fld.value);

    window.open('car_htmledit.asp?FormName='+FormName+'&FieldName='+FieldName+'&FieldTitle='+FieldTitle,'html_window','resizable=1,location=1,left=10,top=10,height=500,width=700');
    }

     
function SubmitWithAction(dform,actionType)
     {
     dform.actiontype.value=actionType;
     dform.submit();
     }
     
function SubmitWithAction2(dform,recordID,actionType,IsPopup)
     {
     //dform.recordid.value=recordID;
    //dform.actiontype.value=actionType;

     
        if (actionType.toUpperCase().indexOf("DELETE")>=0 || actionType.toUpperCase().indexOf("SEND")>=0)
            {
              if (!confirm("Are you sure?"))
                  {
                  return false;
                  }
            }


        if (actionType.toUpperCase().indexOf("REFUND")>=0)
            {
              if (!confirm("You are about to Refund this Transaction. Do you wish to Continue?"))
                  {
                  return false;
                  }
            }

            
     actionKeyword="actiontype";
     recordKeyword="recordid";
     
     //determine if action is second level, or first level
     if (actionType.indexOf("attach")>=0 || actionType.indexOf("detach")>=0 || actionType.indexOf("2")>=0 )
         {
         actionKeyword="subactiontype";
         recordKeyword="subrecordid";         
         }          
     
     var str=window.location.href;

     //exclude # sign
     if (str.indexOf("#")>=0)
         {
         str=str.substring(0,str.indexOf("#"));
         }


     str=ExcludeQuerystring(str,actionKeyword);
     str=ExcludeQuerystring(str,recordKeyword);

     if (actionKeyword=="actiontype")
     {
     str=ExcludeQuerystring(str,"subactiontype");
     str=ExcludeQuerystring(str,"subrecordid");
     }

               
     

     myurl=str+ "&"+recordKeyword+"="+recordID+"&"+actionKeyword+"="+actionType;
     
     //alert(myurl);

     if(IsPopup=="1")
         {
         window.open(myurl +"&type=pfv");
		 }
	 else
         {
         window.location.href=myurl;
         }

     return true;
     }
     
     
function CollectFormFields(dform)
    {
    var url="1=1";
    
        for(i=0;i<dform.elements.length;i++)
        {
        val="";
        
        if (dform.elements[i].type=="checkbox" || dform.elements[i].type=="radio" )
            {
            if (dform.elements[i].checked)
                {
                val=dform.elements[i].value;
                }
            }
        else
            {
            val=dform.elements[i].value;
            }
        
        
        url=url+"&"+escape(dform.elements[i].name)+"="+escape(val);
        }
        
        return url;
    }     
           
   
function ExcludeQuerystring(str,queryStr)
    {
    var localStr=str;
    
    
         if (localStr.indexOf(queryStr)>0)
         {
         indexStart=localStr.indexOf(queryStr);
         indexEnd=localStr.indexOf("&",indexStart);
         
             if (indexEnd==-1)
                {
                indexEnd=localStr.length;
                }             
         
         //alert(queryStr+" found at index"+indexStart+",ends at "+indexEnd+"!");        
         //alert(localStr.substring(localStr,indexEnd,localStr.length));
         localStr=localStr.replace(localStr.substring(indexStart,indexEnd),"");
         
         while (localStr.indexOf("&&")>=0)
             {
             localStr=localStr.replace("&&","");
             }
         
         
         //localStr=localStr.substring(localStr,0,indexStart)+localStr.substring(localStr,indexEnd,localStr.length);
         }
     
    return localStr;
    }     
     

function AddToElement(ElementID,Value)
    {
    var fld=document.getElementById(ElementID);

       if (win_ie_ver>5.5)
           {
           editor_insertHTML(ElementID,'\n<br>'+Value,'',0);
           }
       else
           {
           fld.value=fld.value+'\n<br>'+Value;
           }

    }

/* 

Specific functions from this point on

*/
function JobDetails(JobID)
    {
    window.open('printshop_jobdetails.asp?JobID='+JobID,'job_details','resizable=1,scrollbars=1,location=0,left=10,top=10,height=600,width=450');
    }

function ConvertToPDF(FileID)
    {
    window.open('printshop_pdfconvert.asp?FileID='+FileID,'pdf_conversion','resizable=1,scrollbars=1,location=0,left=10,top=10,height=250,width=300');
    }

function UserDetails(UserID)
    {
    window.open('printshop_customerdetails.asp?UserID='+UserID,'user_details','resizable=1,scrollbars=1,location=0,left=10,top=10,height=400,width=450');
    }

function RerouteJob(JobID)
    {
    window.open('printshop_jobadminreroute.asp?JobID='+JobID,'job_reroute','resizable=1,scrollbars=1,location=0,left=10,top=10,height=400,width=450');
    }

function ManageJob(JobID)
    {
    window.open('printshop_adminmanagejobs.asp?JobID='+JobID,'job_manage','resizable=1,scrollbars=1,location=0,left=10,top=10,height=400,width=450');
    }

function ShippingRequiredSwitch(Nm,Vl,Fm)
    {
    //alert('whopsie!');
    

        for (i=0;i<Fm.elements.length;i++)
           {
           if (Fm.elements[i].name.indexOf("shipping")>=0 && Fm.elements[i].name!=Nm )
               {
               if (Vl=='No')
                   {
                   Fm.elements[i].disabled=true;
                   }
               else
                   {
                   Fm.elements[i].disabled=false;
                   }
               }
           }


 
    }


function SettingDescription(SettingID)
    {
    window.open('printshop_settingdesc.asp?SettingID='+SettingID,'setting_description','resizable=1,scrollbars=1,location=0,left=10,top=10,height=400,width=400');
    }

function DisplayReport(dform)
    {
       if (!validateRequiredFields(dform) )
           {
           return;
           }
     
    /*
    var BaseURL=dform.BaseURL.value;
    
    parameterArray=dform.ReportParameters.value.split(',');
    
    for (i=0;i<parameterArray.length;i++)
        {
          if (trim(dform.elements[parameterArray[i]].value)!="")
              {        
              BaseURL=BaseURL+"&"+parameterArray[i]+"="+dform.elements[parameterArray[i]].value;
              }
        }
        
        BaseURL=BaseURL + "&rs:Format="+dform.ReportDisplayFormat.value;
   
   //document.write(BaseURL);   
   */
           
    window.open("about:blank","reporting_window","location=0,toolbars=0,left=10,top=10,width=800,height=600,resizable=1,scrollbars=1")   
    }
       
function URLencode(sStr) {
    return escape(sStr).replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g, '%2F');
  }

 
function RepointAllLinks(frame_name)  
   {  
   var lnk=window.frames[frame_name].document.links;
    
      for (i=0;i<lnk.length;i++)
          {
          lnk[i].target="_blank";
          }
         
   
   } 
   
   
   
function CheckReportSection(box)
    {
    var dform=box.form;
    
       for (i=0;i<dform.elements.length;i++)
           {
           
               if (dform.elements[i].name.indexOf(box.name)>=0)
                   {
                   dform.elements[i].checked=box.checked;
                   }
           
           }
    
    }  
    
function DisableAllControls(formName)
    {
    var dform=document.forms[formName];
    

       for (i=0;i<dform.elements.length;i++)
           {
           dform.elements[i].disabled=true;           
           }    
    
    }     


function custLog(x,base) {
// Created 1997 by Brian Risk.  http:
//members.aol.com/brianrisk
	return (Math.log(x))/(Math.log(base));
}

function mod(divisee,base) {
// Created 1997 by Brian Risk.  http:
//members.aol.com/brianrisk
	return Math.round(divisee - (Math.floor(divisee/base)*base));
}

function custRound(x,places) {
// Created 1997 by Brian Risk.  http:
//members.aol.com/brianrisk
	return (Math.round(x*Math.pow(10,places)))/Math.pow(10,places)
}

function fractApprox(x,maxDenominator) {
// Created 1997 by Brian Risk.  http:
//members.aol.com/brianrisk
	maxDenominator = parseInt(maxDenominator);
	var approx = 0;
	var error = 0;
	var best = 0;
	var besterror = 0;
	for (var i=1; i <= maxDenominator; i++) {
		approx =Math.round(x/(1/i)); error =(x - (approx/i))
		if (i==1) {best =i; besterror =error;} if (Math.abs(error) != Math.abs(besterror)) {best = i; besterror = error;}
	}
	return (Math.round(x/(1/best)) + "/" + best);
}


function baseConverter (number,ob,nb) {
// Created 1997 by Brian Risk.  http:
//members.aol.com/brianrisk
	number = number.toString().toUpperCase();
	var list = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var dec = 0;
	for (var i = 0; i <=  number.length; i++) {
		dec +=(list.indexOf(number.charAt(i))) * (Math.pow(ob , (number.length - i - 1)));
	}
	number =""; var magnitude =Math.floor((Math.log(dec))/(Math.log(nb))); for (var i =magnitude; i >= 0; i--) {
		var amount = Math.floor(dec/Math.pow(nb,i));
		number = number + list.charAt(amount); 
		dec -= amount*(Math.pow(nb,i));
	}
	return number;
}

function encryptIt(_in) 
  {
  // the following letters are going to be encrypted.
  var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  var letterCode=new Array();

  for(var i=0;i<letters.length;i++)
  {
    var _temp=baseConverter(letters.charCodeAt(i),10,16);
    letterCode[i]="%"+_temp;
  }
  //alert(letterCode[letters.indexOf("j")]);
  var _search = _in.indexOf("?")==-1?"":"?"+_in.split("?")[1];
  var _formIn = _in.indexOf("?")==-1?_in.split("."):_in.split("?")[0].split(".");
  
  var output = _formIn[0]+".";
  
  for(var i = 0; i < _formIn[1].length; i++) {
    if(letters.indexOf(_formIn[1].charAt(i))!=-1) {
	  if (letters.indexOf(_formIn[1].charAt(i))!=-1) {
	   // its a letter
		var x = (Math.random()*1000);
		var j = letters.indexOf(_formIn[1].charAt(i));
		if (x > 500) {
		 // j should be 0 through 25 for lowercase and 26 through 51 for uppercase
		 // switch them
		  if (j < 26) j += 26;
		  else        j -= 26;
		}
		if (x < 300) { output += _formIn[1].charAt(i);
		} else { output += letterCode[j]; }
	  } else { output += escape(_formIn[1].charAt(i)); }
	} else { output += _formIn[1].charAt(i); }
  }
  for(var i=2;i<_formIn.length;i++)
    output += "."+_formIn[i];
  
  return output+_search;
}

function UpdateLookup(dform,ControlName)
    {
    dform.donotvalidate.value="1";
    dform.focuscontrol.value=ControlName;
    }
    
function AssignFormFocus(dform)
    {
    
    if (fieldExists(dform,"focuscontrol"))
        {
           if (dform.elements["focuscontrol"].value!="" && dform.elements["focuscontrol"].value!=null)
               {
               dform.elements[dform.focuscontrol.value].focus();
               }
        }
    
    }
    
 function PageLoadedChecks()
     {
     for (i=0;i<document.forms.length;i++)
         {
         AssignFormFocus(document.forms[i]);
         }
     
     //dw_Tooltip.init();    
     }   
    
 function RefreshWithFocus(ditem)
    {
    ditem.form.donotvalidate.value="1";
    ditem.form.focuscontrol.value=ditem.name;
    ditem.form.submit();
    }   
      
  function doTooltip(id, msg) {
   //alert($(this).attr("id"));
   $("#"+id).attr("title",msg);
   $("#"+id).tooltip();
}

function hideTip(id) {
  //if ( typeof dw_Tooltip == "undefined" || !dw_Tooltip.ready ) return;
  //dw_Tooltip.hide();
  $("#"+id).tooltip().hide();
}

function doHourglass()
{
  document.body.style.cursor = 'wait';
}

function ConfirmDelete(dform)
    {
    if (confirm("Are you sure?"))
        {
        dform.donotvalidate.value="1";
        return true;
        }
        
    return false;    
    }
    
function PrintCommittee(id)
   {
   window.open('../car_about.asp?print=1&id='+id,'print','resizable=1,scrollbars=1,location=0,left=10,top=10,height=600,width=690,menubar=1');    
   }    

function PrintCommitteePDF(id)
   {
   window.open('../car_leadership_pdfconvert.asp?print=1&id='+id,'print','resizable=1,scrollbars=1,location=0,left=10,top=10,height=600,width=690,menubar=1');    
   }


function SendEmail(cust_no)
   {
   window.open('car_about_send_email.asp?cust_no='+cust_no,'email','resizable=1,scrollbars=1,location=0,left=10,top=10,height=420,width=450');    
   }
function ViewDetails(cust_no)
   {
   window.open('car_about_additional.asp?cust_no='+cust_no,'details','resizable=1,scrollbars=1,location=0,left=10,top=10,height=370,width=400');    
   } 
function ViewHTMLPageContent(ViewType, ID)
   {
   window.open('car_html_content.asp?ViewType='+ViewType+'&id='+ID,'details','resizable=1,scrollbars=1,location=0,left=10,top=10,height=500,width=810');    
   }             
function PrintEntireLeadershipDirectory()
   {
   window.open('car_leadership_pdfconvert.asp?print=1&id=','print','resizable=1,scrollbars=1,location=0,left=10,top=10,height=600,width=690,menubar=1');    
   }    
function JoinCommittee(commitee_code)
   {
   window.open('car_about_join_committee.asp?commitee_code='+commitee_code,'email','resizable=1,scrollbars=1,location=0,left=10,top=10,height=450,width=650');    
   }  
   
//
//convention related javascript
//   
function confirmNonMember(mainPage)
    {
    val=confirm("Are you sure that you want to register as non-member? \n You will be charged non-member rates for all Education Courses");
    
       if (val)
           {
           window.location.href=mainPage+"?section=register&NonMember=1";
           }
       else
           {
           window.location.href=mainPage+"?section=register";
           }

    }

function validateLookup(dform)
    {
    if (trim(dform.LastName.value).length<2)
        {
        alert("Please enter at least a Last Name for the search!");
        dform.LastName.focus();
        return false;
        }

    }


function pickMemberRecord(custNum,dform)
    {
    dform.CustomerNumber.value=custNum;
    dform.action="car_events_main.asp?section=register&act=RecordCustomerNumber";
    dform.submit();
    }

function validateRegistrationItems(dform)
   {


   var registrationPurchased=false;

   var disableValidation=false;
   
   if (dform.RegistrationPurchased.value>0) 
       {
       registrationPurchased=true;
       }

       if (dform.eventValidation && dform.eventValidation.value=="1") 
       {
       disableValidation=true;
       }
   
   //alert(registrationPurchased);
   
      for(i=0;i<dform.elements.length;i++)
          {
             if (dform.elements[i].name.substr(0,10)=="REGISTER##" && dform.elements[i].checked)
                 {
                 //alert(dform.elements[i].name);
                 var splitArr=dform.elements[i].name.split("##");
                 
                 itemNum=splitArr[2];
                 itemType=splitArr[1];
                 
                 cost=dform.elements['PRICE_'+itemNum].value;
                 registered=dform.elements['REGISTERED_'+itemNum].value;
                 registration_required=dform.elements['REGISTRATION_REQUIRED_'+itemNum].value; 
                 registration_part=dform.elements['REGISTRATION_PART_'+itemNum].value; 
                 spouse_registration=dform.elements['SPOUSE_REGISTRATION_'+itemNum].value; 
                 is_registration=dform.elements['IS_REGISTRATION_'+itemNum].value; 
				 name=dform.elements['NAME_'+itemNum].value; 
				 non_member=dform.elements["NonMember"].value;

				 
                 
                 if (is_registration=="1")
                     {
                     registrationPurchased=true;
                     }
                 
                 response=true;
                 
                 if (itemType=="P" && !disableValidation)
                     {
                     response=validatePackage(itemNum,registered,cost,name);
                     }
                 else if (itemType=="C"  && !disableValidation )
                     {
                     response=validateCourse(itemNum,registered,cost,registration_required,registration_part,registrationPurchased,name);
                     }
                 else if (itemType=="F"  && !disableValidation )
                     {
                     response=validateFunction(itemNum,registered,cost,registration_required,registration_part,spouse_registration,is_registration,registrationPurchased,non_member,name);
                     }    
                    
                 if (!response)
                     {
                     dform.elements[i].focus();
                     return false;
                     }

                 
                 
                 }
          }
   
   return true;
   
   }
    

function validateFunction(funcNum,registered,price,registration_required,registration_part,spouse_registration,is_registration,registrationPurchased,non_member,name)
    {
		
   //alert("here!");
   //return false;
        if (registered=="1" && is_registration=="1" && spouse_registration!="1" ) 
            {
            alert(name+":\n You are already registered for the event! Please proceed to Checkout \n if you would like to add additional participants.");
            return false;
            }


        if (registration_required=="1" && !registrationPurchased)
            {
            alert(name+":\n You must sign up for REALTOR® Member / Non-Member Registration or Pre-registration to attend this event.");
            return false;
            }
    
        if ( registration_part=="1" && registrationPurchased && is_registration!='1')
           {
           alert(name+":\n This event is included into REALTOR® Member / Non-Member Registration, \n so there is no need to sign up for it separately.");
           return false;
           }

        if (spouse_registration=="1" && non_member=="") 
           {
           val=confirm(name+":\n Please proceed only if your Spouse/Guest are NOT also a REALTOR® member. \n All REALTOR® members have to complete their registration separately \n to ensure their membership account is properly updated! ");
 
              if (!val)
                 {
                 return false;
                 }
           }    

       if (funcNum.indexOf("-T")>=0 && document.RegistrationForm.TshirtPurchased.value=="1") 
           {
           val=confirm("You've already purchased a package that includes a t-shirt. Are you sure that you want to purchase another one?");
 
              if (!val)
                 {
                 return false;
                 }

           }
 

    return true;
    }    
    

function validateCourse(courseNum,registered,cost,registration_required,registration_part,registrationPurchased,name)
    {
    

      if (registered=='1')
          {
          alert("You have already selected this course.  Please scroll down and click on Checkout!");
          return false;
          }

      if (!registrationPurchased && registration_required=='1' )
          {
          alert("You must sign up for REALTOR® Registration or Pre-registration to attend this course.");
          return false;
          }
          
      if (registrationPurchased && registration_part=='1' )
          {
          alert("This item is already part of REALTOR® Registration or Pre-registration. You do not need to purchase it separately.");
          return false;
          }          

    return true;
    }


function validatePackage(packageID,registered,cost,name)
    {
      if (registered=='1')
          {
          alert(name+": You are already registered for this package!");
          return false;
          }
    
    return true;  
    }



function removeItem(itemID,itemType)
    {
    document.Cart.RemoveItem.value=itemID;
    document.Cart.ItemType.value=itemType;
    document.Cart.submit();
    }

function validateItemQuantity(item)
    {
        if (isNaN(item.value) || item.value<=0)
            {
            alert("Quantity has to be a number greater than 0!");
            item.focus();
            }

    }


function updateItem(itemID,itemType,itemQuantity)
    {
    document.Cart.UpdateItem.value=itemID;
    document.Cart.ItemType.value=itemType;
    document.Cart.UpdateQuantity.value=itemQuantity;
    //alert(itemQuantity);
    document.Cart.submit();
    }

function verifyPaymentForm(dform)
   {

  if (dform.TotalAmount.value>0)
   {

   if (dform.PaymentType.value=="CreditCard")
       {
   	   if ( trim(dform.CardNumber.value).length<13 || trim(dform.CardNumber.value).length>16 || isNaN(trim(dform.CardNumber.value)) )
       		{
       		alert("Invalid Credit Card Number!");
       		dform.CardNumber.focus();
       		return false;
       		}

 		    cc=dform.CardNumber.value;

   		if (cc.length==16 && (cc.substring(0,2)=='51' || cc.substring(0,2)=='52' || cc.substring(0,2)=='53' || cc.substring(0,2)=='54' || cc.substring(0,2)=='55') && dform.CardType.value!="Master Card" )
       		{
       		alert("You have picked "+dform.CardType.value+" for the type, \n but the CC Number belongs to Master Card. Please correct.");
       		dform.CardNumber.focus();
       		return false;
       		}

	    if ( (cc.length==16 || cc.length==13) && cc.substring(0,1)=='4' && dform.CardType.value!="Visa")
    	    {
       		alert("You have picked "+dform.CardType.value+" for the type, \n but the CC Number belongs to Visa. Please correct.");
       		dform.CardNumber.focus();
       		return false;
       		}
 
   		if (cc.length==15 && (cc.substring(0,2)=='34' || cc.substring(0,2)=='37') && dform.CardType.value!="American Express" )
        	{
       		alert("You have picked "+dform.CardType.value+" for the type, \n but the CC Number belongs to American Express. Please correct.");
       		dform.CardNumber.focus();
       		return false;
       		}
   

   		if (cc.length==16 && cc.substring(0,2)=='6011' && dform.CardType.value!="Discover" )
       		{
       		alert("You have picked "+dform.CardType.value+" for the type, \n but the CC Number belongs to Discover. Please correct.");
       		dform.CardNumber.focus();
       		return false;
       		}
 


        }
     else if (dform.PaymentType.value=="Check")
        {
        
   		if ( trim(dform.AccountName.value)=="")
       		{
       		alert("Please enter your checking/savings account name!");
       		dform.AccountName.focus();
       		return false;
       		}      

   		if ( trim(dform.email.value)=="")
       		{
       		alert("Please enter your email address!");
       		dform.email.focus();
       		return false;
       		}   

   		if ( trim(dform.DriversLicenseNumber.value)=="")
       		{
       		alert("Please enter your Driver's License Number!");
       		dform.DriversLicenseNumber.focus();
       		return false;
       		}  

   		if ( dform.DriversLicenseState.selectedIndex==0 )
       		{
       		alert("Please Select Driver's License State!");
       		dform.DriversLicenseState.focus();
       		return false;
       		}

        if (trim(dform.ADDRESS_1.value)=="")
           {
           alert('Please enter your billing address!');
           dform.ADDRESS_1.focus();
           return false;
           }

        if (trim(dform.CheckNumber.value)=="")
           {
           alert('Please enter your check number!');
           dform.CheckNumber.focus();
           return false;
           }

        if (trim(dform.MICRNumber.value)=="")
           {
           alert('Please enter your MICR number!');
           dform.MICRNumber.focus();
           return false;
           }

        }
     else if (dform.PaymentType.value=="Counter")
        {
         
        if (trim(dform.city.value)=="")
           {
           alert('Please enter your address for the registration!');
           dform.city.focus();
           return false;
           }

        }
  

    }

     if (fieldExists(dform,"Read Cancellation Policy") && dform.elements["Read Cancellation Policy"].checked==false)
        {
        alert("Please read and agree to the CAR Course Attendance/Cancellation Policy before proceeding!");
        dform.elements["Read Cancellation Policy"].focus();
        return false;  
        }

    if (fieldExists(dform,"CompanyName"))
        {
          if (trim(dform.CompanyName.value)=="")
              {
              alert("Please enter Company Name for Registration Records!");
              dform.CompanyName.focus();
              return false;
              }
        }


   for (i=0;i<dform.elements.length;i++)
       {
       dform.elements[i].disabled=false;
 
       if (dform.elements[i].type=="text" &&  dform.elements[i].name.indexOf('_F')>0 && trim(dform.elements[i].value)=="" && dform.elements[i].name.indexOf("REG_")<0)
           {
           alert("Please fill in all of the participant name information.\n This is needed to print a proper badge for you to attend the event.\n The input fields are as follows: Nickname, First Name and Last Name.");
           dform.elements[i].focus();
           return false; 
           }
       /*
	   else if (dform.elements[i].name.indexOf("REG_")>=0 && trim(dform.elements[i].value)=="")
	       {
		    try
			   {
               dform.elements[i].focus();
		       alert("Please provide all of the required registration information!");
               return false;
			   }
            catch(er)
			   {
			   }
	       }
        */
       }


	   if (!validateRequiredFields(dform))
	   {
		   return false;
	   }
   

   if (dform.TotalAmount.value>0 && dform.PaymentType.value!="Counter" )
      {
      alert("Payment Processing can take up to a minute. \nPlease do not click on the Process Payment button again,\n as it could cause your registration to fail.\nThank you for registering. Have a wonderful day!");
      }
   else
      {
      //alert("Thank you for registering. Have a wonderful day!");
      }
   
   return true;
   }




function goHome()
    {
    window.location.href="car_events_main.asp"
    }

function goHomeOnSite()
    {
    window.location.href="car_events_main.asp?section=register"
    }


function verifyRefund(dform)
    {

    

        if (trim(document.RefundForm.ControlNumber.value)=="")
           {
           alert('Please enter a valid ECC Control Number!');
           dform.ControlNumber.focus();
           return false;
           }


        if (trim(document.RefundForm.NarID.value)=="")
           {
           alert('Please enter a valid NAR ID!');
           dform.NarID.focus();
           return false;
           }
       
        if (trim(document.RefundForm.TotalAmount.value)=="" || isNaN(document.RefundForm.TotalAmount.value))
           {
           alert('Please enter a valid refund amount!');
           dform.TotalAmount.focus();
           return false;
           }

    }


function showCoursePolicy()
    {
    window.open("car_edu_show_policy.asp","policy_window","width=500,height=550,scrollbars=1,resize=1");
    }
    
function openSpecialAccomodations()
    {
    window.open('car_edu_special_accomodations.asp','ada_window','left=10,top=10,width=500,height=500,resizable=1,scrollbars=1');   
    }


function RequestRefund(itemType,memberNumber,documentNumber,itemCode)
    {
    window.open('car_request_refund.asp?itemType='+itemType+'&memberNumber='+memberNumber+'&documentNumber='+documentNumber+'&itemCode='+itemCode,'refund_window','left=10,top=10,width=500,height=600,resizable=1,scrollbars=1'); 
    }

function GoToDetailCode(detailCode)
    {
    document.ParticipantForm.action="car_events_main.asp?section=participants";
    document.ParticipantForm.target="_self";
    document.ParticipantForm.detailCode.value=detailCode;
    document.ParticipantForm.submit();
    }


function GoToParticipants()
    {
    document.ParticipantForm.detailCode.value="";
    document.ParticipantForm.action="car_events_main.asp?section=participants";
    document.ParticipantForm.target="_self";
    document.ParticipantForm.submit();
    }

function PrintParticipants()
    {
    document.ParticipantForm.action="car_event_print_participants.asp";
    document.ParticipantForm.target="_blank";
    document.ParticipantForm.submit();
    }




function EnableInsertButtons(dform)
    {
    dform.InsertImage.disabled=false;
    dform.InsertLink.disabled=false;
    }

function DisableInsertButtons(dform)
    {
    dform.InsertImage.disabled=true;
    dform.InsertLink.disabled=true;
    }

function PickFirm(firmCode)
    {
    for (i=0;i<window.opener.document.forms.length;i++)
        {
        var dform=window.opener.document.forms[i];
        
          if (dform.FirmCode)
              {
              //alert(dform.FirmCode);
              dform.FirmCode.value=firmCode;
              dform.submit();
              }
        
        }
    
    window.close();
    }

function focusElement(elname)
   {
     document.all[elname].focus();
   }





function PrintReceipt(docNo,custNo)
   {
   window.open('car_purchase_receipt.asp?doc_no='+docNo+'&cust_no='+custNo,'receipt_window','left=10,top=10,width=750,height=500,scrollbars=1,resizable=1,menubar=1');
   }

function PrintConfirmation(custNo)
   {
   window.open('car_registration_confirmation_letter.asp?cust_no='+custNo,'letter_window','left=10,top=10,width=750,height=500,scrollbars=1,resizable=1,menubar=1');
   }


function explainMICR()
    {
    window.open('car_explain_micr.asp','micr_window','left=10,top=10,width=500,height=500,resizable=1,scrollbars=1');
    }

function showFunction(funcCode)
    {
    window.open('car_events_show_event.asp?id='+funcCode,'function_window','left=10,top=10,width=700,height=600,resizable=1,scrollbars=1');
    }

function tryFocus()
   {

     if (formExists('MemberSearch'))
         {
         document.MemberSearch.LastName.focus();
         }
   }

function CheckFirstName(i,val)
   {
   dform=document.PaymentForm;

     if (fieldExists(dform,'fname'))
         {
           if (trim(dform.fname.value)=="" && i==1)
               {
               dform.fname.value=val;
               }
         }

   }

function CheckLastName(i,val)
   {
   dform=document.PaymentForm;

     if (fieldExists(dform,'lname'))
         {
           if (trim(dform.lname.value)=="" && i==1)
               {
               dform.lname.value=val;
               }
         }

   }


function SelectAllEditBadges(allSelected)
   {
   dform=allSelected.form;

    for(i=0;i<dform.elements.length;i++)
        {
            if (dform.elements[i].name.indexOf("BadgeSelected_")>=0)
                {
                dform.elements[i].checked=allSelected.checked;
                }
        }
 

   }



   
function DisplaySalesReport(dform)
    {
    window.open('car_sale_report.asp?'+CollectFormFields(dform),'function_window','left=10,top=10,width=800,height=600,resizable=1,scrollbars=1');
    }   

function ValidateRefund(dform)
    {
    val=true;

        if (trim(dform.ReceiptNumber.value)=="" && trim(dform.ApprovalNumber.value)=="" )
             {
             alert("Please enter either receipt number or approval number to validate!");
             dform.ReceiptNumber.focus();
             return false;
             }

        if (dform.LineItem.selectedIndex==0 && !dform.FullRefund.checked)
           {
             alert("Please select the line item for refund!");
             dform.LineItem.focus();
             return false;
           }
 
        if (dform.Quantity.selectedIndex==0 && !dform.FullRefund.checked)
           {
             alert("Please select the line item quantity for refund!");
             dform.Quantity.focus();
             return false;
           }

        if (trim(dform.Reason.value)=="")
             {
             alert("Please provide a refund reson for the records!");
             dform.Reason.focus();
             return false;
             }

         if (dform.FullRefund.checked)
             {
             val=confirm("Are you sure that you want to refund the whole order? \n This will cancel all event/course registrations in the order!");
             }

    return val;
    }       
   
   
   //
   //  edu utilities
   //

   function markLastCourse()
   {

   document.RegistrationForm.LastCourseSelection.value='YES';
   }

   function registerCourse(courseNum,registered,cost)
    {
      if (registered=='1')
          {
          alert("You have already selected this course.  Please scroll down and click on Proceed to Checkout!");
          return;
          }



       /* if (cost==0) 
            {
            alert("Unable to sign up for the course at this time! Please come back later.");
            return;
            } */


    document.RegistrationForm.RegisteredItem.value=courseNum;
    document.RegistrationForm.RegisteredPrice.value=cost;
    document.RegistrationForm.ItemType.value='C';
    document.RegistrationForm.submit();
    }

   function verifyCourseList(val)
    {
        if (val=="") 
            {
            alert("Please select a valid course.");
            return false;
            }

    return true;
    }
    
    
    function validateNewMessage(dform)
    {
        if (trim(dform.MessageSubject.value)=="")
            {
            alert("Please enter a valid message subject");
            dform.MessageSubject.focus();
            return;
            }


        if (trim(dform.course.value)=="")
            {
            alert("Please select a valid course!");
            return;
            }

    dform.submit();
    }

function searchCourse()
    {
    window.open("car_edu_search_course.asp","search_window","width=650,height=600,resize=1,scrollbars=1");
    }
    

function registerCoursePopup(courseNbr)
    {
    var my_window=window;
    var my_closing_window=window;

       while(my_window.opener)
           {
           my_closing_window=my_window;
           my_window=my_window.opener;
           my_closing_window.close();
           }


    my_window.location.href='car_edu_main.asp?section=register&RegisteredItem='+courseNbr;
       

    }

    
function pickSearchCourse(courseNumber) 
    {
    window.opener.document.CourseManagementForm.elements["course"].value=courseNumber;

	if (!window.opener.document.CourseManagementForm.CourseSearchDNU)
	{
		 window.opener.document.CourseManagementForm.submit();
	}
   
    window.close();
    }

function showFutureCourses()
   {
   document.RegistrationForm.program.value="-1";
   document.RegistrationForm.school.value="-1";
   document.RegistrationForm.city.value="-1";
   document.RegistrationForm.title.value="";
   document.RegistrationForm.SearchCourses.click();
   }


function displayCourseCalendar()
    {
    window.open("car_edu_course_calendar.asp","calendar_window","left=10,top=10,resizable=1,scrollbars=1");
    }

function focusOnItem(formName,itemName)
    {
       if (formExists(formName) && fieldExists(document.forms[formName],itemName))
           {
           document.forms[formName].elements[itemName].focus();
           }
    }  
    
function performHostAction(action)
    {
    window.open('car_member_search.asp?actn='+action,"action_window","width=700,height=550,scrollbars=1,resize=1");
    }


function SearchCustomer(formName,fieldName)
    {
    window.open('car_member_search.asp?formName='+formName+'&fieldName='+fieldName,"action_window","width=700,height=550,scrollbars=1,resize=1");
    }


function SearchCustomers(formName,fieldName)
    {
    window.open('car_member_search.asp?formName='+formName+'&fieldName='+fieldName+"&multiple=true","action_window","width=700,height=550,scrollbars=1,resize=1");
    }


function pickAdminMember(custNo)
    {
    document.frmPage.FoundCustomerNumber.value=custNo;
    document.frmPage.submit();
    }

function openChangePasswordWindow()
    {
    window.open("car_edu_change_password.asp","pass_window","width=500,height=300,scrollbars=1,resize=1");
    }    
    
function showApplication(applicationType)
    {
    window.open("car_edu_show_application.asp?method="+applicationType,"app_window","width=600,height=600,scrollbars=1,resizable=1");
    }
    
function displayOfficialTranscript()
    {
    window.open("car_edu_show_transcript.asp","transcript_window","width=800,height=600,scrollbars=1,resizable=1");
    }    

function printAction(actionType,courseNum,memberNum)
    {
    val=true;
 
        if (actionType=="CERTIFICATE")
            {
            val=confirm("Is the certificate paper loaded into your printer\n and IE headers turned off?");
            }

        if (actionType=="TABLE_TENT")
            {
            val=confirm("Is the table tent paper loaded into your printer\n and IE headers turned off?");
            }

       if (val)
           {
           window.open("car_edu_print_action.asp?action="+actionType+"&courseNum="+courseNum+"&memberNum="+memberNum,"print_window","left=10,top=10,scrollbars=1,resizable=1,menubar=1,width=500,height=500");
           }

    }
    
function updateInstructorBio(courseNbr)
    {
    window.open("car_edu_instructor_bio.asp?courseNbr="+courseNbr,"bio_window","left=10,top=10,width=500,height=400,resizable=1,scrollbars=1");
    }    

function verifyGRIReport(dform)
    {
        if (trim(dform.CourseNbr.value)=='' && trim(dform.BoardNbr.value)=='' && trim(dform.NarID.value)=='' )
            {
            alert('You have to specify at least one search parameter!');
            dform.CourseNbr.focus();
            return false;
            }    

    window.open('about:blank','gri_report_window','left=10,top=10,width=650,height=500,resizable=1,scrollbars=1');
    return true;
    }

function displaySurvey(courseNum)
    {
    window.open('car_edu_survey_results.asp?courseNum='+courseNum,'survey_window','left=10,top=10,width=650,height=500,resizable=1,scrollbars=1');
    }
    
function deleteSurveyQuestion(SurveyID,QuestionSeq)
    {
    val=confirm("Are you sure that you want to delete this question?");

       if (val)
           {
           window.location.href="car_edu_main.asp?section=admin&func=survey&DELETE=1&SURVEY_ID="+SurveyID+"&SEQUENCE="+QuestionSeq;
           }

    }    

function editCustomSurveyAnswers(SurveyID,QuestionSeq)
    {
    window.open("car_edu_edit_survey_answers.asp?SURVEY_ID="+SurveyID+"&SEQUENCE="+QuestionSeq,"answer_window","left=10,top=10,width=600,height=500,scrollbars=1,resizable=1");
    }

function deleteSurveyCustomAnswer(SurveyID,QuestionSeq,AnswerSeq)
    {
    val=confirm("Are you sure that you want to delete this custom answer?");

       if (val)
           {
           window.location.href="car_edu_edit_survey_answers.asp?DELETE=1&SURVEY_ID="+SurveyID+"&SEQUENCE="+QuestionSeq+"&ANSWER_SEQUENCE="+AnswerSeq; 
           }

    }
    
    
function runGRIReport(CourseNbr)
    {
    window.open('car_edu_gri_report.asp?CourseNbr='+CourseNbr,'gri_report_window','left=10,top=10,width=650,height=500,resizable=1,scrollbars=1,menubar=1');   
    }    

function displayEthicsReport()
    {
    window.open('car_edu_ethics_report.asp','ethics_window','left=10,top=10,width=500,height=600,resizable=1,scrollbars=1,menubar=1');   
    }
    
function verifyDesigReport(dform)
    {
  
    window.open('about:blank','desig_report_window','left=10,top=10,width=850,height=500,resizable=1,scrollbars=1,menubar=1');
    return true;
    }
    
 function EditSpecialCourseFirms(courseCode)
   {
   window.open('car_edu_special_course_firms.asp?course_code='+courseCode,'special_window','left=10,top=10,width=650,height=500,scrollbars=1,resizable=1');
   }
   
function AddSPCFirm(courseCode)
   {
   window.open('car_edu_search_firm.asp?course_code='+courseCode,'firm_window','left=10,top=10,width=650,height=500,scrollbars=1,resizable=1');
   }

function EditSpecialCourseCourses(offerCode)
   {
   window.open('car_edu_special_course_courses.asp?offer_code='+offerCode,'special_window','left=10,top=10,width=650,height=500,scrollbars=1,resizable=1');
   }
   
    
function SearchMailingCourse(dform)
    {
    dform.action="car_edu_main.asp?section=admin&func=mail";
    dform.target="_self";
    window.open("car_edu_search_course.asp","search_course","left=10,top=10,width=500,height=500,resizable=1,scrollbars=1");
    }          
          
function SearchMailingFirm(dform)
    {
    dform.action="car_edu_main.asp?section=admin&func=mail";
    dform.target="_self";
    window.open("car_edu_search_firm.asp","search_course","left=10,top=10,width=500,height=500,resizable=1,scrollbars=1");
    }
    
function getCourseDetails(courseNbr)
    {
        if (trim(courseNbr)=='') 
             {
             alert("Please select a valid course.");
             }
        else
             {
             window.open('car_edu_show_course.asp?course='+courseNbr,"course_window","width=500,height=550,scrollbars=1,resize=1");
             }
 
    }      
    
function RepointAlLSearchLinks()
    {
    var iframe = document.getElementById("SearchFrame");
    //alert(iframe.contentWindow.document.location.href);
    
    var iframeDoc = iframe.document; 

    //for (i=0;i<iframeDoc.links.length;i++)
    //    {
    //    iframeDoc.links[i].target="top";
    //    alert(iframeDoc.links[i].href);
    //    }    

    }    


function ViewArticle(ArticleID,ExternalURL)
    {
    var URL=ExternalURL;

    if (trim(URL)=="")
        {
        URL="car_news_viewarticle.asp?ArticleID="+ArticleID;
        }

     window.open(URL,"article_detail","left=10,top=10,width=652,height=700,resizable=1,scrollbars=1");

    }

function PreviewNewsletter(id)
   {
   window.open("car_pull_newsletter.asp?id="+id,"newsletter","left=10,top=10,width=672,height=600,scrollbars=1,resizable=1");
   }

function redirectEmbeddedLinks()
   {
   for(i=0;i<document.links.length;i++)
       {
       var link=document.links[i];

       if (link.target=="_embed") 
           {
           var title="";

           if (link.firstChild)
               {
               title=link.firstChild.data;
               }
           else
               {
               title=link.title;
               }


           link.target="_top";
           link.href="index.asp?func=xembeddedlink&link_name="+title+'&link='+link.href;
           }

       }

   }

function InstallAutoTab()
    {

    var nav = window.Event ? true : false;
    if (nav) 
       {
       window.captureEvents(Event.KEYDOWN);
       window.onkeydown = AutoTab;
       } 
    else 
       {
       document.onkeydown = AutoTab;
       }

    }

function AutoTab(e)
    {
       if (!e) var e = window.event;

       var el;

       if (e.srcElement)
           {
           el=e.srcElement;
           }
       else
           {
           el=e.target;
           }



     if (e.keyCode == 13 && el.type != 'submit')
     {
        
         if (el.form)
             {
           
             var dform=el.form;

             if (dform.RunSalesReport)
                 {
                 dform.RunSalesReport.click();
                 return false;
                 }


             var indx=getElementIndex(dform,el.name);

                    try
                        {
                        el.form[indx+1].focus();
                        }
                    catch(ex) {}

             if (el.type == 'button')
                 {
                 el.click();
                 }

             }

         
        

     return false;
     }

    return true;
    }


function getElementIndex(dform,elementName)
    {
    var i=0;

    for (i=0;i<dform.elements.length;i++)
        {
           if (dform.elements[i].name==elementName)
               {
               return i;
               }
        }
    }


function filterForTrademark()
    {
    return;
    var bodyTag=document.body.innerHTML;
    var startCharArray=new Array(" ",">","&nbsp;");
    var endCharArray=new Array(" ","<",".",",","&nbsp;",":",";");
    var replacementMade=false;
 
    if (bodyTag.indexOf("CuteEditor")<=0)
        { 
        for (i=0;i<startCharArray.length;i++)
            {
            for(j=0;j<endCharArray.length;j++)
                {
                //alert("filtering for "+startCharArray[i]+"REALTOR"+endCharArray[j]);
                if (bodyTag.indexOf(startCharArray[i]+"REALTO"+endCharArray[j])>0 || bodyTag.indexOf(startCharArray[i]+"REALTOR"+endCharArray[j])>0 || bodyTag.indexOf(startCharArray[i]+"REALTORS"+endCharArray[j])>0)
                    {
                    //alert("filtering for "+startCharArray[i]+"REALTOR"+endCharArray[j]);
                    replacementMade=true;
                    bodyTag=filterTrademarkCombination(bodyTag,startCharArray[i],endCharArray[j]);
                    }
                }
            }   

        if (replacementMade)
            {
            bodyTag=bodyTag.replace('REALTORS&reg;&reg;','REALTORS&reg;');
            bodyTag=bodyTag.replace('REALTOR&reg;&reg;','REALTOR&reg;');
            bodyTag=bodyTag.replace('REALTOR&reg;®','REALTOR&reg;');
            bodyTag=bodyTag.replace('REALTORS&reg;®','REALTORS&reg;');
            bodyTag=bodyTag.replace('REALTORS&reg;®','REALTORS&reg;');

            document.body.innerHTML=bodyTag;
            }
        }



    }

function filterTrademarkCombination(bodyTag,startChar,endChar)
    {


            bodyTag=bodyTag.replace(startChar+"REALTO"+endChar,startChar+"REALTORS&reg;"+endChar);
            bodyTag=bodyTag.replace(startChar+"REALTOR"+endChar,startChar+"REALTOR&reg;"+endChar);
            bodyTag=bodyTag.replace(startChar+"REALTORS"+endChar,startChar+"REALTORS&reg;"+endChar);
            

    return bodyTag;
    }

function InstructorDetails(CustNo)
    {
    window.open("car_edu_instructor_details.asp?cust_no="+CustNo,"instructor","left=10,top=10,width=672,height=600,scrollbars=1,resizable=1,location=0");
    }

/*
Commercial Property System - RCA

*/

function EditMessage(MessageID)
   {
   SubmitWithAction2(document.frmPage,MessageID,"edit");
   }

function DeleteMessage(MessageID)
   {
   SubmitWithAction2(document.frmPage,MessageID,"delete");
   }


function DeleteMessageFromHistory(MessageID)
   {
   SubmitWithAction2(document.frmPage,MessageID,"deletehistory");
   }


function ActivateMessage(MessageID,ActiveFlag)
   {
   SubmitWithAction2(document.frmPage,MessageID,"toggleactive");
   }


function AddFavoriteMessage(MessageID)
   {
   SubmitWithAction2(document.frmPage,MessageID,"favorite");
   }


function RemoveFavoriteMessage(MessageID)
   {
   SubmitWithAction2(document.frmPage,MessageID,"deletefavorite");
   }


function SendMessage(MessageID)
   {
   SubmitWithAction2(document.frmPage,MessageID,"send");
   }



function ViewMessage(MessageID)
   {
   if (MessageID=="" || MessageID=="-1")
       {
       alert("Please save the message before previewing!");
       return false;
       }
   
   window.open("car_rca_view_message.asp?MessageID="+MessageID,"view_message","left=10,top=10,width=800,height=600,resizable=1,scrollbars=1");
   }

function validateSendMessage(dform)
    {
       if (validateRequiredFields(dform))
           {
           return confirm("Are you sure that you want to send this message now?");
           }
           
    return false;
    }


function SelectAllCheckboxes(dform,fieldName,actiontype)
   {
    for(i=0;i<dform.elements.length;i++)
        {
            if (dform.elements[i].name==fieldName)
                {
                    if (actiontype=="select")
                        {
                        dform.elements[i].checked=true;
                        }
                    else
                        {
                        dform.elements[i].checked=false;
                        }
                    
                }
        }   
   return false;     
   }


function submitLoginForm(dform)
{
   if (validateRequiredFields(dform))
   {
	   dform.submit();
   }
}


function focusOnGrid()
    {
    if (document.getElementById("focuser"))
        {
        var el=document.getElementById("focuser");
        scroll(0,el.style.top+200);
        }
    }

function travelAds()
    {
       if( typeof AdArray == "undefined")
           {
           }
       else
           {
           if (currentPosition>=AdArray.length)
               {
               currentPosition=0;
               }

           var adel=document.getElementById("main_ad");

           
           var el=document.getElementById("ad_"+currentPosition);

           if (el)
           {
           
           adel.innerHTML=el.innerHTML;
           
           adel.style.display="inline";
 
           setTimeout("travelAds()",parseInt(AdArray[currentPosition])*1000);
            currentPosition++;
		   }

           }
    }
    
 function secureImages(securemode)
     {
     return;
     if (securemode=="on")
         {
         if (document.images)
             {
             for (i=0;i<document.images.length;i++)
                 {
                 document.images[i].src=document.images[i].src.replace("http://","https://");
                 }
             }
         }
     }   
    
	function SetEduPassAll(dform)
	{
    for(i=0;i<dform.elements.length;i++)
        {
            if (dform.elements[i].name.indexOf("GR_")>=0)
                {
                dform.elements[i].value="P";
				}
		}

	}


	function SetEduAttendAll(dform)
	{
    for(i=0;i<dform.elements.length;i++)
        {
            if (dform.elements[i].name.indexOf("AT_")>=0)
                {
                dform.elements[i].value="Y";
				}
		}

	}


	function CopyBillingToReg(dform)
	{
		try
		{
        dform.REG_ADDRESS_1.value=dform.ADDRESS_1.value;
        dform.REG_ADDRESS_2.value=dform.ADDRESS_2.value;
		dform.REG_city.value=dform.city.value;
		dform.REG_state.value=dform.state.value;
		dform.REG_zip.value=dform.zip.value;
		dform.REG_email.value=dform.email.value;
        }
		catch(e)
		{
		}
	}

	function CaptureMouseClick()
    {

     if (document.layers){
     document.captureEvents(Event.MOUSEDOWN);
     document.onmousedown=clickNS4;
     }
     else if (document.all&&!document.getElementById){
     document.onmousedown=clickIE4;
     }

     document.oncontextmenu=new Function("return false")


	}

function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}

function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}

function NoRightClick(e) {
if (navigator.appName == 'Netscape' && 
(e.which == 3 || e.which == 2))
return false;
else if (navigator.appName == 'Microsoft Internet Explorer' && 
(event.button == 2 || event.button == 3)) {
return false;
}
return true;
}


	function AddActionNonMember()
	{
    window.open("car_add_action_non_member.asp","add_action_member","left=10,top=10,width=800,height=600,resizable=1,scrollbars=1");
	}


	function bodyOnLoad() 
    {

	      for ( var i = 0 ; i < onloads.length ; i++ )
	         onloads[i]();
    }

	function focusOnElement(el)
	{

       el.focus();
	}


	function URLDecode( encoded )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;   
}


function popupCloseRedirect(href)
{
   var win=window;

   if (window.opener)
   {
	   win=window.opener;
   }

   win.document.location.href=href;

   if (window.opener)
   {
	  window.close();
   }
}

/*

legal directory
*/
function legalDirectoryListing(id)
    {
    window.open('car_legal_directory_details.asp?id='+id,'micr_window','left=10,top=10,width=500,height=450,resizable=1,scrollbars=1');
    }
