var newwindow = '';
var hasStateChanged = false;
var UserRatingTypeRemovePlan = 2;
var CookieUserName = 'CookieUser';
var myRemovedHash = new Hashtable();

function planWarning(){
	
	if (hasStateChanged == true){
		hasStateChanged = false;
		return confirm('Attention: You have changed the ZIP code in your About You settings. As a result, the list of plans you are eligible for may change.  For plans that no longer appear in your list, any ratings you have made--like "Good Fit" or "So-so Fit"--will be lost.  \n\nDo you wish to continue?');
	}
}

function updateUserRatings(dropdown, section, userId){
	
	var myConn = new XHConn();
	var planId = dropdown.options[dropdown.selectedIndex].value.split(':')[0]
	var ratingId = dropdown.options[dropdown.selectedIndex].value.split(':')[1]
		
	//Check to see if the rating selected is the remove plan
	if (ratingId == UserRatingTypeRemovePlan){
		var cookieValue = getCookie(CookieUserName).split(':');
		var newPlanBit = parseInt(cookieValue[1]) - parseInt(planId);
		
		var newValue = cookieValue[0] + ':' + newPlanBit + ':' + cookieValue[2] + ':' + cookieValue[3];
		setCookie( CookieUserName, newValue , null, '/' );
		
		//Add the planid to the hash in case a user decided to not remove the plan
		myRemovedHash.put(planId,planId);
		
		return;	
	}
	
	//If it has already been removed  we have to add the plan back
	if (myRemovedHash.containsKey(planId)){
	
		var cookieValue = getCookie(CookieUserName).split(':');
		var newPlanBit = parseInt(cookieValue[1]) + parseInt(planId);
		
		var newValue = cookieValue[0] + ':' + newPlanBit + ':' + cookieValue[2] + ':' + cookieValue[3];
		setCookie( CookieUserName, newValue , null, '/' );
		
		//Remove the plan from the hash now that it is added back
		myRemovedHash.remove(planId);	
	}
			
	if (!myConn)
		alert("XMLHTTP not available. Try a newer/better browser.");

	var fnWhenDone = function (oXML) { //donothing 
										};

	myConn.connect("AJAX/UpdateUserRating.aspx" , "GET", "userId=" + userId + "&planId=" + planId + "&section=" + section + "&ratingId=" + ratingId + "&random=" + Math.floor(Math.random()*1000), fnWhenDone);

}

function UBOCCalculateFlex(){
	
	if ((document.getElementById('ctl21$txtAge').value == '') 
		|| (document.getElementById('ctl21$txtAnnualSalary').value == '')
			|| (!IsNumeric(document.getElementById('ctl21$txtAnnualSalary').value))
				|| (!IsNumeric(document.getElementById('ctl21$txtAge').value))){
		alert('Please make sure to enter a valid value for salary and age.');
		return false;
	}
	
	var myConn = new XHConn();
	
	document.getElementById('ctl21$hiddenAge').value = document.getElementById('ctl21$txtAge').value;
	document.getElementById('ctl21$hiddenAnnualSalary').value = document.getElementById('ctl21$txtAnnualSalary').value;
	
	if (!myConn)
		alert("XMLHTTP not available. Try a newer/better browser.");

	var fnWhenDone = function (oXML) { document.getElementById('ctl21$inputEstimatedFlex').value = oXML.responseText;
										document.getElementById('ctl21$txtAge').value = '';
										document.getElementById('ctl21$txtAnnualSalary').value = '';
										};

	myConn.connect("AJAX/UBOCCalculateFlex.aspx" , "GET", "AnnualSalary=" + document.getElementById('ctl21$txtAnnualSalary').value + "&Age=" + document.getElementById('ctl21$txtAge').value, fnWhenDone);

	
}

function EligibilityDropdownChanged(ddlFamilyTier){
		
	var myConn = new XHConn();
		
	if (!myConn)
		alert("XMLHTTP not available. Try a newer/better browser.");

	var fnWhenDone = function (oXML) 
			{	
				var columnName = oXML.responseText;
				var divMedicationUseSingleColumn = document.getElementById('divMedicationUseSingleColumn');
				var divMedicationUseMultiColumn = document.getElementById('divMedicationUseMultiColumn');
				var divMedicalUseSingleColumn = document.getElementById('divMedicalUseSingleColumn');
				var divMedicalUseMultiColumn = document.getElementById('divMedicalUseMultiColumn');
				
				var divMedicationDependentColumnName = document.getElementById('divMedicationDependentColumnName');
				var divMedicationDependentRowName = document.getElementById('divMedicationDependentRowName');
				var rdbMedicationF1Elems = getElementsByNameMatch(document,"^\\w+_rdbMedicationF1","input");
				var rdbMedicationF2Elems = getElementsByNameMatch(document,"^\\w+_rdbMedicationF2","input");
				var rdbMedicationF3Elems = getElementsByNameMatch(document,"^\\w+_rdbMedicationF3","input");
				var rdbMedicationF4Elems = getElementsByNameMatch(document,"^\\w+_rdbMedicationF4","input");
				
				var divMedicalDependentColumnName = document.getElementById('divMedicalDependentColumnName');
				var divMedicalDependentRowName = document.getElementById('divMedicalDependentRowName');
				var rdbMedicalF1Elems = getElementsByNameMatch(document,"^\\w+_rdbMedicalF1","input");
				var rdbMedicalF2Elems = getElementsByNameMatch(document,"^\\w+_rdbMedicalF2","input");
				var rdbMedicalF3Elems = getElementsByNameMatch(document,"^\\w+_rdbMedicalF3","input");
				var rdbMedicalF4Elems = getElementsByNameMatch(document,"^\\w+_rdbMedicalF4","input");
				
												
				if (columnName != ''){
								
					divMedicationUseSingleColumn.className = 'inVisible';
					divMedicationUseMultiColumn.className = 'visible';
					divMedicalUseSingleColumn.className = 'inVisible';
					divMedicalUseMultiColumn.className = 'visible';
					
					divMedicationDependentColumnName.className = 'dependentColumnVisible';
					divMedicationDependentColumnName.innerHTML = columnName;
					divMedicationDependentRowName.className = 'levelSelectionHeading';
								
					ChangeDependentMedicationColumnClass('visible');
					
					rdbMedicationF1Elems[0].checked = true;
					
					divMedicalDependentColumnName.className = 'dependentColumnVisible';
					divMedicalDependentColumnName.innerHTML = columnName;
					divMedicalDependentRowName.className = 'levelSelectionHeading';
										
					ChangeDependentMedicalColumnClass('visible');
					
					rdbMedicalF1Elems[0].checked = true;
									
				} else{
				
					divMedicationUseSingleColumn.className = 'visible';
					divMedicationUseMultiColumn.className = 'inVisible';
					divMedicalUseSingleColumn.className = 'visible';
					divMedicalUseMultiColumn.className = 'inVisible';
					
					divMedicationDependentColumnName.className = 'inVisible';
					divMedicationDependentRowName.className = 'inVisible';
						
					ChangeDependentMedicationColumnClass('inVisible');
					
					rdbMedicationF1Elems[0].checked = false;
					rdbMedicationF2Elems[0].checked = false;
					rdbMedicationF3Elems[0].checked = false;
					rdbMedicationF4Elems[0].checked = false;
					
					divMedicalDependentColumnName.className = 'inVisible';
					divMedicalDependentRowName.className = 'inVisible';
									
					ChangeDependentMedicalColumnClass('inVisible');
					
					rdbMedicalF1Elems[0].checked = false;
					rdbMedicalF2Elems[0].checked = false;
					rdbMedicalF3Elems[0].checked = false;
					rdbMedicalF4Elems[0].checked = false;
				}
			
			
			};

	myConn.connect("AJAX/MedicalUseDependentColumnName.aspx" , "GET", "FamilyTierId=" + ddlFamilyTier.options[ddlFamilyTier.selectedIndex].value + "&random=" + Math.floor(Math.random()*1000), fnWhenDone);


}

function ChangeDependentMedicationColumnClass(className){

	document.getElementById('divMedicationF1').className =className;
	document.getElementById('divMedicationF2').className =className;
	document.getElementById('divMedicationF3').className =className;
	document.getElementById('divMedicationF4').className =className;

}

function ChangeDependentMedicalColumnClass(className){

	document.getElementById('divMedicalF1').className =className;
	document.getElementById('divMedicalF2').className =className;
	document.getElementById('divMedicalF3').className =className;
	document.getElementById('divMedicalF4').className =className;

}

function StanfordDropdownChanged(ddlCoverage,ddlEmployment,ddlFamilyIncome){
	
	var ddlC = document.getElementById(ddlCoverage);
	var ddlE = document.getElementById(ddlEmployment);
		
	if (ddlC.options[ddlC.selectedIndex].value != '' && 
		ddlC.options[ddlC.selectedIndex].text.toLowerCase() != 'employee only' && 
			ddlE.options[ddlE.selectedIndex].value == 'F')
			document.getElementById(ddlFamilyIncome).disabled = false;
	else{
		document.getElementById(ddlFamilyIncome).disabled = true;
		document.getElementById(ddlFamilyIncome).options[0].selected = true;
	}
	
}

function UBOConFlexAmtTypeChanged(inputValue){
	
	var disabled;
	if (inputValue == "1")
		disabled = true;
	else
		disabled = false;
	
	document.getElementById('ctl21$txtAge').disabled = disabled;
	document.getElementById('ctl21$txtAnnualSalary').disabled = disabled;
	document.getElementById('btnCalculate').disabled = disabled;
	
	if (disabled){
		document.getElementById('ctl21$txtAge').value = '';
		document.getElementById('ctl21$txtAnnualSalary').value = '';
	}
}

function IsNumeric(sText){

   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

function WellsFargoDoctorLink(zipCode, lastName, subscriberID){

if (lastName == ''){ 
	alert('Please enter doctor\'s last name before clicking "Find Your Doctor". '); 
	return false;
} 
else {
    var url = "http://geoaccess.com/directoriesonline/wf/pbgh/gateway.asp";

    if (subscriberID == 30)  // WF2009
        url += "?gateway=false&zip=" + zipCode + "&lastname=" + escape(lastName) + "&planyear=1";
    else if (subscriberID == 37) // WF2010
        url += "?gateway=false&zip=" + zipCode + "&lastname=" + escape(lastName) + "&planyear=2";
    else if (subscriberID == 50) {// WF2011, for now "2", 2009 must be dropped when Ingenix is switching over
        url += "?gateway=false&zip=" + zipCode + "&lastname=" + escape(lastName) + "&planyear=2";
    }
    else {
        alert('Sorry, doctor directory search is not set up for this chooser.');
        return false;
    }

	OpenNewWindow(url,600,300);
}

}

/*
function WellsFargoDoctorLink(zipCode, lastName, planYear){

if (lastName == ''){ 
	alert('Please enter doctor\'s last name before clicking "Find Your Doctor". '); 
	return false;
} 
else {
	var url;
	
	if (planYear == 1)
		url = "http://geoaccess.com/directoriesonline/wf/pbgh/gateway.asp?gateway=false&"; 
	else
		url = "http://geoaccess.com/directoriesonline/wf/pbgh/gateway.asp?gateway=false&";
		 
	url = url + "zip=" + zipCode + "&lastname=" + escape(lastName) + "&planyear=" + planYear;

	OpenNewWindow(url,600,300);
}

}
*/

function ToggleEnterKey(id) 
{    
 if (event.keyCode == 13) 
 {        
  event.cancelBubble = true;
  event.returnValue = false;
  document.getElementById(id).click();
 }
}

function comparePlans(element){

	if (confirmSelected(element)){
		
		OpenNewWindow('ComparePlans.aspx?PlanOptions=' + GetCheckedIds(element.form),750, 600);
		
		return false;
	} else
		return false;

}

function confirmSelected(element){
	
	if (!IsTwoChecked(element.form)){
		alert('Please choose 1 to 3 plans for comparing.');
		return false;
	} else
		return true;
}

function IsTwoChecked(form){

	var num=0;
	
   for (var i=0;i < form.length;i++) 
   {
      fldObj = form.elements[i];
      if (fldObj.name == 'checkIds')
            if (fldObj.checked)
			  num++;
            
   }
   if ((num >= 1) && (num < 4))
    return true;
   else
   return false;
}

function GetCheckedIds(form){

	var num=0;
	
   for (var i=0;i < form.length;i++) 
   {
      fldObj = form.elements[i];
      if (fldObj.name == 'checkIds')
            if (fldObj.checked)
			  num = num + parseInt(fldObj.value);
            
   }
   return num;
   
}

function OpenNewWindow(URL,Width,Height)
{
	newwindow=window.open(URL,'_blank','top=20,left=20,scrollbars=yes,resizable=yes,height=' + Height + ',width=' + Width);
	if (!newwindow.opener) 
		newwindow.opener = self;

	if (window.focus) 
		newwindow.focus();
		
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar

  return false;
}

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked)
    cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

function getCookieVal( offset )
{
  var endstr = document.cookie.indexOf ( ";", offset );

  if ( endstr == -1 )
  {
    endstr = document.cookie.length;
  }
  return unescape( document.cookie.substring( offset, endstr ) );
}

//---------------------------------------------------------------------------
// Returns the value of a cookie corresponding to the name
// Returns null if the cookie can't be found

function getCookie( name )
{
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;

  while ( i < clen )
  {
    var j = i + alen;

    if ( document.cookie.substring( i, j ) == arg )
    {
      return getCookieVal ( j );
    }

    i = document.cookie.indexOf( " ", i ) + 1;

    if ( i == 0 )
    {
      break;
    }
  }
  return null;
}

//---------------------------------------------------------------------------
// Sets a cookie according to the name and value.
// Optional parameters:
// - expires (Date object)
// - path (use cookiePath for the whole domain)
// - domain
// - secure
// For more information about those parameter, check www.cookiecentral.com

function setCookie( name, value )
{
  var argv = setCookie.arguments;
  var argc = setCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;

  document.cookie = name + "=" + value +
    ( ( expires == null ) ? "" : ( "; expires=" + expires.toGMTString() ) ) +
    ( ( path == null ) ? "" : ( "; path=" + path ) ) +
    ( ( domain == null ) ? "" : ( "; domain=" + domain ) ) +
    ( ( secure == true ) ? "; secure" : "" );
}

function deleteCookie ( name )
{
  var exp = new Date();
  exp.setTime ( exp.getTime() - 1 );  // This cookie is history
  setCookie( name, "", exp, cookiePath );
}

function getElementsByNameMatch(node,searchNameMatch,tag) {
	var classElements = new Array();
	var els = node.getElementsByTagName(tag); // use "*" for all elements
	var elsLen = els.length;
	var pattern = new RegExp("\\b"+searchNameMatch+"\\b");
	
	for (i = 0, j = 0; i < elsLen; i++) {
				
		if ( pattern.test(els[i].id) ) {
	
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

/**
    Created by: Michael Synovic; 
    on: 01/12/2003
    
    This is a Javascript implementation of the Java Hashtable object.
	Copyright (C) 2003  Michael Synovic

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation; either
	version 2.1 of the License, or (at your option) any later version.

	This library is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public
	License along with this library; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA	
    
    Contructor(s):
     Hashtable()
              Creates a new, empty hashtable
    
    Method(s):
     void clear() 
              Clears this hashtable so that it contains no keys. 
     boolean containsKey(String key) 
              Tests if the specified object is a key in this hashtable. 
     boolean containsValue(Object value) 
              Returns true if this Hashtable maps one or more keys to this value. 
     Object get(String key) 
              Returns the value to which the specified key is mapped in this hashtable. 
     boolean isEmpty() 
              Tests if this hashtable maps no keys to values. 
     Array keys() 
              Returns an array of the keys in this hashtable. 
     void put(String key, Object value) 
              Maps the specified key to the specified value in this hashtable. A NullPointerException is thrown is the key or value is null.
     Object remove(String key) 
              Removes the key (and its corresponding value) from this hashtable. Returns the value of the key that was removed
     int size() 
              Returns the number of keys in this hashtable. 
     String toString() 
              Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space). 
     Array values() 
              Returns a array view of the values contained in this Hashtable. 
     Array entrySet()
              Returns a reference to the internal array that stores the data. The Set is backed by the Hashtable, so changes to the Hashtable are reflected in the Set, and vice-versa.
            
*/
function Hashtable(){
    this.hashtable = new Array();
}

/* privileged functions */

Hashtable.prototype.clear = function(){
    this.hashtable = new Array();
}              
Hashtable.prototype.containsKey = function(key){
    var exists = false;
    for (var i in this.hashtable) {
        if (i == key && this.hashtable[i] != null) {
            exists = true;
            break;
        }     
    }
    return exists;
}
Hashtable.prototype.containsValue = function(value){
    var contains = false;
    if (value != null) {
        for (var i in this.hashtable) {
            if (this.hashtable[i] == value) {
                contains = true;
                break;
            }
        }
    }        
    return contains;
}
Hashtable.prototype.get = function(key){
    return this.hashtable[key];
}
Hashtable.prototype.isEmpty = function(){
    return (parseInt(this.size()) == 0) ? true : false;
}
Hashtable.prototype.keys = function(){
    var keys = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            keys.push(i);
    }
    return keys;
}
Hashtable.prototype.put = function(key, value){
    if (key == null || value == null) {
        throw "NullPointerException {" + key + "},{" + value + "}";
    }else{
        this.hashtable[key] = value;
    }
}
Hashtable.prototype.remove = function(key){
    var rtn = this.hashtable[key];
    this.hashtable[key] = null;
    return rtn;
}    
Hashtable.prototype.size = function(){
    var size = 0;
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            size ++;
    }
    return size;
}
Hashtable.prototype.toString = function(){
    var result = "";
    for (var i in this.hashtable)
    {     
        if (this.hashtable[i] != null)
            result += "{" + i + "},{" + this.hashtable[i] + "}\n";  
    }
    return result;
}                                  
Hashtable.prototype.values = function(){
    var values = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            values.push(this.hashtable[i]);
    }
    return values;
}                                  
Hashtable.prototype.entrySet = function(){
    return this.hashtable;
}

