// ****************
// BEGIN: CONTENTS OF PARTNER_PRODUCT_DETAILS_SOAP_CLIENT.JS
// ****************
/* 
    * partner_product_details_soap_client.js  Version 3.0
    * All functions, classes related to product pricing.
    *
	* 7/9/2010
	*	Improved the compression ratio to reduce cookie size
	*	Added method for new compression
    * 10/28/2009
    *   Updated products for 2010  
    *   Moved JSON string conversion to commons since now we need it as a generic function
    *
    * Copyright HRB Digital LLC
*/ 


/*
    An instance of PartnerProduct() represents a partner and its software, office and online product information.
	Methods of the PartnerProduct() object are:
	** status related
	    getStatusTCO() getStatusTCS()
	** Partner related
		getPartnerInfo()::getPartnerCID()::getPartnerName()::getPartnerType()::getPartnerWelcome()
		getPartnerOtpPartnerId()::getPartnerTunnel()::getPartnerID()::getPartnerActive()::
	** Product related
		getProductInfo()::getProductId()::getProductBasePrice()::getProductPartnerPrice()
		getProductName()::getProductStartNow()::getProductLearnMore()::getProductSKU()::getProductPlatform()
		getProductOmnitureName()::getProductsByPlatform()::getCompressedStr()::updatePartnerProduct()::getDecompressedStr()
*/

function PartnerProduct() {
        this._partner_product;

		this.isValued = function(){
			try
			{
				//var tempObj = this.getObj();
				var tempObj = this._partner_product.prodList;
				if (typeof tempObj == 'undefined')
				{
					g_log.debug('g_hrb_partner_product.isValued(): 1 returning false');
					return false;
				}
			}
			catch (e)
			{
				g_log.debug('g_hrb_partner_product.isValued(); 2 returning false');
				return false;
			}
			return true;
		}

        this.getObj =function(){
            return this._partner_product;
        }
        
        this.setObj =function(prodlist){   /* prodList also includes partner information also such as name, cid, etc.*/
            this._partner_product=prodlist;
        }

        // ************** BEGIN STATUS GETTER METHODS **************

        /*Fetch the status for TCO requests*/
        this.getStatusTCO=function () {
            return this._partner_product.status.tco;
        }

        /*Fetch the status for TCS requests*/
        this.getStatusTCS=function () {
            return this._partner_product.status.tcs;
        }
		
		this.getVer=function () {
			if((typeof this._partner_product.status.ver != 'undefined') && this._partner_product.status.ver !=null){
            return this._partner_product.status.ver;
			}
			else{
			return null;
			}
        }
  
        /*Fetch the partner info object*/
        this.getPartnerInfo=function () {
            return this._partner_product.partner;
        }
        /*Fetch the partnerCID for this partner*/
        this.getPartnerCID=function () {
            return this._partner_product.partner.cid;
        }
        /*Fetch the partnerName for this partner*/
        this.getPartnerName=function () {
            return this._partner_product.partner.partnerName;
        }
        /*Fetch the for partnerType this partner*/
        this.getPartnerType=function () {
            return this._partner_product.partner.partnerType;
        }
        /*Fetch the partnerWelcome text for this partner*/
        this.getPartnerWelcome=function () {
            return this._partner_product.partner.partnerWelcome;
        }
        /*Fetch the otpPartnerID for this partner*/
        this.getPartnerOtpPartnerId=function () {
            return this._partner_product.partner.otpPartnerID;
        }
        /*Fetch the partnerTunnel indicator for this partner*/
        this.getPartnerTunnel=function () {
            return this._partner_product.partner.partnerTunnel;
        }
        /*Fetch the yearly CMS partner Id (NOT the otp partner id) for this partner*/
        this.getPartnerID=function () {
            return this._partner_product.partner.partnerID;
        }
        /*Fetch the partnerActive indicator for this partner*/
        this.getPartnerActive=function () {
            return this._partner_product.partner.partnerActive;
        }
	     /*get the product info for a given product*/
        this.getProductInfo=function (prodID){
            var t_prodlist=this._partner_product.prodList;
            for (var i=0; i<t_prodlist.length;i++ ){
                if (t_prodlist[i].pid==prodID){
                    return t_prodlist[i];
                }
            }
            return null;
        }

        /*get the product id for a product*/
        this.getProductId=function (prodID){
            return this.getProductInfo(prodID).pid;
        }
        /*get the base price for a product*/
        this.getProductBasePrice=function (prodID){
           return this.getProductInfo(prodID).bpr;
        }
        /*get the partner price for a product*/
        this.getProductPartnerPrice=function (prodID){
            return this.getProductInfo(prodID).ppr;
        }
        /*get the Name for a product*/
        this.getProductName=function (prodID){
            return this.getProductInfo(prodID).pn;
        }
        /*get the Start Now for a product*/
        this.getProductStartNow=function (prodID){
            return this.getProductInfo(prodID).sn;
        }
        /*get the Learn More for a product*/
        this.getProductLearnMore=function (prodID){
            //return this.getProductInfo(prodID).lm;
			return getPageXref(prodID);		
        }
        /*get the SKU for a product*/
        this.getProductSKU=function (prodID){
            return this.getProductInfo(prodID).sk;
        }
        /*get the Platform for a product*/
        this.getProductPlatform=function (prodID){
            return this.getProductInfo(prodID).pl;
        }

        /*get the Omniture Name for a product*/
        this.getProductOmnitureName=function (prodID){
            return this.getProductInfo(prodID).on;
        }
        
        
        // **************     BEGIN OTHER FUNCTIONS    **************
        /*  fetch list of products by a given platform returns an array of product objects
            Platform type 'O':online 'S':software 'R':retail
        */
        this.getProductsByPlatform=function (platform){
            var prodarr= new Array();
            var t_prodlist=this._partner_product.prodList;
            for (var i=0; i<t_prodlist.length;i++ ){
                if (t_prodlist[i].pl==platform){
                    prodarr[prodarr.length]=t_prodlist[i];
                }
            }
            return prodarr;
        }
        
        /*  compresses the complete product list object
            returns a JSON string which is compressed
            used to store the data in the cookies
        */
        this.getCompressedStr=function(){   
           
                //remove the product name and SK text to compress

			this._partner_product.partner.partnerName='';
			this._partner_product.partner.partnerWelcome='';

            for (var k=0;k< this._partner_product.prodList.length;k++ ){
               this._partner_product.prodList[k].pn='-';
               this._partner_product.prodList[k].sk='-';
               this._partner_product.prodList[k].on='-';
            }

            var str = jsonToString(this._partner_product);
			return resizeWSC(str,"compress");

        }
        /*
        shows the current wsc cookie in decompressed format. call by
        javascript:g_hrb_partner_product.getDecompressedStr();
        */
        this.getDecompressedStr=function(){
            var tmpWin = window.open();
            tmpWin.document.write(resizeWSC(unescape(getCookie("wsc")),"decompress"));
        }
        
        /*  Passes a string representation of the product info
            to be converted into JSON object form
            Normally updated from the cookie value
        */
        this.setPartnerProduct=function(str,decompress) {   
            if (decompress){
               		str= resizeWSC(str,"decompress");
            }
            try{
                this._partner_product=eval('('+str+')');
                var _defresp =  g_online_def_price;
                //strip starting and ending square brackets off the software pricing
                var _tmpSoft=g_soft_def_price.replace(/\[/,'').replace(/\]/,'');
                _defresp=_defresp.replace(/\]}/g, ','+_tmpSoft+']}');
                var _tmp_ppobj=eval('('+_defresp+')');
                //since the object from the cookie does not have sk and on info, add it back from 
                //default obj
                for (var k=0;k< _tmp_ppobj.prodList.length;k++ ){
                        this._partner_product.prodList[k].sk= _tmp_ppobj.prodList[k].sk;
                        this._partner_product.prodList[k].on= _tmp_ppobj.prodList[k].on;
                }
                _tmp_ppobj=null;
            }//end of try
            catch (e){
            	g_log.error('setPartnerProduct:decompress=='+decompress+":failed:e=="+e.message);
                setCookie("wsc", "", null, "/");
				return false; // let caller know parsing failed
            }
			return true;
        }
      
  }
  function resizeWSC(wscstr,typ){
		var ct ={"a":/\/universal\/office_locator.html/g,"b":/\/loginRedirect.html/g,"c":/\.html\",bpr:\"/g,"d":/\"},{pid:\"/g,"e":/\",ppr:\"/g,"f":/\",lm:\"/g,"g":/\",sk:\"/g,"h":/\",pn:\"/g,"i":/\",sn:\"/g,"j":/\",pl:\"/g,"k":/\",on:\"/g,"l":/0.00/g,"m":/9.95/g,"n":/4.95/g,"o":/TaxType=/g,"p":/Target=/g,"q":/product.jsp/g,"r":/office/g,"s":/NOT_APPLICABLE/g,"t":/default/g,"u":/Online/g,"v":/partner/g,"w":/TaxYear=20/g,"x":/otpPartnerID=/g,"y":/productId=/g,"z":/&FV=T&HT=F/g,"1":/state/g,"2":/taxcut/g,"3":/premium/g,"4":/software/g,"5":/online/g};
		if (typ=="compress"){
			for (var j in ct){
				wscstr = wscstr.replace(ct[j],"*"+j)
			}
			return wscstr;
		}
		else if (typ=="decompress"){
			for (var j in ct){
				var tmpsrc =(ct[j].source).replace(/\\/g,'');
				wscstr = wscstr.replace(new RegExp("\\*"+j,"g"),tmpsrc);
			}
			return wscstr;
		}
	} 

    function checkRespIntegrity(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('E21:'+txt.length+':'+keywords);
            }
        }
        catch (e){
            g_log.error('E22');
            return true;
        }
        return false;
    }

    function partnerProductSuccess(resp)
    {
        g_log.debug('<b>Inside partnerProductSuccess.</b>');
        if (resp==''){
            g_log.error('E13');
        }
        /*if the response looks valid, copy required attributes to template obj*/
        if (checkRespIntegrity('{partner:', resp)){
            g_log.debug('partnerProductSuccess partnerinfo from webservice is ok.');
            var _ppobj= g_hrb_partner_product.getObj();
            _ppobj.status.tco=1;
            var _json_partner_prod = eval('('+resp+')');
            
            var tmppartner=g_hrb_partner_product.getPartnerInfo();
            tmppartner.cid=_json_partner_prod.partner.cid;
            tmppartner.partnerName  =_json_partner_prod.partner.partnerName;
            tmppartner.partnerType  =_json_partner_prod.partner.partnerType;
            tmppartner.otpPartnerID =_json_partner_prod.partner.otpPartnerID;
            tmppartner.partnerTunnel=_json_partner_prod.partner.partnerTunnel;
            tmppartner.partnerID    =_json_partner_prod.partner.partnerID;
            tmppartner.partnerActive=_json_partner_prod.partner.partnerActive;
            var _add_prod=new Array();//store the products not found in the default list
            for (var j=0;j<_json_partner_prod.prodList.length ;j++ ){
                var tmpprodobj= g_hrb_partner_product.getProductInfo(_json_partner_prod.prodList[j].pid);
                
                if (tmpprodobj!=null)
                {
                    g_log.debug('partnerProductSuccess WS response::(for products in def) bpr:'+_json_partner_prod.prodList[j].bpr+' | ppr:'+_json_partner_prod.prodList[j].ppr + ' | pid:'+_json_partner_prod.prodList[j].pid);
                    tmpprodobj.bpr=_json_partner_prod.prodList[j].bpr;
                    tmpprodobj.ppr=_json_partner_prod.prodList[j].ppr;
                    tmpprodobj.sn=_json_partner_prod.prodList[j].sn;
                    tmpprodobj.lm=_json_partner_prod.prodList[j].lm;
                    tmpprodobj.sk=_json_partner_prod.prodList[j].sk;
                }
                else{//find products not in the default list
                    g_log.debug('partnerProductSuccess WS response::<b>(products not in def)</b> bpr:'+_json_partner_prod.prodList[j].bpr+' | ppr:'+_json_partner_prod.prodList[j].ppr + ' | pid:'+_json_partner_prod.prodList[j].pid);

                    _add_prod[_add_prod.length]={pid:_json_partner_prod.prodList[j].pid,pn:"-",sn:_json_partner_prod.prodList[j].sn,lm:_json_partner_prod.prodList[j].lm,bpr:_json_partner_prod.prodList[j].bpr,ppr:_json_partner_prod.prodList[j].ppr,sk:"-",pl:_json_partner_prod.prodList[j].pl,on:"-"};

                }
            }
            //add products to the default object
            for (var k=0; k<_add_prod.length ;k++ ){
                _ppobj.prodList.push(_add_prod[k]);
                        
            }
            //_json_partner_prod=null;
            //_add_prod=null;
        }else{
            g_log.error("E12");

            g_hrb_partner_product.getObj().status.tco=0;
        }

        webServiceCallSuccess();
    
    }
    function partnerProductFailure(errorcode)
    {
        g_log.debug('<b>Inside partnerProductFailure</b>');

        g_log.error("E11:"+errorcode);
        webServiceCallFailed();
    }
  
   function callpartnerJSON(partnerid){
        g_log.debug('<b>Inside callpartnerJSON</b>');



        /************** START ONLY for testing **************/

        var failpartner= queryString('forcefail_partner');
        if (failpartner!= null && (failpartner=="true" || failpartner==true))
        {
            partnerProductFailure("404");
            return;
        }
        /************** END   ONLY for testing **************/

        var url='/HrbWebservices/services/servlet/JsonProductInfo';
        
        postData="otpPartnerID="+partnerid;

        new ajaxreq(url,postData,"partnerProductSuccess","partnerProductFailure","");
    }
    function callsoftwarepricing(offer,pgm)
    {
        g_log.debug('<b>Inside callsoftwarepricing</b>::offer::'+offer+' pgm::'+pgm);

        
        /************** START ONLY for testing **************/
        /****************************************************/
        var failsoft= queryString('forcefail_software');
       if (failsoft!= null && (failsoft=="true" || failsoft==true))
       {
            softwareFailure("error");
            return;
        }
        /************** END   ONLY for testing **************/
        /****************************************************/

        var softobj=eval('('+g_soft_def_price+')');
        var prod_params="";
        for (var j=0;j<softobj.length ;j++ )
        {
            if (softobj[j].sk=="-" || softobj[j].sk=="")
            {
                continue;
            }
            prod_params+= (softobj[j].sk+ ""+ ( (j==(softobj.length-1))?"":":"));
        }
        softobj=null;

        var postdata=null;
        
        var url1="/json/JSONProxyServlet";
        
        if (offer=='' || offer==null ||offer=='0'){
                postdata="pid_list="+prod_params;
				
				 /*start sc DR call for peak*/
				
				var dummyresp= "<!-- REQUEST ID: TIME=1328036806050:NODE=c2a9903:THREAD=1309 -->/* Digital River ProductInfo Widget *//* JSON Output */[{\"productID\":235353200,\"price\":{\"taxIncludedInPrice\":false,\"discounted\":false,\"unitPrice\":\"$64.95\",\"unitPriceWithDiscount\":\"$64.95\"}},{\"productID\":235352900,\"price\":{\"taxIncludedInPrice\":false,\"discounted\":false,\"unitPrice\":\"$79.95\",\"unitPriceWithDiscount\":\"$79.95\"}},{\"productID\":235277100,\"price\":{\"taxIncludedInPrice\":false,\"discounted\":false,\"unitPrice\":\"$34.95\",\"unitPriceWithDiscount\":\"$34.95\"}},{\"productID\":235239900,\"price\":{\"taxIncludedInPrice\":false,\"discounted\":false,\"unitPrice\":\"$44.95\",\"unitPriceWithDiscount\":\"$44.95\"}},{\"productID\":235273200,\"price\":{\"taxIncludedInPrice\":false,\"discounted\":false,\"unitPrice\":\"$19.95\",\"unitPriceWithDiscount\":\"$19.95\"}},{\"productID\":244201600,\"price\":{\"taxIncludedInPrice\":false,\"discounted\":false,\"unitPrice\":\"$36.95\",\"unitPriceWithDiscount\":\"$36.95\"}}]";
				softwareSuccess(dummyresp);
				return;
				 
				 /*end sc*/
        }
        else{
            var add_args="";
            if (offer!=null && offer!='' ){
                add_args+="&off_id="+offer;
            }
            
            if (pgm!=null && pgm!='' ){
                add_args+="&pgm_id="+pgm;
            }
            else  {
                add_args+="&pgm_id="+14166300;
            }

            postdata="pid_list="+prod_params+add_args;
        }
        g_log.debug('callsoftwarepricing ::postdata'+postdata);
        new ajaxreq(url1,postdata,"softwareSuccess","softwareFailure","");

    }
     function softwareSuccess(resp)
    {
        g_log.debug('<b>Inside softwareSuccess</b>');

        if (resp==''){
            g_log.error('E18');
        }
        resp=resp.substring(resp.indexOf('[{'),resp.indexOf('}}]')+3);

        if (checkRespIntegrity('productID',resp)) {
            g_log.debug('Software info from DR is ok.');
            g_hrb_partner_product.getObj().status.tcs=1;
            var _softprod_dr = eval('('+resp+')');
            g_log.debug('softwareSuccess DR resp total products '+_softprod_dr.length);

            var _softprod_def= g_hrb_partner_product.getProductsByPlatform('S');


            for (var j=0;j<_softprod_def.length ;j++ ){
                 // remove the dollar sign since online pricing does not have $
                 var  priceobj='-';
                 //if the product is not found in the DR response
                 try{
                        priceobj=_softprod_dr[j].price;
                        g_log.debug('softwareSuccess bpr:'+priceobj.unitPrice+' | ppr:'+priceobj.unitPriceWithDiscount+' | sk:'+_softprod_def[j].sk+ ' | pid:'+_softprod_def[j].pid);

                        _softprod_def[j].bpr=(priceobj.unitPrice			!=null || typeof priceobj.unitPrice				!= 'undefined')?(priceobj.unitPrice.substring(1)):priceobj.unitPrice ;
                        _softprod_def[j].ppr=(priceobj.unitPriceWithDiscount!=null || typeof priceobj.unitPriceWithDiscount != 'undefined')?(priceobj.unitPriceWithDiscount.substring(1)):priceobj.unitPriceWithDiscount ;
                }catch(e){
					g_log.debug('softwareSuccess...inside catch..');
                    if( (typeof _softprod_dr[j]!='undefined') && _softprod_dr[j].pid!=null && _softprod_dr[j].pid!='34')
                    g_log.error("E19:"+_softprod_dr[j].pid);
                }
            }
        }
        else{
            g_log.error('E17');
            g_hrb_partner_product.getObj().status.tcs=0;
        }

       remoteDataProcessComplete();
    
    }
    function softwareFailure(errorcode)
    {
       // g_log.error('E17');

        g_log.debug('<b>Inside softwareFailure</b>');
        remoteDataProcessComplete();
    }


    function getPartnerProduct(partnerid)
    {   
        g_log.debug('<b>Inside getProductInfo</b> :partnerid::'+partnerid);

        //Initialize the final JSON str with onlinepricig
		/*
        var finalresp =  g_online_def_price;

        //strip starting and ending square brackets off the software pricing
        var tmpSoftStr=g_soft_def_price.replace(/\[/,'').replace(/\]/,'');
        finalresp=finalresp.replace(/\]}/g, ','+tmpSoftStr+']}');
        g_hrb_partner_product.setObj(eval('('+finalresp+')'));
		*/

		setFinalResp();

        if (getWebServiceCookie(partnerid))
        {
            g_log.debug('getProductInfo webService call is NOT needed ');
			// Also check if cookie version is current
			var def_ver = (g_online_def_price.match(/ver:[0-9]/))[0].split(':')[1];//def version
			var cookie_ver =g_hrb_partner_product.getVer(); //version from cookie
			g_log.debug('Default WSC version is '+def_ver+' Cookie version is '+cookie_ver);
			if (cookie_ver==null || cookie_ver!= parseInt(def_ver)){
				callpartnerJSON(partnerid);
			}else{
	            webServiceCallNotNeeded();   // shares much logic with the webServiceCallSuccess()
			}
        }
        else{
        	g_log.debug('getWebServiceCookie("'+partnerid+'") failed. calling callpartnerJSON("'+partnerid+'")"');
            callpartnerJSON(partnerid);
        }
    }

	function setFinalResp()
	{
		var finalresp =  g_online_def_price;

        //strip starting and ending square brackets off the software pricing
        var tmpSoftStr=g_soft_def_price.replace(/\[/,'').replace(/\]/,'');
        finalresp=finalresp.replace(/\]}/g, ','+tmpSoftStr+']}');
        g_hrb_partner_product.setObj(eval('('+finalresp+')'));
	}

//initialize the product info object
var g_hrb_partner_product= new PartnerProduct();
// ****************
// END:   CONTENTS OF PARTNER_PRODUCT_DETAILS_SOAP_CLIENT.JS
// ****************


// ****************
// BEGIN: CONTENTS OF DEF_INFO_HRBLOCK_2008.JS
// ****************
/* 
    * commons.js  Version 1.0
    * All common functions and global variables required to render pages.
	* 4/5/2010 Adding exclusion list functionality to pixel pro
	* 12/16/2009 Moved default pricing to common
	* 12/11/2009 Added generic pixel logic
	* 12/10/2009 Added more pixels
	* 10/2/2009  Added pixel processing
	* 10/28/2009 Moving Json toString function from partner_product since this would be commonly used
	* 
    * Copyright HRB Digital LLC
*/

//default pricing for online
var g_online_def_price= '{status:{tco:0,tcs:0,ver:1},partner:{cid:"otpPartnerID=0&pgm=13534200",partnerName:"-",partnerType:"normal",partnerWelcome:"na",otpPartnerID:"0",partnerTunnel:0,partnerID:"0",partnerActive:1},'+
'prodList:['+
//Extension
'{pid:"188",pn:"-",sn:"/loginRedirect.html?TaxType=TCL&FV=T&HT=F&OtpExt=1&TaxYear=2011",lm:"188.html",bpr:"19.95",ppr:"19.95",sk:"EXT",pl:"O",on:"extension"},'+
//Best of Both State -- 193
'{pid:"193",pn:"-",sn:"/loginRedirect.html?TaxType=SIG&FV=T&HT=F&TaxYear=2011",lm:"193.html",bpr:"34.95",ppr:"34.95",sk:"SIGSTA",pl:"O",on:"best_of_both_state"},'+
//Ask a tax advisor -- 44
'{pid:"44",pn:"-",sn:"/loginRedirect.html?TaxType=TCL&FV=T&HT=F&Target=ATA&TaxYear=2011",lm:"44.html",bpr:"19.95",ppr:"19.95",sk:"ATAEMAILBILL",pl:"O",on:"ata"},'+
//Office service -- 65
'{pid:"65",pn:"-",sn:"/universal/office_locator.html?&otpPartnerID=0&pgm=13534200&otpPartnerId=0",lm:"65.html",bpr:"0.00",ppr:"0.00",sk:"NA",pl:"R",on:"-"},'+
//Office service -- 64
'{pid:"64",pn:"-",sn:"-",lm:"64.html",bpr:"0.00",ppr:"0.00",sk:"NA",pl:"R",on:"-"},'+
//Online office state -- 191
'{pid:"191",pn:"-",sn:"/loginRedirect.html?TaxType=PTS&FV=T&HT=F&TaxYear=2011",lm:"191.html",bpr:"34.95",ppr:"34.95",sk:"PTSSTA",pl:"O",on:"ptssta_online_office_state"},'+
//FREE -- Fed 201
'{pid:"201",pn:"-",sn:"/loginRedirect.html?TaxType=TCF&FV=T&HT=F&TaxYear=2011",lm:"201.html",bpr:"0.00",ppr:"-1",sk:"TCFFED",pl:"O",on:"free_edition_fed"},'+
//FREE -- State
'{pid:"202",pn:"-",sn:"/loginRedirect.html?TaxType=TCF&FV=T&HT=F&TaxYear=2011",lm:"202.html",bpr:"27.95",ppr:"27.95",sk:"TCFSTA",pl:"O",on:"free_edition-state"},'+
//Online Office -- 62
'{pid:"62",pn:"-",sn:"/loginRedirect.html?TaxType=PTS&FV=T&HT=F&TaxYear=2011",lm:"62.html",bpr:"109.95",ppr:"109.95",sk:"PTSFED",pl:"O",on:"online_office_default"},'+
//TCO Split page -- 31
'{pid:"31",pn:"-",sn:"-",lm:"31.html",bpr:"0.00",ppr:"0.00",sk:"NA",pl:"O",on:"parent"},'+
//Basic State -- 194
'{pid:"194",pn:"-",sn:"/loginRedirect.html?TaxType=TCL&FV=T&HT=F&TaxYear=2011",lm:"194.html",bpr:"34.95",ppr:"34.95",sk:"TCLSTA",pl:"O",on:"basic_state"},'+
//Extension Filing split page -- 69
'{pid:"69",pn:"-",sn:"-",lm:"69.html",bpr:"0.00",ppr:"0.00",sk:"NA",pl:"O",on:"extension"},'+
//Best of Both -- 33
'{pid:"33",pn:"-",sn:"/loginRedirect.html?TaxType=SIG&FV=T&HT=F&TaxYear=2011",lm:"33.html",bpr:"79.95",ppr:"79.95",sk:"SIGFED",pl:"O",on:"best_of_both_fed"},'+
//Premium State -- 192
'{pid:"192",pn:"-",sn:"/loginRedirect.html?TaxType=OPP&FV=T&HT=F&TaxYear=2011",lm:"192.html",bpr:"34.95",ppr:"34.95",sk:"PAID1040STA",pl:"O",on:"premium_state"},'+
//Basic -- 30
'{pid:"30",pn:"-",sn:"/loginRedirect.html?TaxType=TCL&FV=T&HT=F&TaxYear=2011",lm:"30.html",bpr:"19.95",ppr:"19.95",sk:"TCLFED",pl:"O",on:"basic"},'+
//Premium -- 32
'{pid:"32",pn:"-",sn:"/loginRedirect.html?TaxType=OPP&FV=T&HT=F&TaxYear=2011",lm:"32.html",bpr:"49.95",ppr:"49.95",sk:"PAID1040FED",pl:"O",on:"premium"},'+
//Deluxe -- 204
'{pid:"204",pn:"-",sn:"/loginRedirect.html?TaxType=TCD&FV=T&HT=F&TaxYear=2011",lm:"204.html",bpr:"29.95",ppr:"29.95",sk:"TCDFED",pl:"O",on:"deluxe_fed"},'+
//Deluxe state -- 205
'{pid:"205",pn:"-",sn:"/loginRedirect.html?TaxType=TCD&FV=T&HT=F&TaxYear=2011",lm:"205.html",bpr:"34.95",ppr:"34.95",sk:"TCDSTA",pl:"O",on:"deluxe_state"},'+

//MapPoint Office Locator -- 203
'{pid:"203",pn:"-",sn:"-",lm:"203.html",bpr:"0.00",ppr:"0.00",sk:"NA",pl:"R",on:"-"}]}';
//default pricing for software
//default pricing for software
var g_soft_def_price ='[{'+
//premium + State + E-file --36 preorder --134571300
//'pid:"36",pn:"-",sn:"-",lm:"36.html",bpr:"74.95",ppr:"74.95",sk:"220813300",pl:"S",on:"tcs_premium_state"},'+
//premium -- 36
'pid:"36",pn:"-",sn:"-",lm:"36.html",bpr:"64.95",ppr:"64.95",sk:"235353200",pl:"S",on:"tcs_premium_fed"},'+
//premium and business)
'{pid:"38",pn:"-",sn:"-",lm:"38.html",bpr:"79.95",ppr:"79.95",sk:"235352900",pl:"S",on:"tcs_home_and_business"},'+
//Deluxe  w/o State -- 206
'{pid:"206",pn:"-",sn:"-",lm:"206.html",bpr:"39.95",ppr:"39.95",sk:"235277100",pl:"S",on:"tcs_deluxe_fed"},'+
//Deluxe + State  -- 207
'{pid:"207",pn:"-",sn:"-",lm:"207.html",bpr:"44.95",ppr:"44.95",sk:"235239900",pl:"S",on:"tcs_deluxe_state"},'+
//Basic + E-file -- 199
'{pid:"199",pn:"-",sn:"-",lm:"199.html",bpr:"19.95",ppr:"19.95",sk:"235273200",pl:"S",on:"tcs_basic_fed"},'+
//State -- 39
'{pid:"39",pn:"-",sn:"-",lm:"39.html",bpr:"36.95",ppr:"36.95",sk:"244201600",pl:"S",on:"tcs_state"},'+
//main software prod -- 34
'{pid:"34",pn:"-",sn:"-",lm:"34.html",bpr:"-",ppr:"-",sk:"-",pl:"S",on:"tcs_main"}]';

g_sys = {
    checkFlash : function (){
        if (navigator.plugins != null && navigator.plugins.length > 0) {
        var desc = (navigator.plugins['Shockwave Flash']==undefined)?null:navigator.plugins['Shockwave Flash'].description;
            try {
                return parseInt(desc.match(/[\d.]+\d{1} /g)); 
            }catch (e){
                return null;
            }
        }
        else {
        for(var i=10; i>=5; i--){
            try{
                var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
                return i;
            }
            catch(e){}
            }
        }
        return null;
    },
    checkCookie: function (){
        if (navigator.cookieEnabled)
        {/*cater for the bug in chrome*/
            document.cookie = "$TESTNAME=$TESTVALUE; path=/";
            if(document.cookie==""){
                return false;}
            else return true;
        }
        else {return false;}
    },
    checkBrowser: function (){
        /*Add support for five different browsers*/
		var _ua=navigator.userAgent;
        if (/Firefox[\/\s](\d+\.\d+)/.test(_ua)){ 
        return 'FF';}
        else if (/MSIE (\d+\.\d+);/.test(_ua)){
        return 'IE';
        }
        else if (/Opera[\/\s](\d+\.\d+)/.test(_ua)){
        return 'Opera';
        }
        else if (/Netscape/.test(_ua)){
        return 'NN';
        }
        else if (/Chrome[\/\s](\d+\.\d+)/.test(_ua)){
        return 'Chrome';
        }
        else if (/Safari[\/\s](\d+\.\d+)/.test(_ua)){
        return 'Safari';
        }
        else{
            return navigator.appName;
        }
    }
    ,
    checkBrowserVer: function (){
		var _ua=navigator.userAgent;
		if (/Firefox[\/\s](\d+\.\d+)/.test(_ua)){ 
			return new Number(RegExp.$1);
		}
		else if (/MSIE (\d+\.\d+);/.test(_ua)){ 
			return new Number(RegExp.$1)
		}
		else if (/Opera[\/\s](\d+\.\d+)/.test(_ua)){ 
			return new Number(RegExp.$1)
		}
		else if (/Netscape6/.test(_ua)){//ns 6
		ns='Netscape6'
		return _ua.substr( (_ua.indexOf(ns) + ns.length + 1 ) ,3);
		}
		else if (/Netscape/.test(_ua)){//for ns 7 and 8
		ns='Netscape'
		return _ua.substr( (_ua.indexOf(ns) + ns.length + 1 ) ,3);
		}
    },
    checkOS: function(){
    return navigator.platform ;
    },
    checkSilverLight: function(){
        if (navigator.plugins != null && navigator.plugins.length > 0) {
            var desc = (navigator.plugins['Silverlight Plug-In']==undefined)?null:navigator.plugins['Silverlight Plug-In'].description;
            if (desc!=null && desc.length >0){
                return true;
            }
            else{
                return false;
            }
        }
        else{
            try{
                new ActiveXObject("AgControl.AgControl");
                return true;
            }
            catch (e){
                return false;
            }
        }
    },
	checkEnv: function(){
		var prodenv =new Array('7cc2e7dfbb7d976ff792d3a6b081a5dbe3bcda88','0c342fe190c132e84015c61525345ddb133bf41b','c2518c92be164f6d062e7d127a408105d4fa0bcf','9e8c3f67567af231e189570e625054a2f2326d6d','ec43ba4f1bf417229b1dd5052756acea6c0618db')	;
		var qaenv =new Array('d8e056986ec757838e3069fedb74a8d01ce18251','4cffc0353c97b0b1dc4f3c7f64d518b2a560ef7f');
		var devenv =new Array('98b9938995d7d63dcd7a58b3e5535a75f1aac2df','9607e2e5c5d4a7875aad8389edb351cb7c261204','aba57c16e61a4a84f885522615c27b475059757e','1311a9559c6e56f772120b0374ac539f8eb390a4','48e59efbd74638185dece843f5474075579bdf9c');
		for (var i=0;i< prodenv.length;i++ ){
			if(HRBsha(document.location.hostname) == prodenv[i]){
				return "PROD";
			}
		}
		for (var i=0;i< qaenv.length;i++ ){
			if(HRBsha(document.location.hostname) == qaenv[i]){
				return "QA";
			}
		}
		for (var i=0;i< devenv.length;i++ ){
			if(HRBsha(document.location.hostname) == devenv[i]){
				return "DEV";
			}
		}
		return null;
	},
	getCurrentYear: function(){
		var curryr ="2011"
		if (this.checkEnv() == 'DEV'){
			var sysdate = new Date();
			if ((sysdate.getFullYear())!=curryr){
				//alert('Please update the current year!')
				return null;
			}
	
		}
		return curryr;
	},
	getLoginUrl : function() {

		/* implement like:
			javascript:GB_showCenter('Login',g_login.getLoginUrl()='?ViewType=1',162,433);
		*/

		var tco_url = "https://taxes.hrblock.com/hrblock/DirectLogin/DirectLogin.aspx"; // always default to prod

		/*
		if (g_sys.checkEnv()=="DEV" || g_sys.checkEnv()=="QA"){
			//tco_url = PUT DEV URL HERE
			//tco_url = PUT Q/A URL HERE
		}
		*/

		return tco_url;
	}

}
function queryString( key )
{
    var re = new RegExp( "[?&]" + key + "=([^&$]*)", "i" );
    var offset = location.search.search( re );
    if ( offset == -1 ) return null;
    return RegExp.$1;
}
function Logger(errorlevel){ 
    this.maxlevel = errorlevel;
    this.tracknow=false;
    this.msg=new Array('');
    this.debug = function(msg) {
        if (this.maxlevel=="debug" && this.tracknow){
            this.msg[this.msg.length]=(new Date()).getTime()+"::debug::"+msg;
        }
     }
     this.error = function(msg) {
         if (this.tracknow){
            this.msg[this.msg.length]=(new Date()).getTime()+"::error::"+msg;
         }
         try
         {
            recordExceptionInOmniture("ERR",9,msg+"^"+g_sys.checkBrowser()+"^"+g_sys.checkBrowserVer());
         }
         catch (e)
         {
            g_log.debug('Call Failed: recordExceptionInOmniture("err",9,'+msg+':'+g_sys.checkBrowser()+'-'+g_sys.checkBrowserVer()+')');
         }
     }
    this.display=function(displaytype)
    {
       	var rp= prompt('Enter password','password');		
		if (rp==null || rp=='' || HRBsha(rp) != '38fad0d45a562c767cb85f45dc6ea71ad06bf6ae'){
			alert('Sorry, you cannot access this page.');
			 return;
		 }
		if (displaytype=="alert"){
			 var alertmsg="";
			 for (var i=0;i<this.msg.length ; i++){
				alertmsg+=this.msg[i]+"\n";
			}
            alert(alertmsg);
        }
        else if (displaytype=="win"){
			 var winmsg="";
			for (var i=0;i<this.msg.length ; i++){
				winmsg+=this.msg[i]+"<br><br>";
			}
			var dbg_win= window.open ("","debugwin","resizable=1,width=600,height=350,scrollbars=1");
			dbg_win.document.write("<body><div id='d3' style='font-family:Verdana;font-size:11px;'><p align=center><b>Debug</b></p>"+winmsg+"</body>"); 
				 
			}
        }
    }

function ajaxreq(url,postData,success,fail,headers)
{
	var ajax_type="jquery";
	g_log.debug("ajaxreq("+url+","+postData+","+success+","+fail+","+headers+",env:"+g_sys.checkEnv()+",type:"+ajax_type);
	if (ajax_type=="custom" || g_sys.checkEnv()=="PROD" ){
		g_log.debug("Using custom ajax.");
		ajaxreq_custom(url,postData,success,fail,headers);		
	}
	else if (ajax_type=="jquery") {
		if (!(window.jQuery)){
			//alert("Using custom ajax because jquery has not loaded yet!");
			g_log.debug("Using custom ajax because jquery has not loaded yet!");
			ajaxreq_custom(url,postData,success,fail,headers);
		} 
		else{
			g_log.debug("Using jquery ajax.");
			//ajaxreq_jquery(url,postData,success,fail,headers);
			ajaxreq_custom(url,postData,success,fail,headers);
		}
	}

}

function ajaxreq_jquery(url, postData, callOnSuccess, callOnFailure, headers)
{
	// JQuery AJAX with existing function name and signature pattern
		//alert("in ajaxreq_jquery");
	var reqType = (postData==null || postData=="") ? "GET" : "POST";
try
{
	$.ajax(
		{    
			type: reqType,    
			url: url,    
			data: postData,   
			crossDomain: true,			

			beforeSend: function(jqXHR, settings) { 
				g_log.debug('$.ajax.beforeSend:');
				// ensure success function exists
				try
				{
					if (typeof window.eval(callOnSuccess) != 'function')
					{	alert("ajaxreq(): function "+callOnSuccess+"()' not found.");
						return;
					}
				}
				catch (e)
				{	alert("ajaxreq(): function "+callOnSuccess+"()' "+e.getMessage);
					return;
				}

				// ensure failure function exist
				try
				{
					if (typeof window.eval(callOnFailure) != 'function')
					{	alert("ajaxreq(): function "+callOnFailure+"()' not found.");
						return;
					}
				}
				catch (e)
				{	alert("ajaxreq(): function "+callOnFailure+"()' "+e.getMessage);
					return;
				}

				// append request headers
				if (headers!=null && headers!='' )
				{
					var hdrlist =headers.split(",");
					for (var i=0;i< hdrlist.length; i++)
					{
						var hrd =hdrlist[0].split(":");
						jqXHR.setRequestHeader(hrd[0],hrd[1]);
					}
				}

				// append POST-specific headers
				if (reqType=="POST")
				{	// the following commented line makes IE fail and results in TWO Content-Type header entries sent in request
					//jqXHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
					jqXHR.setRequestHeader("Content-length", postData.length);
					jqXHR.setRequestHeader("Connection", "close");
				} 
			}, 

			success: function(data, msg, jqXHR)
			{   g_log.debug('$.ajax.success:');
				var myRespHeaders	= jqXHR.getAllResponseHeaders();
				if (myRespHeaders != null)
				{
					myRespHeaders = jqXHR.getAllResponseHeaders().replace(/[\r\n]/g, "^");
					myRespHeaders = myRespHeaders.replace(/\^\^/g, "^");
				}
				// BEGIN: Code from custom ajaxreq()
				if (jqXHR.status==200){
					rmsg="$.ajax.success:";
					rmsg+="\r\nmsg:"+msg;				
					rmsg+="\r\njqXHR:"+jqXHR;
					rmsg+="\r\ndata:"+data;
					rmsg+="\r\njqXHR.readyState:"+jqXHR.readyState;
					rmsg+="\r\njqXHR.status:"+jqXHR.status;
					rmsg+="\r\njqXHR.statusText:"+jqXHR.statusText;
					rmsg+="\r\njqXHR.getAllResponseHeaders():"+jqXHR.getAllResponseHeaders();
					g_log.debug(rmsg);
					
					g_log.debug("jqXHR.responseXML:"+jqXHR.responseXML+"\r\njqXHR.responseText:"+jqXHR.responseText);

					var resTxt=jqXHR.responseText;

					if (typeof(resTxt)=='undefined' || resTxt ==null )
					{
						g_log.error('E02');
						return;
					}

					resTxt = (resTxt.replace(/[\n\t\v\r\f]/g, ""));
					resTxt = resTxt.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "");
					resTxt = resTxt.replace(/\'/g,"\\'");

					try{
						eval(callOnSuccess+'(\''+resTxt+'\',\''+myRespHeaders+'\')');
					}
					catch (e){
						g_log.error('F00:' +e.message);
						if(resTxt!=null){
							g_log.error('F01:' +resTxt.length);
						}
						g_log.debug('response text' +resTxt);
					}
				}
				else{
					// if status != 200, like 0, accessing some attributes such as jqXHR.data causes fatal firefox error
					g_log.error('E01:success:'+jqXHR.status);	
					eval(callOnFailure+'(\''+jqXHR.status+'\',\''+myRespHeaders+'\')');
				}
				// END:   Code from custom ajaxreq()  
			} ,
			error: function(jqXHR, textStatus, errorThrown)
			{	g_log.debug('$.ajax.error:');
				// textStatus can be 200 but if JSON was expected but malformed, we can end up here according to accepted answer on this site
				// http://stackoverflow.com/questions/1846086/why-does-ajax-call-for-json-data-trigger-the-error-callback-when-http-status-co
				var myRespHeaders	= jqXHR.getAllResponseHeaders();
				if (myRespHeaders != null)
				{
					myRespHeaders = jqXHR.getAllResponseHeaders().replace(/[\r\n]/g, "^");
					myRespHeaders = myRespHeaders.replace(/\^\^/g, "^");
				}

				rmsg="$.ajax.error:";
				rmsg+="\r\njqXHR:"+jqXHR;
				rmsg+="\r\njqXHR.readyState:"+jqXHR.readyState;
				rmsg+="\r\njqXHR.status:"+jqXHR.status;
				rmsg+="\r\njqXHR.statusText:"+jqXHR.statusText;
				rmsg+="\r\njqXHR.getAllResponseHeaders():"+myRespHeaders;
				rmsg+="\r\ntextStatus:"+textStatus;
				rmsg+="\r\nerrorThrown:"+errorThrown;

				g_log.debug(rmsg);

				g_log.error('E01:error:'+jqXHR.status);
				eval(callOnFailure+'(\''+jqXHR.status+'\',\''+myRespHeaders+'\')');
			},
			complete: function(jqXHR, textStatus)
			{   g_log.debug('$.ajax.complete:');
				jqXHR = null;
			}
		}
	);
}
catch (e)
{	g_log.error('E00:'+e)
	eval(callOnFailure+'(\'E00\')');
}
}

function ajaxreq_custom(url,postData,success,fail,headers)
    {
		this._reqObj=null;
        this._url=url;
        this._post=postData;
        this._success=success;
        this._headers=headers;
        this._fail=fail;
        this.sendReq = function()
        {
            this._getReqObject();
            var tmpObj=this;
            if (this._reqObj==null ){
                var iframereq=new IframeRequest(this._success,this._fail);
                iframereq.open("POST",this._url,true);
                iframereq.send(this._post);
            }
            else {
                    tmpObj._reqObj.onreadystatechange=function ()
                    {
                        if(tmpObj._reqObj.readyState==4 ){
                            // add responseXML when required
                            if (tmpObj._reqObj.status==200){
								g_log.debug('AJAX request :: Response OK :: status::'+tmpObj._reqObj.status);
								var resTxt=tmpObj._reqObj.responseText;
								if (typeof(resTxt)=='undefined' || resTxt ==null )
								{
									g_log.error('E02');
									return;
								}
								resTxt = (resTxt.replace(/[\n\t\v\r\f]/g, ""));
								resTxt = resTxt.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "");
								resTxt = resTxt.replace(/\'/g,"\\'");

								try{
									eval(tmpObj._success+'(\''+resTxt+'\')');
								}
								catch (e){
									g_log.error('F00:' +e.message);
									if(resTxt!=null){
									g_log.error('F01:' +resTxt.length);
									}
									g_log.debug('response text' +resTxt);
								}
                            }
                            else{
								g_log.error('E01:'+tmpObj._reqObj.status)
								eval(tmpObj._fail+'('+tmpObj._reqObj.status+')');
                            }
                        }
                    }
                    try{
                    //check if opening connection has any issues
                    if (this._post==null || this._post=="")
                    {
                        this._reqObj.open('GET', this._url, true);
                    }
                    else{
                        this._reqObj.open('POST', this._url, true);
                    }

                    }catch(e){g_log.error('E00');
					          eval(this._fail+'(\'E00\')');
					}
                    if (this._headers!=null && this._headers!='' )
                    {
                        var hdrlist =this._headers.split(",");
                        for (var i=0;i< hdrlist.length; i++)
                        {
                            var hrd =hdrlist[0].split(":");
                            this._reqObj.setRequestHeader(hrd[0],hrd[1]);
                        }
                    }
                    if (this._post!=null && this._post!="" )
                    {
                        this._reqObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        this._reqObj.setRequestHeader("Content-length", this._post.length);
                        this._reqObj.setRequestHeader("Connection", "close");
                    }
                    g_log.debug('AJAX request :: POST DATA::'+this._post);
                this._reqObj.send(this._post);  
            }
        }
        this._getReqObject=function(){
            try{
                this._reqObj=new XMLHttpRequest(); 
                g_log.debug('AJAX request :: XMLHTTPRequest ');
            }
            catch (e){
                try{
                    this._reqObj=new ActiveXObject("Msxml2.XMLHTTP");
                    g_log.debug('AJAX request :: Msxml2.XMLHTTP ');

                }
                catch (e){

                    try{
                      this._reqObj=new ActiveXObject("Microsoft.XMLHTTP");
                        g_log.debug('AJAX request :: Microsoft.XMLHTTP ');

                    }
                    catch (e){
                    g_log.error("E03");
                    return null;
                  }
                }
              }
            return this._reqObj;
            }
        this.sendReq();
    }
    
/* 
following is the Iframe solution if there is failure create an activeX object with IE 
This would work only if http header info is not required in the request object. 
*/
var IframeRequest = function(success,fail)
{
    this.method = "POST";
    this.url = null;
    this.async = true;
    this.iframe = null;
    this.responseText = null;
    this._success=success;
    this._fail=fail;
    this.header = new Object();
    this.id = "_xmlhttp_"+(new Date()).getTime() ;
    this.container = document.body;
}

IframeRequest.prototype.open = function(method, url, async)
{
    this.method = method;
    this.url = url;
    this.async = async;
    this.readyState = 0;
    var tmpDiv = document.createElement("div");
    tmpDiv.style.display='none';
    tmpDiv.setAttribute("id", "iframe-div");
    this.iframe = document.createElement("IFRAME");
    this.iframe.id = this.id;
    if(document.getElementById(this.id) == null){
        tmpDiv.appendChild(this.iframe);
        this.container.appendChild(tmpDiv);
    }
    //this.setRequestHeader("___xmlhttp", "iframe");
}

IframeRequest.prototype.send = function(data){
    var frmC = [];
    frmC[frmC.length] = '<html><body><form method="' + this.method + '" action="' + this.url + '">';
    if(data != null && data.length > 0){
         var namevalpairList=data.split("&"); 
        for (var i=0;i<namevalpairList.length ;i++ )
        {
            var namevalpair = namevalpairList[i].split("=");
            frmC[frmC.length] = '<input type="hidden" name="'+namevalpair[0]+'" value="'+namevalpair[1]+'">';
        }
    }
    frmC[frmC.length] = '<s'+'cript>document.forms[0].submit();</s'+'cript>';
    frmC[frmC.length] = '</form></body></html>';
    this.iframe._xmlhttp = this;
    this.iframe._xmlhttp._fix = -1;
    this.iframe._xmlhttp.responseText = null;
    this.iframe.onreadystatechange = this._onreadystatechange;
    this.iframe.src = "javascript:document.write('" + frmC.join('').replace(/\'/g,"\\'").replace(/\r\n/g, "\\r\\n") + "');void(0);";

}

IframeRequest.prototype._onreadystatechange = function(){
    this._xmlhttp._fix++;
    if(this._xmlhttp._fix < 1){
        return;
	}
    if(this._xmlhttp._fix == 1){
        this._xmlhttp.readyState = 1;
    }
    else if(this._xmlhttp._fix > 1){
        g_log.debug('AJAX request IFRAME::  '+this.readyState);
        switch(this.readyState.toString())
        {
            case "loading":
                this._xmlhttp.readyState = 2;
                break;
            case "interactive":
                this._xmlhttp.readyState = 3;
                break;
            case "complete":
                /*4/30/2009 Ajay reading from iframe is not straightforward. Evaluate nodes till you find a BODY tag*/
                var docobj=window.frames[this.id].document;
                var resTxt=""
                for (var j=0;j<docobj.childNodes.length ; j++ ){
					for (var k=0;k< docobj.childNodes[j].childNodes.length; k++ ){
							try{
								if (docobj.childNodes[j].childNodes[k].nodeName=='BODY'){
									resTxt+=docobj.childNodes[j].childNodes[k].innerHTML;
									g_log.debug('AJAX request IFRAME:: BODY TAG '+resTxt);
								}
							}
							catch (e){
								g_log.error('E07');
							}
						}
                }
				if (typeof(resTxt)=='undefined' || resTxt==null){
					g_log.error('E08');
					return;
				}
                resTxt = (resTxt.replace(/[\n\t\v\r\f]/g, ""));
                resTxt= resTxt.replace(/\&amp;/g,'&');
                this._xmlhttp.responseText=resTxt
                this.onreadystatechange = function(){}
                this._xmlhttp.readyState = 4;
                eval(this._xmlhttp._success+'(\''+resTxt+'\')');
                break;
        }   
    }
    else{
            eval(this._xmlhttp._fail+'(\'E06\')');
			g_log.error('E06');

    }
    
    if(typeof(this._xmlhttp.onreadystatechange) == "function")
            this._xmlhttp.onreadystatechange();
}
 

var g_log = new Logger("debug");
var trackval = queryString("debug");
if (trackval!=null)
{
    g_log.tracknow=((trackval=="true" || trackval==true)?true:false);
}



String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}


// when calling this function, value stringSpecialCharsAllowed like this "%+-@" in the call
function _checkvalidstr(strCheck,strValidChars){
	var strChar;
   if (strCheck.length == 0) return false;
   strCheck = strCheck.toLowerCase();
    for (var i = 0; i < strCheck.length; i++){
        strChar = strCheck.charAt(i);
        if (strValidChars.indexOf(strChar) == -1){
            return false;
        }
    }
   return true;

}
function isNumeric(stringToCheck,  stringSpecialCharsAllowed)
{
   var strValidChars = "0123456789"+stringSpecialCharsAllowed;
   return  _checkvalidstr(stringToCheck,strValidChars);
 }

function isString(valueToCheck)
{
}

// when calling this function, value stringSpecialCharsAllowed like this "%+-+@" in the call
function isAlpha(stringToCheck, stringSpecialCharsAllowed)
{
   var strValidChars = " abcdefghijklmnopqrstuvwxyz"+stringSpecialCharsAllowed;
   return  _checkvalidstr(stringToCheck,strValidChars);
}

// when calling this function, value stringSpecialCharsAllowed like this "=-+@" in the call
function isAlphaNumeric(stringToCheck, stringSpecialCharsAllowed)
{
   var strValidChars = " abcdefghijklmnopqrstuvwxyz0123456789"+stringSpecialCharsAllowed;
   return  _checkvalidstr(stringToCheck,strValidChars);

}

function isNumber(field) 
{
    var re = /^[0-9-'.'-',']*$/;
    if (!re.test(field.value)) 
    { 
        field.value = field.value.replace(/[^0-9-'.'-',']/g,"");
    }
}
//sha1 one way hash
function HRBsha(msg)
{
var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
msg += String.fromCharCode(0x80);
var l = Math.ceil(msg.length/4) + 2;
var N = Math.ceil(l/16);
var M = new Array(N);
for (var i=0; i<N; i++) {
M[i] = new Array(16);
for (var j=0; j<16; j++) {
	M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) |
			  (msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
	}
}
M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14])
M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;

var H0 = 0x67452301;var H1 = 0xefcdab89;var H2 = 0x98badcfe;var H3 = 0x10325476;var H4 = 0xc3d2e1f0;
var W = new Array(80); var a, b, c, d, e;
for (var i=0; i<N; i++) {
for (var t=0;  t<16; t++) W[t] = M[i][t];
for (var t=16; t<80; t++) W[t] = ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);
a = H0; b = H1; c = H2; d = H3; e = H4;
for (var t=0; t<80; t++) {
	var s = Math.floor(t/20); 
	var T = (ROTL(a,5) + f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
	e = d;
	d = c;
	c = ROTL(b, 30);
	b = a;
	a = T;
}
H0 = (H0+a) & 0xffffffff;
H1 = (H1+b) & 0xffffffff;
H2 = (H2+c) & 0xffffffff;
H3 = (H3+d) & 0xffffffff;
H4 = (H4+e) & 0xffffffff;
}
return H0.toHexStr() + H1.toHexStr() + H2.toHexStr() + H3.toHexStr() + H4.toHexStr();
}
function f(s, x, y, z){
	switch (s) {
	case 0: return (x & y) ^ (~x & z);   
	case 1: return x ^ y ^ z;
	case 2: return (x & y) ^ (x & z) ^ (y & z); 
	case 3: return x ^ y ^ z;  
	}
}

function ROTL(x, n){
return (x<<n) | (x>>>(32-n));
}

Number.prototype.toHexStr = function(){
var s="", v;
for (var i=7; i>=0; i--) { v = (this>>>(i*4)) & 0xf; s += v.toString(16); }
return s;
}


/*
 Pixels to be triggered is defined as a JSON object
 The identification of page is either based on a 
 token passed or based on the current URL
*/
function processPixelTracking(_token){


	var _url_or_token=null;
	var add_params=null;
	if (typeof _token != 'undefined' && _token!=null && _token!=''){
		_url_or_token=_token;
		if (typeof arguments[1]!= 'undefined' && arguments[1]!=null && arguments[1]!=''){
			add_params=arguments[1];
		}
	
	}else if (typeof location.pathname != 'undefined' || location.pathname!=null){
		_url_or_token=location.pathname;
		if (_url_or_token.indexOf('/')!=-1 && _url_or_token.indexOf('.html') == -1){
			_url_or_token=_url_or_token+'index.html';
		}
		//patch for taxtips article, detect if the page is TTIP article
		if (location.href.indexOf('ttiptitle') != -1){
			if (typeof g_tax_tip_id !='undefined'){
				_url_or_token='TAXTIP';
			}
		}
	}
	
	var pixel_obj = {

	 _pixelobj: [

		//{pagetoken:'/tax-software/index.html',pixel:['001.html']},
		//{pagetoken:'/online-tax-preparation/index.html',pixel:['002.html','010.html']},
		//{pagetoken:'/online-tax-preparation/free-edition.html',pixel:['010.html']},
		//{pagetoken:'/offices/index.html',pixel:['012.html','013.html']},
		//{pagetoken:'/online-tax-preparation/best-of-both.html',pixel:['012.html']},
		//{pagetoken:'/taxes/products/office/second_look.html',pixel:['012.html']},
		//{pagetoken:'/taxes/planning/tax_courses/index.html',pixel:['003.html']},
		//{pagetoken:'/espanol/curso_de_impuestos/index.html',pixel:['021.html']},

		/* might be deleted
		{pagetoken:'/cmpgn/office/110000_taxpros.html',pixel:['015.html']},
		{pagetoken:'/cmpgn/office/we_search.html',pixel:['016.html']},
		{pagetoken:'/cmpgn/office/save_money.html',pixel:['016.html']},
		{pagetoken:'/cmpgn/office/money_faster.html',pixel:['016.html']},*/

		{pagetoken:'/taxes/office/pi_form.html',pixel:['018.html']},
		{pagetoken:'/espanol/curso_de_impuestos/index.html', pixel:['021.html','026.html']},
		{pagetoken:'/tax-software/back-editions.html', pixel:['022.html']},
		{pagetoken:'/tax-software/basic.html', pixel:['022.html','031.html']},
		{pagetoken:'/tax-software/current-state-update-forms.html', pixel:['022.html']},
		{pagetoken:'/tax-software/current-update-forms.html', pixel:['022.html']},
		{pagetoken:'/tax-software/deluxe.html', pixel:['022.html','032.html']},
		{pagetoken:'/tax-software/download-updates.html', pixel:['022.html']},
		{pagetoken:'/tax-software/index.html', pixel:['022.html','030.html','042.html']},
		{pagetoken:'/tax-software/mac.html', pixel:['022.html']},
		{pagetoken:'/tax-software/premium.html', pixel:['022.html','033.html']},
		{pagetoken:'/tax-software/premium-business.html', pixel:['022.html','034.html']},
		{pagetoken:'/tax-software/special-offers.html', pixel:['022.html']},
		{pagetoken:'/tax-software/state-editions.html', pixel:['022.html']},
		{pagetoken:'TPF_PIXEL', pixel:['048.html']},
		{pagetoken:'W2_GO',pixel:['011.html']},
		{pagetoken:'W2_SUCCESS',pixel:['012.html']},
		{pagetoken:'W2_FAILURE',pixel:['013.html']},
		{pagetoken:'TE2009',pixel:['004.html']},
		{pagetoken:'WIDGET',pixel:['005.html']},
		{pagetoken:'EMAIL_DISCOUNT',pixel:['006.html']},
		{pagetoken:'DEDUCTION_FINDER',pixel:['007.html']},
		{pagetoken:'LIFE_TAXES',pixel:['008.html']},
		{pagetoken:'TCO_LOGIN',pixel:['tco_login.html']},
		{pagetoken:'/taxes/planning/tax_courses/course_schedule.html',pixel:['023.html']},
		{pagetoken:'/espanol/curso_de_impuestos/course_schedule.html',pixel:['024.html']},
		{pagetoken:'/taxes/planning/tax_courses/index.html',pixel:['025.html']},	
			
		{pagetoken:'/index.html',pixel:['029.html']}, 
		{pagetoken:'/online-tax-preparation/free-edition.html',pixel:['029.html']},
		//{pagetoken:'/tax-software/index.html',pixel:['030.html']},
		//{pagetoken:'/tax-software/basic.html',pixel:['031.html']},
		//{pagetoken:'/tax-software/deluxe.html',pixel:['032.html']},
		//{pagetoken:'/tax-software/premium.html',pixel:['033.html']},
		//{pagetoken:'/tax-software/premium-business.html',pixel:['034.html']},
		{pagetoken:'/online-tax-preparation/index.html',pixel:['035.html','042.html']},
		{pagetoken:'/online-tax-preparation/basic.html',pixel:['036.html']},
		{pagetoken:'/online-tax-preparation/deluxe.html',pixel:['037.html']},
		{pagetoken:'/online-tax-preparation/premium.html',pixel:['038.html']},
		{pagetoken:'/offices/index.html',pixel:['039.html']},
		//{pagetoken:'/loginRedirect.html',pixel:['040.html']},		
		{pagetoken:'/offices/find-an-office/index.html',pixel:['043.html']},
		{pagetoken:'GENERIC',pixel:['002.html','014.html','041.html'],exclusion:['/espanol/$/puerto_rico/$/taxes/doing_my_taxes/w2/index.html','/espanol/$/puerto_rico/$/taxes/doing_my_taxes/w2/index.html$/index.html','/espanol/$/puerto_rico/$/taxes/doing_my_taxes/w2/index.html$/online-tax-preparation/index.html$/tax-software/index.html']}		


	 ],

	 getPixels:function(_url_or_token){


		 var tmppathname =location.pathname;
		if (tmppathname.indexOf('/')!=-1 && tmppathname.indexOf('.html') == -1){
			tmppathname=tmppathname+'index.html';
		}

		
		 for (var i=0;i< this._pixelobj.length;i++ ){
			if (this._pixelobj[i].pagetoken==_url_or_token){
					if (typeof (this._pixelobj[i].exclusion) != 'undefined'){
						var _excl_px =new Array();
						for(var j=0;j< this._pixelobj[i].exclusion.length;j++){
							var exclusionArr =this._pixelobj[i].exclusion[j].split('$');
							
							var matchfound=false;
							for (var k=0;k< exclusionArr.length;k++ ){
								var regex = new RegExp(exclusionArr[k]);
								if (tmppathname.match(regex)!=null){
									
									matchfound=true;
									break;
								}

							}
							if (!matchfound){
							_excl_px[_excl_px.length]=this._pixelobj[i].pixel[j]
							}

						}

						return _excl_px;
					}else{
						 return this._pixelobj[i].pixel;
					}
				

				}
			}

			return null;
		}

	}
	
	// create a empty div
	var pixDiv = document.createElement("div");
	pixDiv.setAttribute("id", "hrb_pixel_tracker_div");
	//pixDiv.style.display='none';
	pixDiv.style.width='0px';
	pixDiv.style.height='0px';

	document.body.appendChild(pixDiv);

	var pixel_arr_gen = null
	if (typeof _token != 'undefined' && _token!=null && _token!=''){
		/*if called for pixel with token do not fire Generic*/
		pixel_arr_gen=null;
	}else{
		/*fetch the	generic pixels(to be run for all pages)*/

		pixel_arr_gen=pixel_obj.getPixels('GENERIC');
	}
	
	var pixel_arr = pixel_obj.getPixels(_url_or_token)
	if (pixel_arr!=null){
		//concat the pixel(s) for the token


		if (pixel_arr_gen!=null){
			pixel_arr=pixel_arr_gen.concat(pixel_arr);
		}
		
	}else{
		pixel_arr=pixel_arr_gen;
	}

	

	if (pixel_arr!=null){
		for (var i=0;i<pixel_arr.length ;i++ ){
			if (pixel_arr[i]!=null)	{
				var _ifobj= pixelCreateIFrame(pixel_arr[i],add_params);
				pixDiv.appendChild(_ifobj);
			}

		}
	}
}
function createIframe(_frameURL,_attr){
	var rand_frameid = 'pixel_frame_'+parseInt(Math.random()*100)
   	var iframe = document.createElement("IFRAME");

	if (typeof _attr =='undefined' || _attr==null)
	{ 
		iframe.style.width='30px';
		iframe.style.height='0px';
		iframe.style.border='0px';
		iframe.width='30px';
		iframe.height='0px';

	}
	else{
		iframe.style.width=_attr.w+'px';
		iframe.style.height=_attr.h+'px';
		iframe.width=_attr.w+'px';
		iframe.height=_attr.h+'px';
		if (typeof _attr.b !='undefined'){
				iframe.style.border=_attr.b+'px';
				iframe.frameBorder=_attr.b;
		}
		else{
				iframe.style.border='0px';
				iframe.frameBorder=0;
		}
		if (typeof _attr.s !='undefined'){
					iframe.scrolling=(_attr.s==1)?"yes":"no";
		}
		else{
				iframe.style.scrolling='no';
		}
	}
	iframe.id = rand_frameid;
	iframe.src=_frameURL; 

	return iframe;
}

function pixelCreateIFrame(_frameURL,add_param){
		_frameURL = "/includes/pixel/pix_"+_frameURL+( (add_param==null)?"":("?"+add_param));
		return createIframe(_frameURL);
}

function removeChildNodes(_obj){
// todo make this recursive
if ( typeof (_obj) != "undefined" && _obj != null){
	if ( typeof (_obj.childNodes[0]) != "undefined" && _obj.childNodes[0] != null){
			_obj.removeChild(_obj.childNodes[0]);
		}
	}
}


/********************************************************************
 JSON  toString function
**********************************************************************/

var typobj = {"boolean":function(){return Boolean},
            "function":function(){return Function},
            "number":function(){return Number},
            "object":function(o){return o instanceof o.constructor?o.constructor:null},
            "string":function(){return String},
            "undefined":function(){return null}
       }

function jsonToString(){

		var self = arguments.length ? arguments[0] : null,
			result, tmp;


		if(self === null){
			result = "null";
		}
		else if(self !== undefined && (tmp = typobj[typeof self](self))) {
			switch(tmp){
				case    Array:
					result = [];
					for(var i = 0, j = 0, k = self.length; j < k; j++) {
						if(self[j] !== undefined && (tmp = jsonToString(self[j]))){
							result[i++] = tmp;
						}
					};
					result = "[".concat(result.join(","), "]");
					break;
				case    Boolean:
					result = String(self);
					break;
				case    Date:
					break;
				case    Function:
					break;
				case    Number:
					result = isFinite(self) ? String(self) : "null";
					break;
				case    String:
					result = '"'.concat(self, '"');
					break;
				default:
					var i = 0, key;
					result = [];
					for(key in self) {
						if(self[key] !== undefined && (tmp = jsonToString(self[key]))){
							result[i++] = ''.concat(key, ':', tmp);
						}
					};
					result = "{".concat(result.join(","), "}");
					break;
			}
		}
		return result;
	}

	/****************************************************************************
		Personalization cookie
	*****************************************************************************/
g_per_cookie = {
	_cookieObj: null,

	initialize:function(){
	 this._cookieObj=null
	},
	updateCookie: function(){

	},
	getInfo: function (mod, year){

	},
	getProductInfo: function (pid,year){
		return getInfo("p",year);
	},
	updateProductInfo: function(pid,year,status){
	
	}

}

function getPageXref(product_id)
{	
	// The caller must know to use /taxes/partner/product.jsp?productId=xx,
	// not the value returned from this function, if on a tunneled page.
	var xref = {
	"30":{"url":"/online-tax-preparation/basic.html"},
	"31":{"url":"/online-tax-preparation/index.html"},
	"32":{"url":"/online-tax-preparation/premium.html"},
	"33":{"url":"/online-tax-preparation/best-of-both.html"},
	"34":{"url":"/tax-software/index.html"},
	"36":{"url":"/tax-software/premium.html"},
	"38":{"url":"/tax-software/premium-business.html"},
	"39":{"url":"/tax-software/state-editions.html"},
	"40":{"url":"/online-tax-preparation/index.html"},
	"44":{"url":"/taxes/products/44.html"},
	"64":{"url":"/offices/index.html"},
	"65":{"url":"/offices/tax-office-products-services.html"},
	"199":{"url":"/tax-software/basic.html"},
	"201":{"url":"/online-tax-preparation/free-edition.html"},
	"204":{"url":"/online-tax-preparation/deluxe.html"},
	"206":{"url":"/tax-software/deluxe.html"},
	"207":{"url":"/tax-software/deluxe.html"}
	};

	var destUrl=null;

	try
	{
		destUrl	=  xref[product_id].url;
	}
	catch (e)
	{
	}
	
	return destUrl;		// returns null if not match not found

}


// ****************
// END:   CONTENTS OF DEF_INFO_HRBLOCK_2008.JS
// ****************


// ****************
// BEGIN: CONTENTS OF HEADER_INIT_HRBLOCK_2008.JS
// ****************

// File Structure
//  Global Variables 
//  Functions - Display
//  Functions - DOM 
//  Functions - Generic Cookie 
//  Functions - Prototype 
//  Functions - Validation 
//  Functions - URL 
//  Functions - Misc
//  Calculator code

// *********************************************************
// BEGIN: Global Variables 
// Having "g_" variables avoids name conflict with other .js files.
// *********************************************************

//default hrblock.com info
var g_partner_id            = 0;
var g_partnerName           = "hrblock";
var g_partner_cid           = "";
var g_partnerType           = "normal";
var g_partnerWelcomeText    = "";
var g_partnerTunneledInd    = "0";

var g_extensionFilingEnabled=false;

//clear the wsc cookie to reduce upstream data in each request
var g_wsc_backup = getCookie('wsc');
setCookie('wsc','');

//executes mboxCreate() if variable is set to true
var g_omatica_home_design      = true;
var g_omatica_office_design    = true;
var g_omatica_online_design    = true;
var g_omatica_software_design  = true;
var g_omatica_taxtips_design   = true;
var g_omatica_competitor_design= false;
var g_omatica_ffa_design       = true;
var g_omatica_cmpgn_design     = true;
var g_omatica_price            = true;
var g_omatica_header           = true;
var g_omatica_footer           = true;

// default taxcut.com info
//var g_partner_id                    = 2246;
//var g_partnerName                   = "taxcut";
//var g_partner_cid                   = "";
//var g_partnerType                   = "normal";
//var g_partnerWelcomeText            = "";

var g_tunneledPage                  = false;

var g_nvpCount                      = 0;        // number of name value pairs in the current url
var nvp_count                       = 0;        // required for backward compatibility with office locator code only 

var useThisCID                      = "";       // sometimes the CID from web service must be overridden

var g_bPreLoadProductRunning        = true;
var g_bOffermaticaProductRunning    = false;

var g_b_ws_partner_id_different     = false;    // true if web service returns info for a partner other than the one requested
var g_b_ws_call_failed              = false;

var g_partner_id_from_cookie        = "";       // the value of otp partner id in the cookie if found
var g_partner_id_from_url           = "";       // the value of otp partner id in the url if found
var g_partner_id_from_offermatica   = "";       // the value of otp partner id in specified by offermatica price test if applicable
var g_partner_id_from_search_engine = "";       // identifies search engine from which organic searchs originated from
var g_partner_id_from_ws_cookie     = "";       // the partner id found in the cookie valued with web service call results

var g_dr_url_info                   =  "";      // dr info in url
var g_dr_cookie_info                =  "";      // dr info currently in digitalriver cookie
var g_dr_ws_info                    =  "";      // dr info returned from web service call

var g_b_drInfoInUrl                 = false;    // true if digital river info found in url
var g_b_drInfoInCookie              = false;    // true if digital river info found in digitalriver cookie

var g_searchEngineTerm              = "";
var g_bReferrerIsSearchEngine       = false;    // set to true if referrer is a search engine

var g_dr_info_to_use                = "";       // digitalriver parm info to use when building digitalriver store links
var g_campaign_id                   = "";       // holds the value found in the CampaignID parm

var g_flashVersion                  = "";

var g_bGetProductInfo               = "";

var g_dr_pgm_info_from_url          = "";
var g_dr_offer_info_from_url        = "";
var g_dr_pgm_info_from_cookie       = "";
var g_dr_offer_info_from_cookie     = "";

var g_query_string_names    = new Array();
var g_query_string_values   = new Array();

var g_curr_query_names      = new Array();       // array of names  in the current url
var g_curr_query_values     = new Array();       // array of values in the current url

var g_time_entered      = "";
var g_paidSearch        = 0;

var g_offermatica_allow = "";

var FLASH_VERSION       = 0;

// *********************************************************
// END: Global Variables
// *********************************************************

// several functions require the split query string so the splitQueryString() call
// has been moved inline - 2004/12/28 pintar
try
{
    splitQueryString(location.search);
}
catch (e)
{
    //alert("splitQueryString:"+e.description);  
}

if (document.location.href.toLowerCase().indexOf("/taxes/partner/index.jsp?otppartnerid=180")!=-1 && document.location.search.toLowerCase().indexOf("campaignid=") == -1)
{
	document.location=document.location.href+"&campaignId=pw_mcm_180_0001";
}

// pintar 05/07/2009
//g_tunneledPage  = (document.location.pathname.indexOf("/taxes/partner/") != -1) ? true : false;
g_tunneledPage = isTunneledPage();

// *********************************************************
// BEGIN: Functions - Display Related
// *********************************************************

// *** START INPUT FIELD MASK
// [dFilter] - A Numerical Input Mask for JavaScript
// Written By Dwayne Forehand - March 27th, 2003
// Please reuse & redistribute while keeping this notice.

var dFilterStep

function dFilterStrip (dFilterTemp, dFilterMask)
{
    dFilterMask = dReplace(dFilterMask,'#','');
    for (dFilterStep = 0; dFilterStep < dFilterMask.length++; dFilterStep++)
		{
		    dFilterTemp = dReplace(dFilterTemp,dFilterMask.substring(dFilterStep,dFilterStep+1),'');
		}
		return dFilterTemp;
}

function dFilterMax (dFilterMask)
{
 		dFilterTemp = dFilterMask;
    for (dFilterStep = 0; dFilterStep < (dFilterMask.length+1); dFilterStep++)
		{
		 		if (dFilterMask.charAt(dFilterStep)!='#')
				{
		        dFilterTemp = dReplace(dFilterTemp,dFilterMask.charAt(dFilterStep),'');
				}
		}
		return dFilterTemp.length;
}

function dFilter (key, textbox, dFilterMask)
{
		dFilterNum = dFilterStrip(textbox.value, dFilterMask);
		
		if (key==9)
		{
		    return true;
		}
		else if (key==8&&dFilterNum.length!=0)
		{
		 	 	dFilterNum = dFilterNum.substring(0,dFilterNum.length-1);
		}
 	  else if ( ((key>47&&key<58)||(key>95&&key<106)) && dFilterNum.length<dFilterMax(dFilterMask) )
		{
        dFilterNum=dFilterNum+String.fromCharCode(key);
		}

		var dFilterFinal='';
    for (dFilterStep = 0; dFilterStep < dFilterMask.length; dFilterStep++)
		{
        if (dFilterMask.charAt(dFilterStep)=='#')
				{
					  if (dFilterNum.length!=0)
					  {
				        dFilterFinal = dFilterFinal + dFilterNum.charAt(0);
					      dFilterNum = dFilterNum.substring(1,dFilterNum.length);
					  }
				    else
				    {
				        dFilterFinal = dFilterFinal + "";
				    }
				}
		 		else if (dFilterMask.charAt(dFilterStep)!='#')
				{
				    dFilterFinal = dFilterFinal + dFilterMask.charAt(dFilterStep); 			
				}
//		    dFilterTemp = dReplace(dFilterTemp,dFilterMask.substring(dFilterStep,dFilterStep+1),'');
		}


		textbox.value = dFilterFinal;
    return false;
}

function dReplace(fullString,text,by) {
// Replaces text with by in string
    var strLength = fullString.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return fullString;

    var i = fullString.indexOf(text);
    if ((!i) && (text != fullString.substring(0,txtLength))) return fullString;
    if (i == -1) return fullString;

    var newstr = fullString.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += dReplace(fullString.substring(i+txtLength,strLength),text,by);

    return newstr;
}
// **** END USER INPUT MASK


var objDebugWindow;
var bugTxt = "*** START ***<br/>";

/*bugTxt += "<b>*** INITIAL COOKIE VALUES ***</b><br/>";
bugTxt += "NOTE: If otpPartnerId is in both cookie digitalriver AND main_cookie, it must have the same value:<br/>";
bugTxt += "<font color='red'>getCookie('digitalriver')</font>=='"+getCookie("digitalriver")+"'<br/>";
bugTxt += "<font color='red'>getCookie('main_cookie')</font>=='" +getCookie("main_cookie")+"'<br/>";
bugTxt += "<font color='red'>getCookie('wsc')</font>=='"         +getCookie("wsc")+"'<br/>";    
bugTxt += "<font color='red'>getCookie('hrblockCampaignIDcookie')</font>=='"+getCookie("hrblockCampaignIDcookie")+"'<br/>";   
*/
var bBugWin     = getQueryValue("bugLogic");  // display debug window if bugLogic=true.  remove on production code.
var bBugClicks  = getQueryValue("bugClicks");

if (bBugClicks=="true")
{   bBugClicks = true;
}

if (bBugWin=="true")
{
    bBugWin=true;
    objDebugWindow=window.open("","debugWindow","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=800,height=300");    
}
else
{
    bBugWin=false;
}

function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'none' ) {
        el.style.display = 'none';
    }
    else {
        el.style.display = '';
    }
}

function WinOpen_(page,w,h) {
    popupWin=open(page,"popup","status=yes,toolbar=no,directories=no,scrollbars=yes,menubar=no,resizable=yes,width=" + w + ",height=" + h);
    popupWin.focus();
}

function closePopUnder()
{
    try
    {       
        window.open("","popunder","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=10,height=10,left=2000,top=2000").close();
    }
    catch(e)
    {
    }
}

function getFlashVersion(){
     return g_sys.checkFlash();
}
function checkFlash(){
    return g_sys.checkFlash();
}

// *********************************************************
// END: Functions - Display Related
// *********************************************************


// *********************************************************
// BEGIN: Functions - DOM Related
// *********************************************************

function getAllElements()
{ 
  var all = null;

  if (document.all)
  {
    // we're IE
    all = document.all;
  }
  else if (document['getElementsByTagName'])
  {
    // we're DOM-aware (Mozilla)
    all = document.getElementsByTagName("*");
  }

  // if we're not IE or DOM-aware, we'll return null
  return all;
}

function getElementsByAttribute(attr, attrVal)
{   
    var all     = document.all || document.getElementsByTagName('*');
    var arr     = new Array();
    var tempId  = "";

    for(var k=0;k<all.length;k++)
    {
        tempId  = all[k].getAttribute(attr);

        if (tempId != null && tempId.indexOf(attrVal)==0)
        {
            arr[arr.length] = all[k];
        }
    }
    return arr;
}

// *********************************************************
// BEGIN: Functions - DOM Related
// *********************************************************


// *********************************************************
// BEGIN: Functions - Generic Cookie Functions
// *********************************************************

function getCookie(name)
{
    //if (bBugWin) bugTxt += "top of getCookie("+name+")<br/>";
    var search = name + "=";
    if (document.cookie.length > 0)
    {
        // if there are any cookies
        offset = document.cookie.indexOf(search);
        if (offset != -1)
        {   // cookie exists
            offset += search.length;

            // set index of beginning of value
            end = document.cookie.indexOf(";", offset);

            // set index of end of cookie value
            if (end == -1)
            {   end = document.cookie.length;
            }
            return unescape(document.cookie.substring(offset, end));
        }
        else
        {
            return null;
        }
    }
    else
    {
        return null;
    }
}

function getexpirydate(nbrOfDays)
{
    var UTCstring;
    Today       = new Date();
    nomilli     = Date.parse(Today);
    Today.setTime(nomilli+nbrOfDays*24*60*60*1000);
    UTCstring   = Today.toUTCString();
    return UTCstring;
}

function getDomain()
{
    // Returns the current domain w/o the subdomain name.  
    // Called by setCookie() so the same named cookie isn't created for both hrblock.com and WWW.hrblock.com.
    // Return null if we have a domain (like a test server) that isn't constructed like regular domains

    
    var tempHost    = document.location.hostname;

    /* DO NOT delete::: optimized code

    if (/hrblock\.com/g.test(tempHost)){
    return ".hrblock.com";
    }
    else if(/^\w+$/.test(str)){
        return null;
    }
    else{
        tempHost;
    }

    */


    var dotCount = 0;

    for (var d=0; d<tempHost.length; d++)
    {
        if (tempHost.substr(d,1)==".")
        {
            dotCount++;
        }
    }

    if (dotCount == 2)
    {
        tempHost = tempHost.substr(tempHost.indexOf("."));  // www.hrblock.com returned as .hrblock.com
    }
    else if (dotCount == 1)
    {
        tempHost = "." + tempHost;  // hrblock.com returned as .hrblock.com
    }
    else if (dotCount == 3)
    {
        tempHost = tempHost;    // ip.ip.ip.ip          returned as ip.ip.ip.ip
                                // cms.kc.hrbock.net    returned as cms.kc.hrbock.net
    }
    else if (dotCount == 0)
    {
        tempHost = null;    // testserver returned as null
    }

    return tempHost;
}

function setCookie(cookieName, cookieValue)
{
    // setCookie(cookiename", "cookievalue", null, "/");
    // cookiename == arg0
    // cookievalue== arg1
    // expdate    == arg2
    // path       == arg3
    // domain     == arg4
    // secure     == arg5

    // always make cookies specific to the TOP level domain (like hrblock.com, not www.hrblock.com)
    var args    = setCookie.arguments;
    var arglen  = setCookie.arguments.length;

    var expires = (arglen > 2) ? args[2] : null;
    var path    = (arglen > 3) ? args[3] : null;
    //var domain  = (arglen > 4) ? args[4] : null;  // commented out. see below.
    var secure  = (arglen > 5) ? args[5] : false; // true or false not null

if (bBugWin) bugTxt += "<font color='red'><b>setCookie('"+cookieName+"','"+cookieValue+"')</b></font>: received "+arglen+" arguments: expires=="+expires+",path=="+path+",secure=="+secure+".<br/>";

    // Call getDomain() so the same named cookie isn't created for both hrblock.com and WWW.hrblock.com.
    // That function returns ".hrblock.com" for "www.hrblock.com", and ".hrblock.com" for "hrblock.com" and
    // null for "testserver:8080", allowing browser to make the determination.
    
    var domain = getDomain();
if (bBugWin) bugTxt += "setCookie(): call to getDomain() returned domain as '"+domain+"'.<br/><br/>";

    if(cookieName=="main_cookie")
    {
        if (isTunneledPage())
        {
            cookieValue += "&tpage=1";
        }
    }

    document.cookie = cookieName + "=" + escape (cookieValue)+
    //document.cookie = cookieName + "=" + cookieValue+
    ((expires == null) ? ""         : ("; expires=" + getexpirydate(expires))) +
    ((path    == null) ? "; path=/"  : ("; path="   + path))   +
    ((domain  == null) ? ""         : ("; domain=" + domain)) +
    ((secure  == true) ? "; secure" : "");
}

function deleteCookie( name, path, domain ) {

if (bBugWin) bugTxt += "<font color='blue'><b>top of deleteCookie("+name+","+path+","+domain+")</b></font> (name,path,domain).<br/>";

    if ( getCookie( name ) ) document.cookie = name + '=' +
            ( ( path ) ? ';path=' + path : '') +
            ( ( domain ) ? ';domain=' + domain : '' ) +
            ';expires=Thu, 01-Jan-1970 00:00:01 GMT';

if (bBugWin) bugTxt += "botom of deleteCookie("+name+","+path+","+domain+") (name,path,domain).<br/>";
}

// *********************************************************
// END: Functions - Generic Cookie Functions
// *********************************************************

function getYodleeParameters()
{
	// Yodlee parameters are pre-encoded with encodeURIComponent() when sent to hrblock.com.
	// Since TCX requires the original values, we must re-encode them using encodeURIComponent()
	// before going to TCX login.  

	// yodlee specific
	var yodleeParms = "";

	if (getCookie("main_cookie") != null && getCookie("main_cookie").indexOf("oauth") != -1)
	{
		yodleeParms  = "&coname="				 +encodeURIComponent(getCookieElementValue("main_cookie","coname", true));
		yodleeParms += "&coid="				     +encodeURIComponent(getCookieElementValue("main_cookie","coid", true));
		yodleeParms += "&oauth_consumer_key="	 +encodeURIComponent(getCookieElementValue("main_cookie","oauth_consumer_key", true));
		yodleeParms += "&oauth_nonce="			 +encodeURIComponent(getCookieElementValue("main_cookie","oauth_nonce", true));
		yodleeParms += "&oauth_signature_method="+encodeURIComponent(getCookieElementValue("main_cookie","oauth_signature_method",true));
		yodleeParms += "&oauth_timestamp="	     +encodeURIComponent(getCookieElementValue("main_cookie","oauth_timestamp",true));
		yodleeParms += "&oauth_version="		 +encodeURIComponent(getCookieElementValue("main_cookie","oauth_version",true));
		yodleeParms += "&oauth_signature="	     +encodeURIComponent(getCookieElementValue("main_cookie","oauth_signature",true));
		yodleeParms += "&uid="				     +encodeURIComponent(getCookieElementValue("main_cookie","uid",true));
	}

	return yodleeParms;
}

// *********************************************************
// BEGIN: TCO Direct Login - Added 08/23/2010
// *********************************************************
function tco_login()
{
	var tmpPid = getCookiePartnerId("main_cookie");
	var tmpCmpgn = getCookieElementValue("hrblockCampaignIDcookie", "CampaignID", false);
    
	processPixelTracking('TCO_LOGIN');	
	GB_show('Log In',g_sys.getLoginUrl()+'?ViewType=1&PartnerId='+tmpPid+'&CampaignId='+tmpCmpgn+getYodleeParameters(),163,364);	
}
// *********************************************************
// END: TCO Direct Login
// *********************************************************


// *********************************************************
// BEGIN: Functions - Validation Functions
// *********************************************************

function validateZipCode()
{
    var strZip      = "";
    var ValidChars  = "0123456789.";
    var returnCode  = true;
    var Char;

    try
    {
        strZip = document.getElementById('tfZipCode').value
    }
    catch (e)
    {
        // if no zip code field calls tfZipCode on form, then assume first parameter received is the zip code
        if (arguments.length == 0)
        {
            // no parameters received
            alert("Please provide a zip code.");
            return false;
        }
        else
        {
            strZip  = arguments[0];
        }
    }

    if (strZip == '')
    {
        alert("Please enter a zip code.");
        return false;
    }

    for (i = 0; i < strZip.length; i++)
    {
        Char = strZip.charAt(i);
        if (ValidChars.indexOf(Char) == -1)
        {
            alert("Please enter a valid zip code.");
            return false;
        }
    }

    if (strZip.length != 5)
    {
        alert("Please enter a 5 digit zip code.");
        return false;
    }

    if (document.location.href.indexOf("/mortgages")!= -1 || (typeof (t1_default) != "undefined" && t1_default.indexOf("mortgage") != -1) )
    {
        if (!confirm(strMortgageExit))
        { 
            return false;
        }
    }

    if ( (document.location.href.indexOf("/bank")!= -1) || (document.location.href.indexOf("/emerald")!= -1) || (typeof (t1_default) != "undefined" && t1_default.indexOf("bank") != -1) )
    {
        if (!confirm(strBankExit))
        { 
            return false;
        }       
    }

    // ***********************************************************************************
    // begin special parms processing
    // ***********************************************************************************
    // parms that need to be passed to office_locator.html can be specified by calling this function as follows:
    // validateZipCode("parms_to_pass:name1=value&name2=value");
    // validateZipCode("parms_to_pass:CouponID=1");
    // validateZipCode("parms_to_pass:CouponID=1&FC=tax_ind");
 
    var parmsToPassToLocator = "";
    var bAmpAdded    = 0;

    var argArray;
    var tempStr = "";

    for(var i=0; i<arguments.length; i++)
    {
       argArray = arguments[i].split(":");

       if (argArray[0].toLowerCase()=="parms_to_pass")
       {
            if (bAmpAdded==0)
            {
                parmsToPassToLocator += "&";
                bAmpAdded=1;
            }
            parmsToPassToLocator += argArray[1];
       }
    }

    // if on a page that is in the /investments section, always append &FC=fs_ind
    
    if (document.location.pathname.indexOf('/investments') != - 1 && parmsToPassToLocator.indexOf("&FC=fs_ind") == -1)
    {
        parmsToPassToLocator += "&FC=fs_ind";
    }

    // end special parms processing

    //window.location="//www.hrblock.com/universal/office_locator.html?zip="+strZip+parmsToPassToLocator;

	window.location="/universal/office_locator.html?zip="+strZip+parmsToPassToLocator;
    return false;
}


function validateAddress(_add){
     if (_add == ''){
        alert("Please enter a address.");
        return false;
    }

     if (document.location.href.indexOf("/mortgages")!= -1 || (typeof (t1_default) != "undefined" && t1_default.indexOf("mortgage") != -1) ){
        if (!confirm(strMortgageExit)){ 
            return false;
        }
    }

	if ( (document.location.href.indexOf("/bank")!= -1) || (document.location.href.indexOf("/emerald")!= -1) || (typeof (t1_default) != "undefined" && t1_default.indexOf("bank") != -1) ) {
		if (g_sys.checkEnv()=="DEV" || g_sys.checkEnv()=="QA"){
			
		}else{
			if (!confirm(strBankExit)) { 
				return false;
			}               
		}     
	}
	
    var parmsToPassToLocator = "";
    var bAmpAdded    = 0;

    var argArray;
    var tempStr = "";
g_log.debug("_add"+_add);
g_log.debug("arguments len "+arguments.length);
g_log.debug("arguments "+arguments[0]);

    for(var i=0; i<arguments.length; i++){
       g_log.debug("arguments[i]"+arguments[i]);
	   
	   argArray = arguments[i].split(":");

       if (argArray[0].toLowerCase()=="parms_to_pass"){
            if (bAmpAdded==0) {
                parmsToPassToLocator += "&";
                bAmpAdded=1;
            }
            parmsToPassToLocator += argArray[1];
       }
    }
// if on a page that is in the /investments section, always append &FC=fs_ind
    
    if (document.location.pathname.indexOf('/investments') != - 1 && parmsToPassToLocator.indexOf("&FC=fs_ind") == -1)
    {
        parmsToPassToLocator += "&FC=fs_ind";
    }

	 //window.location="//www.hrblock.com/universal/office_locator.html?address="+_add+parmsToPassToLocator;
     //window.location="/offices/find-an-office/office-locator-index.html?address="+_add+parmsToPassToLocator;
		window.location="/universal/office_locator.html?address="+_add+parmsToPassToLocator;
     return false;
}


function validateZipCode2(strZip, coupon_value)
{
    // validates the zip code by passing a zipcode value and forwarding to office locator
    //var strZip      = document.getElementById('tfZipCode').value
    var ValidChars  = "0123456789.";
    var returnCode  = true;
    var Char;

    if (strZip == '')
    {
        alert("Please enter a zip code.");
        return false;
    }
    
    for (i = 0; i < strZip.length; i++)
    {
        Char = strZip.charAt(i);
        if (ValidChars.indexOf(Char) == -1)
        {
            alert("Please enter a valid zip code.");
            return false;
        }
    }
    
    if (strZip.length != 5)
    {
        alert("Please enter a 5 digit zip code.");
        return false;
    }
    
    if (document.location.href.indexOf("/mortgages")!= -1 || (typeof (t1_default) != "undefined" && t1_default.indexOf("mortgage") != -1) )
    {
        if (!confirm(strMortgageExit))
        { 
            return false;
        }
    }

    if (document.location.href.indexOf("/bank")!= -1 || (typeof (t1_default) != "undefined" && t1_default.indexOf("bank") != -1) )
    {
        if (!confirm(strBankExit))
        { 
            return false;
        }       
    }
    
    if (coupon_value == '1')
    {
        window.location='//www.hrblock.com/universal/office_locator.html?CouponID=1&zip='+strZip;        
//    window.location='/universal/office_locator.html?CouponID=1&zip='+strZip;        
    }
    else
    {
        window.location='//www.hrblock.com/universal/office_locator.html?zip='+strZip;
// window.location='/universal/office_locator.html?zip='+strZip;
    }
    //return true;
}


function validateOfficeLocatorRequest(zip_form_value, coupon_flag)
{
    var zip_value = zip_form_value;
    var coupon_value = coupon_flag;
    
    if (!validateZipCode2(zip_value, coupon_value))
    {
        return false;
    }

    return true;
}


function findofficebyzip(zip_form_value, coupon_flag)
{
    var zip_value = zip_form_value;
    var coupon_value = coupon_flag;
    
    validateZipCode2(zip_value, coupon_value);
}

//Used by the taxtips articles
function findoffice()
{
    validateOfficeLocatorRequest(document.getElementById('txtzipcode').value);
}
// *********************************************************
// END: Functions - Validation Functions
// *********************************************************


// *********************************************************
// BEGIN: Functions - URL Functions
// *********************************************************

// ********************************************
// function splitQueryString(str)
//
// ONLY CALL THIS FUNCTION ONE TIME PER PAGE LOAD!  It values and stores variables that are assumed by other
// code on the page to contain the original values in the search string.  If you need to split any other
// query string, use splitQueryStringLocal() / getQueryValueLocal() instead!
// ********************************************
function splitQueryString(stringToSplit)
{
    // splits stringToSplit query string into array elements
    
if (bBugWin) bugTxt += "<font color='blue'><b>top of splitQueryString("+stringToSplit+")</b></font><br/>";

    g_curr_query_names     = new Array();   // array of names  in the current string being split
    g_curr_query_values    = new Array();   // array of values in the current string being split

    if (stringToSplit.substr(0,1)=="?")
    {
        stringToSplit = stringToSplit.substr(1); // remove leading ? if present
    }
    
    if (stringToSplit.substr(0,1)=="&")
    {
        stringToSplit = stringToSplit.substr(1); // remove leading & if present
    }    

    var pairs       = stringToSplit.split("&");
    var argname     = "";
    var value       = "";

    if (pairs[0]==null || pairs[0]=="")
    {
        g_nvpCount      = 0;
    }
    else
    {
        g_nvpCount      = pairs.length;
    }

    for (var i=0; i<g_nvpCount; i++)
    {
        var pos = pairs[i].indexOf('=');

        if (pos >= 0)
        {
            argname = pairs[i].substring(0,pos);
            value   = pairs[i].substring(pos+1);

            g_curr_query_names[g_curr_query_names.length]     = argname;            
            g_curr_query_values[g_curr_query_values.length]   = unescape(value);
        }
    }
    nvp_count   = g_nvpCount;   // required for backward compatibility with office locator code only 
}

function getQueryValue(name)
{
    // returns name/value pair value if parsed in splitQueryString() function else returns null
    var value       = null;
    var lowerName   = name.toLowerCase();

    for (var i=0;i<g_curr_query_names.length;i++)
    {
        if (g_curr_query_names[i].toLowerCase()==lowerName)
        {
            value = g_curr_query_values[i];
            break;
        }
    }
    return value;
}

// *********************************************************
// END: Functions - URL Functions
// *********************************************************

// *********************************************************
// BEGIN: Functions - Misc
// *********************************************************
function str_replace(strSource, strReplaceThis, strWithThis) 
{
    var temp = strSource.split(strReplaceThis);
    return temp.join(strWithThis);
}
// needle may be a regular expression
function str_replace_reg(strSource, strReplaceThis, strWithThis) 
{
    var r = new RegExp(strReplaceThis, 'g');
    return strSource.replace(r, strWithThis);
}

function taxcutLogin(bNewWindow)
{   // only call this function if visitor hasn't selected a tax product yet
    
    var genericLoginLink    = "/loginRedirect.html?TaxType=OPP&FV=T&HT=F&TaxYear=2008&PartnerID="+g_partner_id;
    if (bNewWindow)
    {
        window.open(genericLoginLink,"","");
    }
    else
    {
        window.location = genericLoginLink;
    }
}

function setPartnerIdToUse()
{
   g_log.debug("<b>Inside setPartnerIdToUse</b>");

    // FOR NON-TUNNELED AND TUNNELED PARTNERS
    // partner id from offermatica when running a price test (non-tunneled pages only)
    // partner id in the url
    // partner id in the cookie

    // not that the the web service results will replace g_partner_id if that partner is determined to be invalid or inactive

    if (g_partner_id_from_offermatica != "")
    {
        g_partner_id = g_partner_id_from_offermatica;
    }
    else if (g_partner_id_from_url != "")
    {
        g_partner_id = g_partner_id_from_url;
    }
    else if (g_partner_id_from_cookie != "")
    {
        g_partner_id = g_partner_id_from_cookie;
    }
    else if (g_partner_id_from_search_engine != "")        
    {
        g_partner_id = g_partner_id_from_search_engine;
    }
    else
    {
        // default hrblock.com info
        g_partner_id = 0;    // hrblock.com default partner id

        // default taxcut.com info
        //g_partner_id = 2246; // taxcut.com default partner id
    }
    g_log.debug(" setPartnerIdToUse PID to be used "+g_partner_id);
	//window.status="id"+g_partner_id;
}

function getUrlPartnerId()
{
    if (bBugWin) bugTxt += "<font color='blue'><b>top of getUrlPartnerId()</b></font><br/>";

    var tempId  = "";

    var qs  = window.parent.location.search;

    tempId = getNVPV(qs, 'otpPartnerId', false);

    if ((typeof tempId)=="undefined" || tempId=="" || tempId==null  || tempId=="undefined") 
    {
       tempId = "";
    }
    if (bBugWin) bugTxt += "getUrlPartnerId() returning '"+tempId+"'</b></font><br/>";

    return tempId;
}
    
function getCookiePartnerId(strCookieName)
{
    // strCookieName == "main_cookie" or "digitalriver"
    tempId = getNVPV("&" + getCookie(strCookieName), 'otpPartnerId', false);

    if ((typeof tempId)=="undefined" || tempId=="" || tempId==null || tempId=="undefined") 
    {
        tempId   = "";
    }

    return tempId;
}

function getOffermaticaPartnerId()
{
    if (bBugWin) bugTxt += "<font color='blue'><b>top of getOffermaticaPartnerId()</b></font><br/>";
    if (bBugWin) bugTxt += "getOffermaticaPartnerId() returning '"+g_partner_id_from_offermatica+"'<br/>";
    return g_partner_id_from_offermatica;
}

// added on 1/14/2009 (ajay)
// set a given cookie element with new value
// The cookie element name is CaSe SeNsItIvE.
function setCookieElementValue(strCookieName, strElementNameToSet, strElementValueToSet)
{
    var tmpcookieval=getCookie(strCookieName);
    //alert('tmpcookieval::'+tmpcookieval+'::setCookieElementValue in cookie'+strCookieName);
    if (tmpcookieval!='' && tmpcookieval!=null)
    {
        var NVPVarr = tmpcookieval.split("&");
        var finalcookiestr=''
        for (var i=0;i< NVPVarr.length; i++ )
        {
          var tmparr=NVPVarr[i].split("="); 
          if ( (tmparr[0] != null) && (tmparr[0] == strElementNameToSet))
          {
              finalcookiestr+=strElementNameToSet+'='+strElementValueToSet+'&';
          }
          else
          {
              finalcookiestr+=NVPVarr[i]+'&';
          }
        }
        if (finalcookiestr!='')
        {
           finalcookiestr=finalcookiestr.substring(0,finalcookiestr.length-1);
        }
        setCookie(strCookieName,finalcookiestr, null, "/");
    if (bBugWin) bugTxt += "setCookieElementValue("+strCookieName+","+strElementNameToSet+","+strElementValueToSet+") set cookie "+strCookieName+" to "+finalcookiestr+"<br/>";
    }
}

function getCookieElementValue(strCookieName, strElementValueToGet, bCaseSpecific)
{
    tempId = getNVPV("&" + getCookie(strCookieName), strElementValueToGet, bCaseSpecific);

    if ((typeof tempId)=="undefined" || tempId=="" || tempId==null || tempId=="undefined") 
    {
        tempId   = "";
    }

    return tempId;
}

function productIdValid(productId)
{
    try
    {
        if (g_hrb_partner_product.getProductId(productId).length)
        {   // no action needed
        }
    }
    catch (e)
    {   // failure means g_hrb_partner_product is not completely valued
        return false;
    }
    return true;
}

function setPricesOnPage()
{
    g_log.debug('<b>Inside setPricesOnPage</b>');
    var arrg_pPPriceElements         = new Array();
    var arrg_pPPriceElementsLength   = 0;

	 var productId                    = 0;
    
    arrg_pPPriceElements         = getElementsByAttribute("id", "prodPrice");
    arrg_pPPriceElementsLength   = arrg_pPPriceElements.length;

    
    // for every prodPriceXX element on the page, find its price in the g_hrb_partner_product._partner_product.prodList object
    for (var x=0; x < arrg_pPPriceElementsLength; x++)
  {
        // get the number (productId) following 'prodPrice'        
        productId   = arrg_pPPriceElements[x].getAttribute("id").substr(9);

        if (productIdValid(productId))
{            
            myObject = arrg_pPPriceElements[x];
			displayPrices(myObject,productId)
            
        }
        else{
        g_log.debug('setPricesOnPage product id '+productId+' is invalid ');

       // g_log.error('E27');
        }

    }
	
	$('span[class^="price"]').each(function(ind){
		var pid= $(this).attr('class');
		
		if(typeof pid !='undefined'){
			pid=pid.substring(15);
		}
		if (productIdValid(pid)){            
            myObject = this;
			displayPrices(this,pid)
            
        }
        else{
        g_log.debug('setPricesOnPage product id '+productId+' is invalid ');
       // g_log.error('E27');
        }
	
	});

	
}

function displayPrices(myObject,productId){          
         
            // Price Color is purple if dynamic product retrieval fails
            // If this is a TCO product, use purple pricing if g_hrb_partner_product.getStatusTC0()==0
            // If this is a TCS product, use purple pricing if g_hrb_partner_product.getStatusTCS()==0
           var fontPre     = "";
           var fontPost    = "";
			var bIsSoftware = false;
            if (g_hrb_partner_product.getProductPlatform(productId).toLowerCase()=="s")
            {   // product is TCS
				bIsSoftware=true;
                if (g_hrb_partner_product.getStatusTCS()==0)
                {
                    fontPre = "<span style='color:#7D007D;'>";
                    fontPost= "</span>";
                }
            }
            else
            {   // product is TCO
                if (g_hrb_partner_product.getStatusTCO()==0)
                {
                    fontPre = "<span style='color:#7D007D;'>";
                    fontPost= "</span>";
                }
            }
            var _bpr=g_hrb_partner_product.getProductBasePrice(productId);
            var _ppr=g_hrb_partner_product.getProductPartnerPrice(productId);
            g_log.debug("setPricesOnPage: productID:"+productId+" bpr:"+_bpr+" ppr:"+_ppr);
            // _ppr == -1    == free
            // _ppr == 0.00  == use base price instead
            // _ppr == n.nn  == use this price
			// if software ever wants to display $0.00 with strikethrough pricing, use this code
			//		else if (_ppr == "0.00" && (!bIsSoftware))
			// instead of the current
			//		else if (_ppr == "0.00")
            if (_ppr == "-1")
            {
                myObject.innerHTML=fontPre+"FREE"+fontPost;
            }
            else if (_ppr == "0.00")
            {
                if (_bpr != "0.00") {
                    myObject.innerHTML=fontPre+"$"+_bpr+fontPost;
                }
                else {
                    myObject.innerHTML="";
                }
            }
            else
            {
                try
                {   
                    var f_partnerPrice  = parseFloat(_ppr);
                    var f_basePrice     = parseFloat(_bpr);
                  
                    if (f_basePrice > f_partnerPrice)
                    {
                        //myObject.innerHTML="<del>$"+_bpr+"</del>&nbsp;&nbsp;$"+_ppr+" -- f_basePrice=="+f_basePrice+"f_partnerPrice,=="+f_partnerPrice;                     
                        if (parent.document.location.href.indexOf("/compare_online_product.html") != -1) {   
                            //product comparison page does NOT get strikethrough due to space limitations 
                            myObject.innerHTML="$"+_ppr;                                 
                        }
                        else
                        {
                            // if the current innerHTML of this span tag has a space, then put a line break between the base and discounted pricing
                            if (myObject.innerHTML.toLowerCase() == "&nbsp;"){   
                                myObject.innerHTML="<del>$"+_bpr+"</del><br/>$"+_ppr+"&nbsp;";  
                            }
                            else {
                                myObject.innerHTML="<del>$"+_bpr+"</del>&nbsp;$"+_ppr+"&nbsp;";  
                            }
                        }                                                
                    }
                    else{
                        //myObject.innerHTML="$"+_ppr+" -- f_basePrice=="+f_basePrice+"f_partnerPrice,=="+f_partnerPrice;                      
                        if (!g_tunneledPage && g_partner_id == 0)
                        {
                            // Some A/B tests require the price NOT be split over two lines.  The presense of &nbsp;&nbsp; singals that.
                            var breakCode = "&nbsp;&nbsp;";
                            
                            if (myObject.innerHTML.toLowerCase() != "&nbsp;&nbsp;"){
                                breakCode   = "<br/>";
                            }
                      
                                 myObject.innerHTML=fontPre+"$"+_ppr+fontPost;   
                                                     
                        }
                        else{
                            myObject.innerHTML=fontPre+"$"+_ppr+fontPost; 
                        }
                    }
                }
                catch (e)
                {
                    //alert(e.description);
                }
            }
     }



function webServiceCallSuccess()
{
    // called from partner_product_details_soap_client.js after successful ajax call
    g_log.debug('<b>Inside webServiceCallSuccess</b>');
  
    // If partner is tunneled and we are not on a tunneled page,  forward this request to the tunneled index page for the partner.
    // If partner is non-tunneled and we are non on a non-tunneled page, forward this request to the UHP.
    // alert("webServiceCallSuccess(): g_hrb_partner_product.getPartnerTunnel() == "+g_hrb_partner_product.getPartnerTunnel()+" and g_tunneledPage=="+g_tunneledPage);
	
	// THIS CHECK IS DONE IN TWO PLACES IN THIS FILE
    if (g_hrb_partner_product.getPartnerTunnel() == 1 && !g_tunneledPage && document.location.pathname.indexOf("/popup") == -1 && document.location.pathname.indexOf("/cmpgn") == -1 && document.location.pathname.indexOf("/check_status.html") == -1)
    {   // Tunneled partner GENERALLY cannot be displayed on an unitunneled pages. There are some un-tunneled pages they
        // CAN access, such as  /taxes/products/online/popups/state_fees.html.
        g_log.debug("webServiceCallSuccess(): sending tunneled partner "+g_hrb_partner_product.getPartnerOtpPartnerId()+" to /taxes/partner/index.jsp?otpPartnerId="+g_hrb_partner_product.getPartnerOtpPartnerId());
		//alert("1:going to tunnel. document.location.pathname.indexOf('/cmpgn')"+document.location.pathname.indexOf("/cmpgn"));
        document.location = "/taxes/partner/index.jsp?otpPartnerId="+g_hrb_partner_product.getPartnerOtpPartnerId();
        return;
    }
    else if (g_hrb_partner_product.getPartnerTunnel() == 0 && g_tunneledPage)
    {   // Un-tunneled partners cannot be displayed on tunneled pages
        g_log.debug("webServiceCallSuccess(): sending un-tunneled partner "+g_hrb_partner_product.getPartnerOtpPartnerId()+" to /index.html?otpPartnerId="+g_hrb_partner_product.getPartnerOtpPartnerId());
        document.location = "/index.html?otpPartnerId="+g_hrb_partner_product.getPartnerOtpPartnerId();
        return;
    }
    else
    {
        // no action needed
    }

    g_partnerName       = g_hrb_partner_product.getPartnerName();
    g_partnerType       = g_hrb_partner_product.getPartnerType();
    g_partnerWelcomeText= g_hrb_partner_product.getPartnerWelcome();
    g_partnerTunneledInd= g_hrb_partner_product.getPartnerTunnel();
    
    // If server call returned partner/product info for a partner that wasn't the one we asked for, that partner was either invalid or inactive.  
    // Since we have already written the main_cookie with the partner id we THOUGHT we were going to use, we must overwrite it with the 
    // partner id returned by the server call.

    useThisCID = g_hrb_partner_product.getPartnerCID();
    
    if (useThisCID == "no__thanks" || useThisCID == "0" || useThisCID == "na")
    {
        useThisCID = "";
    }

    if (g_hrb_partner_product.getPartnerOtpPartnerId() != g_partner_id)
    {  
        g_b_ws_partner_id_different = true;
        
        g_partner_cid   = useThisCID;    
        g_partner_id    = g_hrb_partner_product.getPartnerOtpPartnerId();

        setCookie("main_cookie", "otpPartnerId="+g_partner_id+"&PartnerId="+g_partner_id, null, "/");
    }

    processDigitalRiverCookie();

    callsoftwarepricing(getCookieElementValue("digitalriver", "offerid", false),getCookieElementValue("digitalriver", "pgm", false));
}

function remoteDataProcessComplete()
{
    g_log.debug('<b>Inside remoteDataProcessComplete</b>');
    writeWebServiceCookie();
    setPricesOnPage();
    continueOnloadProcessing();
}

function webServiceCallNotNeeded()
{
    g_log.debug('<b>Inside webServiceCallNotNeeded</b>');

    g_partnerName           = g_hrb_partner_product.getPartnerName();
    g_partnerType           = g_hrb_partner_product.getPartnerType();
    g_partnerWelcomeText    = g_hrb_partner_product.getPartnerWelcome();
    g_partnerTunneledInd    = g_hrb_partner_product.getPartnerTunnel();
    g_partner_cid           = g_hrb_partner_product.getPartnerCID(); 
    g_partner_id            = g_hrb_partner_product.getPartnerOtpPartnerId(); 

    // The reason this re-direct code is required is that if you go to a non-tunneled page w partner 0, changet it to a
    // tunneled partner id and hit enter, then hit the back button, you are on a non-tunneled page with a tunneled partner
    // id in the wsc cookie.  So best bet is to double check the tunneled indicator in the wsc cookie and ensure
    // you are where you should be.
    // alert("webServiceCallNotNeeded(): g_hrb_partner_product.getPartnerTunnel() == "+g_hrb_partner_product.getPartnerTunnel()+" and g_tunneledPage=="+g_tunneledPage);
	
	// THIS CHECK IS DONE IN TWO PLACES IN THIS FILE
    if (g_partnerTunneledInd == 1 && !g_tunneledPage && document.location.pathname.indexOf("/popup") == -1 && document.location.pathname.indexOf("/cmpgn") == -1 && document.location.pathname.indexOf("/check_status.html") == -1)
    {   // Tunneled partner GENERALLY cannot be displayed on an un-tunneled pages. There are some un-tunneled pages they
        // CAN access, such as  /taxes/products/online/popups/state_fees.html.
        g_log.debug("webServiceCallNotNeeded(): sending tunneled partner "+g_partner_id+" to /taxes/partner/index.jsp?otpPartnerId="+g_partner_id);
		//alert("2:going to tunnel. document.location.pathname.indexOf('/cmpgn')"+document.location.pathname.indexOf("/cmpgn"));
        document.location = "/taxes/partner/index.jsp?otpPartnerId="+g_partner_id;
        return;
    }
    else if (g_partnerTunneledInd == 0 && g_tunneledPage)
    {   // Un-tunneled partners cannot be displayed on tunneled pages
        g_log.debug("webServiceCallNotNeeded(): sending un-tunneled partner "+g_partner_id+" to /index.html?otpPartnerId="+g_partner_id);
        document.location = "/index.html?otpPartnerId="+g_partner_id;
        return;
    }
    else
    {
        // no action needed
    }

    setPricesOnPage();
    continueOnloadProcessing();
}

function webServiceCallFailed(strReason)
{
    // ************************************************* TBD: **********************************************************************
    // This fuction has been replace with partnerJSONFailed(errorcode)
    // *********************************************************************************************************************************
    g_log.debug('<b>Inside webServiceCallFailed </b>strReason'+strReason);
    g_b_ws_call_failed  = true;
   // called by partner_product_client_soap_details.js: callProductPricingWebService() on 500 http response code
    setCookie("main_cookie", "otpPartnerId="+g_partner_id+"&PartnerId="+g_partner_id, null, "/");
    //setCookie("wsc", "", null, "/");
    // TBD:
    setCookie("digitalriver", "", null, "/");
    g_log.debug("webServiceCallFailed(strReason):"+getCookieElementValue("digitalriver", "offerid", false)+","+getCookieElementValue("digitalriver", "pgm", false));
    callsoftwarepricing(getCookieElementValue("digitalriver", "offerid", false),getCookieElementValue("digitalriver", "pgm", false)); 
    setPricesOnPage();      
}

function getAllProductInfo(bAlert)
{
    bugTxt += "<font color='blue'><b>top of getAllProductInfo()</b></font>.<br/><br/><span style='font-size: 8pt;'>";

    var prodListSize = g_hrb_partner_product._partner_product.prodList.length;
    var prod;
    var tstr  = "";
    var pid;

    for (var i=0; i<prodListSize; i++)
    {   
        prod = g_hrb_partner_product.getProductInfo(prodList[i].getProductId());
        pid  = prod.getProductId();
        tstr+= "product id=="+pid+",BasePrice=="+prod.getProductBasePrice(pid)+",PartnerPrice=="+prod.getProductPartnerPrice(pid)+",Name=="+prod.getProductName(pid)+",StartNow=="+prod.getProductStartNow(pid)+",LearnMore=="+prod.getProductLearnMore(pid)+"<br/>";
    }
    bugTxt += tstr+"</span><br/>";
}


function getDR_url_info()
{ 
    g_dr_pgm_info_from_url      = getNVPV2(location.search, "pgm",          false, "=", "&");
    g_dr_offer_info_from_url    = getNVPV2(location.search, "OfferID",      false, "=", "&");

    var tempValue   = "";

    if ( (g_dr_pgm_info_from_url != null && g_dr_pgm_info_from_url != "") && (g_dr_offer_info_from_url != null && g_dr_offer_info_from_url != "") )
    { // both PGM and OFFERID are in the URL
      tempValue = "pgm=" + g_dr_pgm_info_from_url + "&OfferID="+g_dr_offer_info_from_url;
    }
    else if (g_dr_pgm_info_from_url != null && g_dr_pgm_info_from_url != "")
    {   // only PGM is in the url
        tempValue = "pgm=" + g_dr_pgm_info_from_url;
    }
    else if (g_dr_offer_info_from_url != null && g_dr_offer_info_from_url != "")
    {   // only OFFERID is in the url
        tempValue = "OfferID=" + g_dr_offer_info_from_url;
    }

    g_b_drInfoInUrl = false;

    if (tempValue != "")
    {
        g_b_drInfoInUrl = true;
    }

    return tempValue;
}

function getDR_cookie_info()
{
    g_dr_pgm_info_from_cookie   = getNVPV2(getCookie("digitalriver")==null ? "" :getCookie("digitalriver") ,   'pgm',            false, "=", "&"); 
    g_dr_offer_info_from_cookie = getNVPV2(getCookie("digitalriver")==null ? "" :getCookie("digitalriver") ,   'OfferID',        false, "=", "&");

    var tempValue   = "";
   
    if ( (g_dr_pgm_info_from_cookie != null && g_dr_pgm_info_from_cookie != "") && (g_dr_offer_info_from_cookie != null && g_dr_offer_info_from_cookie != "") )
    { // both PGM and OFFERID are in the cookie "digitalriver"
        tempValue = "pgm=" + g_dr_pgm_info_from_cookie + "&OfferID="+g_dr_offer_info_from_cookie;
    }
    else if (g_dr_pgm_info_from_cookie != null && g_dr_pgm_info_from_cookie != "")
    {   // only PGM is in the cookie "digitalriver"
        tempValue = "pgm=" + g_dr_pgm_info_from_cookie;
    }
    else if (g_dr_offer_info_from_cookie != null && g_dr_offer_info_from_cookie != "")
    {   // only OFFERID is in the cookie "digitalriver"
        tempValue = "OfferID=" + g_dr_offer_info_from_cookie;
    }    

    g_b_drInfoInCookie = false;

    if (tempValue != "")
    {
        g_b_drInfoInCookie = true;
    }

    return tempValue;
}

function getDR_ws_info()
{
    // Returns CID info from the web service call.  Note!  The useThisCID value may be different 
    // from what was really returned from the w/s call, so do not directly us w/s call value.
    return useThisCID;
}

function processDigitalRiverCookie()
{
    g_log.debug('<b>Inside processDigitalRiverCookie</b>');
    // This function is called from one of three places:
    //  - onloadProcessing()        if web service not called
    //  - webServiceCallSuccess()  if web service was called
    //  - webServiceCallNotNeeded() if  we found the wsc cookie already had the info we needed

    // if the otpPartnerId we determine we should use is different from the otpPartnerId in the digitalriver cookie, the cookie is:
    // - deleted if no pgm or pgm/OfferID info available to us (in url or web service)
    // - deleted if the web service returned a partner id other than the one we requested
    // - replaced with the otpPartnerId and pgm or pgm/OfferID we think we should use

    // if digitalriver cookie already exists but its otpPartnerId != the one we want to use, clear out the digitalriver cookie

    if (g_partner_id != getCookiePartnerId("digitalriver"))
    {
        // wipe out current digitalriver cookie
        tempCookieValue = "";   // since IE has issues deleting/expiring session cookies, just set cookie to ""
        setCookie("digitalriver", "", null, "/");
        g_log.debug('processDigitalRiverCookie : g_partner_id:'+g_partner_id+' != getCookiePartnerId:'+getCookiePartnerId("digitalriver"));
     }

    // The rules regarding what DR info to write to the digitalriver cookie is as follows:
    // - the DR info from the web service IF it returned information for a partner other than the one we requested
    // - the DR info in the URL    - UNLESS the otpPartnerId in the digitalriver cookie <> partner id we determine is the correct one to use
    // - the DR info in the cookie - UNLESS the otpPartnerId in the digitalriver cookie <> partner id we determine is the correct one to use
    // - the DR info returned from the partner web service call if any 

    var dr_url_info    =  getDR_url_info();        // dr info in url
    var dr_cookie_info =  getDR_cookie_info();     // dr info in existing digitalriver cookie
    var dr_ws_info     =  getDR_ws_info();         // dr info returned from web service call
    
    var tempValue   = "";

    if (g_b_ws_partner_id_different)
    {
        // Web service successful but returned a different partner id than was requested.  Use information from the web service (WS) over url or cookie values.
        tempValue = g_partner_cid;
        g_log.debug('processDigitalRiverCookie: use DR info from url :'+tempValue);

    }
    else if ( g_b_drInfoInUrl && (g_partner_id == getCookiePartnerId("digitalriver") || !g_b_drInfoInCookie) )
    {
        // DR info found in URL AND (partner id in DR COOKIE is same as partner id we determined we need to use OR 
        // the digitalriver cookie is empty), write dr url info to digitalriver cookie
        tempValue = dr_url_info;
        g_log.debug('processDigitalRiverCookie: use DR info from url :'+tempValue);

    }
    else if ( g_b_drInfoInCookie && (g_partner_id == getCookiePartnerId("digitalriver")) )
    {
        // DR info found in COOKIE and partner id in COOKIE is same as the partner id we determined we need to use.  Sounds
        // redundant, but if we don't value tempValue here, then g_partner_cid wouldn't be correctly valued below!
        tempValue = dr_cookie_info;
        g_log.debug('processDigitalRiverCookie: use DR info from COOKIE :'+tempValue);
    }
    else if (dr_ws_info != null && dr_ws_info != "" && dr_ws_info != 0)
    {   
        // take information from the web service if any
       tempValue = dr_ws_info;
       g_log.debug('processDigitalRiverCookie: use DR info from ws call:'+tempValue);
        
    }
    else{
        tempValue = ""; // if unable to determine what DR info to use, use ""
    }

    g_partner_cid = tempValue;  // now we know the dr info to use, so set the global variable to hold it
    if (g_b_ws_call_failed) 
    {
        tempValue = ""; 
    }

    if (tempValue != ""){
        tempValue = "otppartnerid="+g_partner_id+"&"+tempValue;
    }  
    
    setCookie("digitalriver", tempValue, null, "/");    
    g_log.debug('processDigitalRiverCookie :: main cookie:'+getCookie("main_cookie")+' DR cookie:'+getCookie("digitalriver"));
   
}

function isDRUrlAndCookieDifferent()
{
    // Returns true if DR info in url is different from what is currently in the digitalriver cookie.
    // If yes, then this flags a condition that we must get call the software product info servlet
    var url_pgm      = getNVPV2(location.search, "pgm",          false, "=", "&");
    var url_offer    = getNVPV2(location.search, "OfferID",      false, "=", "&");

    var cookie_pgm   = getNVPV2(getCookie("digitalriver")==null ? "" :getCookie("digitalriver") ,   'pgm',      false, "=", "&"); 
    var cookie_offer = getNVPV2(getCookie("digitalriver")==null ? "" :getCookie("digitalriver") ,   'OfferID',  false, "=", "&");

    // generally, pgm and offerid are NOT going to be in the url, just on the first page visited
    if (url_pgm != "" || url_offer != "")
    {   //alert("isDRUrlAndCookieDifferent(): url_pgm=="+url_pgm+" and url_offer=="+url_offer);
        if (url_pgm == cookie_pgm && url_offer == cookie_offer)
        {
            // DR info in url and cookie are the same
            return false;
        }
        else
        {   // DR info in url and cookie are the different.  This triggers a call to get updated partner/product info.
            return true;
        }
    }
}

// ***********************************************
// onloadProcessing()
// ***********************************************
function onloadProcessing()
{   
    // By the time we get here, any offermatica calls that might have changed the partner
    // id (and thus the product pricing) will have executed and called offermaticaPartnerSelect().
    
	// reset the cookie value from the backup variable
	setCookie('wsc',g_wsc_backup);

    g_log.debug('<b>Inside onloadProcessing</b>');

    g_partner_id_from_search_engine = getSearchEnginePartnerId();
    g_partner_id_from_url           = getUrlPartnerId();
    g_partner_id_from_cookie        = getCookiePartnerId("main_cookie");
    g_partner_id_from_offermatica   = getOffermaticaPartnerId();

    g_log.debug("<table border=1 bordercolor='#EEEEEE' cellspacing=0 style='font-family:Verdana;font-size:11px;'><tr> <th>partner id Source</th><th>value</th><th>priority</th></tr><tr> <td>g_partner_id_from_offermatica</td><td>&nbsp;"+g_partner_id_from_offermatica+"</td><td>1</td></tr><tr> <td>g_partner_id_from_url</td><td> "+g_partner_id_from_url+"</td><td>2</td></tr><tr> <td>g_partner_id_from_cookie</td><td> "+g_partner_id_from_cookie+"</td><td>3</td></tr><tr> <td>g_partner_id_from_search_engine</td><td> "+g_partner_id_from_search_engine+"</td><td>4</td></tr></table>");

    setPartnerIdToUse();
    processMainCookie();
    // check if CampaignID should be written to a cookie
    campaignIdCheck();

    // ********************************************************************
    // If g_bGetProductInfo is true if getElementsByAttribute() finds at least one element 
    // with an id that begins with prodPrice, as in <span id="prodPrice31"></span> 
    // then call the product web service
    // ********************************************************************
    g_log.debug(" onloadProcessing: price span tags:<b>"+getElementsByAttribute("id", "prodPrice").length+"</b>");

    // dynamic partner and product info not available until post-hrblock.com launch
    //if (g_bGetProductInfo || (getElementsByAttribute("id", "prodPrice").length > 0) || (document.location.pathname.indexOf('/taxes/partner/index.jsp') != - 1) || document.location.href.indexOf("search2.h")!= -1 || document.location.href.indexOf("atomzdev.")!= -1)
    var bDomainOkForCall    = true;
    // To avoid cross-domain call errors in the xmlHttpRequest, add non hrblock.com sites, including subdomains, in this if statement
    if (document.location.href.indexOf("search2.h")!= -1)
    {
        bDomainOkForCall = false;
    }
    //if (bDomainOkForCall && (g_bGetProductInfo  || (document.location.pathname.indexOf('/taxes/partner/index.jsp') != - 1)) )
	if (bDomainOkForCall)
    {       
        // NOTE: Javascript processing continues on without waiting for the asynchronous web service call in getProductInfo() to finish.  If you want
        // code to execute AFTER the web service call is complete, put the code in function webServiceCallSuccess().
        g_log.debug('calling getPartnerProduct('+g_partner_id+','+g_tunneledPage+')');
        try {
        	g_log.debug('inside try/catch...');
        	getPartnerProduct(g_partner_id,g_tunneledPage);       // get partner & product information
        }
        catch(e)
        {
			g_log.debug('error:'+e);
        }
    }
    else
    { g_log.debug(" onloadProcessing():going directly to continueOnloadProcessing");
        continueOnloadProcessing();
    }
}

function continueOnloadProcessing()
{
    g_log.debug('<b>Inside continueOnloadProcessing</b>');
    // if no web service calls on page: this is called directly by onloadProcessing()
    // if web services calls were done: this is called by webServiceCallSuccess()

    if ( (typeof is_homepage) !='undefined' && (is_homepage) )
    {
        try{
            updatePriceValuesInFlash(); 
        }
        catch (e){}
    }

    //hightlight taxtips links
    updateTaxTipsArticleLink();
    if ( document.location.pathname.indexOf("/taxes/products/software/back_editions") != -1 )
    {
        try{
             g_log.debug(" continueOnloadProcessing():BACK EDITION page");
            getSoftwareProductsInfo(); 
        }
        catch (e) {
            g_log.error('E26');
        }
    }

    try{  
        specialOnloadProcessing();  // this function can be defined by anyone requiring a special function 
                                    // to run after the document has loaded, like Ajay needed for Omniture
    }
    catch (e){
        g_log.debug('No specialOnloadProcessing is found ');
    }

    try{  
            //run pixel processing only for block domains
            var _env =g_sys.checkEnv();
                if (_env=='PROD' || _env=="QA" || _env=="DEV"){
                        processPixelTracking();

                }
    }
    catch (e){
        g_log.debug('Problem calling processPixelTracking().');
    }

if (bBugWin) bugTxt += "<br/>continueOnloadProcessing(): *** ALL PROCESSING COMPLETE.  BELOW ARE FINAL VALUES USED. ***<br/>";

if (bBugWin)
{
    bugTxt += "g_nvpCount      =='"+g_nvpCount+"' [valued by splitQueryString()]<br/><br/>";

    bugTxt += "<b>*** GLOBAL PARTNER DATA ***</b><br/>";
    bugTxt += "g_partner_id=='"         +g_partner_id +"'<br/>";
    bugTxt += "g_partnerName=='"        +g_partnerName+"'<br/>";
    bugTxt += "g_partner_cid=='"        +g_partner_cid+"'<br/>";
    bugTxt += "g_partnerType=='"        +g_partnerType+"'<br/>";
    bugTxt += "g_partnerTunneledInd=='" +g_partnerTunneledInd+"'<br/>";
    bugTxt += "g_partnerWelcomeText=='" +g_partnerWelcomeText+"'<br/><br/>";

    bugTxt += "<b>*** DATA FROM WEB SERVICE CALL / WSC COOKIE ***</b><br/>";
    bugTxt += "partner ID is '"        +g_hrb_partner_product.getPartnerOtpPartnerId()+"'<br/>";
    bugTxt += "partner Name is '"      +g_hrb_partner_product.getPartnerName() +"'<br/>";
    bugTxt += "partner CID is '"       +g_hrb_partner_product.getPartnerCID()  +"'<br/>";
    bugTxt += "partner Type is '"      +g_hrb_partner_product.getPartnerType() +"'<br/>";
    bugTxt += "partner Tunneled is '"  +g_hrb_partner_product.getPartnerTunnel() +"'<br/>";
    bugTxt += "partner Welcome is '"   +g_hrb_partner_product.getPartnerWelcome()+"'<br/><br/>";

    bugTxt += "<b>*** PARTNER ID SOURCES/VALUES ***</b><br/>";
    bugTxt += "g_partner_id_from_cookie        =='"+g_partner_id_from_cookie+"'<br/>";
    bugTxt += "g_partner_id_from_url           =='"+g_partner_id_from_url+"'<br/>";
    bugTxt += "g_partner_id_from_offermatica   =='"+g_partner_id_from_offermatica+"'<br/>";
    bugTxt += "g_partner_id_from_search_engine =='"+g_partner_id_from_search_engine+"'<br/>";

    bugTxt += "<b>*** INFORMATION ABOUT THE WEB SERVICE CALL ***</b><br/>";
    bugTxt += "<b>Ignore these values if web service call was skipped.</b><br/>";

    // use a try/catch here because the http_request object may not exist
    try
    {
        bugTxt += "http_request.status=="+http_request.status+"<br/>";
    }
    catch (e)
    {
        //
    }

    bugTxt += "<b>*** SEARCH ENGINE DATA ***</b><br/>";
    bugTxt += "g_searchEngineTerm       =='"+g_searchEngineTerm+"'<br/>";
    bugTxt += "g_bReferrerIsSearchEngine=='"+g_bReferrerIsSearchEngine+"'<br/><br/>";

    bugTxt += "<b>*** CAMPAIGN DATA ***</b><br/>";
    bugTxt += "g_campaign_id   =='"+g_campaign_id+"'<br/><br/>";

    bugTxt += "<b>*** DIGITAL RIVER DATA ***</b><br/>";
    bugTxt += "g_dr_info_to_use=='"     +g_dr_info_to_use+"'  [Currently never valued]<br/>";
    bugTxt += "getDR_url_info()   =='"  +getDR_url_info()+"'<br/>";
    bugTxt += "getDR_ws_info()    =='"  +getDR_ws_info()+"'<br/>";
    bugTxt += "getDR_cookie_info()=='"  +getDR_cookie_info()+"'<br/><br/>";

            
    bugTxt += "<b>*** COOKIE VALUES ***</b><br/>";
    bugTxt += "NOTE: If otpPartnerId is in both cookie digitalriver AND main_cookie, it must have the same value:<br/>";
    bugTxt += "<font color='red'>getCookie('digitalriver')</font>=='"+getCookie("digitalriver")+"'<br/>";
    bugTxt += "<font color='red'>getCookie('main_cookie')</font>=='" +getCookie("main_cookie")+"'<br/>";
    bugTxt += "<font color='red'>getCookie('wsc')</font>=='"         +getCookie("wsc")+"'<br/>";    
    bugTxt += "<font color='red'>getCookie('hrblockCampaignIDcookie')</font>=='"+getCookie("hrblockCampaignIDcookie")+"'<br/>";   
   
    writeDebugWindow();
}
/*
    if (getCookiePartnerId("digitalriver") != "" && (getCookiePartnerId("digitalriver") != getCookiePartnerId("main_cookie")) )
    {
        alert("Condition: The dr value '"+getCookiePartnerId("digitalriver")+"' <> main_cookie value '"+getCookiePartnerId("main_cookie"));
    }
*/

    if (getQueryValue("testExceptionLogging")=="true")
    {
        recordExceptionInOmniture("ocs","0","Exception logging is working.");
    }
}

function writeDebugWindow()
{
    objDebugWindow.document.write(bugTxt+"<br/>*** END***");
}

// ***********************************************
// offermaticaPartnerSelect()
// ***********************************************
function offermaticaPartnerSelect(om_partner_id)
{
    if (bBugWin) bugTxt += "<font color='purple'><b>top of offermaticaPartnerSelect("+om_partner_id+")</b></font> [This function is only called by content being served from Offermatica.]<br/>";
    g_partner_id_from_offermatica = om_partner_id;
}

function getNVPvalue(strURL, strParmName, bCaseSpecific)
{
    return getNVPV(strURL, strParmName, bCaseSpecific);
}

// ****************
// similar to getNVPV2(strURL, strParmName, bCaseSpecific, operator, delimiter) below
// ****************




function getNVPV(strURL, strParmName, bCaseSpecific)
{   
    // Description: returns value of a name/value pair in the passed URL string
    // Usage: getNVPV(url, 'ADCAMPAIGN', '1');
    //
    // Parameters:
    //   strURL: url to extract the name/value pair from
    //   strParmName: name part of name/value pair
    //   bCaseSpecific: when searching for name, use case passed to function. 1==true; 0==false
    //
    // Returns:
    //  the value of the nvp if found and "" if not found

    if (strURL==null || strURL=="")
    {
        return "";
    }

    if (bCaseSpecific)
    { 
    }
    else
    {
        strParmName = strParmName.toLowerCase();
        strURL      = strURL.toLowerCase();
    }

    var strChar = "";

    if (strURL.indexOf("?"+strParmName+"=") != -1)
    {   strChar = "?";
    }
    else if (strURL.indexOf("&"+strParmName+"=") != -1)
    {   strChar = "&";
    }
    else
    {   return "";
    }

    var strTemp1 = strURL.substring(strURL.indexOf(strChar+strParmName+"=")+strParmName.length+2, strURL.length);

    if (strTemp1.indexOf("&", 0) == -1)
    {   return strTemp1;
    }
    else
    {   return strTemp1.substring(0, strTemp1.indexOf("&"));
    }
}

// ****************
// similar to getNVPV(strURL, strParmName, bCaseSpecific) above
// ****************
function getNVPV2(strURL, strParmName, bCaseSpecific, operator, delimiter)
{   
    // Description: returns value of a name/value pair in the passed URL string
    // Usage: getNVPV2(url, 'otpPartnerId', '1', '=', '&');
    // Usage: getNVPV2(url, 'OfferID', '1', '.', '/');
    // Usage: getNVPV2(url, 'pgm', '1', '.', '/');
    //
    // Parameters:
    //   strURL: url to extract the name/value pair from
    //   strParmName: name part of name/value pair
    //   bCaseSpecific: when searching for name, use case passed to function. 1==true; 0==false
    //
    // Returns:
    //  the value of the nvp if found and "" if not found

    if (strURL==null || strURL=="")
    {
        return "";
    }

    if (bCaseSpecific)
    { 
    }
    else
    {
        strParmName = strParmName.toLowerCase();
        strURL      = strURL.toLowerCase();
    }

    var strChar = "";

    if (strURL.indexOf("?"+strParmName+operator) != -1)
    {   strChar = "?";
    }
    else if (strURL.indexOf(delimiter+strParmName+operator) != -1)
    {   strChar = delimiter;
    }
    else
    {   return "";
    }

    var strTemp1 = strURL.substring(strURL.indexOf(strChar+strParmName+operator)+strParmName.length+2, strURL.length);

    if (strTemp1.indexOf(delimiter, 0) == -1)
    {   return strTemp1;
    }
    else
    {   return strTemp1.substring(0, strTemp1.indexOf(delimiter));
    }
}

function getSearchTerm()
{
    // If possible, get the search term passed to us from certain search engines.  This term can be
    // used for various purposes across the site

    // determine if referrer is available
    // determine if referrer is a search engine
    // extract search term from appropriate name/value pair

    var referrer_query = "";

    if (document.referrer != null)
    {   // referrer information is available
        if (document.referrer.indexOf("?") != -1)
        {   // referrer sent a query string in url
            referrer_query = document.referrer.substr(document.referrer.indexOf("?")); 
        }
    }   
    else
    {
        return;
    }

    if ((document.referrer.indexOf('google.com') > -1) )
    {
        g_bReferrerIsSearchEngine = true;
        g_searchEngineTerm    =  referrer_query=="" ? "" : getNVPV(referrer_query, 'q', false); 
    } 
    else if ((document.referrer.indexOf('yahoo.com') > -1)) 
    {
        g_bReferrerIsSearchEngine = true;
        g_searchEngineTerm    = referrer_query=="" ? "" : getNVPV(referrer_query, 'p', false); 
    } 
    else if ((document.referrer.indexOf('bing.com') > -1)) 
    {
        g_bReferrerIsSearchEngine = true;
        g_searchEngineTerm    = referrer_query=="" ? "" : getNVPV(referrer_query, 'q', false);                
    } 
    else if ((document.referrer.indexOf('aol.com') > -1)) 
    {
        g_bReferrerIsSearchEngine = true;
        g_searchEngineTerm    = referrer_query=="" ? "" : getNVPV(referrer_query, 'query', false); 

        if (g_searchEngineTerm=="")
        {
            g_searchEngineTerm    = referrer_query=="userQuery-nfd" ? "" : getNVPV(referrer_query, 'userQuery', false); 
        }               
    } 
    else if ((document.referrer.indexOf('netscape.com') > -1)) 
    {
        g_bReferrerIsSearchEngine = true;
        g_searchEngineTerm    = referrer_query=="" ? "" : getNVPV(referrer_query, 'query', false); 

        if (g_searchEngineTerm=="")
        {
            g_searchEngineTerm    = referrer_query=="userQuery-nfd" ? "" : getNVPV(referrer_query, 'userQuery', false); 
        }                
    } 
    else if ((document.referrer.indexOf('ask.com') > -1)) 
    {
        g_bReferrerIsSearchEngine = true;
        g_searchEngineTerm    = referrer_query=="" ? "" : getNVPV(referrer_query, 'q', false);

        if (g_searchEngineTerm=="")
        {
            g_searchEngineTerm    = referrer_query=="" ? "" : getNVPV(referrer_query, 'ask', false); 
        }
    }  

    if (g_bReferrerIsSearchEngine)
    {
        if (g_searchEngineTerm=="") 
        {
            g_searchEngineTerm="search_term_not_available";
        }
        else
        {
            try
            {                
                document.getElementById('tt_searchText').focus();
                g_searchEngineTerm=unescape(g_searchEngineTerm);
                if (g_searchEngineTerm.indexOf("+")==0)
                {   // some srch engines have a leading + in the search term, remove it.
                    g_searchEngineTerm=g_searchEngineTerm.substr(1);
                }
                g_searchEngineTerm=g_searchEngineTerm.replace(/\+/g, " ");    
                document.getElementById('tt_searchText').value=g_searchEngineTerm;                
            }
            catch (e)
            {   
                // noop
            }
        }
    }
}

function getSearchEnginePartnerId()
{
    // if (no partner id passed in url and no partner id in cookie) AND
    //   if (not from paid search) AND
    //      if (from search engine) THEN
    //          write appropriate partner id assigned to that search engine to the cookie
    //          so it gets passed along to otp
    if (bBugWin) bugTxt += "<font color='blue'><b>top of getSearchEnginePartnerId()</b></font><br/>";

    var searchPID   = "";
    var srchsim     = "";

    // this line allows us to simulate search engine referrals
    srchsim = getQueryValue("srchsim");    

    if (document.referrer != null)
    {
        getSearchTerm();
    }
    else
    {
        // can't get referrer so return null for search engine partner id
        if (bBugWin) bugTxt += "getSearchEnginePartnerId() returning '"+searchPID+"' since no referrer found.<br/>";
        return searchPID;
    }

    // check if visitor came from paid search

    if ( (g_bReferrerIsSearchEngine && location.search.indexOf('omnisource=') != -1) || ((srchsim != "") && location.search.indexOf('omnisource=') != -1) )
    {
        g_paidSearch = 1; // g_paidSearch value is referenced in the omniture code
    }

    if (g_paidSearch!="1")
    {
        // if we came from a search engine (but not paid search),  write that search engine partner id to the cookie
        if ( (document.referrer != null) || (srchsim != "") )
        {
            if ((document.referrer.indexOf('google.com') > -1)          || (srchsim=="google") )
            {
                searchPID   =  2054;    // hrblock.com
                //searchPID   =  2260;    // taxcut.com
            } 
            else if ((document.referrer.indexOf('yahoo.com') > -1)      || (srchsim=="yahoo") ) 
            {
                searchPID   =  2055;    // hrblock.com
                //searchPID   =  2259;    // taxcut.com
            } 
            else if ((document.referrer.indexOf('bing.com') > -1)        || (srchsim=="bing") ) 
            {
                searchPID   =  2056;    // hrblock.com
                //searchPID   =  2258;    // taxcut.com
            } 
            else if ((document.referrer.indexOf('aol.com') > -1)        || (srchsim=="aol") ) 
            {
                searchPID   =  2057;    // hrblock.com
                //searchPID   =  2263;    // taxcut.com
            } 
            else if ((document.referrer.indexOf('netscape.com') > -1)   || (srchsim=="netscape") ) 
            {
                searchPID   =  2058;    // hrblock.com
                //searchPID   =  2261;    // taxcut.com
            } 
            else if ((document.referrer.indexOf('ask.com') > -1)  || (srchsim=="ask") ) 
            {
                searchPID   =  2059;    // hrblock.com
                //searchPID   =  2262;    // taxcut.com
            } 
        }
    }   
    if (bBugWin) bugTxt += "getSearchEnginePartnerId() returning '"+searchPID+"'. document.referrer=='"+document.referrer+"'<br/>";
    return searchPID;
}

function campaignIdCheck() 
{
    g_campaign_id      = getQueryValue('CampaignID');

    if (bBugWin) bugTxt += "<font color='blue'><b>top of campaignIdCheck(): CampaignID in url is '"+g_campaign_id+"'.</b></font><br/>";

    if(g_campaign_id != null) 
    {
        setCookie('hrblockCampaignIDcookie', 'CampaignID=' + g_campaign_id, null, "/");
        if (bBugWin) bugTxt += "campaignIdCheck(): cookie 'hrblockCampaignIDcookie' set to 'CampaignID="+g_campaign_id+"'.<br/>";
    }
    else
    {
        if (bBugWin) bugTxt += "campaignIdCheck(): do not write cookie 'hrblockCampaignIDcookie' since it wasn't in the url.<br/>";
    }
}

function getCookieInfoForSignon()
{
   taxType  = getQueryValue("TaxType");

    if (taxType == null)
    {   // if no TaxType specified then assume opp for unavailable check below
        taxType = "opp";   // default to opp if TaxType nvp not specified
    }
   
   document.signon.PartnerID.value      = g_partner_id;
   document.signon.time_entered.value   = g_time_entered;      
}

function isTunneledPage()
{
    if (document.location.pathname.indexOf("/taxes/partner/") != - 1 && document.location.pathname.indexOf('.jsp') != - 1)
    {   
        return true;
    }
    else
    {
        return false;
    }
}

function processMainCookie()
{
    g_log.debug('<b>Inside processMainCookie</b>');
    var qs      = "";
    var tempQS  = "";

    qs  = location.search;
    qs  = unescape(qs);

    if (g_partner_id_from_offermatica != "" && g_partner_id_from_offermatica != null)
    {
        // write cookie using offermatica id and tag on partnerid for otp

        g_log.debug("processMainCookie(): writing partner id '"+g_partner_id_from_offermatica+"' assigned by offermatica. Call setCookie('main_cookie','otpPartnerId="+g_partner_id+"&PartnerId="+g_partner_id+"')<br/>");
        setCookie("main_cookie","otpPartnerId="+g_partner_id+"&PartnerId="+g_partner_id, null, "/");
    }
    else if (g_partner_id_from_url != "" && g_partner_id_from_url != null)
    {
        if (g_partner_id_from_url == g_partner_id_from_cookie)
        {
            // url id == cookie id so do not re-write the cookie otherwise other parms in the cookie would be lost
           g_log.debug("processMainCookie(): no need to write/re-write main_cookie since g_partner_id_from_url["+g_partner_id_from_url+"] == g_partner_id_from_cookie["+g_partner_id_from_cookie+"].  Re-writing would delete site-visit parm values anyway.<br/>");
        }
        else
        {        
            // url id != cookie id so write cookie using current query string and tag on partnerid for otp
            if (qs.indexOf("?")!=-1) 
            {
                qs = qs.slice(qs.indexOf("?")+1);
            }
            tempQS      = qs.toLowerCase();     // allows search for parm otppartnerid to be case indifferent
            iBeginPos   = tempQS.indexOf("otppartnerid");
            qs = qs.substring(0,iBeginPos)+"otpPartnerId="+qs.substring(iBeginPos+13,qs.length);
            g_log.debug("processMainCookie(): g_partner_id_from_url["+g_partner_id_from_url+"] != g_partner_id_from_cookie["+g_partner_id_from_cookie+"] so write g_partner_id["+g_partner_id+"] to the cookie.<br/>");
            setCookie("main_cookie", qs+"&PartnerID="+g_partner_id, null, "/");  
        }
    }
    else if (g_partner_id_from_cookie != "" && g_partner_id_from_cookie != null)
    {
        // do nothing
        g_log.debug("processMainCookie(): g_partner_id_from_cookie["+g_partner_id_from_cookie+"] is not == '' and not == null, so don't write main_cookie.<br/>");
    }
    else if (g_partner_id_from_search_engine != "" && g_partner_id_from_search_engine != null)
    {
        // is this an organic, non-paid search engine referral
        g_log.debug("processMainCookie(): g_partner_id_from_search_engine["+g_partner_id_from_search_engine+"] valued so write it to main_cookie.<br/>");
        setCookie("main_cookie", "otpPartnerId="+g_partner_id+"&PartnerId="+g_partner_id_from_search_engine+"&srchTerm="+g_searchEngineTerm, null, "/");
    }
    else
    {
        // no partner id specified in url/cookie or can be inferred, so use default partner id for this domain + current query string 
        if (qs.indexOf("?")!=-1) 
        {
            qs = qs.slice(qs.indexOf("?")+1);
        }
         g_log.debug("processMainCookie(): no partner id available from anywhere so use default partner id for this domain + current query string.<br/>");
        setCookie("main_cookie", qs+"&otpPartnerId="+g_partner_id+"&PartnerID="+g_partner_id, null, "/");  
    }
}

function FindAction(Entity)
{
    // this function is called by the TCO login section in the header

    getCookieInfoForSignon();

    if (Entity == 'Register' )
    {
        SubmitValidation();
        return true;
    }
    else if (Entity == 'ForgotPassword' )
    {
        window.location = 'ForgotPassword.aspx?BackPage=Login&'
                }
    else if (Entity == 'Update' )
    {
        window.location = 'Login.aspx?Target=UpdateUserInformation&taxtype=OTP&PartnerID='
    }
    else if (Entity == 'Policy' )
    {
        openCTWindow('SecurityPolicy','/universal/privacy.html','status,resizable,width=' + parseInt(Math.min(screen.availWidth,800)) + ',height=' + parseInt(Math.min(screen.availHeight,600)-25) + ',left=0,top=0,screenX=0,screenY=0,scrollbars=1');
    }
    else if (Entity == 'Login' )
    {
        return true;
    }

} //end FindAction()

function doTaxes()
{   //document.location="/taxes/doing_my_taxes/";
        document.location="/taxes/products/product.jsp?productId=31";
}

function doExtension()
{   //document.location="/taxes/doing_my_taxes/products/extension.html";
        document.location="/taxes/products/product.jsp?productId=69";
}    

function otpLogin() 
{
    if(document.getElementById('txtusername').value != '' && document.getElementById('txtpassword').value != '') {
        if ( (typeof sysprop_showPopUnder) !='undefined' && sysprop_showPopUnder==1 ) {
            try {
                window.open('','popunderotp','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=10,height=10,left=2000,top=2000').close();
            } catch(e) { }
        }
        if ( (typeof sysprop_otpStatus)!='undefined' && (sysprop_otpStatus==1 || sysprop_otpStatus==2)) {
            showDownPage();
            return false;
        } else {
            FindAction('Login');
        }
    }
}

function loadinparent(url)
{
    top.location.href = url;
}

var omniName="";
function showCalcs(indx,referlink)
{
 location.href='/free-tax-tips-calculators/';
}

// specifically for calculators as the start button should open this in a new window

function staticProductStartNowNewWin(requestedProductId)
{ 
    // Read the main_cookie to retrieve (if available) the otpPartnerId and other parms
    // that may have been passed into inital visit to hrblock.com.  
    
    // if no cookie value is found, use otpPartnerId=0
    
if (bBugWin) bugTxt += "staticProductStartNowNewWin("+requestedProductId+") calling getCookie('main_cookie')<br/>";
    var cookieValue = getCookie("main_cookie");    
    
    // Sometimes we pass additional name/value pairs to start now links which
    // need to be appended to the target start now link. 
    // Add additional parms to this method following one of these two methods:
    // staticPageStartNow(31,"&newparm1=newvalue1","&newparm2=newvalue2");
    // staticPageStartNow(31,"&newparm1=newvalue1&newparm2=newvalue2");
    
    var additionalParms = "";
    
    var args    = staticProductStartNowNewWin.arguments;
    var argsLen = staticProductStartNowNewWin.arguments.length;
            
    for(var i=0; i<argsLen; i++) {       
        if (args[i].toString().charAt(0)=="&"){ 
            additionalParms = args[i];
        }
    }
    
    var parms = cookieValue + additionalParms;        

    window.open(hrb_s[requestedProductId] + parms,'productwin','left=20,top=20,width=900,height=500,toolbar=1,resizable=1');
}
// **********************************************************************************
// END: Calculator related code
// **********************************************************************************


function bookmark()
{
  if (window.sidebar) { 
      // Mozilla Firefox Bookmark       
      window.sidebar.addPanel(document.title, location.href,"");    
  } 
  else if( window.external ) { 
        // IE Favorite      
      window.external.AddFavorite( location.href, document.title); 
  }
  else  {
    alert("Press CTRL-D (Netscape) or CTRL-T (Opera) or CTRL-D (Safari) to bookmark");
  }
}

function emailtaxtips()
{
    var tax_tip_email_path = "/taxes/tax_tips/email_taxtips.html?taxtip_id="+g_tax_tip_id;
    //WinOpen_(tax_tip_email_path, 580, 500);
    var popup=open(tax_tip_email_path,"popup","status=yes,toolbar=no,directories=no,scrollbars=no,menubar=no,resizable=no,width=585,height=530");
    popup.focus();
}

// ********
// This function accepts the parameters
//  site           Required: Valid value is currently just 'hrblock'.
//  linkname       Optional: Used for omniture reporting
//  &              Optional: A parm starting with "&" will be appended to the destURL
//
// sample usage:
//  productLearnMore(34, "site:hrblock");
//  productLearnMore(34, "site:hrblock", "linkname:uniqueId"); 
//
//  There are two ways to have this pass along additional parameters to the destination page:
//  productLearnMore(34, "site:hrblock", "linkname:uniqueId", "&customname=customvalue&a=b&name=value"); 
//  productLearnMore(34, "site:hrblock", "linkname:unqiueId", "parms:&customname=customvalue&a=b&name=value");
// ********
function productLearnMore(requestedProductId)
{ 
    if (requestedProductId == 84)
    {
        window.top.location="/tango/index.html";
        return;
    }

    if (requestedProductId == 197)
    {
        window.open("https://www.deductionpro.com/dpro/Welcome.jsp","dedpro","");
        return;
    }

    var siteName        = "";
    var destURL         = "";
    var destDomain      = "";
    var uniqueId        = "";   // Valued from optional parm. Sent to webAnalytics() call to uniquely identify which object on page was clicked
    var bTargetPageIsJSP= false;
    var passParms       = "";

	// value destDomain  for third party sites
	//var _env =g_sys.checkEnv();
    //if (_env!='PROD' && _env!="QA" && _env!="DEV"){
	//	destDomain="//www.hrblock.com";
	//}
	
	if (!g_hrb_partner_product.isValued())
	{
		// populates g_hrb_partner_product with default information
		setFinalResp();
	}

    // certain flash objects pass additional name/value pair to this function which
    // need to be appended to the target learn more link.  start at 2nd argument
    // since first arg is always the product id - pintar    
    var additionalParms = "";
        
    var args            = arguments;
    var argsLen         = arguments.length;
  
    // determine which "learn more" function should be called
    for (var x=0; x<argsLen; x++ )    {
        if ((''+arguments[x]).indexOf("site:") != -1)   {
            siteName    = arguments[x].substr(5).toLowerCase();

            if (siteName != "hrblock")      {
                //alert("invalid site '"+siteName+"' to productLearnMore()");
            }
        }

        if ((''+arguments[x]).indexOf("linkname:") != -1)  {
            // if found, append that value to the webAnalytics() call in the linkname: parm.
            // var uniqueId   = the value part of the parm 'linkname:value'      
            uniqueId    = arguments[x].substr(9);
        }

        if ((''+arguments[x]).indexOf("parms:") != -1) {
            // if found, append that value to the webAnalytics() call in the linkname: parm.
            // var uniqueId   = the value part of the parm 'linkname:value'      
            additionalParms    = arguments[x].substr(6);
            if (additionalParms.indexOf("&") != 0) {
                additionalParms = "&" + additionalParms;
                alert('additionalParms '+additionalParms)
            }
        }
    }

    if (siteName=="") {
		// Domains other than hrblock.com not currently supported
        siteName    = "hrblock";
    }

    if (siteName == "hrblock") {
        var args    = productLearnMore.arguments;
        var argsLen = productLearnMore.arguments.length;
    
        for(var i=0; i<argsLen; i++)    {                   
            if (args[i].toString().charAt(0)=="&")  { 
                additionalParms += args[i];
            }
        }

        if (productIdValid(requestedProductId))  {
            if (g_hrb_partner_product.getProductLearnMore(requestedProductId).indexOf("product.jsp") != -1) {
                bTargetPageIsJSP  = true;
            }
        }
        else   {
            // It could be that the current page didn't create the g_hrb_partner_product object since it
            // wasn't flagged as having products or doesn't have any elements with id like "prodPriceXXXXX" on it.
            // In this case just go to "/taxes/products/"+requestedProductId+".html"            
            //document.location = "/taxes/products/"+requestedProductId+".html";
            document.location = destDomain+getPageXref(requestedProductId);
            return;
        }
      
        //destURL = g_hrb_partner_product.getProductLearnMore(requestedProductId)+additionalParms;
        
        if (g_tunneledPage) {   
            //destURL = "/taxes/partner/" + destURL;
            destURL = "/taxes/partner/product.jsp?productId=" + requestedProductId;
        }
        else{   
            //destURL = "/taxes/products/" + requestedProductId + ".html";
            //destURL = g_hrb_partner_product.getProductLearnMore(requestedProductId);
            destURL =   getPageXref(requestedProductId);
        }

        if (additionalParms != ""){
            if (destURL.indexOf("?") == -1){
                destURL += "?" + additionalParms;
            }
            else {
                destURL += additionalParms;
            }

            //alert('final URL '+destURL)
        }

        if (getQueryValue("bBugClicks")=="true"){   
            alert(" bTargetPageIsJSP=="+bTargetPageIsJSP+"\r destURL=="+destURL);
        }
    }
    else if (siteName == "taxcut" || siteName == "external") {
        // Domains other than hrblock.com not currently supported
        // destURL = g_hrb_partner_product.getProductLearnMore(requestedProductId) + "&" + getCookie("main_cookie");
    }

    var pageNameToUse   = ((typeof omni_pagename)!="undefined" && omni_pagename != "") ? omni_pagename : "";

    var newanchor = document.createElement("a");

    newanchor.setAttribute('href',  document.location.href);        
	document.body.appendChild(newanchor);
    try  {
        // remove & characters from pageNameToUse and uniqueId otherwise webAnalytics() will not properly parse the parameters when these are used in prop6 and eVar11
        pageNameToUse   = pageNameToUse.replace(/&/g, "^");
        uniqueId        = uniqueId.replace(/&/g, "^");
        //webAnalytics(newanchor, 'trackvars:prop6='+pageNameToUse+"-"+requestedProductId+"-"+uniqueId+'&eVar11='+pageNameToUse+"-"+requestedProductId+"-"+uniqueId+'&', 'trackevents:' ,'linkname:'+pageNameToUse+"-"+requestedProductId+"-"+uniqueId, 'type:o');                        
        var prop6_eVar11 = getProductPlatform(requestedProductId)+"-"+requestedProductId+"-"+getProductName(requestedProductId)+"-"+pageNameToUse+"-"+uniqueId;
        webAnalytics(newanchor, "trackvars:prop6="+prop6_eVar11+"&eVar11="+prop6_eVar11+"&", "trackevents:" ,"linkname:"+pageNameToUse+"-"+requestedProductId+"-"+uniqueId, "type:o");                
    }
    catch (e) {
       //alert("productLearnMore("+requestedProductId+"): error calling webAnalytics:"+e.description);  
    }

    //destURL += "&otpPartnerId=" + getCookieElementValue("main_cookie", "otpPartnerId", false); 

    if (getQueryValue("bBugClicks")=="true")
    {   
        alert("going to '"+destURL+"'\rsiteName=="+siteName+"\rpageNameToUse=="+pageNameToUse+"\rbFound=="+bFound+"\rbTargetPageIsJSP=="+bTargetPageIsJSP+"\rrequestedProductId=="+requestedProductId+"\rhrb_s["+requestedProductId+"]=="+hrb_s[requestedProductId]);
    }
    window.top.location = destDomain + destURL; // specify (.top.)  window.top.location for tunneled office locator page
}

// ********
// This function can take additional parameters:
//  site           Required: Valid value is currently just 'hrblock'.
//  format         Required for software products.  Valid values are "dl" or "cd".
//  platform       Required for software products.  Valid values are "pc" or mac".
//  linkname       Optional: Used for omniture reporting.
//
// sample usage:
//  productStartNow(35, "format:cd", "platform:pc", "site:taxcut");  // software products required 'format','platform', and 'site'
//  productStartNow(32, "site:taxcut")                               // non-software products only require 'site'
//
// sample usage: receiving a uniqueId to send to webAnalytics()
//  productStartNow(35, "site:hrblock", "format:dl", "platform:mac", "linkname:unique"); // software products required 'format','platform', and 'site'
//  productStartNow(32, "site:taxcut", "linkname:uniqueId")                              // non-software products only require 'site'
//  
// ********
function productStartNow(requestedProductId)
{ 
    if (requestedProductId == 84)  {
       // return openTango(); // special tango code
    }
    
    if (requestedProductId == 197)
    {
        window.open("https://www.deductionpro.com/dpro/Welcome.jsp","dedpro","");
        return;
    }

    var siteName        = "";
    var destURL         = "";
    var destDomain      = "";
    var bSoftware       = false;
    var sku;

    var bTargetPageIsJSP    = false;
    var bTargetPageIsLogin  = false;

    var uniqueId        = "";   // Valued from optional parm. Sent to webAnalytics() call to uniquely identify which object on page was clicked
    var tcs_format      = "";
    var tcs_platform    = "";

	// value destDomain  for third party sites
	var _env =g_sys.checkEnv();
    if (_env!='PROD' && _env!="QA" && _env!="DEV"){
		destDomain="//www.hrblock.com";
	}
	
	if (!g_hrb_partner_product.isValued())
	{
		// populates g_hrb_partner_product with default information
		setFinalResp();
	}

    if (requestedProductId==46) {   // send old extension product to new extension product
        requestedProductId = 188;
    }

    var args    = arguments;
    var argsLen = arguments.length;

    // process additional parameters we may have received
    for (var x=0; x<argsLen; x++ )
    {   
        if ((''+arguments[x]).indexOf("format:") != -1) {
            tcs_format      = arguments[x].substr(7).toLowerCase();
            if (tcs_format != "dl" && tcs_format != "cd"){
                alert("invalid format value '"+tcs_format+"' to productStartNow()");
            }
        }
        if ((''+arguments[x]).indexOf("platform:") != -1)    {
            tcs_platform    = arguments[x].substr(9).toLowerCase();
            if (tcs_platform != "pc" && tcs_platform != "mac" ){
                alert("invalid platform value '"+platform+"' to productStartNow()");
            }
        }
        if ((''+arguments[x]).indexOf("site:") != -1)   {
            siteName        = arguments[x].substr(5).toLowerCase();
            if (siteName != "hrblock"){
                alert("invalid site value '"+siteName+"' to productStartNow()");
            }
        }
        if ((''+arguments[x]).indexOf("linkname:") != -1) {
            // if found, append that value to the webAnalytics() call in the linkname: parm.
            // var uniqueId   = the value part of the parm 'linkname:value'      
            uniqueId    = arguments[x].substr(9);
        }
        if ((''+arguments[x]).indexOf("sku:") != -1)   {
            sku    = arguments[x].substr(4);
        }    
    }

    if (siteName=="")   {
		// Domains other than hrblock.com not currently supported
        siteName    = "hrblock";
    }

    if (g_hrb_partner_product.getProductPlatform(requestedProductId).toLowerCase() == "s" )
    {
		if (sku=="200998000")
		{
			sku="223009800";
		}
        destDomain  = "http://shop.hrblock.com";
        destURL     = "/store/taxcut/en_US/AddItemToRequisition/productID."+sku+'?'+getCookie("digitalriver");
        bSoftware   = true;
        g_log.debug("productStartNow()....s.k=="+g_hrb_partner_product.getProductSKU(requestedProductId));
    }

    if (siteName == "hrblock")
    {   
        if (!bSoftware)
        {
            destURL = g_hrb_partner_product.getProductStartNow(requestedProductId);

            if (destURL.indexOf("product.jsp") != -1)
            {
                bTargetPageIsJSP    = true;
            }  
            else if (destURL.indexOf("loginRedirect.html") != -1)
            {
                bTargetPageIsLogin  = true;
            }


            if (!bTargetPageIsLogin)
            {   
                if (g_tunneledPage)
                {   
                    destURL = "/taxes/partner/" + destURL;
                }
                else
                {   
                    destURL = "/taxes/products/"+requestedProductId+".html";
                }
            }
        }
        else
        {
            // no action
        }

        if (getQueryValue("bBugClicks")=="true")
        {   
            alert(" bTargetPageIsJSP=="+bTargetPageIsJSP+"\r destURL=="+destURL);
        }
    }    
    else if (siteName == "taxcut" || siteName == "external")
    {
        // Domains other than hrblock.com not currently supported.
        // destURL += tc_s[requestedProductId] + "&" + getCookie("main_cookie");
    }

    var pageNameToUse   = ((typeof omni_pagename)!="undefined" && omni_pagename != "") ? omni_pagename : "";

    var newanchor = document.createElement("a");

    newanchor.setAttribute('href', document.location.href);
	document.body.appendChild(newanchor);
    try
    {
        // remove any & characters from pageNameToUse and uniqueId otherwise webAnalytics() will not properly parse the paraemters when these are used in prop6 and eVar11
        pageNameToUse   = pageNameToUse.replace(/&/g, "^");
        uniqueId        = uniqueId.replace(/&/g, "^");
        var prop5_eVar10 = getProductPlatform(requestedProductId)+"-"+requestedProductId+"-"+getProductName(requestedProductId)+"-"+pageNameToUse+"-"+uniqueId;
      //webAnalytics(newanchor, 'trackvars:prop5='+pageNameToUse+"-"+requestedProductId+"-"+uniqueId+'&eVar10='+pageNameToUse+"-"+requestedProductId+"-"+uniqueId+'&', 'trackevents:event14' ,'linkname:'+pageNameToUse+"-"+requestedProductId+"-"+uniqueId, 'type:o');
        webAnalytics(newanchor, "trackvars:prop5="+prop5_eVar10+"&eVar10="+prop5_eVar10+"&", "trackevents:event14" ,"linkname:"+pageNameToUse+"-"+requestedProductId+"-"+uniqueId, "type:o");
    }
    catch (e)
    {
       //alert("productLearnMore("+requestedProductId+"): error calling webAnalytics:"+e.description);  
    }

    if (destURL.indexOf("loginRedirect.html") != -1)
    {   
		var cValue = getCookie("main_cookie");
		if (cValue != null && cValue != "null" && cValue != "")
		{
			destURL += "&" + getCookie("main_cookie");
		}
    }

    if (getQueryValue("bBugClicks")=="true")
    {   
        alert("going to '"+destURL+"'\rsiteName=="+siteName+"\rpageNameToUse=="+pageNameToUse+"\rbFound=="+bFound+"\rbTargetPageIsJSP=="+bTargetPageIsJSP+"\rrequestedProductId=="+requestedProductId+"\rhrb_s["+requestedProductId+"]=="+hrb_s[requestedProductId]);
    }

    window.top.location = destDomain + destURL;  // need window.top.location for tunneled office locator page
}

// **************************************************************************************
// returns tco, tcs or off sourced from d_pName[][] array
// **************************************************************************************
function getProductPlatform(requestedProductId)
{
    if (productIdValid(requestedProductId))
    {
        if (g_hrb_partner_product.getProductPlatform(requestedProductId).toLowerCase() == "o")
        {
            return "tco";    // online
        }
        else if (g_hrb_partner_product.getProductPlatform(requestedProductId).toLowerCase() == "r")
        {
            return "off";    // office
        }
        else if (g_hrb_partner_product.getProductPlatform(requestedProductId).toLowerCase() == "s")
        {
            return "tcs";    // software
        }
        else
        {
            return "nfd";    // not found (nfd)
        }
    }
    else
    {
        return "nfd";
    }
}

// **************************************************************************************
// returns tco, tcs or off sourced from d_pName[][] array
// **************************************************************************************
function getProductName(requestedProductId)
{
    if (productIdValid(requestedProductId)){
        return g_hrb_partner_product.getProductOmnitureName(requestedProductId);
    }
    else{
        return "nfd";
    }
}

// *********************************************************
// END: TCS and TCO link code
// *********************************************************


// *********************************************************
// BEGIN: Web Service Cookie Code
// *********************************************************

function getWebServiceCookie(partnerID)
{
    var cValue = unescape(getCookie("wsc"));
        g_log.debug("Inside getWebServiceCookie("+partnerID+")  Cookie value "+cValue); 

    if (cValue != null && cValue != "null" && cValue != false && cValue != "")
    {
		try
		{       
			if (!g_hrb_partner_product.setPartnerProduct(cValue,true))
			{
				// this would happen if parsing failed
				return false;
			}
			// these values used in webServiceCallNotNeeded() to value global variables


			if ((g_hrb_partner_product.getPartnerOtpPartnerId() != partnerID))
			{   g_log.debug("getWebServiceCookie(): URL PID and wsc COOKIE PID are different!  Get updated product info.");
				// The partner id in the cookie isn't the one we want.
				// By returning false, will call the partner information from the server.
				return false;
			}
			else if (isDRUrlAndCookieDifferent())
			{   g_log.debug("getWebServiceCookie(): DR in both URL and COOKIE but different!  Get updated product info.");
				// The partner id in URL and cooke match but URL DigitalRiver info is different from digitalriver cookie
				// By returning false, will call the partner information from the server.
				return false;
			}
			else
			{   // The partner id in the cookie is the correct one, so no need to call the server
				// to get partner/product info since it's already in the cookie.
				g_log.debug("getWebServiceCookie(): No partner or digital river info changed, so no web service call needed.");
				return true;
			}
			
		}
		catch (e)
		{
			g_log.debug(":getWebServiceCookie("+partnerID+"):"+e.message);
		}
    }   

    // The cookie doesn't exist so get the partner information from the server.
    return false;
}

function getWebServiceCookie_OLD(partnerID)
{
    var cValue = unescape(getCookie("wsc"));
        g_log.debug("<b>Inside getWebServiceCookie</b>("+partnerID+")  Cookie value "+cValue); 

    if (cValue != null && cValue != "null" && cValue != false && cValue != "")
    {
        g_hrb_partner_product.setPartnerProduct(cValue,true);
        // these values used in webServiceCallNotNeeded() to value global variables

        if (g_hrb_partner_product.getPartnerOtpPartnerId() != partnerID)
        {
            // The partner id in the cookie isn't the one we want, so returning false will
            // cause us to get the correct partner information from the server.
            return false;
        }
        else
        {   // The partner id in the cookie is the correct one, so no need to call the server
            // to get partner/product info since it's already in the cookie.
            return true;
        }
    }   

    // The cookie doesn't exist so get the partner information from the server.
    return false;
}

function writeWebServiceCookie() 
{   
    g_log.debug('<b>Inside writeWebServiceCookie </b>');
    // This function is called after a successful call to the server for partner/product information.

    var wsinfo  = g_hrb_partner_product.getCompressedStr();
    g_log.debug(' writeWebServiceCookie : wsinfo:'+wsinfo);

    // ****************************** TBD: COMPLETE THIS SECTION!! ********************************
    // First get the current size of document.cookie.  If its size, plus the size of wsinfo, exceeds 4096 bytes, do NOT write the
    // cookie as it will likely fail due to domain cookie constraints imposed by browsers.
   
    setCookie("wsc",wsinfo, null, "/");
}

// *********************************************************
// END: Web Service Cookie Code
// *********************************************************

//function to escape tax tips url
function createTaxTipsUrl(sPath, sTaxTipTitle)
{
    var titleQuery = "?ttiptitle=";
    var sUrl = sPath + titleQuery + escape(sTaxTipTitle);
    document.location = sUrl;
}

// *********************************************************
// BEGIN: Tango Product Code
// *********************************************************
function MM_preloadImages(){ 
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
  var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
  if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { 
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { 
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { 
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
  if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/*function openTango()
{
    var w = window.screen['availWidth']?window.screen.availWidth:window.screen.width;
    var h = window.screen ['availHeight']?window.screen.availHeight:window.screen.height;
    var dw = w<1024?w:1024;
    var dh = h<2048?h:2048;
    dw = dw-12;
    dh = dh-30;
    var x = (w-dw-12)/2; 
    var y = (h-dh-30)/2;      
    var tgw = window.open("https://tangotax.hrblock.com/tango.html","_blank","status=no, location=no, toolbar=no, menubar=no, width="+dw+", height="+dh+", left="+x+", top="+y+", resizable=yes");         
    return tgw==null;
}*/

// *********************************************************
// END: Tango Product Code
// *********************************************************

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

// example calls
// onclick="omnitureOnClick('navLocation:h',  'navName:logo');"
// onclick="omnitureOnClick('navLocation:hpn','navName:taxes');"
// onclick="omnitureOnClick('navLocation:fpn','navName:customer_support');"
// onclick="omnitureOnClick('navLocation:f',  'navName:site_map');"
// onclick="omnitureOnClick('navLocation:b',  'navName:selectCompany', 'pageName:override_current_omni_pagename');"

function omnitureOnClick()
{
    if (typeof(s_hrb) != "undefined")
    {

        var tempPageName= "";
        var origPageName= s_hrb.pageName;
        
        var navLocation = "unknown";
        var navName     = "unknown";        
        
        var additionalTrackVars = "";
        
        var args        = arguments;
        var argsLen     = arguments.length;    

        for (var x=0; x<argsLen; x++)
        {
            if ((''+arguments[x]).indexOf("navLocation:") != -1)
            {
                navLocation    = arguments[x].substr(12).toLowerCase().replace(/&/g, "^");
            }
            else if ((''+arguments[x]).indexOf("navName:") != -1)
            {
                navName    = arguments[x].substr(8).toLowerCase();
                navName    = navName.replace(/&amp;/g, "and");
                navName    = navName.replace(/&nbsp;/g, " ");
                navName    = navName.replace(/&/g, " and ");
                
                // remove common html markup that may be in the anchor that called this function
                navName    = navName.replace(/<br>/g, "");
                navName    = navName.replace(/<br \/>/g, "");            
                navName    = navName.replace(/<b>/g, "");
                navName    = navName.replace(/<\/b>/g, "");
                navName    = navName.replace(/<sup>/g, "");
                navName    = navName.replace(/<\/sup>/g, "");
            }    
            else if ((''+arguments[x]).indexOf("pageName:") != -1)
            {
                tempPageName = arguments[x].substr(9).toLowerCase().replace(/&/g, "^");
                if (tempPageName != "undefined")
                {   
                    s_hrb.pageName = tempPageName;
                }
            }
            else if ((''+arguments[x]).indexOf("trackvars:") != -1)
            {
                additionalTrackVars = arguments[x].substr(10);
                if (additionalTrackVars.length > 0)
                {
                    additionalTrackVars += "&"; 
                }
            }
        }
            
        var newanchor = document.createElement("a");

        newanchor.setAttribute('href',  document.location.href); 
		document.body.appendChild(newanchor);

        var bOmniPageNameResolved    = false;

        if ( (typeof omni_pagename)=="undefined" || omni_pagename=="" || omni_pagename==null  || omni_pagename=="undefined")
        {
            // IF you click on a nav item BEFORE the page has finished loading, then omni_pagename will not be defined because
            // it is the omniture_std.html file included at the very bottom of the page that defines this variable.  In those
            // cases, the try/catch blocks below will handle the resulting javascript errors.

            // track the domain of the page that isn't setting omni_pagename
            omni_pagename = document.location.hostname;

            // is this is a page on hrblock.com domain?
            if ( (omni_pagename.indexOf("hrblock.com") != -1) || (omni_pagename.indexOf("handrblock.com") != -1) || (omni_pagename.indexOf("hrbtax.com") != -1) || (omni_pagename.indexOf("hrbtrade.com") != -1)  )
            {
                // is this is a internal search page?
                if (  (omni_pagename.indexOf("search2.") != -1) || (omni_pagename.indexOf("ahp.") != -1) || (omni_pagename.indexOf("taxpro.") != -1) || (omni_pagename.indexOf("jobs.") != -1) )
                {
                    // if hrblock.com, and internal search or not ocs owned, just use document.location.hostname for omni_pagename 
                    bOmniPageNameResolved = true;
                }
                else if (document.location.pathname.indexOf(".jsp") != -1) {
                    // if a jsp page, try to identify the jsp application that is not valuing pagename
                    omni_pagename += "/application";
                    
                    if (document.location.pathname.indexOf("/taxes/fast_facts/") != -1)
                    {
                        omni_pagename += "/tax_faq";
                    }
                    else
                    {
                        omni_pagename += "/unknown/"+document.location.pathname;
                    }
                }
            }
            else {
                bOmniPageNameResolved   = true;
            }

            if (bOmniPageNameResolved){
                // no action needed
            }
            else   {
                try
                {
                    recordExceptionInOmniture("ocs-nopagename","9","using "+omni_pagename+"/nav/"+navLocation+"/"+navName);
                }
                catch (e)
                {
                    // alert("omnitureOnClick(): error calling recordExceptionInOmniture:"+e.description);  
                }
                
            }
        }

        try  {
            webAnalytics(newanchor, "trackvars:eVar48="+omni_pagename+"/nav/"+navLocation+"/"+navName+"&"+additionalTrackVars, "trackevents:" ,"linkname:"+"/nav/"+navLocation+"/"+navName, "type:o");                
        }
        catch (e) {
            // alert("omnitureOnClick(): error calling webAnalytics:"+e.description);  
        }
        
        //s_hrb.pageName = origPageName;
    }
    else
    {
        // omniture has not loaded before onclick was processed
        // so evaluating s_hrb would have cause javascript error
    }
}        

//load the software processing JS for the product learn more in online pages
if ( document.location.pathname.indexOf('product.jsp') != - 1)
{
    document.write('<script type=\"text\/javascript\" src=\"\/includes\/js\/soft_product_processing.js\"><\/script>');
}

function hasValue(v)
{
    // returns true if this variable is defined and has a non empty value
    if (typeof v!='undefined' && v!=null && v!='')
    {
        return true;
    }
    return false;
}

// *********************************************************
// allow_offermatica_test()
// Checks to see if an offermatica test can be run or not by 
// checking if an otpPartnerId exists in the url or in the cookie.
// *********************************************************
function allow_offermatica_test()
{
    if (bBugWin) bugTxt += "<font color='blue'><b>top of allow_offermatica_test()</b></font><br/>";

    var pid_from_cookie = getCookiePartnerId("main_cookie");    
    var pid_from_url    = getUrlPartnerId();
    var pid_to_use;

    if (hasValue(pid_from_url))
    {
        pid_to_use = pid_from_url;
    }
    else if (hasValue(pid_from_cookie))
    {
        pid_to_use = pid_from_cookie;
    }
    else 
    {
        pid_to_use = 0; // tbd: 1) organic search engine partner id and 2) 2631 returned from partner info servlet call
    }
    
   // if (bBugWin) bugTxt += "allow_offermatica_test(): getCookiePartnerId('main_cookie')=='"+pid_from_cookie+"'<br/>";
    //if (bBugWin) bugTxt += "allow_offermatica_test(): getUrlPartnerId()=='"+pid_from_url+"'<br/>";
    //if (bBugWin) bugTxt += "allow_offermatica_test(): pid_to_use=='"+pid_to_use+"'<br/>";
    
    var offermatica_pids = new Array("","0","180",
                                     "3346","3347","3348","3349","3350","3351","3352","3353","3401","3405", /* UHP Image Test */
                                     "3407","3408","3409","3410","3411","3412","3413",  /* 1040EZ Test */
                                     "3416","3417","3418","3419","3420","3421", /* DIY Main Online Test */
                                     "3511","3512","3513","3514","3515","3516","3517",  /* Organic Search - UHP */
                                     "3523","3524","3525","3526","3527","3528","3529","3530",   /* FFA Top Section Design */
                                     "3548","3549","3550","3551","3552","3553","3554","3555",   /* Paid Search - UHP */
                                     "3536","3537","3538","3539","3540","3541",     /* Paid Search - Office */
                                     "3542","3543","3544","3545","3546","3547",     /* Paid Search - DIY */
                                     "3602","3603","3604","3605","3606",    /* Organic Search - UHP - Round 2 */
                                     "3571","3572","3573",   /* Lineup - UHP */
                                     "3574","3575","3576",   /* Lineup - DIY */
                                     "3567","3568","3569","3570","3569","3558","3559","3560","3561","3562","3563","3564","3565","3566",  /* Banner Ad - Retail */
                                     "3607","3608","3610","3611", 	/* BoB Online Price Test */
									 "3402","3403","3404", /* Basic Online Price Test */
									 "3724","3725","3726");	/* UHP */
                                       
    g_offermatica_allow = "0";

    for (var i=0;i<offermatica_pids.length;i++)
    {       
        if (offermatica_pids[i] == pid_to_use)
        {
            g_offermatica_allow = "1";            
            break;
        }
    }
}

// *********************************************************
// END allow_offermatica_test()
// *********************************************************
// *********************************************************
// callOffermatica(clicksrc)
// Passes the mbox onclick name for links and buttons to 
// register within offermatica.
// *********************************************************
function callOffermatica(clicksrc)
{
    var defaultImageURL = document.location.protocol + '//www.hrblock.com/images/pixel.gif';
    var clickedMboxName = clicksrc;  

    clickRequestUrl = document.location.protocol + '//mbox9e.offermatica.com/m2/hrblock/' + 'ubox/image?mbox=' + clickedMboxName + 
                     '&mboxSession=' +  mboxFactoryDefault.getSessionId().getId() + '&mboxPC=' + 
                     mboxFactoryDefault.getPCId().getId() + '&mboxXDomain=disabled&mboxDefault=' + escape(defaultImageURL) + 
                     '&profile.productClicked=home_office' + '&t=' + (new Date()).getTime();   

    (new Image()).src = clickRequestUrl;   

    return;
}
// *********************************************************
// END callOffermatica(clicksrc)
// *********************************************************
//used by software pages
function updateProductVariation(pid,variation,obj)
{   
    document.getElementById(pid+'_variation').value=variation;
}

/* function to hightlight taxtips article links*/
function updateTaxTipsArticleLink(){
    var page_nav_tax_tip =getElementsByAttribute("id", "page_nav_tax_tip");
    var  title = unescape(getQueryValue('ttiptitle'));
     for (var k=0;k<page_nav_tax_tip.length;k++){
        var tax_tip_items = page_nav_tax_tip[k].getElementsByTagName("li");
        
        for (var i=0;i<tax_tip_items.length;i++){
            var tax_tip_item = "";
            var tmpHref=tax_tip_items[i].childNodes[0].href;
            title = title.trim();
            var indx = tmpHref.indexOf("ttiptitle");
            tax_tip_item = (unescape(tmpHref.substring(indx+10))).trim();
            if(tax_tip_item == title){
                tax_tip_items[i].childNodes[0].style.color = "white";
                tax_tip_items[i].style.background = "#7DC242";
                break;
            }
        }
    }
}

function handleNonClickable(e){
/*    var obj =null;
    var ypos=0;
    if (window.event){
        obj=event.srcElement;
        ypos=(event.clientY + document.documentElement.scrollTop  )  ;
    }
    else {
    obj=e.target;
    ypos =e.pageY ;      
    }
    var objTagNm= obj.tagName;
    if ((objTagNm.toLowerCase())=='input' ||  (objTagNm.toLowerCase())=='a'  || (objTagNm.toLowerCase())=='select' ){
       return;
    }
    if (obj.onclick!= undefined && obj.onclick!=null&& obj.onclick!=''){
       return;
    }
    if (typeof obj.parentNode !='undefined'){
        if (obj.parentNode.tagName=='A' ){
           return;
        }
        else if (obj.parentNode.onclick!= undefined && obj.parentNode.onclick!=null && obj.parentNode.onclick!=''){
            return false;
        }
    }
    var navname='';
    var navloc='NONClK';
    if(obj.tagName=='IMG'){
        var tmpimgName=obj.src;
        if ( typeof tmpimgName!='undefined' && tmpimgName!=null && tmpimgName!=''){
        tmpimgName=tmpimgName.substring(tmpimgName.lastIndexOf('/')+1,tmpimgName.length)
        }
        navname+='im|'+tmpimgName;
    }
    else if ((typeof obj.style!='undefined')&& obj.style.backgroundImage!=''){
        var tmpimgName=obj.style.backgroundImage;
        if ( typeof tmpimgName!='undefined' && tmpimgName!=null && tmpimgName!=''){
        tmpimgName=tmpimgName.substring(tmpimgName.lastIndexOf('/')+1,tmpimgName.length)
        }
        navname+='im|'+tmpimgName;
    }
    else if ((typeof obj.id!='undefined') && obj.id!=''){
        navname+='id|'+obj.id;
    }
    else if ((typeof obj.className!='undefined') && obj.className!='' ){
        navname+='cl|'+obj.className;
    }

    if(obj.tagName=='BODY'){
       navname+='black_area';
    }
    if (ypos > 135 && ypos <635){
     navloc+='/BODY';
    }
    else if (ypos < 135){
     navloc+='/HEAD';
    }
    else{
     navloc+='/FOOT';
    }
    omnitureOnClick('navLocation:'+navloc,'navName:'+navname);
*/
}

// ***************************************
// *** BEGIN: CODE RELATED TO BAZAARVOICE
// ***************************************

function processRatings()
{   // called by hrb_script.js if page has pageHasInlineRatings=="true"
	
	try
	{
		$.ajax(
		{
			url: "/includes/bazaarvoice/xml/bv_hrblock_ratings.xml",		
			type: "GET",
			dataType: "xml",
			error:function (jqXHR, textStatus, errorThrown){				
				//alert("ajax1:error:"+jqXHR.status+"\r\n"+textStatus+"\r\n"+errorThrown);                     
			},
			success: processInlineRatings,
			complete: function (jqXHR, textStatus){
				//alert("ajax1:complete:\r\njqXHR.status:"+jqXHR.status+"\r\ntextStatus:"+textStatus);  
			}
		 });

	}
	catch (e)
	{
		//alert("20:"+e.description+"\r\n"+e.message);
	}	 
}

var prodReviewArr	= new Array();
var firstReviewMsg	= "Be the first to write a review!";

function processInlineRatings(data, textStatus, jqXHR){

	var xml	= jqXHR.responseXML;

	var currentProductId;
	var currentAverageOverallRating;
	var currentTotalReviewCount;
	var currentProductPageUrl;

	var starImageObj;
	var starImageWidth	= "115px";
	var starImageHeight	= "21px";

	var productArray= new Array();
	var inx			= 0;
	var endIndex	= 0;

	if (typeof bvStarImageWidth != 'undefined')
	{	starImageWidth=bvStarImageWidth;
	}

	if (typeof bvStarImageHeight != 'undefined')
	{	starImageHeight=bvStarImageHeight;
	}

	// find all elements that have "*RatingsImg" as an id, such as prod201RatingsImg
	$("img:[id*='RatingsImg']").each(function() {
		endIndex=this.id.indexOf("RatingsImg");
		productArray[inx]=this.id.substring(4,endIndex);
		inx++;
	});

	var bProductRatingSuccessful = false;

	for (var x=0; x<productArray.length; x++ ) {
		currentProductId		= productArray[x];
		
		bProductRatingSuccessful= false;

		$(xml).find('Product').each(function(){

			if ($(this).attr('id') == productArray[x])
			{
				currentAverageOverallRating		= $(this).find('ReviewStatistics').find('AverageOverallRating').text(); // in format x.x from 0.0 to 5.0
				currentTotalReviewCount			= $(this).find('ReviewStatistics').find('TotalReviewCount').text();
				currentProductPageUrl			= $(this).find('ProductPageUrl').text();
				
				currentAverageOverallRating		= roundNumber(currentAverageOverallRating,1);
				currentAverageOverallRating		+="";

				ratingsArray					= currentAverageOverallRating.split(".");

				if (ratingsArray.length==0)
				{
					ratingsArray[0] = 0;
					ratingsArray[1] = 0;
				} 
				else if (ratingsArray.length==1)
				{
					ratingsArray[1] = 0;
				}

				currentRatingImage = "/includes/bazaarvoice/images/rating-"+ratingsArray[0]+"_"+ratingsArray[1]+".gif";

				starImageObj=document.getElementById('prod'+currentProductId+'RatingsImg');
				starImageObj.src=currentRatingImage;

				if(starImageObj && starImageObj.style) { 
					starImageObj.style.height	= starImageHeight;
					starImageObj.style.width	= starImageWidth;
				}

				if (currentTotalReviewCount==0)	{
					$('#prod'+currentProductId+'NbrOfRatings').html(firstReviewMsg);
				}
				else {
					$('#prod'+currentProductId+'NbrOfRatings').html(currentTotalReviewCount+" customer reviews");
				}
				
				bProductRatingSuccessful = true;
				return false; // breaks out of the .each loop
			}
		});

		// at this point we:
		//  - found the product in the BV xml file and processed it
		//  - didn't find the product in the BV xml file so give it default values 
		if (bProductRatingSuccessful != true)
		{   
			currentRatingImage = "/includes/bazaarvoice/images/rating-0_0.gif";

			starImageObj=document.getElementById('prod'+currentProductId+'RatingsImg');
			starImageObj.src=currentRatingImage;

			if(starImageObj && starImageObj.style) { 
				starImageObj.style.height	= starImageHeight;
				starImageObj.style.width	= starImageWidth;
			}

			$('#prod'+currentProductId+'NbrOfRatings').html(firstReviewMsg);
		}

		currentProductPageUrl = "//reviews.hrblock.com/4531-en_us/"+currentProductId+"/submission.htm?return=http%3A%2F%2Fwww.hrblock.com/index.html";
		prodReviewArr[currentProductId]=currentProductPageUrl;

	}

	$('.bvRatings').css({'visibility':'visible','display':'block'});
}

function handleInlineProductRatingsClick(prodId) {
	if ($('#prod'+prodId+'NbrOfRatings').html()==firstReviewMsg){
		document.location=prodReviewArr[prodId];
	}
	else {
		productLearnMore(prodId);
	}
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
// ***************************************
// *** END: CODE RELATED TO BAZAARVOICE
// ***************************************


/*

Bank rates display
*/
function displayRates(rate_type,product_type){
if(rate_type||product_type){
		$.ajax({
			url:"/bank/rateservice.jsp?rt="+rate_type+"&pt="+product_type,
			dataType: 'json',
			success: function(response) {
				$('#productDetails').html('');
				$('#productDetails').append($('#productTemplate').tmpl(response));
				$('#bankratesdate').html(response[1].ratePublishDt); 
			},
			error: function(response) {
			//  if ajax call fails need to handle here	
			},
			timeout: 10000,
			cache: false
		});
	}
}

// ****************
// END:   CONTENTS OF HEADER_INIT_HRBLOCK_2008.JS
// ****************


