image1 = new Image();
image1.src = "images/button_blue_26.gif";

image2 = new Image();
image2.src = "images/button_blue_right26.gif";

image3 = new Image();
image3.src = "images/button_blue_30.gif";

image4 = new Image();
image4.src = "images/button_blue_right30.gif";
var theClickedButton = null;

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
  
  // --- private methods ---
 
  // 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 ="<div id='popupDivClose'>close</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 + 20;
    var closeHandlerFunc = function(t)
    {
      PopUpBehaviour.hide(t);
    }
    Event.observe('popupDivClose', "click", closeHandlerFunc);
    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


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 MINIMUM_AGE=64.5;
var IDEAL_AGE=65;
var popUpWin=0;
function popUpWindow(theObject,URLStr,width, height)
{
  var w = 480, h = 340;
  if (document.all) {
     /* the following is only available after onLoad */
     w = document.body.clientWidth;
     h = document.body.clientHeight;
  }
  else if (document.layers) {
     w = window.innerWidth;
     h = window.innerHeight;
  }
  var left = (w-width)/2, top = (h-height)/2;
  var leftprop = 200;
  var topprop = 200;
  if(popUpWin)
  {
    if(!popUpWin.closed) popUpWin.close();
  }
  popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width='+width+',height='+height+',left='+leftprop+', top='+topprop+',screenX='+leftprop+',screenY='+topprop+'');
  return false;
}

function displayGlossary(selectedObject, url)
{
  var handlerFunc =  function(t)
  {
      PopUpBehaviour.show(selectedObject,t.responseText);
  }
  var errFunc = function(t) {
    alert('Error ' + t.status + ' -- ' + t.statusText);
  }  
  new Ajax.Request(url,{onSuccess:handlerFunc,onFailure:errFunc});
  return false;
}

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

window.onload = function(e) {
  var cookie = Cookie.get("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  Cookie.set("style", title, 365);
}

var cookie = Cookie.get("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);

function submitForm(theEventId,theButton)
{
  currentForm._eventId.value=theEventId;
  //disable button
  theClickedButton = theButton;
  if(theClickedButton != null)
  {
    theClickedButton.disabled = true;
  }
  
  if((theEventId == "previous") || (theEventId == "cancel")||
  (theEventId == "assistance") || (theEventId == "justcurious")) 
  {
    currentForm.submit(); // this does NOT do validation
  }
  else
  {
    theButton = $('fakeSubmitButton');  // this does validation
    theButton.click();
  }    
}

function validateRange(theValue, startRange, endRange)
{
  var success = false;
  if(!isNaN(theValue))
  {
    var theNum = parseInt(theValue,10);
    if((theNum >= startRange) && (theNum <= endRange))
    {
      success = true;
    }    
  }
  return success;
}

//given a message replace the {} parameters with the value from the passed in arguments
function format(message, arguments)
{
  for (var i=0;i < arguments.length ; i++)
  {
    var regexp = new RegExp("\\{" + i +"\\}");
    message = message.replace(regexp, arguments[i]);
  }
  return message;
}

//simple hashmap object to handle rudimentary behaviour in the browser
HashMap = Class.create();
HashMap.prototype = {
	initialize : function()
  {
	 this.keys = new Array();
	 this.values = new Array();
	},
	put : function(key,value)
  {
    if(!this.containsKey(key))
    {
      this.keys[this.keys.length] = key;
      this.values[this.values.length] = value;
    }    
  },
  get : function(key)
  {
    var results = null;
    var index = this.getKeyIndex(key);
    if(index!= null)
    {
      results = this.values[index];
    }
    return results;
  },
  getKeyIndex : function(key)
  {
    var index = null;
    for(var i = 0; i < this.keys.length;i++)
    {
      if(key == this.keys[i])
      {
        index = i;
        break;
      }
    }
    return index;    
  },
  length : function()
  {
    return this.keys.length;
  },
  containsKey: function(key)
  {
    var success = false;
    for(var i = 0; i < this.keys.length;i++)
    {
      if(key == this.keys[i])
      {
        success = true;
        break;
      }
    }
    return success;
  },
  containsValue: function(value)
  {
    var success = false;
    for(i = 0; i < this.values.length;i++)
    {
      if(key == this.values[i])
      {
        success = true;
        break;
      }
    }
    return success;
  }  
}

function replaceFieldLabel(rowId,newContent)
{
  //replace the verbiage for a question given the row and content
  var aRow = $(rowId);
  var aCell = aRow.cells[0];
  var aNode = null;
  for (var i=0 ; i < aCell.childNodes.length; i++)
  {
    aNode = aCell.childNodes[i];
    if(aNode.nodeName == "LABEL")
    {
      break;
    }
  }
  aNode.innerHTML = newContent;
}

//object used to manage zip code county and city
ZipCode = Class.create();
ZipCode.prototype = {
	initialize : function(aCity,aCounty)
  {
	 this.city = aCity;
	 this.county = aCounty;
	}
}
Object.extend(ZipCode,{
	initializeFromXML : function(xmlNode)
	{
    var cityVal = "";
    var countyVal = "";
    for(var i=0; i < xmlNode.childNodes.length; i++)
    {
      var aNode = xmlNode.childNodes[i];
      if(aNode.nodeName == "city")
      {
        cityVal = aNode.firstChild.nodeValue;
      }
      if(aNode.nodeName == "county")
      {
        countyVal = aNode.firstChild.nodeValue;
      }              
    } 	
    return new ZipCode(cityVal,countyVal);
  }
}
)

function getZipCodeInfo()
{
  if(Validation.validate('field_zip_code'))
  {
    var handlerFunc = function(t) {    
      var zips = t.responseXML.getElementsByTagName('zipCodeInfo');
      if(zips != null)
      {
        if(zips.length == 1)
        {
          var zipCode = ZipCode.initializeFromXML(zips[0]);
          $('field_city').value = zipCode.city;
          $('field_county').value = zipCode.county;
          var aMesg = format(messages.get('demographics_1.page.question.validation.zip_code.city_county_confirm'),new Array(zipCode.city,zipCode.county));
          $('mesg_row_zip_code_content').innerHTML = aMesg;
          Element.show('mesg_row_zip_code');
          Element.show('mesg_spacer_row_zip_code');
        }
        else if (zips.length > 1)
        {
          var citys = new HashMap();
          var countys = new HashMap();   
          for(i=0; i < zips.length; i++)
          {         
            var zipCode = ZipCode.initializeFromXML(zips[i]);
            citys.put(zipCode.city,zipCode);
            countys.put(zipCode.county,zipCode);            
          }//end for 
          //if county has only one element then just display message
          if(countys.length() == 1)
          {
            var zipCode = countys.values[0];
            $('field_county').value = zipCode.county;
            $('field_city').value = "";
            var aMesg = format(messages.get('demographics_1.page.question.validation.zip_code.county_confirm'),new Array(zipCode.county));
            $('mesg_row_zip_code_content').innerHTML = aMesg;
            Element.show('mesg_row_zip_code');
            Element.show('mesg_spacer_row_zip_code');            
          }
          else
          {
            //need to process the multipe couties or multiple cities
            //create a select box that when click populates the appropriate fields
            var orgCityCountyVal = $('field_city').value + ":" + $('field_county').value;
            var fieldLabel="<div id='real_county_city_errormsg' style='display:none'>" + messages.get('demographics_1.page.question.label.validation.city_county') + "</div><table width='100%'><tr><td width='50%' class='questionsub'><label for='real_county_city'>"+messages.get('demographics_1.page.question.label.city_county')+"</label></td>";
            var fieldObject="<td class='questionformfield'><select class='validate-select-required' id='field_real_county_city' name='real_county_city' onchange='populateCityCountyFields(this)'><option value=''>&lt;Select&gt;</option>";
            
            var results = citys;
            if(countys.length() >= citys.length())
            {
              results = countys;  
            }
            for(var i= 0; i < results.length();i++)
            {
              var zipCode = results.values[i];
              tmpCityCountyVal = zipCode.city+":"+zipCode.county;
              fieldObject+="<option value='"+tmpCityCountyVal+"' " + ((tmpCityCountyVal == orgCityCountyVal)? "selected":"") + " >"+ zipCode.city +" / "+ zipCode.county +" County</option>";
            }
            fieldObject+="</select></td></tr></table>";
            if(orgCityCountyVal == ":")
            {
              $('field_city').value = "";
              $('field_county').value = "";            
            }
            $('mesg_row_zip_code_content').innerHTML = fieldLabel + fieldObject;
            Element.show('mesg_row_zip_code');
            Element.show('mesg_spacer_row_zip_code');
          }
        }
        else
        {
          $('field_city').value = "";
          $('field_county').value = "";          
          Element.hide('mesg_row_zip_code');
          Element.hide('mesg_spacer_row_zip_code'); 
          //clear the field so that they can't get pass the screen
          $('field_zip_code').value = "";
          //if they want to see a directory then give a javascript alert
          if(confirm(messages.get('demographics_1.page.question.validation.zip_code.uncovered_area')))
          {
              var w = 480, h = 340 , width=400, height=480;
              if (document.all) {
                 /* the following is only available after onLoad */
                 w = document.body.clientWidth;
                 h = document.body.clientHeight;
              }
              else if (document.layers) {
                 w = window.innerWidth;
                 h = window.innerHeight;
              }
              
              var left = (w-width)/2, top = (h-height)/2;
              var zipDialog = window.open(messages.get('global.url.zip.directory'),"zipCodes" ,'scrollbars=yes, resize=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
              zipDialog.focus();
          }
        }   
      }//end if block
             
    }//end function definition
    
    var errorHandler = function(t)
    {
      alert('Error ' + t.status + ' -- ' + t.statusText);
    }
    new Ajax.Request(zipCodeValidationURL, {parameters:'method=find&zip_code='+$F('field_zip_code'), onSuccess:handlerFunc, onFailure:errorHandler});
  }
}		

function populateCityCountyFields(elm)
{
  var results = elm.options[elm.selectedIndex].value;
  if(results != -1)
  {
    $('field_city').value = results.substring(0,results.indexOf(":"));
    $('field_county').value = results.substring(results.indexOf(":")+1);
  }
  else
  {
    $('field_city').value = "";
    $('field_county').value = "";
  }
}

function buyerConfirmation()
{
  var theField = $("field_who_is_buying");
  if(!theField.visible()) return false;
  for(var i =0; i < theField.options.length;i++)
  {
    if(theField.options[i].selected && (theField.options[i].value != "myself") && 
    (theField.options[i].value != ""))
    {
      alert(messages.get("demographics_1.page.question.alert.who_is_buying"));
      break;
    }
  }
}

// show 'Rank' of drug items if user selected an importance for 'drug_coverage'
function askDrugCoverageRanking()
{
  //determine if rank questions should be asked
  var theField = currentForm['drug_coverage'];
  var aValue ="";
  validateDrugRanking = false;
  for(var i =0; i < theField.length;i++)
  {
    if(theField[i].checked)
    {
      aValue = theField[i].value;
      break;
    }
  }
    
  //if(aValue != "not_important")
  if(aValue != "0")
  {
    Element.show('rank_drug_coverage_medicalrx');
    validateDrugRanking = true;
  }
  else
  {
    Element.hide('rank_drug_coverage_medicalrx');
    validateDrugRanking = false;
  }
}

function askMedicareSupplementInfo()
{
  //determine if supplemental questions should be asked
  var theField = currentForm['medicare_program'];
  var aValue ="";
  for(var i =0; i < theField.length;i++)
  {
    if(theField[i].checked)
    {
      aValue = theField[i].value;
      break;
    }
  }
    
  if(aValue == "original_medicare")
  {
    Element.show('field_row_additional_medicare_coverage_original');
    Element.show('spacer_row_additional_medicare_coverage_original');
    Element.hide('field_row_additional_medicare_coverage_advantage'); 
    Element.hide('spacer_row_additional_medicare_coverage_advantage'); 
    clearMedicareAdvantage();    
  }
  else if(aValue =="medicare_advantage_no_drugs")
  {
    Element.show('field_row_additional_medicare_coverage_advantage');
    Element.show('spacer_row_additional_medicare_coverage_advantage');
    Element.hide('field_row_additional_medicare_coverage_original');
    Element.hide('spacer_row_additional_medicare_coverage_original');
    clearOriginalMedicare();
  }
  else
  {
    Element.hide('field_row_additional_medicare_coverage_original');
    Element.hide('spacer_row_additional_medicare_coverage_original');
    Element.hide('field_row_additional_medicare_coverage_advantage'); 
    Element.hide('spacer_row_additional_medicare_coverage_advantage'); 
    clearMedicareAdvantage();
    clearOriginalMedicare();
  }
}
//clears original medicare child fields when the original medicare field is no selected
function clearOriginalMedicare()
{
  var theField = currentForm['additional_medicare_coverage_original'];
  for(var i =0; i < theField.length;i++)
  {
    theField[i].checked = false;
  }
}
//clears the medicare advantage child field when medicare advantage is not selected
function clearMedicareAdvantage()
{
  var theField = currentForm['additional_medicare_coverage_advantage'];
   theField.checked = false;
}

function fillPartBEffectiveDate()
{
  //this function is called when the user hits the previous button
  //this functions assumes there is a global variable for birthday month
  //day and year
  var theField = currentForm['medicare_program'];
  var aValue ="";
  for(var i =0; i < theField.length;i++)
  {
    if(theField[i].checked)
    {
      aValue = theField[i].value;
      break;
    }
  }
  //birthdate  
  var birthD = new Date(birthYear,birthMonth-1,birthDay);
  //calculate age
  var age = calcAge(birthD);    
  if((aValue == "not_currently_enrolled") && ((age >= MINIMUM_AGE) && (age <= IDEAL_AGE)))
  { 
    //calculate the effective date and pre fill the effective date question    
    var calcD = calculateEffectiveDate(birthD); 

    // NOT USED IN 2008
    //var calcedEffectiveDate = calcD.getMonthName() + " " + calcD.getDate() +", " + calcD.getFullYear();
    //var aMesg = format(messages.get('demographics_2.page.question.label.partb_effective_date.not_currently_enrolled'),new Array(calcedEffectiveDate));
    //replaceFieldLabel("field_row_partb_effective_date",aMesg);
    
    Element.show('field_row_partb_effective_date');
   // Element.show('spacer_row_partb_effective_date');  
  }
  else if(aValue == "none")
  {
    //prefill effective date to decemeber 12/2007 or whatever comes from the properties file 
    var aMonth = messages.get('partb_effective_date.default_month');
    var aYear = messages.get('partb_effective_date.default_year');
    populatePartBEffectiveDate(aMonth,aYear);
    Element.hide('field_row_partb_effective_date');
    Element.hide('spacer_row_medicare_program');
    //Element.hide('spacer_row_partb_effective_date');
    //Element.hide('field_row_requested_effective_date'); 
    //Element.hide('spacer_row_requested_effective_date');     
    //Element.show('field_row_not_eligible');     // 2008 - don't show 'not_eligible' question when 'none'
    //Element.hide('field_row_not_eligible');
  }
  else if((aValue == "not_currently_enrolled") && ((age < MINIMUM_AGE) || (age > IDEAL_AGE)))
  {
    replaceFieldLabel("field_row_partb_effective_date",messages.get('demographics_2.page.question.label.partb_effective_date.estimated'));
    Element.show('field_row_partb_effective_date');
    //Element.hide('spacer_row_partb_effective_date');
    //Element.hide('field_row_requested_effective_date'); 
    //Element.hide('spacer_row_requested_effective_date');     
    Element.show('spacer_row_medicare_program'); 
    //Element.hide('field_row_not_eligible');     
  }   
  else
  {
    replaceFieldLabel("field_row_partb_effective_date",messages.get('demographics_2.page.question.label.partb_effective_date'));
    Element.show('field_row_partb_effective_date');
    //Element.show('spacer_row_partb_effective_date');
    //Element.hide('field_row_requested_effective_date'); 
    //Element.hide('spacer_row_requested_effective_date');     
    //Element.hide('field_row_not_eligible');     
  }   
}

//remove the current month and all months that have passed
//user should not beable to select them if the current year is the same
// NOT USED FOR 2008
function filterPastMonthsForEffectiveDate()
{
  var aYear = messages.get('requested_effective_date.default_year');
  var todayDate = new Date();
  if(todayDate.getFullYear() == aYear)
  {
    var aMonth = parseInt(todayDate.getMonth(),10) + 1;
    var aField = $('field_requested_effective_date_month');
    var optionHolder = new Array();
    for (var i = 0; i < aField.options.length; i++) 
    {
      var aOption = aField.options[i];
      if((aOption.value == "") || ((parseInt(aOption.value,10)) > aMonth))
      {
        optionHolder[optionHolder.length] = aField.options[i];
      }    
    }    
    //clear original list
    aField.options.length = 0;
    var selectedIndex = 0;
    for(var i = 0; i < optionHolder.length; i ++)
    {
      if((optionHolder[i].selected) && (optionHolder[i].value != ""))
      {
        aField.options[i] = new Option(optionHolder[i].text,optionHolder[i].value,optionHolder[i].selected);
        selectedIndex = i;
      }
      else
      {
        aField.options[i] = new Option(optionHolder[i].text,optionHolder[i].value);
      }
    }
    
    //preselect if available used to fix bug in IE 
     aField.selectedIndex = selectedIndex;
  }
}

function calcAge(dateOfBirth){
  var dy = dateOfBirth.getDate();
  var mo = dateOfBirth.getMonth();
  var yr = dateOfBirth.getFullYear();
  var nDate = new Date();  // current date (local)
  var nowTime = nDate.getTime();  // current time (UTC)
  var thenTime = Date.UTC(yr, mo, dy);  // specified time (UTC)
  var thisYear = nDate.getFullYear();
  var thisMonth = nDate.getMonth();
  var thisDay = nDate.getDate();
  var whYrs =0;
  var spareDys =0;

if (nowTime >= thenTime) {   //-----------------Past or present time
if ((thisMonth > mo) || ((thisMonth == mo) && (thisDay >= dy))) {
  whYrs = thisYear - yr;
  spareDys = parseInt((nowTime - Date.UTC(thisYear,mo,dy))/(3600000*24));
   if ((mo == 2 && dy == 29)  && ((thisYear%4 != 0) || (thisYear%100 == 0 &&  thisYear%400 != 0))) {spareDys = spareDys + 1}
  } else {
  whYrs = thisYear - yr - 1;
  spareDys = parseInt((nowTime - Date.UTC(thisYear-1,mo,dy))/(3600000*24));
   if ((mo == 2 && dy == 29)  && (((thisYear-1)%4 != 0) || ((thisYear-1)%100 == 0 && (thisYear-1)%400 != 0))) {spareDys = spareDys + 1}
   }
 } else {   //----------------------------Future time
if ((thisMonth < mo-1) || ((thisMonth == mo)&& (thisDay <= dy))) {
  whYrs = yr - thisYear;
  spareDys = parseInt((thenTime - Date.UTC(yr,thisMonth,thisDay))/(3600000*24));
   if ((thisMonth == 1 && thisDay == 29)  && ((yr%4 != 0) || (yr%100 == 0 && yr%400 != 0))) {spareDys = spareDys - 1}
  } else {
  whYrs = yr - thisYear - 1;
  spareDys = parseInt((thenTime - Date.UTC(yr-1,thisMonth,thisDay)) /(3600000*24));
   if ((thisMonth == 1 && thisDay == 29)  && (((yr-1)%4 != 0) || ((yr-1)%100 == 0 && (yr-1)%400 !=   0))) {spareDys = spareDys - 1};
   }
  }

  return (whYrs + (spareDys/365));
}

function calculateEffectiveDate(birthDate)
{
  var seniorBD = birthDate.addYears(IDEAL_AGE);
  var aMonth = birthDate.getMonth();
  var aYear = seniorBD.getFullYear();
  var aDay = messages.get('partb_effective_date.default_day');
  if((seniorBD.getDate () == 1) && (seniorBD.getMonth() == 0))
  {
    aMonth = 12;
    aYear--;
  }
  else if(seniorBD.getDate () == 1)
  {
    aMonth--;
  }
  return new Date(aYear,aMonth,aDay);
}

function askPartBEffectiveDate()
{
  //this functions assumes there is a global variable for birthday month
  //day and year
  var theField = currentForm['medicare_program'];
  var aValue ="";
  for(var i =0; i < theField.length;i++)
  {
    if(theField[i].checked)
    {
      aValue = theField[i].value;
      break;
    }
  }
  //calculate the effective date and pre fill the effective date question
  var birthD = new Date(birthYear,birthMonth-1,birthDay);
   //calculate age
  var age = calcAge(birthD);
 
  var calcD = calculateEffectiveDate(birthD);
    
  //store the calculated effective date for the back end - NOT USED IN 2008  
  //$('field_calculated_partb_effective_date').value = calcD.format('%MM-%DD-%YYYY');
        
  if((aValue == "not_currently_enrolled") && ((age >= MINIMUM_AGE) && (age <= IDEAL_AGE)))
  {    
    var calcedEffectiveDate = calcD.getMonthName() + " " + calcD.getDate() +", " + calcD.getFullYear();
    populatePartBEffectiveDate((calcD.getMonth() + 1),calcD.getFullYear());
    var aMesg = format(messages.get('demographics_2.page.question.label.partb_effective_date.not_currently_enrolled'),new Array(calcedEffectiveDate));
    replaceFieldLabel("field_row_partb_effective_date",aMesg);
    Element.show('spacer_row_medicare_program');
    Element.show('field_row_partb_effective_date');
    //Element.show('spacer_row_partb_effective_date');
    
    //if the effective date / senior's 65 birthday is greater than current year
    //show not eligible question
    // NOT USED IN 2008
    //var aYear = messages.get('partb_effective_date.default_year');
    //if(calcD.getFullYear() > aYear)
    //{
    //  Element.hide('field_row_requested_effective_date'); 
    //  Element.hide('spacer_row_requested_effective_date'); 
    //  Element.show('field_row_not_eligible'); 
    //}
    //else
    //{
    //  Element.show('field_row_requested_effective_date');   
    //  Element.hide('spacer_row_requested_effective_date'); 
    //  Element.hide('field_row_not_eligible'); 
    //}
    //Element.show('spacer_row_medicare_program'); 
  }
  else if(aValue == "none")
  {
    //prefill effective date to decemeber 12/2007 or whatever comes from the properties file 
    // NOT USED IN 2008
    var aMonth = messages.get('partb_effective_date.default_month');
    var aYear = messages.get('partb_effective_date.default_year');
    populatePartBEffectiveDate(aMonth,aYear);
    Element.hide('spacer_row_medicare_program'); 
    Element.hide('field_row_partb_effective_date');
    //Element.hide('spacer_row_partb_effective_date');
    //Element.hide('field_row_requested_effective_date'); 
    //Element.hide('spacer_row_requested_effective_date');   
    //Element.show('spacer_row_medicare_program');  
    //Element.show('field_row_not_eligible');     
  }
  else if((aValue == "not_currently_enrolled") && ((age < MINIMUM_AGE) || (age > IDEAL_AGE)))
  {
    populatePartBEffectiveDate("","");
    replaceFieldLabel("field_row_partb_effective_date",messages.get('demographics_2.page.question.label.partb_effective_date.estimated'));
    Element.show('spacer_row_medicare_program'); 
    Element.show('field_row_partb_effective_date');
    //Element.hide('spacer_row_partb_effective_date');
    //Element.hide('field_row_requested_effective_date'); 
    //Element.hide('spacer_row_requested_effective_date');     
    //Element.show('spacer_row_medicare_program'); 
    //Element.hide('field_row_not_eligible');     
  }   
  else
  {
    populatePartBEffectiveDate("","");
    replaceFieldLabel("field_row_partb_effective_date",messages.get('demographics_2.page.question.label.partb_effective_date'));
    Element.show('spacer_row_medicare_program'); 
    Element.show('field_row_partb_effective_date');
    //Element.hide('spacer_row_partb_effective_date');
    //Element.hide('field_row_requested_effective_date'); 
    //Element.hide('spacer_row_requested_effective_date');     
    //Element.show('spacer_row_medicare_program'); 
    //Element.hide('field_row_not_eligible');     
  } 
}

//populates the effective date fields given the month and year
function populatePartBEffectiveDate(aMonth,aYear)
{
    var yearField =$('field_partb_effective_date_year');
    var monthField =$('field_partb_effective_date_month');
    aMonth = parseInt(aMonth,10);
    if(isNaN(aMonth))
    {
        aMonth="";
    }    
    aYear = parseInt(aYear,10);
    if(isNaN(aYear))
    {
        aYear="";
    }
    monthField.value = aMonth;
    yearField.value = aYear;
}

function askAdditionalQuestions()
{
  askMedicareSupplementInfo();
  askPartBEffectiveDate();
  
  //insert default values for partb effective date
  var aDay = messages.get('partb_effective_date.default_day');
  $('field_partb_effective_date_day').value=aDay;    
  
  //insert default values for requested effective date
  //var aDay = messages.get('requested_effective_date.default_day');
  //var aYear = messages.get('requested_effective_date.default_year');
  //$('field_requested_effective_date_day').value=aDay;
  //$('field_requested_effective_date_year').value=aYear;  
  
}

// NOT USED IN 2008
function askRequestedEffectiveDate()
{
    theDate = $('field_partb_effective_date_year');
    //if the effective date is greater than current year
    //show not eligible question
    var aYear = messages.get('partb_effective_date.default_year');
    if(theDate.value > aYear)
    {
      Element.hide('field_row_requested_effective_date'); 
      Element.hide('spacer_row_requested_effective_date'); 
      Element.show('field_row_not_eligible'); 
    }
    else
    {
      Element.show('field_row_requested_effective_date');   
      Element.hide('spacer_row_requested_effective_date');       
      Element.show('spacer_row_partb_effective_date');
      Element.hide('field_row_not_eligible');       
    }     
}

function prefillForm()
{
  var aValue ="";
  // if agent scripting is enabled and there's no value set, default to on
  if (currentForm['agent_scripting'] != null)
  {
    var aValue ="";
    var theField = currentForm['agent_scripting'];
    for (var i =0; i < theField.length;i++)
    {
      if(theField[i].checked)
      {
        aValue = theField[i].value;
        break;
      }
    }
    if(aValue=="")
    {
      theField[0].checked=true;
    }
  }
  
  
  if(($('field_zip_code') != null) && ($F('field_zip_code') != ""))
  {
    getZipCodeInfo();
  }
  
  aValue ="";
  if(currentForm['medicare_program'] != null)
  {
    var theField = currentForm['medicare_program'];
    for(var i =0; i < theField.length;i++)
    {
      if(theField[i].checked)
      {
        aValue = theField[i].value;
        break;
      }
    }
    if(aValue=="")
    {
      Element.hide('spacer_row_medicare_program'); 
    }
  }
  
  if((currentForm['medicare_program'] != null) && (aValue !=""))
  {
    askMedicareSupplementInfo();
    fillPartBEffectiveDate();
    //if(aValue != "none")
    //{
    //  askRequestedEffectiveDate();
    //}    
  }
}

// NOT USED IN 2008
function setDefaultEffectiveDate()
{
  //insert default values for requested effective date
  //if the passed in month has passed then switch to
  //a month in future;
  var today = new Date();
  var aMonth = messages.get('requested_effective_date.default_month');
  if((today.getMonth() + 1) > aMonth)
  {
    var futureDate = today.addMonths(1);
    //the date script thinks of a month as 30 days if we are in a month
    //where there are 31 and we call the script on the first of that month
    //we are still stuck in the same month so we need to add 1 day to get to the
    //the next month
    if(futureDate.getMonth() == today.getMonth())
    {
      futureDate = futureDate.addDays(1);
    }
    aMonth = futureDate.getMonth() + 1;
  }
  var aDay = messages.get('requested_effective_date.default_day');
  var aYear = messages.get('requested_effective_date.default_year');
  if(today.getFullYear() > aYear)
  {
    var futureDate = today.addYears(1);
    aMonth = futureDate.getFullYear();
  }  
  $('field_requested_effective_date_month').value=aMonth;
  $('field_requested_effective_date_day').value=aDay;
  $('field_requested_effective_date_year').value=aYear;
}

//event watcher for the special enrollment question
//clear all the options except the n
function clearSpecialEnrollmentSelections(e)
{
  theCheckbox = Event.element(e);
  if((theCheckbox.value == "n") && (theCheckbox.checked))
  {
      var theField = currentForm[theCheckbox.name];
      for (var i=0; i < theField.length; i++)
      {
        if((theField[i].checked) && (theField[i].value != "n"))
        {
          theField[i].checked = false;
        }
      }  
  }
}

//event watcher for the special enrollment question
//don't allow the user to make any options if they check n
function preventSpecialEnrollmentSelections(e)
{
  theCheckbox = Event.element(e);
  if(theCheckbox.checked)
  {
      var theField = currentForm[theCheckbox.name];
      var allowSelection = true;
      for (var i=0; i < theField.length; i++)
      {
        if((theField[i].checked) && (theField[i].value == "n"))
        {
          allowSelection = false;
        }
      }  
      if(!allowSelection)
      {
        theCheckbox.checked = false;
      }
  }
}

function doSpecialEnrollment()
{
    if(confirm(messages.get('demographics_special_enrollment_page.page.question.label.special_enrollment_period.alert')))
    {
      submitForm("previous");
    }
}

function disableCoverageOptions(theField,currentCase)
{
  var medicalCases = [9,10];
  //
  //case 9 needs only one option (out of 3) disabled...medical only
  //case 10 needs only one option  (out of 3) disabled...medical only
  
  if(currentCase == 3)
  {
    disableOtherOptions(theField,"rx");
  }
  else if(currentCase == 5)
  {
    disableOtherOptions(theField,"medicalSuppOnly");
  }
  else if(currentCase == 7)
  {
    disableOtherOptions(theField,"medical");
  }
  else if (medicalCases.include(currentCase))
  {
    disableThisOption(theField,"medical");
  }
  else
  {
    if(theField.length > 1)
    {
      var isChecked = false;
      for (var i=0; i < theField.length; i++)
      {
        if(theField[i].checked)
        {
          isChecked = true;
          break;
        }
      }
      if(!isChecked)
      {
        theField[0].checked=true;
      }      
    }
    else
      theField.checked=true;
  }
}

function disableOtherOptions(theField,goodOption)
{
  //helper function to disable coverage options
  for (var i=0; i < theField.length; i++)
  {
    if(theField[i].value != goodOption)
    {
      theField[i].disabled = "true";
    }
    else if (!theField.defaultChecked)
    {
      theField[i].checked=true;
    }
  }
}

function disableThisOption(theField,OptionToBeDisabled)
{
  //helper function to disable coverage options
  for (var i=0; i < theField.length; i++)
  {
    if(theField[i].value == OptionToBeDisabled)
    {
      theField[i].disabled = "true";
    }
    else if (!theField.defaultChecked)
    {
      theField[i].checked=true;
    }
  }
}

function doPrint()
{
  if((agentEnabled) && (currentForm.name == "preference"))
  {
    var userName = prompt(messages.get("global.instruction.save.alert"),"");
    currentForm.userName.value = userName;
  }
  window.print();
}

function getParameter(parameter)
{
  queryString = "";
  queryMap = location.search.split("&");  
  queryMap.each(function(item)
  {
    if (item.indexOf(parameter) > -1)
    {
      queryString = item.substring(item.indexOf("=")+1);
    }
  });
  return queryString;
}

//process the fast find only validate when the form is demographics
function doFastFind()
{
  if(!agentEnabled)
  {
    var msg = messages.get("fastfind.demographics.answered");
    
    if(currentForm.name != "demographics_3")
    { 
    	msg = messages.get("fastfind.preferences.notanswered");
    	
    	Element.hide("validation_messages");
    	
    	var result = formValidator.validate();
    	
    	if(result)
    	{
        	msg = messages.get("fastfind.preferences.answered");
    	} 
    	 else if (typeof validateDrugRanking != "undefined" && validateDrugRanking )
       { Element.show("validation_messages");
      return;} 
    }

    if(!confirm(msg))
    {
     formValidator.reset();
       Element.show("validation_messages");
      return;
    }
  }
  
  currentForm._eventId.value="fastfind";
  if(currentForm.name == "demographics_3")
  {
    theButton = $('fakeSubmitButton');
    theButton.click();
  }
  else
  {
    currentForm.submit();
  }     
}


function doEnroll(conversation,url)
{
  if((conversation.indexOf("medicalrx") > -1) && (url.indexOf("mpadv") == -1))
  {
    alert(messages.get("products.page.plan.enroll.alert"));
  }
  window.location = url;
}

function focusHandler(results,theForm)
{
  //helper function to always put focus on the top of the page
  //when an error occurs
  if(!results)
  {
    scroll(0,0);
    //undisable button
    if(theClickedButton != null)
    {
      theClickedButton.disabled=false;
    }    
  }
}


function doSave(anchor)
{
  var win = new PopupWindow('savePrompt'); 
  
  var coord = getAnchorPosition(anchor);

  win.showPopup(anchor);
  document.forms["reportSaveDisplay"].userName.focus();
}

function showCalculator(event, url, interview,serviceArea) {

  if (interview == null){
    var win = new PopupWindow();
    win.offsetX=Event.pointerX(event) + 10;
    win.offsetY=Event.pointerY(event) - 150;
    win.setSize(800, 680); 
    win.autoHide();  
    win.showPopup('page_top');
    
    win.setUrl(url);
    win.refresh();
    
  } else if(interview == "senior-medicalrx") {
    var anchor = this.document.createElement('a');
    anchor.setAttribute('rev', 'width: 395px; height: 135px; scrolling: no;');
    anchor.setAttribute('title', 'Choose Drug Calculator');
    //anchor.setAttribute('href', url);
    anchor.setAttribute('href', 'drugCalculator.ehtml?serviceArea='+serviceArea);
     
    anchor.setAttribute('rel', 'lyteframe');
    
    myLytebox.start(anchor, false, true);
    return false;
    
  } else {
    popUpWindow(this,url,'900','640');
  }
}


function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function showEligibility(messageKey)
{
  popUpWindow(this,'message.ehtml?messageKey='+messageKey,'450','450')
}
