
/* 
    * w2.js  Version 1.0
    * Handles all the request response processing with the servlet
    * Make calls to get metadata, company listing, FI data and tax docs
    * 
    * Copyright HRB Digital LLC
*/

var g_fieldmaxlen   =32;

var w2_global={ 
	_showMaint: true,
    // company meta data related
    _lastErrorCode: null,
    _maxRowCount: null,
    _metadata :null,
        getRecords:function(key){
            w2_global._maxRowCount = this._metadata.maxRowCount;
            var num = 0;
            for (var i=0;i< this._metadata.companyMetaDataVOList.length ;i++){
                var res=searchmetakey(this._metadata.companyMetaDataVOList[i],key);
                if(typeof res !='undefined'){
				 return res;
                }
            } 
            return num;
        },

    //selected company information
    _companyInfo:null,

    getCompanyInfo: function ()     {return this._companyInfo},
    getCoId: function ()            {return this._companyInfo.i},
    getCoName: function ()          {return this._companyInfo.n},
    getCoMilitaryInd: function ()   {return this._companyInfo.m},
    getCoFIProfileID: function()    {return this._companyInfo.fi},
    getCoAvailabilityDate: function()    {return this._companyInfo.availabilityDate},
    // financial institution related
    _fiInfo:null,
    getFiInfo: function()       {return this._fiInfo},
    getOFXAuthParms: function() {return this._fiInfo.OFXAuthParms},
    _pageNameForOmniture: "",
	_defDate:          "2007-01-01",
	_defEndDate:          "2010-01-25",
    _defEndDateDisp:   "January 25, 2010",
	_fieldToGetFocus: "",

    //navigation related code
    _navobj:new Array(),
    _currentPage:0,
    getTotalPages:function(){return this._navobj.length},
    getPage:function(pgnum){
            //alert('get page '+pgnum)

    for (var i=0;i< this._navobj.length;i++ ){
        if (this._navobj[i].pg==pgnum) {
            return this._navobj[i];
        }
    }
    return -1;
    },
    getNextPage:function(){
        if(this._currentPage==this.getTotalPages()){
            return -1;
        }
        return this.getPage(++this._currentPage);   
    },
    getPrevPage:function(){
        if (this._currentPage==1){
            //alert('no more back')
            return -1;
        }
        return this.getPage(--this._currentPage);   
    }
}
var _json_fi_info='';

/*
defaults to initial values and starts the loading process
*/
function w2initialize(){


/*var _u =document.location.href;
if(_u.indexOf('index_test.html') == -1){
	selected_step('w2_service_down');
	return;
}
*/
	document.getElementById('co_name').value='Your employer name';
	w2_global._metadata=null;
	w2_global._companyInfo=null;
	w2_global._fiInfo=null;
	w2_global._lastErrorCode=null;
    document.getElementById('navigationDiv').style.visibility='hidden';
    document.forms['w2actionform'].st.value='sw';
    document.forms['w2actionform'].sv.value='';
    document.forms['w2actionform'].actionstr.value='md';

	if (w2_global._showMaint)
	{
		selected_step('step1_w2_service_down');
	}
	else
	{
		if (g_sys.checkEnv()=="DEV" ){
			// noop			
		}
		else
		{
			loadMetaData();
		}
	}
}

/*
    Display the list of the company in the select option
*/
function displaycompany(resp){
 var compselect=document.getElementById('co_list');
 compselect.options.length=0
 var companyobj=eval('('+resp+')');
        for (var i=0;i< companyobj.length;i++ ) {
        compselect.options[compselect.options.length]= new Option(companyobj[i].n,'{"i":"'+companyobj[i].i+'","m":'+companyobj[i].m+',"fi":"'+companyobj[i].fi+'","availabilityDate":"'+companyobj[i].availabilityDate+ '"}'); 
   }

   if (companyobj.length==1){
	document.getElementById("co_list").selectedIndex=0;
   }
}

/*
    Make an AJAX request for the company metadata
*/
function loadMetaData(){
        g_log.debug('<b>Inside callW2()</b>');
        document.forms['w2actionform'].actionstr.value="md"
        GB_showCenter('W-2 Company List','/taxes/doing_my_taxes/w2/w2process.html',150,400,null,false);           
}

/*
    Make an AJAX request for the company data
*/
function loadCompanyList(){
        document.forms['w2actionform'].actionstr.value="gc";
		//processPixelTracking('W2_GO')

       GB_showCenter('W-2 Company List','/taxes/doing_my_taxes/w2/w2process.html',150,400,null,false);           
}

/*
    Make an AJAX request for the company data
*/
function loadFIList()
{
    //Gets the index of the company selected in the listbox
    var co_listbox_index = document.getElementById("co_list").selectedIndex;
    if (co_listbox_index==-1) {
        alert('Please select an employer from the list.');
        return;
    }
        
    //Gets the value of the company selected in the listbox
    var co_listbox_value = document.getElementById("co_list").options[co_listbox_index].value;
    if (co_listbox_value==''){
        alert('Please search for your employer using the search box.');
        return;
    }
    
    w2_global._companyInfo = eval('('+co_listbox_value+')');
    w2_global._companyInfo.n=document.getElementById("co_list").options[co_listbox_index].text;
    document.forms['w2actionform'].actionstr.value='gfi';//
    document.forms['w2actionform'].cid.value=""+w2_global.getCoId();
    document.forms['w2actionform'].fiprofileid.value=""+w2_global.getCoFIProfileID();
    GB_showCenter('FI information','/taxes/doing_my_taxes/w2/w2process.html',150,400,null,false);           
}

/*
    Make an AJAX request for the tax form
*/



function getTaxForm(){
	/*
	1) clone _json_fi_info as _json_fi_info_clone
	2) if OFXAuthParms[k] has subfields, 
		2a) make the parent value = concat of sub field values
		2b) delete OFXAuthParms[k].att_sub_field
    3) send the cloned JSON string to server
	*/

	
	var validationres='';
	var _json_fiInfo_clone_obj = eval('('+jsonToString(_json_fi_info)+')');
	for (var m=0;m <_json_fiInfo_clone_obj.length ;m++ ){
		var authObj =_json_fiInfo_clone_obj[m].OFXAuthParms;
		for (var n=0; n< authObj.length; n++ ){
			var concatVal ='';
			if (typeof authObj[n].attr_sub_field != 'undefined' && authObj[n].attr_sub_field.length > 0){
				for (var p= (authObj[n].attr_sub_field.length-1) ;p>=0 ;p-- ){

					
					 if (authObj[n].attr_sub_field[p].attr_Value=='' || authObj[n].attr_sub_field[p].attr_Value==null || authObj[n].attr_sub_field[p].attr_Value=='0' ){ 
						 /*check for blank*/
						 validationres+=(''+authObj[n].attr_sub_field[p].attr_Display_Desc)+'\n';
					 }
					concatVal+=authObj[n].attr_sub_field[p].attr_Value;
				}				
				authObj[n].attr_Value=concatVal;
				delete authObj[n].attr_sub_field;
			}else{
				 if (authObj[n].attr_Value=='' || authObj[n].attr_Value==null || authObj[n].attr_Value=='0' ){
					 /*check for blank*/
					 validationres+=(''+authObj[n].attr_Display_Desc)+'\n';
				}
			}
		}
	}
	 if (!document.forms['formAuthFields'].w2_terms_conditions.checked){
        alert('In order to send a copy of your W-2 to H&R Block, you must check the box agreeing to the terms and conditions.');
        return false;
    }
	//currently assume only one element in the array of FIinfo
    if(validationres!=''){
		alert('You must enter:\n\n'+validationres);
        return false;
    }

  
    document.forms['w2actionform'].actionstr.value  ='gtf';
    document.forms['w2actionform'].tft.value        ='W2';
    document.forms['w2actionform'].jsondata.value   = jsonToString(_json_fiInfo_clone_obj);
    GB_showCenter('Tax Document Request','/taxes/doing_my_taxes/w2/w2process.html',150,400,null,false);   
}  

/* close the email window */
function emailSuccessCloseWindow(){
    setTimeout('parent.parent.GB_hide()',800);

}
/*
On success of AJAX API for metadata
*/

function metadataRequestSuccess(resp)
{
    setTimeout('parent.parent.GB_hide()',800);
    document.getElementById('co_name').focus();
    resp=''+resp.replace(/\'/g,"%27");

    //replace single quotes and double quotes by their escape value
    var reg_dq= new RegExp('\"\"',"g");
    var reg_w_dq=new RegExp('[a-z]+\"[a-z]+',"gi");

	/*

	comented to fix double quote issues	
	var list_w_dq =resp.match(reg_w_dq);

    if (list_w_dq!=null){
        for (var i=0;i< list_w_dq.length ;i++ ){
        var tmp =list_w_dq[i];
        tmp=tmp.replace("\"","%22");
        resp=resp.replace(list_w_dq[i],tmp);
        }
    }
    resp=resp.replace(reg_dq,"\"%22")
*/

    var reg_w_dq_1=new RegExp('\"\"[a-z0-9]+',"gi");
	var reg_w_dq_2=new RegExp('[a-z0-9]+\"[a-z0-9]+',"gi");
   var reg_w_dq_3=new RegExp('\"\"\"',"gi");

    var list_w_dq =resp.match(reg_w_dq_1);
	if (list_w_dq!=null){
        for (var i=0;i< list_w_dq.length ;i++ ){
        var tmp =list_w_dq[i];
		tmp=tmp.replace("\"\"","\"%22");
        resp=resp.replace(list_w_dq[i],tmp);
        }
    }

	
	list_w_dq =resp.match(reg_w_dq_2);
    if (list_w_dq!=null){
        for (var i=0;i< list_w_dq.length ;i++ ){
        var tmp =list_w_dq[i];
		tmp=tmp.replace("\"","%22");
        resp=resp.replace(list_w_dq[i],tmp);
        }
    }

	 list_w_dq =resp.match(reg_w_dq_3);
     if (list_w_dq!=null){
	   for (var i=0;i< list_w_dq.length ;i++ ){
        var tmp =list_w_dq[i];
		tmp=tmp.replace("\"\"\"","\"%22\"");
        resp=resp.replace(list_w_dq[i],tmp);
        }
    }


   // resp=resp.replace(reg_dq,"\"%22")

    
    //if the cache in the server is empty, goes to servererror
    //screen as soon as the page loads
    if (checkW2Resp('errorCode', resp)){
        selected_step('step3_server_error');
        return;
    }

    w2_global._metadata=eval('('+resp+')');
	//fix to ensure metadata maxrowcount should not be zero. 
	//this is only a safety net, should never occur
	
	if ( w2_global._metadata.maxRowCount==0 || w2_global._metadata.maxRowCount=='0'){
		w2_global._metadata.maxRowCount=500;
	}
}

function companylistsuccess(resp)
{   
    if (resp.indexOf("ERR_203")!=-1){
//        alert("No companies found matching your search critera.");
           selected_step('step3_co_not_participant');
    }
    g_log.debug('<b>Inside companylistsuccess()</b>');
    displaycompany(resp);
    setTimeout('parent.parent.GB_hide()',800);
}

function companylistfailure(errorcode)
{
    g_log.debug('<b>Inside companylistfailure()</b>');
    setTimeout('parent.parent.GB_hide()',800);
    g_log.error("EXXXXXX:"+errorcode);
}

/*
On success of AJAX API for response after a company is selected from the listbox
*/
function financialInstSuccess(resp)
{   

	        g_log.debug('inside financialInstSuccess');

    var cssDisplay      = "block";
    var cssVisibility   = "visible";
    var divToShow='';
    resp=resp.replace(/\n/g, "");
    if (resp=='')
    {   
        //g_log.error('EXXXXXX');
    }

    if (checkW2Resp('errorCode', resp))
    {
        var errorobj=eval('('+resp+')');
        if (errorobj.errorCode=='ERR_62'){
            selected_step('step3_co_not_participant');
        }
        else if (errorobj.errorCode.indexOf('FATAL')>=0){
                selected_step('step3_server_error');
        }        
    //in case of error hold the display for 2 seconds
    setTimeout('parent.parent.GB_hide()',2000);

    }
    else if (checkW2Resp('FIProfileId', resp))
    { 
        g_log.debug('select_co_success FI information from webservice is ok.');
        _json_fi_info = eval('('+resp+')');

        var numberOfFI  = _json_fi_info.length; //Number of FIs to return, in case more than 1 tax document (like a w2 AND a 1099) is returned

        var numberOfAuthFields=0;
        var summaryMsg  = "";   
        var fiName;

        // currently handling only first FI, but the client is 
        // capable of handling multiple at this point change the j <numberOfFI for multiple
        for (var j=0; j<1; j++) 
        {   

			if (getQueryValue("simulate")=="1"){ //simulate future
				 _json_fi_info[j].availabilityDate=  "2011-01-26";
				 //_json_fi_info[j].systemDate=  "2011-01-26";
			}
            
            w2_global._fiInfo = _json_fi_info[j];  

            // Format a system date to be used for FI and COMPANY compare
            var tmpsysDate=(_json_fi_info[j].systemDate).split("-");

            //remove leading zero
            tmpsysDate[1]=tmpsysDate[1].replace(/[0]?/,'');

            //sysDate.setFullYear(tmpsysDate[0],parseInt(tmpsysDate[1])-1,tmpsysDate[2]);
            var sysDate = new Date(tmpsysDate[0],parseInt(tmpsysDate[1])-1,tmpsysDate[2],0,0,0,0);

            // TBD If we are going to support multiple FI's, setting this field here will not work
            document.forms['w2actionform'].fiprofileid.value = _json_fi_info[j].FIProfileId;

                summaryMsg += "Selected Company Information:\n";
                summaryMsg += "name == "            +w2_global.getCoName()+"\n";
                summaryMsg += "companyId == "       +w2_global.getCoId()+"\n";
                summaryMsg += "FIProfileId == "     +w2_global.getCoFIProfileID()+"\n";
                summaryMsg += "Company Availability Date == "+w2_global.getCoAvailabilityDate()+"\n";
                summaryMsg += "militaryIndicator==" +w2_global.getCoMilitaryInd()+"\n\n";
                summaryMsg += "Financial Institution that handles "+w2_global.getCoName()+"'s W2 data\n";
                summaryMsg += "FIProfileId=="       + w2_global._fiInfo.FIProfileId +"\n";
                summaryMsg += "Name=="              + w2_global._fiInfo.FIName      +"\n";
                summaryMsg += "global availabilityDate=="  + w2_global._fiInfo.availabilityDate +"\n";
				summaryMsg += "Current JSON object availabilityDate=="  + _json_fi_info[j].availabilityDate +"\n";
                summaryMsg += "militaryIndicator==" + w2_global._fiInfo.militaryIndicator +"\n\n";
                summaryMsg += "OFX Authorization Fields" + w2_global._fiInfo.militaryIndicator +"\n";

                numberOfAuthFields  = 0;

                if (w2_global._fiInfo.OFXAuthParms != null){
                    numberOfAuthFields = w2_global._fiInfo.OFXAuthParms.length;
                }
                for (var k=0;k<numberOfAuthFields; k++){
                    summaryMsg += "    "+w2_global._fiInfo.OFXAuthParms[k].attr_Display_Desc+"\n";
                }
	            summaryMsg += "\nOther Information in FI Response\n";
                summaryMsg += "systemDate=="+ w2_global._fiInfo.systemDate +"\n";
                //alert(summaryMsg);

				var fiHelp = _json_fi_info[j].authParagraph;

				var fiHelpURL =_json_fi_info[j].FIHelpURL;
				if (fiHelpURL!=null && fiHelpURL.toLowerCase() !='null'){
					if (fiHelpURL.toLowerCase().indexOf('http')==-1){
						fiHelpURL="<a href=\"http://"+fiHelpURL+"\" target=_blank> "+fiHelpURL+"</a>";
					}else{
						fiHelpURL="<a href=\""+fiHelpURL+"\" target=_blank> "+fiHelpURL+"</a>";
					}
				}
				else{
					fiHelpURL="";
				}
				//ADP custom changes
				var auth_help_div= getElementsByAttribute("id", "w2_authhelp");   
				if(w2_global._fiInfo.FIProfileId == "1253223209643"){
					fiHelpURL="<a href=\"#\" onclick=\"GB_showCenter('Paystub Example and iPay Link','/taxes/doing_my_taxes/w2/w2_adp_paystub.html',550,600);\">Paystub Example and iPay Link</a>";
					document.getElementById('fi_auth_custom_msg').innerHTML="<font color=\"#ff4444\"><b> <a href=\"#\" onclick=\"GB_showCenter('Paystub Example and iPay Link','/taxes/doing_my_taxes/w2/w2_adp_paystub.html',550,600);\">Learn more</a> to fill out the fields below using your YEAR END PAYSTUB.</b> </font>";
				}else{
					document.getElementById('fi_auth_custom_msg').innerHTML="";
				}
				for (var x=0;x<auth_help_div.length ;x++ ){ 
					auth_help_div[x].innerHTML=fiHelp + "<br><br>"+fiHelpURL;

				}

            //reseting the authparagraph and help paragraph (special characters in this data causes issues) when posting it back for getTaxdocs
            w2_global._fiInfo.authParagraph='';
            w2_global._fiInfo.helpParagraph='';


            numberOfAuthFields  = 0;
            if (w2_global._fiInfo.OFXAuthParms != null){
                // military will not have auth parms
                numberOfAuthFields = w2_global._fiInfo.OFXAuthParms.length;
            }

            if (w2_global.getCoMilitaryInd()==1){   
                // for military companies, availability date is part of the company information
                divToShow = "step2_military_w2";
                var military_avail_date_spans= getElementsByAttribute("id", "militaryAvailableDate"); 
                
                var tmpMilAvailabilityDate =(w2_global.getCoAvailabilityDate()).split("-");
                tmpMilAvailabilityDate[1]=tmpMilAvailabilityDate[1].replace(/[0]?/,'');
                
                for (var x=0;x<military_avail_date_spans.length ;x++ ){   
                    military_avail_date_spans[x].innerHTML='<b>'+tmpMilAvailabilityDate[1]+'/'+tmpMilAvailabilityDate[2]+'/'+tmpMilAvailabilityDate[0]+'</b>';
                }
            }            
            else { /* non military companies */     
								
				var tmpDefDtArr= w2_global._defEndDate.split("-");
				var defEndAvailDt=new Date();
				defEndAvailDt.setFullYear(tmpDefDtArr[0],parseInt(tmpDefDtArr[1])-1,tmpDefDtArr[2]);

			
				var _w2Avail = false;
				var _w2AvailDt=null
				if (w2_global._fiInfo.availabilityDate==null || (w2_global._fiInfo.availabilityDate == w2_global._defDate)){

					_w2Avail=false;
					divToShow ='step2_w2_not_yet_available_def';
				}
				else{
					var tmpDtArr =w2_global._fiInfo.availabilityDate.split("-");
					_w2AvailDt=tmpDtArr[1]+"/"+tmpDtArr[2]+"/"+tmpDtArr[0];
					tmpDtArr[1]=tmpDtArr[1].replace(/[0]?/,'');
					var fiAvailDt=new Date(tmpDtArr[0],parseInt(tmpDtArr[1])-1,tmpDtArr[2],0,0,0,0);
					//fiAvailDt.setFullYear(tmpDtArr[0],parseInt(tmpDtArr[1])-1,tmpDtArr[2]);
//alert('fiAvailDt'+fiAvailDt +' ::  sysDate'+sysDate);
					if(fiAvailDt.getTime() > sysDate.getTime()){
						_w2Avail=false;
						document.getElementById('w2_avail_future_date').innerHTML =_w2AvailDt;
						divToShow ='step2_w2_not_yet_available';

					}
					else{
						
						_w2Avail=true;
					}
				}
//alert('_w2Avail::'+_w2Avail);

				if (!_w2Avail){ //W2 is not yet available
			
					if (_w2AvailDt==null){//should never occur
					_w2AvailDt="";
					}
					
					// show the required fields in case the W2 is not available
					var tmpofxfielddiv='';
					for (var k=0;k<numberOfAuthFields; k++){
						if (w2_global._fiInfo.OFXAuthParms[k].attr_Field_Name.toLowerCase()=="taxyear"){ 
							continue;
						}
						var pipeFound=containsSymbol(w2_global._fiInfo.OFXAuthParms[k].attr_Display_Desc,"|");
						if (pipeFound){
							var name_array = w2_global._fiInfo.OFXAuthParms[k].attr_Display_Desc.split("|");
							for (var j1 in  name_array){   
								tmpofxfielddiv+='<li><b> '+name_array[j1]+'</b>&nbsp;<br><br></li>';
							}
						}else{
						tmpofxfielddiv+='<li><b> '+w2_global._fiInfo.OFXAuthParms[k].attr_Display_Desc+'</b>&nbsp;<br><br></li>';
						}


					}
					if (tmpofxfielddiv!=''){
						tmpofxfielddiv='<div style="padding-left:15px;padding-top:5px;"><ul>'+tmpofxfielddiv+'</ul></div>';
					}

					document.getElementById('w2download_ofxfields').innerHTML=tmpofxfielddiv;
					document.getElementById('w2download_ofxfields_def').innerHTML=tmpofxfielddiv;



				}
				else{                        
					//build authfields
					
						if(w2_global._fiInfo.FIProfileId == "1252945856159"){
								alert("You must first RESET your PIN with w2express.com. See instructions on next page.");
							}
							

						/*if(w2_global._fiInfo.FIProfileId == "1252945856159"){
							alert("Access to your payroll provider is currently not available.  Please check back later.");
							selected_step('step1_co_lookup');
						    setTimeout('parent.parent.GB_hide()',300);
							return;
				}*/

					for (var k=0;k<numberOfAuthFields; k++){

						if (w2_global._fiInfo.OFXAuthParms[k].attr_Field_Name.toLowerCase()=="taxyear"){ 
								var tmpsysyear=w2_global._fiInfo.systemDate.split("-")[0];
								 w2_global._fiInfo.OFXAuthParms[k].attr_Value = ""+(parseInt(tmpsysyear)-1) ;
								 continue;
						}

						// If a | is found in attr_Display_Desc it must be broken into two input fields as:
						var pipeFound=containsSymbol(w2_global._fiInfo.OFXAuthParms[k].attr_Display_Desc,"|");
						if (pipeFound){ 
							if (typeof w2_global._fiInfo.OFXAuthParms[k].attr_sub_field == "undefined"){   
								w2_global._fiInfo.OFXAuthParms[k].attr_sub_field = new Array();
								
								var name_array = w2_global._fiInfo.OFXAuthParms[k].attr_Display_Desc.split("|");
								var myObj = null;

								for (var j in  name_array){   
								    myObj = new Object();
									myObj.attr_Field_Name			= "sub_field_"+j;
									myObj.attr_Display_Desc			= name_array[j];
									myObj.attr_Value_Clear_Text_Flag= true;
									myObj.attr_Value				= null;
									myObj.attr_Value_Max_Len		= null;


									//ADP custom changes, max length for Company name is 3
									if(w2_global._fiInfo.FIProfileId == "1253223209643" && j==0){
										myObj.attr_Value_Max_Len=3;
									}
									w2_global._fiInfo.OFXAuthParms[k].attr_sub_field[j] = myObj;
									var tmpInpFld =paintField(w2_global._fiInfo.OFXAuthParms[k].attr_sub_field[j]);
									if (j==0){
										_fieldToGetFocus =tmpInpFld.id
									}
								}
							}
						}
						else{
								paintField(w2_global._fiInfo.OFXAuthParms[k]);
						}
					}     
					//show authorization form
					divToShow = 'step2_w2_form_msg';
				} //End of W2 is available
            }
        }   
		selected_step(divToShow);
	    setTimeout('parent.parent.GB_hide()',300);
		document.getElementById(_fieldToGetFocus).focus();
    }
    else {
        alert("no FI information or errors in response.\n"+resp);
        // no FID's found in response
	    setTimeout('parent.parent.GB_hide()',300);
    }
}

function paintField(OFXobj){
	var tmpo= new OFXField(OFXobj,'');
	var tmpLabelDiv=document.createElement("div");
	tmpLabelDiv.style.height='20px';
	tmpLabelDiv.innerHTML='<b> '+OFXobj.attr_Display_Desc+'</b>';
	document.getElementById('labels').appendChild(tmpLabelDiv)
	document.getElementById('labels').appendChild(document.createElement("br"));
	var tmpInputDiv=document.createElement("div");
	tmpInputDiv.style.height='20px';
	var inp =tmpo.getInputFld();
	tmpInputDiv.appendChild(inp);
	document.getElementById('flds').appendChild(tmpInputDiv);
	document.getElementById('flds').appendChild(document.createElement("br"));
	return inp;

}

function containsSymbol(str,symbol){
	return (str.indexOf(symbol) != -1)?true:false;
}

function setFirstInputFieldFocus(){
	//alert("first field to get focus will be "+w2_global._firstFieldToGetFocus);
	document.getElementById(w2_global._firstFieldToGetFocus).focus();
}

function checkW2Resp(keywords, txt){        
    var chkformat_reg= /[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/;
    try{
        var rc=new RegExp(keywords)
        if (chkformat_reg.test(txt) && rc.test(txt) ){
            return true;
        } 
        else{
            //g_log.error('EXXXXX:'+txt.length+':'+keywords);
        }
    }
    catch (e){
        return true;
    }
    return false;
}

/*
On failure of AJAX API for response after a company is selected from the listbox
*/
function financialInstFailure(errorcode){
    hideProcessingMsg();
    g_log.debug('<b>Inside select_co_failure()</b>');
}
/*
    Ajax success for getTaxDocs request
*/
function taxFormRequestSuccess(resp){   
    g_log.debug('<b>Inside taxFormRequestSucess()</b>');
   // g_log.debug('taxFormRequestSucess():resp==\n'+resp);
    w2_global._bW2Found=false;
    var divToShow = "step3_not_successful";
    if (checkW2Resp('serviceStatusVO', resp)){
        g_log.debug('taxFormRequestSucess():text "errorCode" found in response');
		resp=resp.replace(/\n/g, "");
	    var errorobj=null
		var _errCode="";			
		try{
			errorobj=eval('('+resp+')');
			g_log.debug("errorobj.serviceStatusVO.errorCode=="+errorobj.serviceStatusVO.errorCode);  
			if (errorobj.taxFormInfoResponseVO != null){
				g_log.debug("taxFormInfoResponseVO has W2 information");
				if (errorobj.serviceStatusVO.errorCode.toLowerCase().indexOf("success") != -1){
					w2_global._bW2Found=true;
				}
			}
			_errCode=errorobj.serviceStatusVO.errorCode;
		}
		catch (e){
			var key="errorCode"
			var re = new RegExp( "[\"]" + key + "\":\"[0-9a-zA-Z-]+\"", "i" );
			var match=resp.match( re );
			if (match!=null && match.length==1){
				match=match[0];
				_errCode=match.split(":")[1];
				_errCode=_errCode.replace(/\"/gi,"");
			}
			if ( (typeof _errCode !='undefined') && _errCode!=null && (_errCode.toLowerCase().indexOf("success") !=-1 )){
				w2_global._bW2Found=true;
			}
		}
        if (w2_global._bW2Found){
            g_log.debug('w2_global._bW2Found=='+w2_global._bW2Found);
            divToShow="step3_w2_sent";
           // var tmpcompspan=getElementsByAttribute("id", "w2_currentCompany");  
            /*for (var i=0;i<tmpcompspan.length ;i++ ) {
                tmpcompspan[i].innerHTML=w2_global.getCoName();
            }*/

        }
        else if (false && errorobj.serviceStatusVO.errorCode=='TAXFORMTYPE-ALREADY-REQUESTED'){
            divToShow="step3_already_sent";
        }
        else{
            g_log.debug('show step3_not_successful');
            divToShow="step3_not_successful";
            if (_errCode.indexOf('-') >0){
                _lastErrorCode =_errCode.split("-")[0];
                g_log.debug("_lastErrorCode=="+_lastErrorCode);
                document.getElementById('w2_failuremessage').innerHTML="<b><br/>"+W2ErrorCodes.getErrorMsg( w2_global._fiInfo.FIProfileId,_lastErrorCode)+"</b>";
                g_log.debug("element w2_failuremessage == "+document.getElementById('w2_failuremessage').innerHTML);
            }
        }
        // translate error into user friendly version
    }
    else if (checkW2Resp('errorCode', resp)){
        divToShow="step3_server_error";
    }
    g_log.debug('execute selected_step('+divToShow+')');
    selected_step(divToShow);
    g_log.debug('set timeout at 800');
    setTimeout('parent.parent.GB_hide()',800);
}

function taxFormRequestFailure(errorcode){   

    g_log.debug('<b>Inside taxFormRequestFailure()</b>');
    if (resp==''){
        //g_log.error('EXXXXXX');
    }
    else if (checkW2Resp('errorCode', resp)){
        var errorobj=eval('('+resp+')');
        // translate error into user friendly version
    }
    else{ }
    selected_step('step3_not_successful');
    setTimeout('parent.parent.GB_hide()',800);
}

function metadataFailure(error){
 selected_step('step3_not_successful');
    setTimeout('parent.parent.GB_hide()',800);

}

function buildSubmitRequest(){
    //alert("convert inputs to json string for posting");
}

//function OFXField(fieldAttr,cssClassName,indx)
function OFXField(fieldAttr,cssClassName)
{
    this._fieldAtt=fieldAttr;
    this._cssClassName=cssClassName

    var str=''
    var tmpMaxLen=g_fieldmaxlen;
    if ((typeof this._fieldAtt.attr_Value_Max_Len !='undefined') && this._fieldAtt.attr_Value_Max_Len!=null && this._fieldAtt.attr_Value_Max_Len!=0){
        tmpMaxLen=parseInt(this._fieldAtt.attr_Value_Max_Len);
    }
    var tmpMinLen=1;
    if ((typeof this._fieldAtt.attr_Value_Min_Len !='undefined') && this._fieldAtt.attr_Value_Min_Len!=null){
        tmpMinLen=parseInt(this._fieldAtt.attr_Value_Min_Len);
    }

    this.ofx_txt=document.createElement("input");
    this.ofx_txt.type       = ""+((this._fieldAtt.attr_Value_Clear_Text_Flag)?"text":"password");
    this.ofx_txt.id         = "ofx_"+this._fieldAtt.attr_Field_Name;
    this.ofx_txt.name       = "ofx_"+this._fieldAtt.attr_Field_Name;
    this.ofx_txt.size       = 15;
    this.ofx_txt.maxLength  = tmpMaxLen;
    this.ofx_txt.onclick=function(){
    }
    this.ofx_txt.onblur=function(){
        /*if (self.ofx_txt.value==''){
            alert('Please enter a value for '+self._fieldAtt.attr_Display_Desc);
            return false;
        }*/

		var tmpfldval=self.ofx_txt.value;
		if (tmpfldval.indexOf("\"")>=0 || tmpfldval.indexOf("\\")>=0){
			tmpfldval=tmpfldval.replace("\\","\\\\");
			tmpfldval=tmpfldval.replace("\"","\\\"");
		}
        self._fieldAtt.attr_Value=escape(tmpfldval);
    }

    this.getInputFld=function(){
        return this.ofx_txt;
    }
    this.getAttributeObject=function(){
        return this._fieldAtt;
    }

    /*can expand this functionality if field entry needs restriction*/
	/*this.ofx_txt.onkeypress=function(clickevent){
		
        var allowedchar='';
        var tmpFldType= (typeof self._fieldAtt.attr_Value_Type =='undefined')?null:self._fieldAtt.attr_Value_Type;
        
        if (tmpFldType!=null){
            if (tmpFldType=='NUMERICONLY'){
                allowedchar='^\d{'+tmpMinLen+','+tmpMaxLen+'}$'
            }
        }
        var keynum = window.event?event.keyCode : clickevent.which;
        keychar =String.fromCharCode(keynum);
        var tmpReg= new RegExp(allowedchar);
        return tmpReg.test(keychar);
    }
		*/
	

    var self=this; 
   
}

function OFXFieldError(fieldAttr,cssClassName)
{
    this._fieldAtt      = fieldAttr;
    this._cssClassName  = cssClassName

    this.getInputFldError=function(){
        return this.ofx_txt_err;
    }

    this.ofx_txt_err=document.createElement("span");
    this.ofx_txt_err.type       = "text";
    this.ofx_txt_err.id         = "ofx_"+this._fieldAtt.attr_Field_Name+"_error";
    this.ofx_txt_err.name       = "ofx_"+this._fieldAtt.attr_Field_Name+"_error";
    this.ofx_txt_err.innerHTML  = "id is ofx_"+this._fieldAtt.attr_Field_Name+"_error";
//alert("OFXFieldError()"+this._fieldAtt.attr_Field_Name);
    if (this._fieldAtt.attr_Error_Code != null && this._fieldAtt.attr_Error_Code != ""){
        this.ofx_txt_err.innerHTML  = this._fieldAtt.attr_Error_Code;
    }

    var self=this;
}
function displayErrorMessages(resp)
{
    // errors were detected on server side validation
    //alert("Top of displayErrorMessages()\n"+resp);
    setTimeout('parent.parent.GB_hide()',100);
}

function submitw2office()
{
    var city=document.forms['w2_officeform'].city.value;
    var zip=document.forms['w2_officeform'].zipcode.value;
    var state=document.forms['w2_officeform'].state.value;    
    if (zip==''){
        if (city=='' && state!=''){
            alert('Enter City information.')
             return false;
        }else if (state=='' && city!=''){
            alert('Enter select a State.')
             return false;
        }else if (state=='' && city==''){
            alert('Please enter City and State or ZIP.')
             return false;
        }
    }else if (zip.length!=5){
        alert('Please enter a valid ZIP code')
        return false;
    }

    //document.forms['w2_officeform'].submit();
    var w2Parm="";
    if (getCookie("w2")=="1"){
        w2Parm="&w2=yes";
    }
    else{
     w2Parm="&w2=no";
    }
    document.location="http://taxprofinder.hrblock.com/referralEntry.aspx?searchOption=office&oZipCode="+zip+"&oAddress=&oCity="+city+"&oState="+state+"&espanol=no"+w2Parm;
    return true;
}

//FI specific error messages
 W2ErrorCodes={
        _err: [ {   //Generic error messages
                fid:'-9999',indx:-1,name:'default',errcode:['2000','2001','2002','2003','2004','2005','14600','14601','15000','15500','15501','20050','1007','1111'],
                errmsg:[
				'We are experiencing technical difficulties in retrieving your tax form. Please check back later or wait to receive your tax form in the mail.',
                'We are sorry, but we are unable to process your request. Please try again later.',
                'Your tax information is not available. You will need to wait until you receive your tax form in the mail.',
                'We are sorry, but we are unable to process your request. Please try again later.' ,
                'We are sorry, but we are unable to process your request. Please try again later.',
                'We are unable to access your W-2 information at this time due to a system or user error.  Please re-enter your authentication information.  If you continue to fail you will need to wait until you get your W-2 from your employer.',
				'We are unable to access your W-2 information at this time due to a user or system error. Please re-enter your authentication information using the help displayed at the right of the screen. If you continue to fail you will need to wait until you receive your W-2 from your employer.',
				'We are unable to access your W-2 information at this time due to a system or user error. Please re-enter your authentication information. If you continue to fail you will need to wait until you get your W-2 from your employer.',
				'We are sorry, but we are unable to process your request.  Please check with your company&#39;s payroll department to ensure your authentication information is correct.',
				'One of the required fields is not populated or contains wrong information. Please try again. If you continue to fail, please contact your company&#39;s payroll department to ensure your authentication information is correct.',
				'We are sorry, but we are unable to process your request. Please try again later.',
				'We are sorry, but we are unable to process your request. Please try again later.',
				'Your W-2 is currently unavailable.  Please try again later or wait until you receive your W-2 from your employer.','The payroll provider your company uses is currently unable to process your request.  Please try again later.'
				
                ] 
            },
            {   //JAT
                fid:'1286898812294',indx:1,name:'JA',errcode:['2001','2003','15000','15502'],
                errmsg:['We are sorry, but we are unable to process your request.  You may need to change your Password.  For help go to https://www.eprintview.com','We are sorry, but we are unable to process your request.  You may need to change your Password.  For help go to https://www.eprintview.com','We are sorry, but we are unable to process your request.  You will need to change your Password.  For help go to https://www.eprintview.com','We are sorry, but we are unable to process your request. You may need to reset your password and try again later.'
                ]

            },{   //NFC
                fid:'1287684461003',indx:1,name:'NF',errcode:['2001','2003','15000','15502'],
                errmsg:['We are sorry, but we are unable to process your request.  You may need to change your Password.  For help go to https://www.nfc.usda.gov/personal','We are sorry, but we are unable to process your request.  You may need to change your Password.  For help go to https://www.nfc.usda.gov/personal','We are sorry, but we are unable to process your request.  You will need to change your Password.  For help go to https://www.nfc.usda.gov/personal','You have exceeded the maximum number (3) of attempts to login.  Please wait 24 hours for account to reset.  You may need to change your password and try again later.'
                ]

            }	
			,{   //CIC plus
                fid:'1252945856155',indx:1,name:'CI',errcode:['15502'],
                errmsg:['We are sorry, but we are unable to process your request.  Please try again later.',
                ]

            },
            {   //Ingentra
                fid:'1252945856156',indx:1,name:'IN',errcode:['15502'],
                errmsg:['You have exceeded the maximum number (3) of attempts to login.  Please contact Customer Service 1-866-664-3113 for assistance.',
                ]
            },
            {   //CERIDIAN
                fid:'1252945856168',indx:1,name:'CE',errcode:['15502'],
                errmsg:['You have exceeded the maximum number of attempts to login.  Your employer limits the number of login attempts to help keep the W-2 information secure. You need to contact your company&#39;s payroll department for a new password.',
                ]
            },
            {   //ADP
                fid:'1253223209643',indx:1,name:'AD',errcode:['15502'],
                errmsg:['You have exceeded the maximum number of attempts. Your access is blocked.  Please use the W-2 received from your employer to prepare your tax return. ',
                ]
            },
            {   // - TALX3/ID&PIN
                fid:'1252945856161',indx:5,name:'T3',errcode:[['2001','2003','15000'],'15502'],
                errmsg:[
				'We are sorry, but we are unable to process your request. You may need to reset your PIN.  For help go to www.w2express.com/help','You have exceeded the maximum number (5) of attempts to login.  Please wait 15 minutes for account to reset and try again.'
                ]

            },
            {   // - TALX4/Equifax/ID&PIN
                fid:'1252945856162',indx:4,name:'T4EQ',errcode:[['2001','2003','15000'],'15502'],
                errmsg:[
				'We are sorry, but we are unable to process your request. You may need to reset your PIN.  For help go to www.w2express.com/help','You have exceeded the maximum number (5) of attempts to login.  Please wait 15 minutes for account to reset and try again.'
                ]

            },		   
            {   // - TALX 2/SSN&PIN Equifax
                fid:'1252945856160',indx:5,name:'T2EQ',errcode:[['2001','2003','15000'],'15502'],
                errmsg:[
                'We are sorry, but we are unable to process your request. You may need to reset your PIN.  For help go to www.w2express.com/help','You have exceeded the maximum number (5) of attempts to login.  Please wait 15 minutes for account to reset and try again.'
				]
            }
            ,
            {   // - TALX 1/ID&PIN Equifax
                fid:'1252945856158',indx:6,name:'T1EQ',errcode:[['2001','2003','15000'],'15502'],
                errmsg:[
				'We are sorry, but we are unable to process your request. You may need to reset your PIN.  For help go to www.w2express.com/help','You have exceeded the maximum number (5) of attempts to login.  Please wait 15 minutes for account to reset and try again.'
                ]
            }
            ,
            {   // - TALX 2/SSN&PIN NO Equifax
            fid:'1252945856159',indx:7,name:'T2NOEQ',errcode:[['2001','2003','15000'],'15502'],
            errmsg:[
               'We are sorry, but we are unable to process your request. You may need to reset your PIN.  For help go to www.w2express.com/help','You have exceeded the maximum number (5) of attempts to login.  Please wait 15 minutes for account to reset and try again.'
				]
            },
            {   // - TALX 1/ID&PIN NO Equifax 
                fid:'1252945856157',indx:8,name:'T1NOEQ',errcode:[['2001','2003','15000'],'15502'],
                errmsg:[
				'We are sorry, but we are unable to process your request. You may need to reset your PIN.  For help go to www.w2express.com/help','You have exceeded the maximum number (5) of attempts to login.  Please wait 15 minutes for account to reset and try again.'
                ]
            },
            {   // - TALX 2/Walmart/SSN&PIN
				fid:'1252945856167',indx:9,name:'T2WMRT',errcode:[['2001','2003','15000'],'15502'],
				errmsg:[
				'We are sorry, but we are unable to process your request. You may need to reset your PIN.  For help go to www.w2express.com/help','You have exceeded the maximum number (5) of attempts to login.  Please wait 15 minutes for account to reset and try again.'
				]
			},
			{   // - TALX 2/Sears/SSN&PIN
				fid:'1252945856166',indx:10,name:'T2Srs',errcode:[['2001','2003','15000'],'15502'],
				errmsg:[
				'We are sorry, but we are unable to process your request. You may need to reset your PIN.  For help go to www.w2express.com/help','You have exceeded the maximum number (5) of attempts to login.  Please wait 15 minutes for account to reset and try again.'
				]
			},
			{   // - TALX 2/Labor Ready/SSN&PIN
				fid:'1252945856164',indx:11,name:'T2LR',errcode:[['2001','2003','15000'],'15502'],
				errmsg:[
				'We are sorry, but we are unable to process your request. You may need to reset your PIN.  For help go to www.w2express.com/help','You have exceeded the maximum number (5) of attempts to login.  Please wait 15 minutes for account to reset and try again.'
				]
			},
			{   // - TALX 2/Lowe's/SSN&PIN
				fid:'1252945856165',indx:12,name:'T2',errcode:[['2001','2003','15000'],'15502'],
				errmsg:[
				'We are sorry, but we are unable to process your request. You may need to reset your PIN.  For help go to www.w2express.com/help' ,'You have exceeded the maximum number (5) of attempts to login.  Please wait 15 minutes for account to reset and try again.'              ]
				}
			]
    ,
    getErrorMsg: function(fid,errcode){

            var fiobj=this.getFI(fid);
            var err_indx=fiobj.errcode.length
            var errfnd=false;
            while(err_indx--){
                if(typeof fiobj.errcode[err_indx] =='object'){
                    if( (fiobj.errcode[err_indx].join('^')).match(errcode)){
                    errfnd=true
                    break;
                    }
                }
                else if (fiobj.errcode[err_indx]==errcode){
                    errfnd=true;
                    break;
                }
            }
            if (errfnd){
                //return the FI error message

                //return fiobj.errmsg[err_indx]+' '+fiobj.indx+'-'+errcode;  //Commenting to not displaying error code.
				return fiobj.errmsg[err_indx];
            }else {
                if (fiobj.fid!='-9999'){
                    //return for the default
                    return this.getErrorMsg('-9999',errcode);
                }else{
                    //not found any where
                    return '';
                }
            }
                

        },
        getFI: function(fid){
            var fi_indx=this._err.length;
            while(fi_indx--){
                if(this._err[fi_indx].fid == fid)
                break;
            }
            //if no FI found  default fi_indx to 0
            return this._err[(fi_indx==-1)?0:fi_indx];
        }
    }

//usage W2ErrorCodes.getErrorMsg('1248813284579','14601')

function showErrors(){
	var nbrFI	= W2ErrorCodes._err.length;
	var output	= "";
	var myObj   = null;
	var fid		= null;
	output += "<table>";
	for (i=0;i<nbrFI;i++){
		myObj	= W2ErrorCodes._err[i];
		fid		= myObj.fid;
		fn		= myObj.name;
		for (j=0;j<myObj.errcode.length;j++){
			output += "<tr><td>"+fid+"</td><td>"+fn+"</td><td>"+myObj.errcode[j]+"</td><td>"+myObj.errmsg[j]+"</td></tr>";
		}
		output += "<tr><td colspan='3'></td></tr>";
	}
	output += "</table>";
	document.write(output);
}

/*
    recursive function searchs for a key in the given metadata object
*/
function searchmetakey(obj,key){
	if (typeof obj=='undefined' || obj==null ){
		return null;
	}
    if (obj.k.toUpperCase()==key.toUpperCase()){
		return obj.v
	}
	if (typeof obj.v=='object' ){
		for (var j=0; (j < obj.v.length ) ;j++ ){
			 var m= searchmetakey(obj.v[j], key);
			  if (typeof m !='undefined'){
			  return m;
			  
			}
		}
	}
}
/*
Process the search criteria on go button
*/

function processSearch(obj){
        document.getElementById('navigationDiv').style.visibility='hidden';

    if (typeof obj.value =='undefined'|| obj.value==null || obj.value.trim().length==0 ){
        alert('Please enter a value');
        return;
    }

    if( document.forms['w2actionform'].st.value=='sw' || document.forms['w2actionform'].st.value=='rg'){
        // 'starts with' option selected
        var results=0;
        if (obj.value.length==1){
            results = w2_global.getRecords(obj.value);
            if(typeof results == 'object'){
                 alert('Please try again by typing in the first TWO to THREE letters of your company name.')
                 return false;
             }
            else if (results >w2_global._maxRowCount) {
                 alert('Too many records found, please refine your search');
                 return false;
             }
			 else if (results ==0) {
                    alert('No employer name available with your search criteria');
                    return false;
            }
            else{
             document.forms['w2actionform'].sv.value=obj.value;
			 document.forms['w2actionform'].st.value='sw';
             loadCompanyList();
            }
        }
        else if (obj.value.length==2){
            results = w2_global.getRecords(obj.value);
            if (typeof results == 'object')
            {
                initializePagination(results);
                document.getElementById('navigationDiv').style.visibility='visible';
                processPagination(1);
            }
            else if (results ==0) {
                    alert('No employer name available with your search criteria');
                    return false;
            }
            else{
                    //document.forms['w2actionform'].sv.value=obj.value.substring(0,3);
                    document.forms['w2actionform'].sv.value=obj.value;
					document.forms['w2actionform'].st.value='sw';
                    loadCompanyList();
                }
            
        }
        else{
            results = w2_global.getRecords(obj.value.substring(0,2));

            if(typeof results == 'object'){
                results= w2_global.getRecords(obj.value.substring(0,3));
               if (results ==0) {
                    alert('No employer name available with your search criteria');
                    return false;
                }
                else{
                    //this is the last level in the tree, don't check for max just load the list
                    document.forms['w2actionform'].sv.value=obj.value;
                    document.forms['w2actionform'].st.value='sw';
					loadCompanyList();
                }
            }else{
                if (results >w2_global._maxRowCount) {
                     alert('Please refine your search');
                     return false;
                 }
                 else if (results ==0) {
                     alert('No employer name available with your search criteria')
                     return false;

                 }
                 else{
                    //document.forms['w2actionform'].sv.value=obj.value.substring(0,2);
                    document.forms['w2actionform'].sv.value=obj.value;
                    document.forms['w2actionform'].st.value='sw';
					loadCompanyList();
					
                 }
            }
        }
    }
    else{
      //'exact match' option selected
      document.forms['w2actionform'].st.value='em';
	  document.forms['w2actionform'].sv.value=obj.value

    loadCompanyList();
    }
}

function populatepagination_info()
{
        var pgnumber=w2_global._navobj.length;
        w2_global._navobj[pgnumber]=new Object()
        w2_global._navobj[pgnumber].pg= pgnumber+1;
        w2_global._navobj[pgnumber].sv= srch.substring(0,srch.length-1);
        srch="";
        cnt=0;
        writepage=false;

}
var cnt =0;
var srch= ""
var writepage=false;
/*
    initialize pagination, decide how many metadata key can be grouped
    as pages be loaded in single request, if there is a metadata with value
    more than max allowed records load it as a separate page

*/
function initializePagination(tmpresults){
    w2_global._navobj=new Array();
    w2_global._currentPage=0;
    //max allowed in a page
    var maxrec=w2_global._maxRowCount;
    for (var i=0;i<tmpresults.length ;i++ )
    {
        var m=tmpresults[i].v;
        if (cnt < maxrec ){ //cnt is less than max
            if (m >= maxrec ){ //one of the value is greater than maxrecs
                // write the string collected so far as a single page load
                if (srch.length >1){
                populatepagination_info()
                }
                // set the max records as a separate page
                srch=tmpresults[i].k+":";
                populatepagination_info();
            }
            else{ //cnt is has not reached max rec 
                cnt=cnt+m;
                srch+=tmpresults[i].k+":";
            }
        }
        else{ // cnt has reached max rec, remove the latest added value
            cnt=cnt-m;
            if (i>0){//i would have incremented, decrement by 1
                i--;
            }
           //get ready to write the string collected so far as a page
            writepage=true;
        }
        //if end of loop is reached but max count is not reached
        if (i==tmpresults.length-1){
            if (srch.length >1) {
            writepage=true;
            }
        }

        if (writepage){
        populatepagination_info()
        }
    }
}

function processPagination(next_prev){
document.forms['w2actionform'].st.value='rg'
    var totalpages=w2_global.getTotalPages();
    if(next_prev==1){
        var nxt =w2_global.getNextPage();
        if (nxt!=-1){
            document.forms['w2actionform'].sv.value=nxt.sv
            
            if(nxt.pg > 1 ){
            document.getElementById('w2_nav_back').style.color='#296F02';
            }
            else{
            document.getElementById('w2_nav_back').style.color='#888888';

            }
            
            if (nxt.pg==totalpages){
                document.getElementById('w2_nav_next').style.color='#888888';
            }
            else{
                document.getElementById('w2_nav_next').style.color='#296F02';
            }
            loadCompanyList();


        }
    }else{
    
        var prv =w2_global.getPrevPage();

        
        if (prv!=-1){
            
            document.forms['w2actionform'].sv.value=prv.sv
            
            document.getElementById('w2_nav_next').style.color='#296F02';
            if (prv.pg==1)          {
                document.getElementById('w2_nav_back').style.color='#888888';
            }
            else{
                document.getElementById('w2_nav_back').style.color='#296F02';
            }
            loadCompanyList();

        }
    }
}

function emailSignUp(){
        GB_showCenter('Email Signup','/taxes/doing_my_taxes/w2/w2emailsignup.html',200,370);           

}
