//prod id
var gTrackingId = "UA-11250392-1";
//testing id
//var gTrackingId = "UA-10624741-2";
var oIDebugMode = false;
var pageTracker = null;

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


// Javascript Behaviour for the popup control
// Copyright (c) by Matthias Hertel, http://www.mathertel.de
// This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx
// ----- 
// 03.06.2005 created by Matthias Hertel

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof(navigator.cookieEnabled) ==  'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') == 1);
  }
};


var PopUpBehaviour = {
  // ----- Events -----
  // terminate the timer and remove the popUp information
  hide: function(evt) {
    Element.hide("popupDivHolder");
  }, // onmouseout 

  // now show the popUp information
  show: function(selectedObj,poptext) {
    var obj = selectedObj; 
    if (obj != null) {
      pos = PopUpBehaviour._absolutePosition(obj);
      PopUpBehaviour._create(poptext, pos);     
    } // if
  }, // show
  
  // now show the popUp information
  showRollOver: function(selectedObj,poptext) {
    var obj = selectedObj; 
    if (obj != null) {
      pos = PopUpBehaviour._absolutePosition(obj);
      PopUpBehaviour._createRollOver(selectedObj.id, poptext, pos);     
    } // if
  }, // show  
  // --- private methods ---
  
    // terminate the timer and remove the popUp information
  hideRollOver: function(evt) {
      if($('rollOverDivHolder'))
      {
        Element.hide("rollOverDivHolder");  
      }
  }, // onmouseout 
 
  // create or reuse the popUp element
  _create: function(text, pos) {
    var oPop = $("popupDivHolder");
   
    if (oPop == null) {
      // create a popUp object for the first time
      oPop = document.createElement("div");
      oPop.id= "popupDivHolder";
      var htm ="";
      htm += "<div id='popupDivClose'><ul id='logoBarLinks'><li class='logoBarLinkLast'><a id='popupCloser' href='#'>Close</a></li></ul></div>";
      htm += "<div id='popupDivShadow'></div><div id='popupDivContent'></div>";
      oPop.innerHTML = htm;
      document.body.appendChild(oPop);
    } // if

    // adjust tht position and choos the right point gif file
    oPop.style.display="block";
    oPop.style.top = ((pos.top + pos.height) - 40) + "px";
    var leftPos = pos.left + pos.width/2 - 10;

    if (leftPos < 8) {
      oPop.style.left = "8px";
    } else if (leftPos + 240 < document.documentElement.clientWidth) {
      oPop.style.left = leftPos + "px";
    } else {
      leftPos = pos.left + pos.width/2 - 200;
      if (leftPos + 250 > document.documentElement.clientWidth)
        leftPos = document.documentElement.clientWidth - 250;
      oPop.style.left = leftPos + "px";
    } // if

    // adjust the shadow object
    var pContent = $('popupDivContent');
    pContent.innerHTML = text;
    $('popupDivShadow').style.height = pContent.offsetHeight + 36;
    var closeHandlerFunc = function(t)
    {
      PopUpBehaviour.hide(t);
      Event.stop(t);
    }
    Event.observe('popupCloser', "click", closeHandlerFunc);
    return(oPop); 
  }, // _create

  // create or reuse the popUp element
  _createRollOver: function(selectedObjectId, text, pos) {    
    var oPop = $("rollOverDivHolder");
    if (oPop == null) {
      // create a popUp object for the first time
      oPop = document.createElement("div");
      oPop.id= "rollOverDivHolder";
      var htm ="<!--[if lte IE 6.5]><iframe id=\"rollOverDivFrame\"></iframe><![endif]-->" +
      "<div id=\"rollOverDivContent\" class=\"rollOverDivContent\"></div>";
      oPop.innerHTML = htm;
      document.body.appendChild(oPop);
    } // if

    // adjust tht position and choos the right point gif file
    oPop.style.display="block";
    oPop.style.top = ((pos.top + pos.height) - 30) + "px";
    var leftPos = pos.left + pos.width/2 ;

    if (leftPos < 8) {
      oPop.style.left = "8px";
    } else if (leftPos + 240 < document.documentElement.clientWidth) {
      oPop.style.left = leftPos + "px";
    } else {
      leftPos = pos.left + pos.width/2 - 200;
      if (leftPos + 250 > document.documentElement.clientWidth)
        leftPos = document.documentElement.clientWidth - 250;
      oPop.style.left = leftPos + "px";
    } // if
    
    // adjust the shadow object
    var pContent = $('rollOverDivContent');
    pContent.innerHTML = text;
    return(oPop); 
  }, // _create
  
  // get the absolute position of a html object
  _absolutePosition: function(obj) {
    var pos = null;
    
    if (obj != null) {
      pos = new Object();
      pos.top = obj.offsetTop;
      pos.left = obj.offsetLeft;
      pos.width = obj.offsetWidth;
      pos.height= obj.offsetHeight;

      obj = obj.offsetParent;
      while (obj != null) {
        pos.top += obj.offsetTop;
        pos.left += obj.offsetLeft;
        obj = obj.offsetParent;
      } // while
    }
    return(pos);
  } // _absolutePosition

} // PopUpBehaviour

//rollover glossary helper
var rollOverGlossaryCanceled = false;
var rollOverGlossaryCache = new Hash();
function doRollOverGlossary(selectedObject,glossaryKey,headerContent)
{
	rollOverGlossaryCanceled = false;
	var errHandler = function(t) {
		alert('doRollOverGlossary.Error ' + t.status + ' -- ' + t.statusText);
	}
	var successHandler = function(t) {
	    var content = headerContent != null? headerContent + t.responseText:t.responseText;
	    //put in cache
	    rollOverGlossaryCache.set(glossaryKey,content);
	    if(!rollOverGlossaryCanceled)
	    {
            PopUpBehaviour.showRollOver(selectedObject,content);
        }		
	}  	
	//if glossary Key is in the cache and mouseover wasn't canceled then go their instead
	if(rollOverGlossaryCache.get(glossaryKey))
	{
 	   if(!rollOverGlossaryCanceled)
	   {
        PopUpBehaviour.showRollOver(selectedObject,rollOverGlossaryCache.get(glossaryKey));
       }          
    }
    else
    {
        var url = getContextPath() + "/sections/glossary.jsp?key=" + glossaryKey;
       // submit the form using Ajax
       new Ajax.Request(url, {method: 'get',
         onSuccess : successHandler,
         onFailure: errHandler
       }); 
   }
}

function hideRollOverGlossary()
{
    rollOverGlossaryCanceled = true;
    PopUpBehaviour.hideRollOver();
}

/**
 * @author Ryan Johnson <ryan@livepipe.net>
 * @copyright 2007 LivePipe LLC
 * @package Control.ProgressBar
 * @license MIT
 * @url http://livepipe.net/projects/control_progress_bar/
 * @version 1.0.1
 */

if(typeof(Control) == 'undefined')
	Control = {};
Control.ProgressBar = Class.create();
Object.extend(Control.ProgressBar.prototype,{
	container: false,
	containerWidth: 0,
	progressContainer: false,
	progress: 0,
	executer: false,
	active: false,
	poller: false,
	initialize: function(container,options){
		this.container = $(container);
		this.containerWidth = this.container.getDimensions().width - (parseInt(this.container.getStyle('border-right-width').replace(/px/,'')) + parseInt(this.container.getStyle('border-left-width').replace(/px/,'')));
		this.progressContainer = $(document.createElement('div'));
		this.progressContainer.setStyle({
			width: this.containerWidth + 'px',
			height: '100%',
			position: 'absolute',
			top: '0px',
			right: '0px'
		});
		this.container.appendChild(this.progressContainer);
		this.options = {
			afterChange: Prototype.emptyFunction,
			interval: 0.25,
			step: 1,
			classNames: {
				active: 'progress_bar_active',
				inactive: 'progress_bar_inactive'
			}
		};
		Object.extend(this.options,options || {});
		this.container.addClassName(this.options.classNames.inactive);
		this.active = false;
	},
	setProgress: function(value){
		this.progress = value;
		this.draw();
		if(this.progress >= 100)
			this.reset();
		this.notify('afterChange',this.progress,this.active);
	},
	poll: function(url,interval){
		this.active = true;
		this.poller = new PeriodicalExecuter(function(){
			new Ajax.Request(url,{
				onSuccess: function(request){
					this.setProgress(parseInt(request.responseText));
					if(!this.active)
						this.poller.stop();
				}.bind(this)
			});
		}.bind(this),interval || 3);
	},
	start: function(){
		this.active = true;
		this.container.removeClassName(this.options.classNames.inactive);
		this.container.addClassName(this.options.classNames.active);
		this.executer = new PeriodicalExecuter(this.step.bind(this,this.options.step),this.options.interval);
	},
	stop: function(reset){
		this.active = false;
		if(this.executer)
			this.executer.stop();
		this.container.removeClassName(this.options.classNames.active);
		this.container.addClassName(this.options.classNames.inactive);
		if(typeof(reset) == 'undefined' || reset == true)
			this.reset();
	},
	step: function(amount){
		this.active = true;
		this.setProgress(Math.min(100,this.progress + amount));
	},
	reset: function(){
		this.active = false;
		this.setProgress(0);
	},
	draw: function(){
		this.progressContainer.setStyle({
			width: (this.containerWidth - Math.floor((this.progress / 100) * this.containerWidth)) + 'px'
		});
	},
	notify: function(event_name){
		if(this.options[event_name])
			return [this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))];
	}
});
if(typeof(Object.Event) != 'undefined')
	Object.Event.extend(Control.ProgressBar);
	
  	
//OI SPECIFIC INFO

var PersonBirthDate = Class.create();
PersonBirthDate.prototype = {
  initialize: function(fieldPrefix,today) 
  {
    this.month = callbackForm[fieldPrefix + '.birthMonth'].value;
    this.day = callbackForm[fieldPrefix + '.birthDay'].value;
    this.year = callbackForm[fieldPrefix + '.birthYear'].value;
    this.today = today;
    this.setAge();
  },

  isValid: function() {
    if(isNaN(this.month) || this._isEmpty(this.month))
    {
      return false;
    }
    if((this.month > 12) || (this.month == 0))
    {
      return false;
    }
    if(isNaN(this.day) || this._isEmpty(this.day))
    {
      return false;
    }
    if((this.day > 31) || (this.day == 0))
    {
      return false;
    }    
    if(isNaN(this.year) || this._isEmpty(this.year) || (this.year < 1000))
    {
      return false;
    }      
    return true;
  },
  
  _isEmpty: function(aValue) {
    if(aValue =="")
    {
      return true;
    }
    return false;
  },
  
  getAge: function() {
   return this.calculatedAge;
  },
  
  setAge: function() {
      var birthDate = new Date(this.month + "/" + this.day + "/" + this.year);
      var age = this.today.getFullYear() - birthDate.getFullYear();
      if (birthDate.getMonth()  > this.today.getMonth() ) 
      {
        age = age -1;
      }
      else if ( birthDate.getMonth() == this.today.getMonth() &&
        birthDate.getDate() > this.today.getDate() ) 
      {
          age = age -1;
      }
    this.calculatedAge = age;
  }
}


function setCommand(arg,form,currentButton) {
		form.command.value = arg;
		if(!self.validateThisForm || validateThisForm(form)) {
		    if($('progress_bar'))
		    {
		      if (currentButton)
          {
            disableButton(currentButton);
          }
		      Element.show('progress_holder');
		      var progress_bar = new Control.ProgressBar('progress_bar',{interval: 0.15});
          progress_bar.start();
        }		    
        else if (currentButton)
        {
            disableButton(currentButton);
        }
        
        //if the action is apply then clear out the cookies for the tab interface
        if(arg == "apply")
        {
          Cookie.erase("medicalURL");
          Cookie.erase("DentalURL");      
        }
			  form.submit();
		}
		return false;
}

function disableButton(currentButton)
{
    //if the current button is a link then disable is setting the 
    //onclick to do nothing
    if(currentButton.tagName === "A")
    {
        currentButton.onclick = function() { return false; }
    }
    else
    {
        currentButton.disabled = true;
    }     
}

function submitPrevious(sectionName, form,currentButton){
		if ((sectionName !="Pairs") && (sectionName !="Importance") && (sectionName !="Constraints")) {
    //if ((sectionName !="Importance") && (sectionName !="Constraints")) { 
			  window.history.back();
		}
		else {
			  setCommand('previous',callbackForm,currentButton);
		}
}

function sortPlans(selectedObject,sortKey,sortCommand)
{
  callbackForm.sort.value = sortKey;
  if(sortCommand == null)
  {
    sortCommand = 'sort'
  }
  setCommand(sortCommand,callbackForm);
}
	
function openNewWindow(url) { window.open(url,"","height=400,width=500,resizable=yes,scrollbars=yes,menubar=no,location=no,toolbar=no"); }

function displayErrorMessage(message)
{
  if((message == null) || (message ==""))
  {
    Element.hide('errorMessageArea');
    $('errorMessageArea').innerHTML = "";
  }
  else
  {
    $('errorMessageArea').innerHTML = message;
    Element.show('errorMessageArea');
    window.scrollTo(0,0);
    if(window.parent)
    {
      window.parent.scrollTo(0,0);
    }
  }
}

function showLogin()
{
  var anElement = $('loginPanel'); 
  var t = document.documentElement.clientWidth / 2;
  var x = t + 120;
  var y = 50;
  if(anElement)
  {
    //clear error messages
    displayErrorMessage("");
    anElement.style.top = y +"px";
    anElement.style.left = x +"px"; 
    Element.show('loginPanel');
    Form.focusFirstElement('loginForm');
  }
  else
  {
    displayErrorMessage("Please wait until the page is done loading.");
  }

}

function hideLogin()
{
  Element.hide('loginPanel');
}


function displayGlossary(selectedObject,glossaryKey,path)
{
  var handlerFunc =  function(t)
  {
      PopUpBehaviour.show(selectedObject,t.responseText);
  }
  var errFunc = function(t) {
    alert('Error ' + t.status + ' -- ' + t.statusText);
  }  
  var url = 'sections/';
  if(path != null)
  {
    url = path;
  }
  url += "glossary.jsp?key=" + glossaryKey;
  
  new Ajax.Request(url,{method: 'get',onSuccess:handlerFunc,onFailure:errFunc});
  return false;
}

function numbersonly(myfield, e, dec)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) || 
    (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;

// decimal point jump
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}

//add the ability to auto tab
function autotab_series()
{	
  var strung_fields=$$('div.autotab_series');
	for(var i=0;i<strung_fields.length;i++)
	{
  	var inputs=strung_fields[i].getElementsByTagName('input');
		for (var n=0;n<inputs.length;n++)
		{	
      Event.observe(inputs[n],'keyup',function(event)
			{	
        var elm=Event.element(event);
        if(event.keyCode!=16 && event.keyCode!=9)
				{
        	if($F(elm).length==elm.maxLength)
					{	
            if(elm.nextSiblings().length)
						{
            	elm.nextSiblings()[0].focus();
            }
          }
        }
      });
    }
  }
}

function doProductChange(rowId,changer)
{
    var productCacheKey = $F("productCacheKey");
    var productLine = $F("productLine");
    var familyName = $F("familyName_" + rowId);
	  var jsonString =  $F("primaryAttributeMatrixJSON_" + rowId);
    window.status = "Processing product change.....";
    var successFunc =  function(t)
    {
      window.status = "Product change started.";
      var productInfo = eval('(' + t.responseText + ')');
      var familyInfo = eval('(' + jsonString + ')');
     // get row id 
      if(productInfo != null)
      {
      	//determine what the changer was if deductible find the item in the list 
      		//and build the hashmap from the value;
      		var familyHash = null;
      		if (changer == familyInfo.primaryAttributeFieldPrefix) {
               	var anOption = familyInfo.primaryAttributeMap.find( function(s) {			 
       			 var theSelectedValue = $F(changer+"Select_" +rowId);
       			 var aVal = eval('s.'+changer);
      				return (aVal == theSelectedValue);
      			});
      			familyHash = $H(anOption); 
      		}
      		
          //update the product id row
  		    $('recommendedProductForm['+productInfo.rowId+'].productId').value = productInfo.productId;
  		    $('planName_'+productInfo.rowId).value = productInfo.planName;  		    
  		
      		// change product attribute values
          //loop through all the member variables on the productInfo object and update
          //the web page with those objects. To do this we must convert the object to a
          //hash map. Thanks to prototype magic hash create this is a piece of cake    
          var productInfoHash = $H(productInfo);
          productInfoHash.each(function(item) {

            var cellKey = item.key + "Cell_" + productInfo.rowId;
            var fieldName = item.key + "Select_" + productInfo.rowId;
            //if there is a field in the cell don't update it at least not yet
            var aField = $(fieldName);
            var prodAttrElement = $(cellKey);
            if(aField == null)
            {
              if(prodAttrElement)
              {
              	prodAttrElement.innerHTML = item.value;
              }
            }
            else if((item.key != familyInfo.primaryAttributeFieldPrefix) && (item.key != changer))
            {
                //if the change has a list  of options then match it up
                var choices = (familyHash == null?null:familyHash.get(item.key));
                if((aField.type == "select-one") || (choices && (choices.size() > 1) && prodAttrElement))
                {
                	// build the drop down based on the product info and the options from the family
        				  buildSelectField(item.key, choices,
        						item.value, productInfo.rowId,(changer == familyInfo.primaryAttributeFieldPrefix),
                                "doProductChange"); 						
                }
	            else if(!prodAttrElement && aField.type == "hidden")
	            {
	              	aField.value = item.value;
	            }
	            else
	            {
	                //build the hidden form field
	        		var data = "<input id=\"" + fieldName	+ "\" type=\"hidden\" name=\"";
	        		data += fieldName + "\" value=\""
	        					+ item.value + "\"/>"
	        					+ item.value;
	        		prodAttrElement.innerHTML = data;          
	              }
            	}
          });  
                                     
          if(scoringAvailable)
          {
            buildScoreTable("planFit_" + productInfo.rowId,productInfo.score);
          }
          
         // update product selection value for submittal (to 'apply' for plan)
            buildSelectButtons(productInfo.conversionCode,productInfo.rowId,productInfo.productId); 
            
         //if there is already a message in the error area clear it out by sending null
          displayErrorMessage(null);
      }
     
      else
      {
          displayErrorMessage(statusInfo.message);
      }
      window.status = "Product change completed.";
    }
    
    var errFunc = function(t) {
      alert('Error ' + t.status + ' -- ' + t.statusText);
    }  

   	var url = "sections/coc/getNewProductAttributeValues.jsp?productCacheKey="
		+ productCacheKey + "&familyName=" + encodeURIComponent(familyName) + "&rowId=" + rowId
		+ "&productLine=" + productLine + "&changer=" + changer;
		 //build a dynamic list of query parameters based on field names
		var fieldNames = $F("fieldNames_" + rowId);
		fieldNames.split(",").each(function(item,index){
		   var fieldName = item + "Select_"+ rowId;
		   var aField = $(fieldName);
		   if(aField)
		   {
          url += "&" +item +"=" + encodeURIComponent($F(fieldName));
       }
    });
    new Ajax.Request(url,{onSuccess:successFunc,onFailure:errFunc});
    return false;    	 
}
	
  	
// controller for doing product changes on the compare page
function doComparePageProductChange(colId,changer)
{
  	var productCacheKey = $F("productCacheKey");
  	var productLine = $F("productLine");
  	var familyName = $F("familyName_" + colId);
  	var jsonString = $F("primaryAttributeMatrixJSON_" + colId);
  
  	// -------------------------------------------------------//
  	window.status = "Processing product change.....";
  	var successFunc = function(t) {
  		window.status = "Product change started.";
  		// get server data
  		var productInfo = eval('(' + t.responseText + ')');
  		var familyInfo = eval('(' + jsonString + ')');
  		//determine what the changer was if deductible find the item in the list 
  		//and build the hashmap from the value;
  		var familyHash = null;
  		if (changer == familyInfo.primaryAttributeFieldPrefix) {
           	var anOption = familyInfo.primaryAttributeMap.find( function(s) {			 
   			 theSelectedValue = $F(changer+"Select_" +colId);
   			 var aVal = eval('s.'+changer);
  				return (aVal == theSelectedValue);
  			});
  			familyHash = $H(anOption); 
  		}
  		//update the product id row
  		$('productId_'+productInfo.rowId).value = productInfo.productId;
  		$('planName_'+productInfo.rowId).value = productInfo.planName;
  		// change product attribute values
      //loop through all the member variables on the productInfo object and update
      //the web page with those objects. To do this we must convert the object to a
      //hash map. Thanks to prototype magic hash create this is a piece of cake    
      var productInfoHash = $H(productInfo);
      productInfoHash.each(function(item) {
        var cellKey = item.key + "Cell_" + productInfo.rowId;
        var fieldName = item.key + "Select_" + productInfo.rowId;    
        //if there is a field in the cell don't update it at least not yet
        var aField = $(fieldName);
        var prodAttrElement = $(cellKey);
        if(aField == null)
        {
          if(item.key == "pdfAppLink")
          {                   
                //we need to account for the fixedRate period and redrawn the get pdf button  
                var isFixedRate = false;
                var premiumPeriod = $("premiumPeriodSelect_" + productInfo.rowId);
                if(premiumPeriod)
                {
                    var premiumPeriodVal = $F("premiumPeriodSelect_" + productInfo.rowId);
                    if(premiumPeriodVal.toLowerCase() != "standard")
                    {
                        isFixedRate = true;
                    }
                }         
                if(isFixedRate)
                {
                    $(cellKey).innerHTML = $('fixedRateLinkInfo').innerHTML;
                }
                else
                {
                    var cellData = $('standardLinkInfo').innerHTML;
                    if(item.value.toLowerCase().indexOf("state specific") > -1)
          		    {
                        cellData+="<a target='_pdf' onclick=\"trackEvent('Tools Used','Get Application PDF','"+productInfo.planName+"');\" href='" + $('stateSpecificPDFLink').innerText + "'><img src='images/btn-getpdf.gif' alt='Get Application PDF'/></a>";
                    }
                    else
                    {
                        cellData+="<a target='_pdf' onclick=\"trackEvent('Tools Used','Get Application PDF','"+productInfo.planName+"');\" href='" + item.value + "'><img src='images/btn-getpdf.gif' alt='Get Application PDF'/></a>"
                    }
                    $(cellKey).innerHTML = cellData;
                }
          }
          else if (prodAttrElement)
          {
            prodAttrElement.innerHTML = item.value;
          }	
        }
        else if((item.key != familyInfo.primaryAttributeFieldPrefix) && (item.key != changer))
        {
          //if the change has a list  of options then match it up
          var choices = (familyHash == null?null:familyHash.get(item.key));
          if((aField.type == "select-one") || (choices && (choices.size() > 1)))
          {
          	// build the drop down based on the product info and the options from the family
  				  buildSelectField(item.key, choices,
  						item.value, productInfo.rowId,(changer == familyInfo.primaryAttributeFieldPrefix),
                          "doComparePageProductChange"); 						
          }
          else
          {
            //build the hidden form field
    				var data = "<input id=\"" + fieldName	+ "\" type=\"hidden\" name=\"";
    				data += fieldName + "\" value=\""
    						+ item.value + "\"/>"
    						+ item.value;
    				prodAttrElement.innerHTML = data;          
          }
        }
      });  
  
      //update scoring information
  		if (scoringAvailable) {
  
  			buildComparePageScoreTable("planFit_" + productInfo.rowId,
  					productInfo.score, "isScore");
  			buildComparePagePrefScores(productInfo);
  		}
  
      //if select button is available then update it
      prodAttrElement = $('SelectButtonTop_'+productInfo.rowId);
      if(prodAttrElement)
  		{
  		  buildComparePageSelectButtons(productInfo.conversionCode,
  				productInfo.rowId, productInfo.productId);
  		}
  
  		// change product's BenefitHighlights
  		prodAttrElement = $("benefitHighlightsCell_"+ productInfo.rowId); // in this function, rowId is the colId
  		if(prodAttrElement)
  		{
    		var images = " ";
    		if (productInfo.productBenefitHighlights) {
    			for ( var j = 0; j < productInfo.productBenefitHighlights.length; j++) {
    				images = images + "<a href='#' onclick='displayGlossary(this,\""
                + productInfo.productBenefitHighlights[j]
                + "\");return false;'><img src='images/icon_"
    						+ productInfo.productBenefitHighlights[j]
    						+ ".gif' alt='"
    						+ productInfo.productBenefitHighlights[j] + "'></a><br />";
    						//add account contribution value
    						if(productInfo.productBenefitHighlights[j]=="accountcontrib")
    						{
    						  anAttrib = productInfo.productDetailElements.find(function(s){return s.attribKey == "Account_Contribution";});
    						  if(anAttrib)
    						  {
    						    images+= anAttrib.attribValue+"<br />";
    						  }
                }
    			}
    		}  		
        prodAttrElement.innerHTML = images;
      }
  		
  		// change product detail
  		if (productInfo.productDetailElements) {
  			for ( var i = 0; i < productInfo.productDetailElements.length; i++) {
  				if (productInfo.productDetailElements[i]) {
  					var detailRowId = "detailCol_" + productInfo.rowId + "_"
  							+ productInfo.productDetailElements[i].attribKey;
  					var detailRow = $(detailRowId);
  					if (detailRow) {
  						if(productInfo.productDetailElements[i].attribKey == "Link")
  						{
  							detailRow.innerHTML = "<a target='_pdf' class='pdfLink' onclick=\"trackEvent('Tools Used','Get Application PDF','"+productInfo.planName+"');\" href='" + productInfo.productDetailElements[i].attribValue +"'>Get Application PDF</a>";
  						}
  						else
  						{
  							detailRow.innerHTML = productInfo.productDetailElements[i].attribValue;	
  						}								
  					} else {
  						window.status = "Failed to find attribute="
  								+ detailRowId;
  					}
  				}
  			}
  		}
  
  		// if there is already a message in the error area clear it out by
  		// sending null
  		displayErrorMessage(null);
  		window.status = "Product change completed.";
  	}
  
  	var errFunc = function(t) {
  		alert('Error ' + t.status + ' -- ' + t.statusText);
  	}
  
  	var url = "sections/coc/getNewProductAttributeValues.jsp?productCacheKey="
  			+ productCacheKey + "&familyName=" + encodeURIComponent(familyName) + "&rowId=" + colId
  			+ "&productLine=" + productLine + "&changer=" + changer;
  			 //build a dynamic list of query parameters based on field names that are select boxes
  			var fieldNames = $F("fieldNames_" + colId);
  			fieldNames.split(",").each(function(item,index){
  			   var fieldName = item + "Select_"+ colId;
  			   var aField = $(fieldName);
  			   if(aField)
  			   {
              url += "&" +item +"=" + encodeURIComponent($F(fieldName));
           }
        });
  
  	new Ajax.Request(url, {
  		onSuccess :successFunc,
  		onFailure :errFunc
  	});
  	return false;
}		
  
  // build the scoreTable when we switch products
  function buildComparePageScoreTable(tableId, score, scoreStyle)
  {
    var scoreResult = score * 0.8;
    var scoreReverseResult = (100 - score) * 0.8;
    data = '<table cellpadding="0" cellspacing="0" border="0" align="left">';
    data +='<tr><td class="'+ scoreStyle +'" style="width:'+ scoreResult +'&nbsp;px"><img src="images/clear.gif" height="10" width="'+scoreResult+'"></td>';
		if(score != 100)
    {
      data += '<td class="isScoreEmpty" style="width:' +scoreReverseResult+'&nbsp;px">';
      data += '<img src="images/clear.gif" height="10" width="'+ scoreReverseResult +'"></td>';
    }
		data +='</tr></table>&nbsp;' + score + "%";              
    $(tableId).innerHTML = data;
  }
  
  //build the select or apply buttons based on conversion codes
  function buildComparePageSelectButtons(coversionCode,rowId,productId)
  {
    var buttonData = "";
    var cocData = "";
    if(coversionCode == "")
    {
      buttonData ='<input type="image" src="images/btn2-apply.gif" onclick="callbackForm.selectedId.value=\''+productId;
      buttonData +='\';trackApply('+rowId+');setCommand(\'apply\',callbackForm);" alt="Apply" name="Apply"/>';
    }    
    else if(coversionCode == "CC")
    {
      cocData ='<img src="images/coc_icon_under.gif" alt="Underwriting required; you will be notified of status.">Underwriting required; you will be notified of status.';
      buttonData ='<input type="image" src="images/btn2-apply.gif" onclick="callbackForm.selectedId.value=\''+productId;
      buttonData +='\';trackApply('+rowId+');setCommand(\'apply\',callbackForm);" alt="Apply" name="Apply"/>';
    }
    else
    {
      cocData ='<img src="images/coc_icon_nounder.gif" alt="No underwriting needed">No underwriting needed.';
      buttonData ='<input type="image" src="images/btn2-select.gif" onclick="callbackForm.selectedId.value=\''+productId;
      buttonData +='\';trackApply('+rowId+');setCommand(\'apply\',callbackForm);" alt="Select" name="Select"/>';    
    }  
    $('SelectButtonTop_'+rowId).innerHTML = buttonData;
    if($('COCIcon_'+rowId))
    {
      $('COCIcon_'+rowId).innerHTML = cocData;  
    }   			    
    // keep productId id value current for print functionality
    $('productId_' + rowId).value = productId;	// in this function, rowId is the colId
  }
  
  //given a product generate the preference scores
  function buildComparePagePrefScores(productInfo)
  {
    for (var i=0; i < productInfo.productDetailElements.length; i++) 
    {
       if(productInfo.productDetailElements[i])
       {  
          if(fitAttributes.include(productInfo.productDetailElements[i].attribKey))
          {
            buildComparePageScoreTable("detailFit_" + productInfo.productDetailElements[i].attribKey + "_" + productInfo.rowId, productInfo.productDetailElements[i].attribScore, "isScoreAlt");
          }
       }    	  																							
    }      
  }
  
  //show product details on the compare page
  function showComparePageDetails(numAttribs)
  {
	  //use the css class method for hiding and showing tables
      Element.toggle('detailRowHeader');
      numAttribs.times(function(n) {
        tname = 'detailRow_' + n;
        Element.toggle(tname);  
      });     
      
      // toggle button image 
      var btn_gif = document.getElementById("details_btn").src;
      var btn_top_gif = document.getElementById("details_btn_top").src;
       
      if ((btn_gif.search("hidedetails") != -1) || (btn_top_gif.search("hidedetails") != -1)) 
      {
         var legacy_gif =((btn_gif.indexOf("btn3") == -1) && (btn_gif.indexOf("senior") > -1))?"images/btn-showdetails-senior.gif":"images/btn-showdetails.gif";
       	 btn_gif = (btn_gif.indexOf("btn3") > -1)?"images/btn3-showdetails.gif":legacy_gif;
      }
      else
      {
        var legacy_gif =((btn_gif.indexOf("btn3") == -1) && (btn_gif.indexOf("senior") > -1))?"images/btn-hidedetails-senior.gif":"images/btn-hidedetails.gif";
      	 btn_gif = (btn_gif.indexOf("btn3") > -1)?"images/btn3-hidedetails.gif":legacy_gif;
      }
      document.getElementById("details_btn_top").src = btn_gif;
      document.getElementById("details_btn").src = btn_gif;
	  if ($('detailRowNotice')) {
			Element.toggle('detailRowNotice'); }
      Element.toggle("topShowDetailsInfo");
      Element.toggle("bottomShowDetailsInfo");
  }
		
  //given a select field name find it and repopulate with the passed in choices
  function buildSelectField(fieldPrefix,choices,defaultVal,rowId,primaryAttribSelected,changeListenerName)
  {
     var fieldId = fieldPrefix +'Select_' + rowId;
     var theField = $(fieldId);
     //if choices has more than one element then continue else
     //just select the item in the list
     //but if the field that caused the change is the primary attribute
     //then rebuild the list because we should only have right values 
     if(((choices == null) || (choices.size() == 1)) && (!primaryAttribSelected))
     {
        if((theField) && (theField.options))
        {
          for(var i = 0; i < theField.options.length; i++)
          {
            if(theField.options[i].value == defaultVal)
            {
              theField.options[i].selected = true;
            }
          }
        }
        return;
     }
     
     if((theField) && (theField.options))
     {
       theField.options.length = 0;
       choices.each(function(s) {
        var opt = document.createElement('OPTION');
        opt.value = s;
        opt.text = s;
        if(defaultVal == s)
        {
          opt.selected = true;
        }
        theField.options.add(opt);       
       });
     }
     else if (theField)
     {
        buildHTMLSelectField(fieldPrefix,choices,defaultVal,rowId,changeListenerName);                  
     }
  }
  
  function buildHTMLSelectField(fieldPrefix,choices,defaultVal,rowId,changeListenerName)
  {
    var fieldId = fieldPrefix +'Select_' + rowId;
    var theField = $(fieldId);
    if (theField)
    {       
       //find the parent and update
       aParent = theField.parentNode;
       if(aParent)
       {
         var data = "<select name=\"" + fieldId +"\" id=\""+fieldId + "\" onchange=\""+changeListenerName+"("+rowId+",'" + fieldPrefix+"')\" onkeyup=\""+changeListenerName+"("+rowId+",'"+fieldPrefix+"')\">";
         choices.each(function(s) {
          
          var opt = "<option value=\""+s+"\"";
          if(defaultVal == s)
          {
            opt+=" selected";
          }  
          opt+=">"+s +"</option>";
          data+= opt;
         });  
         data+="</select>"
         aParent.innerHTML = data;
       }            
    }
  }
  

  //build the scoreTable  when we switch products
  function buildScoreTable(tableId, score,multiplier)
  {
    var scoreResult = score;
    var scoreReverseResult = (100 - score);
    if(multiplier)
    {
        scoreResult = scoreResult * multiplier;
        scoreReverseResult = scoreReverseResult * multiplier;
    }
    data = '<table style="width:75px" cellpadding="0" cellspacing="0" border="0" align="left">';
    data +='<tr><td class="isScore" style="width:'+ scoreResult +' px"><img src="images/clear.gif" height="10" width="'+scoreResult+'"></td>';
		if(score != 100)
    {
      data += '<td class="isScoreEmpty" style="width:' +scoreReverseResult+' px">';
      data += '<img src="images/clear.gif" height="10" width="'+ scoreReverseResult +'"></td>';
    }
		data +='</tr></table>' + score + "%";              
    $(tableId).innerHTML = data;
  }
  
  	
 
  //build the select or apply buttons based on conversion codes  
  function buildSelectButtons(coversionCode,rowId,productId)
  {
    aSelectButtonCell = $('SelectButtonTop_'+rowId);
    if((aSelectButtonCell) && (aSelectButtonCell.innerHTML != ""))
    {
      window.status = "generating apply button";
      var topData = '<input type="hidden" id="recommendedProductForm['+rowId+'].productId" name="recommendedProductForm['+rowId+'].productId" value="'+productId+'">';
      if(coversionCode == "")
      {
        topData +='<input type="image" class="noPrint" src="images/btn2-apply.gif" onclick="callbackForm.selectedId.value=\''+productId;
        topData +='\';trackApply('+rowId+');setCommand(\'apply\',callbackForm);" alt="Apply" name="Apply"/><br />';     
      }    
      else if(coversionCode == "CC")
      {
        topData +='<input type="image" class="noPrint" src="images/btn2-apply.gif" onclick="callbackForm.selectedId.value=\''+productId;
        topData +='\';trackApply('+rowId+');setCommand(\'apply\',callbackForm);" alt="Apply" name="Apply"/><br />';
        topData +='<img src="images/coc_icon_under.gif" alt="Underwriting required; you will be notified of status.">Underwriting required; you will be notified of status.';      
      }
      else
      {
        topData +='<input type="image" class="noPrint" src="images/btn2-select.gif" onclick="callbackForm.selectedId.value=\''+productId;
        topData +='\';trackApply('+rowId+');setCommand(\'apply\',callbackForm);" alt="Select" name="Select"/><br />';    
        topData +='<img src="images/coc_icon_nounder.gif" alt="No underwriting needed">No underwriting needed.';      
      }
      aSelectButtonCell.innerHTML = topData;  
    }    				
  }   
    	
  //show the details of the selected plan family
  function showPrintListDetails(rowId)
  {
    selectedId = $F('recommendedProductForm['+rowId+'].productId');
    callbackForm.selectedId.value = selectedId;
    setCommand('details-family',callbackForm);
  }   


function showEmailPlansDialog(selectedObject,currentFormName,planLayout)
{  
  $('emailRequestForm.formNameOfCurrentPlans').value = currentFormName;
  $('emailRequestForm.productLine').value = $F('productLine');
  if(planLayout)
  {
    $('emailRequestForm.layoutType').value = planLayout;
  }
  Element.show('popupDivEmailPlans');   
  Element.show('emailPanel');
}

function closeEmailPlansDialog()
{  
  Element.hide('emailPanel');
  $('emailErrorMessageArea').innerHTML = "";
  Element.hide('emailErrorMessageArea');   
}

function validateEmailRequestForm()
{
  var success = true;
  var emailPattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
  if(!emailPattern.test($F('emailRequestForm.mailTo')))
  {
    $('emailErrorMessageArea').innerHTML = "Please enter a valid email address for the To field.";
    Element.show('emailErrorMessageArea');
    $('emailRequestForm.mailTo').focus();
    success = false;
  } 
  else if(!emailPattern.test($F('emailRequestForm.mailFrom')))
  {
    $('emailErrorMessageArea').innerHTML = "Please enter a valid email address for the From field.";
    Element.show('emailErrorMessageArea');    
    $('emailRequestForm.mailFrom').focus();
    success = false;
  } 
  else if($F('emailRequestForm.mailSubject') =="")
  {
    $('emailErrorMessageArea').innerHTML = "Please enter the subject for this email.";
    Element.show('emailErrorMessageArea');
    $('emailRequestForm.mailSubject').focus();
    success = false;
  }  

  return success;
}

function submitEmailRequest()
{
  //do validation
  if(!validateEmailRequestForm())
  {
    return false;
  }
  else
  {
    var planType = ($F('emailRequestForm.layoutType') == 'list')? "Email Plan List":"Email Plan Compare";
    trackEvent('Tools Used','Completed',planType);
  }
  
	var errHandler = function(t) {
	 window.status = 'Error ' + t.status + ' -- ' + t.statusText;
  }
  	
	var successHandler = function(t) {
	 window.status = t.responseText;
  }  	
  
	var url = "tiles/emailPlanProcessor.jsp?"
			+ Form.serialize($('emailRequestForm'));
			 //build a dynamic list of query parameters based on field names that are select boxes       
	var productFields = Form.getInputs($F('emailRequestForm.formNameOfCurrentPlans'),'hidden');
	if(productFields)
	{
	  var productIds =[];
    productFields.each(function(item){
        if(item.name.indexOf("productId") > -1)
        {
          productIds.push(item.value);
        }
    });
    url+="&productIds="+productIds.join(",");
  }
        
  // submit the form using Ajax
   new Ajax.Request(url, {
     onSuccess : successHandler,
     onFailure: errHandler
   }); 
   
   $('emailErrorMessageArea').innerHTML = "Email sent.";
   Element.show('emailErrorMessageArea');
   Element.hide('popupDivEmailPlans');   
}

/************************************
 *   Click To Call functions START  *
 ************************************/
function showClickToCall()
{
  var anElement = $('callPanel'); 
  if(anElement)
  {
    //clear error messages
    displayErrorMessage("");        
    $('callPanel').innerHTML ="Loading...."; 
    Element.show('callPanel');
    var handlerFunc = function(t)
    {
        $('callPanel').innerHTML = t.responseText;
        Form.focusFirstElement('callRequestForm');
        //get the product cache key from the parent form 
        //and stick it on the callDIalog form
        var productCacheKey = $('productCacheKey');
        if(productCacheKey)
        {
            $('callRequestForm.productCacheKey').value = productCacheKey.value;
        }
    }    
	var errHandler = function(t) {
	 $('callPanel').innerHTML = 'Error ' + t.status + ' -- ' + t.statusText;
    }    
    var url = "tiles/callDialog.jsp?fullHTMLText=false";
    new Ajax.Request(url, {onSuccess: handlerFunc, onFailure: errHandler});
  }
  else
  {
    displayErrorMessage("Please wait until the page is done loading.");
  }

}

function hideClickToCall()
{
  var anElement = $('callPanel'); 
  //if the panel is available then hide it otherwise close the window because it
  //was called using old school popup box.
  if(anElement)
  {
    Element.hide(anElement);
    anElement.innerHTML = "";
  }
  else
  {
    self.close();
  }  
}



function validateCallForm(){
  var success = true;
  var emailPattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
  if(!/^[2-9]\d{2}$/.test($F('callRequestForm.1')))
  {
    $('callErrorMessageArea').innerHTML = "Please enter the Area Code.";
    Element.show('callErrorMessageArea');
    $('callRequestForm.1').focus();
    success = false;
  } 
  else if(!/\d{3}-\d{4}$/.test($F('callRequestForm.2')))
  {
    $('callErrorMessageArea').innerHTML = "Please enter the Phone Number (###-####).";
    Element.show('callErrorMessageArea');
    $('callRequestForm.2').focus();
    success = false;
  }   
  else if(($F('callRequestForm.3') !="") && !emailPattern.test($F('callRequestForm.3')))
  {
    $('callErrorMessageArea').innerHTML = "Please enter a valid Email Address.";
    Element.show('callErrorMessageArea');
    $('callRequestForm.3').focus();
    success = false;
  } 

  else if($F('callRequestForm.4') =="")
  {
    $('callErrorMessageArea').innerHTML = "Please enter the First Name.";
    Element.show('callErrorMessageArea');
    $('callRequestForm.4').focus();
    success = false;
  }
  else if($F('callRequestForm.5') =="")
  {
    $('callErrorMessageArea').innerHTML = "Please enter the Last Name.";
    Element.show('callErrorMessageArea');
    $('callRequestForm.5').focus();
    success = false;
  }   
  else if($('callRequestForm.7').checked)
  {
    //if the users selected time slots is chosen then validate
    //that the user seelected a time
    if($F('callRequestForm.8') =="")
    {
        $('callErrorMessageArea').innerHTML = "Please enter the Day.";
        Element.show('callErrorMessageArea');
        $('callRequestForm.8').focus();
        success = false;
    }
    else if($F('callRequestForm.9') =="")
    {
        $('callErrorMessageArea').innerHTML = "Please enter the Time of Day.";
        Element.show('callErrorMessageArea');
        $('callRequestForm.9').focus();
        success = false;    
    }
  }  
	return success;
}

function submitCallRequest(){
	if(!validateCallForm()){
		return false;
	}
  else
  {
    trackEvent('Tools Used','CallMe','Completed');
  }	
	var errHandler = function(t) {
		window.status = 'Error ' + t.status + ' -- ' + t.statusText;
	}
	var successHandler = function(t) {
		window.status = t.responseText;
	}  	
	var url = getContextPath() + "/tiles/callProcessor.jsp?"
		+ Form.serialize($('callRequestForm'));
   // submit the form using Ajax
   new Ajax.Request(url, {
     onSuccess : successHandler,
     onFailure: errHandler
   }); 
   
	$('callErrorMessageArea').innerHTML = "<img src='/roi/images/hdr-thankyoucall.gif'/><br /><br /><a href='#' class='button btnPad btn2Close' onclick='hideClickToCall();return false;'><span>Close</span><img src='/roi/images/spacer.gif' alt='Close' /></a>";
	Element.show('callErrorMessageArea');
	Element.hide('popupDivCallPlans');
}

function disableCallFields(aRadioObj)
{
    if((aRadioObj.checked) && (aRadioObj.value == "Now"))
    {
        //clear the other values
        //gray the background
        $('callRequestForm.8').value ="";
        $('callRequestForm.9').value ="";
    }
    else
    {
        //clear the other values
        //gray the background        
    }
    
}
/************************************
*   Click To Call functions END  *
************************************/


function printPlan(isAgentLogin)
{
// capture current product ids
    var prod_ids = '';
    var productFields = Form.getInputs('RecommendationPutListForm','hidden');
    if(productFields)
    {
     var productIds =[];
    productFields.each(function(item){
      if(item.name.indexOf("productId") > -1)
      {
        productIds.push(item.value);
      }
    });
    prod_ids="&productIds="+productIds.join(",");
    }
    theURL='getCCRecommendationsForPrint.do?productLineId='+ $F('productLineId') +
        '&printerFriendlyEnabledTopFiveShown=true&productLine='+$F('productLine') +	prod_ids;
	if((isAgentLogin != null) && (isAgentLogin =="true"))
	{
		printerTitle = getPrinterTitle();
		if((printerTitle != null) && (printerTitle.length != 0))
		{
			theURL +="&printerTitle=" + printerTitle;
		}
    }        	
    tempWin = window.open(theURL,"PrintList","toolbar=no,scrollbars=yes,width=850,height=600,resizable=yes");
    tempWin.focus();
}

function getPrinterTitle()
{
	//for agent prompt for an input box to capture the page title;
	var printerTitle="";
	printerTitle = window.prompt("Please enter the text you would like to appear at the top of your quote." +
	"\n(Note: basic html commands are also recognized)","");
	return printerTitle;
}	

  //function to help control the medical tab when the user is clicking around
  function openPrimaryTab(productName)
  {
    aURL =Cookie.get(productName+"URL");
    if(aURL == null)
    {
        aURL = 'productLineRedirector.do?productLine='+productName;
    }
    window.location = aURL;
  }   
  
  function openAuxillaryTab(productName)
  {
    aURL =Cookie.get(productName+"URL"); 
    if(aURL == null)
    {
      aURL = 'getSideBySideRecommendations.do?productLine='+productName+'&medicalProductLineId='+$F('productLineId');
    }
    window.location = aURL;
  }   

function getContextPath()
{
    var pathname = location.pathname;
    return pathname.substring(0,pathname.indexOf("/",1));
}
//iniitalize the tracking technology
function initializeTracking()
{
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
}
function trackVariable(index,name,value,scope)
{
    try
    {
        doDebug(index + " " + name + " " + value+" "+scope);
        pageTracker = getTracker();
        if(scope)
        {
            pageTracker._setCustomVar(index, name, value,scope);
        }
        else
        {
            pageTracker._setCustomVar(index, name, value);
        }
    }
    catch(err){doDebug(err.message);}
}
//wrapper for tracking events. Delegates the call to the GATC
function trackEvent(category,action,label,value)
{
    try
    {
        doDebug(category + " " + action + " " + label);
        pageTracker = getTracker();
        if(label && value)
        {
            pageTracker._trackEvent(category, action, label, value);
        }
        else if(label)
        {
            pageTracker._trackEvent(category, action, label);
        }        
        else
        {
            pageTracker._trackEvent(category, action);
        }
    }catch(err) {doDebug(err.message);}
}

function trackTransaction(orderId,total,brand,state,cartItems)
{
    try{
      pageTracker = getTracker();
      pageTracker._addTrans(
          orderId, // order ID - required
          brand, // affiliation or store name
          total, // total - required
          "", // tax
          "", // shipping
          "", // city
          state, // state or province
          "USA" // country
        );         
       // add item might be called for every item in the shopping cart
       // where your ecommerce engine loops through each item in the cart and
       // prints out _addItem for each
       cartItems.each(function(s)
       { 
            doDebug(s);
           pageTracker._addItem(
              orderId, // order ID - necessary to associate item with transaction
              s[0], // SKU/code - required
              encodeURIComponent(s[1]), // product name
              s[2], // category or variation
              s[3], // unit price - required
              "1" // quantity - required
           );
       });
    
       pageTracker._trackTrans(); //submits transaction to the Analytics servers
    } catch(err) {doDebug("trackTransaction.."+err.message);}
}
//function to track the cart apply
function trackCartApply()
{
    try
    {
        //find the cross refrerence id of the product and then 
        //trak the id
        var orderId = $F('caseInfoId');
        var brand = $F('brand');
        var state = $F('state');
        var total = $('shoppingcart_totalpremium').innerHTML.strip().substr(1);
        var items = [];
        var cartRows = countCartItems();
        if(cartRows > 0)
        {
            for(var i=0; i < cartRows;i++)
            {
                cartItem = [];
                cartItem.push($('shoppingcart_row_id_'+i).innerHTML);
                cartItem.push($('shoppingcart_row_name_'+i).innerHTML);
                cartItem.push($('shoppingcart_row_type_'+i).innerHTML);
                cartItem.push($('shoppingcart_row_premium_'+i).innerHTML.strip().substr(1));
                items.push(cartItem);
            }
        }         
        doDebug('orderId' + orderId + brand+state+total+items);
        trackTransaction(orderId,total,brand,state,items);
    }
    catch(err)
    {doDebug("trackCartApply.."+err.message);}
}

//function to track the event of clicking apply
function trackApply(productRowId)
{
    try
    {
        //find the cross refrerence id of the product and then 
        //trak the id
        var orderId = $F('caseInfoId');
        var brand = $F('brand');
        var state = $F('state');
        var total = $('premiumCell_'+productRowId).innerText.strip().substr(1);
        var items = [[$F('productId_'+productRowId),$F('planName_'+productRowId),$F('productLine'),total]];
        
        doDebug('orderId' + orderId + brand+state+total+items);
        trackTransaction(orderId,total,brand,state,items);      
    }
    catch(err)
    {doDebug("trackApply.."+err.message);}
}

//function to track the event of clicking apply
function trackPDFApply(productRowId)
{
    try
    {
        //find the cross refrerence id of the product and then 
        //trak the id
        doDebug('PDF Apply' + $F('productLine')+ $F('planName_'+productRowId));
        trackEvent('PDF Apply', $F('productLine'),$F('planName_'+productRowId));
    }
    catch(err)
    {doDebug(err.message);}
}
//function to track the page 
function trackPage(pageId,varText)
{
    try
    {
        pageTracker = getTracker();
        if(pageId && varText)
        {
            pageTracker._setVar(varText);        
            pageTracker._trackPageview(pageId);
        }
        else if(pageId)
        {   
            pageTracker._trackPageview(pageId);
        }        
        else
        {
            pageTracker._trackPageview();
        }
    }
    catch(err)
    {doDebug("trackPage.."+err.message);}
}
function getTracker()
{
    if(pageTracker == null)
    {
        pageTracker = _gat._getTracker(gTrackingId);
    }
    return pageTracker;
}
//print alert message
function doDebug(message)
{
    if(oIDebugMode)
    {
        alert(message);
    }
}

// toNumber by Greg Burghardt - Converts a string to a number 
/* @param   string (req)   String to convert to a number
 * @param   bool   (opt)   Make it an integer and drop decimal
 * @param   bool   (opt)   Round number up or down to nearest int
 */
function toNumber(str, isInteger, roundNum) {
  var num;
  var strType = typeof(str);
  if (strType == "string") {
    num = Number(str.replace(/[^0-9-.]/g, ""));
  } else if (strType != "number") { return NaN; }
  if (isNaN(num)) {
    return NaN;
  } else if (isInteger) { return Math.floor(num);
  } else if (roundNum) { return Math.round(num);
  } else { return num; }
}