// JavaScript Document - 3.25

// ---------------- Begin Top Nav Menu Functionality ------------------------ //

	/* jQuery Suckerfish dropdowns emulation */
		$.fn.hoverClass = function(c) {
			return this.each(function(){
			  if ($(this).attr('class')!='spacer'){
				$(this).hover(
					function() { $(this).addClass(c);  },
					function() { $(this).removeClass(c); }
				);
			  }
			});
		};

// ---------------- End Top Nav Menu Functionality ------------------------ //

// ---------------- Begin Right Menu Fuctions ------------------------ //

$('.rightMenu li').each(function(){
		tURL = $(this).find('a').attr('href')
		if (tURL != undefined) {
			$(this).attr('style','cursor:pointer')
		};
	}).click(function(){
		tURL = $(this).find('a').attr('href')
		if (tURL != undefined) {
			window.open(tURL,'_self')
		};
	});

// ---------------- End Right Menu Fuctions ------------------------ //

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

// Return value of a parameter from current URL
function writeAgentAndReferralInfo( name ) {  
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	var regexS = "[\\?&]"+name+"=([^&#]*)";  
	var regex = new RegExp( regexS );  
	var results = regex.exec( window.location.href );  
	//alert("GUP RESULT: "+results[1]);
	
	if (results != null) {
		createCookie('AGENTID',results[1],0);
	}
	//regexS = "https+://";
	//var nregex = new RegExp( regexS );
	var urlDomain = window.location.hostname + window.location.pathname; //nregex.exec(location.href);
	var queryString = window.location.search.toString().replace(/\?/,"%3F");
	queryString = queryString.replace(/\&/g,"%26");
	queryString = queryString.replace(/\=/g,"%3D");
	createCookie('ENTRANCE-URL',urlDomain + queryString);
//	alert("REFERER INFO: "+document.referrer.toString());
//	alert("location.href INFO: "+location.host+location.pathname);
	if (document.referrer != '') {
		urlDomain = document.referrer.toString().replace(/https?\:\/\//,"");
		urlDomain = urlDomain.replace(/\?/,"%3F");
		urlDomain = urlDomain.replace(/\&/g,"%26");
		urlDomain = urlDomain.replace(/\=/g,"%3D");
//		alert("urlDomain: "+urlDomain);
		createCookie('REFERER-FULL',urlDomain);
		urlDomain = document.referrer.toString().match(/:\/\/(.[^/]+)/)[1];
		//alert("REFERER INFO: "+urlDomain);
		createCookie('REFERER',urlDomain,30);
	}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
			} while (obj = obj.offsetParent);
		return [curleft,curtop];
	}
}

jQuery.fn.truncate = function(){
	
		var tNum;
    	var cString = jQuery(this).attr('class')
		var eTrunc = jQuery(this)
		var preTunc;
		
		cArray = cString.split(' ');
		for (i=0;i<cArray.length;i++){
			if (cArray[i].match('truncate') != null) {
				tNum = cArray[i].match(/\d+/)
			}
		}

		jQuery(this).expander({slicePoint:parseInt(tNum),expandText:'read more',userCollapse:false});

};


/* Modal Script Start */
function getPageUrl(hrefStr) {
	var queryStr = (hrefStr.indexOf("?") == -1) ? hrefStr : hrefStr.substring(0,hrefStr.indexOf("?"));
	return queryStr;
}

function getParams( hrefStr,params ) {
	
	var queryStr = hrefStr.substring(hrefStr.indexOf("?")+1);
	
	parameters = queryStr.split('&');
	
	for(var i = 0; i < parameters.length; i++) {
		parameters[i] = parameters[i].split('=');
		parameters[i][1] = (isNaN(parameters[i][1])) ? parameters[i][1] : parseInt(parameters[i][1]);
		params[parameters[i][0]] = parameters[i][1];
	}
	return params;
} 

function checkModalDefaults(pageUrl) {
	var params = new Object();
	
	// reference http://jqueryui.com/demos/dialog/#options for valid parameters
	
	// set defaults
	params.resizable = false;
	params.draggable = false;
	params.dialogClass = 'modalStyle';
	params.modal=true;
	params.width=500;
	params.height=200;			
	params.buttons= { "Close": function() { $(this).dialog('close'); } };
	// DLS: Since the button is outside the Iframe, I assigned 
	// the button to click a hidden input in the appropriate modal.
	switch (pageUrl)
		{
		case "/individual/modals/requestInfo.jsp":
			params.width=580;
			params.height=460;
			params.title="Request a literature packet";
			params.buttons="";
		break;
		case "/home/modals/dental.jsp":
		case "/individual/modals/dental.jsp":
			params.resizable = false;
			params.draggable = false;
			params.title="Add dental coverage to your medical plan"
			params.width=650;
			params.height=400;
			params.buttons={ 'Continue': function(){
			$('iframe[name=thisIframe]').contents().find('input#submit_form').click(); },
			  'Cancel': function() { $(this).dialog('close');}};
			break;
		case "/home/modals/applynow.jsp":
		case "/individual/modals/applynow.jsp":
			params.resizable = true;
			params.draggable = true;
			params.title="Checkout";
			params.width=660;
			params.height=475;
			params.buttons={ 'Continue': function(){
			$('iframe[name=thisIframe]').contents().find('input#submit_form').click(); },
			  'Cancel': function() { $(this).dialog('close');}};
			break;
		case "/individual/modals/privacy.jsp":
			params.title="Privacy Agreement";
			params.height=650;
			params.width=750;
			params.iframeScroll = 'auto';
			params.buttons= { 'Close': function() { $(this).dialog('close');}};
			break;
		case "/home/modals/email.jsp":
		case "/individual/modals/email.jsp":
			params.title="E-Mail A Friend";
			params.height=260;
			params.buttons= { 'Send Email':function() {
			 $('iframe[name=thisIframe]').contents().find('input#submit').click(); },
			 'Cancel': function() { $(this).dialog('close'); } };
			break;
		case "/home/modals/demographic.jsp":
		case "/individual/modals/demographic.jsp":
			params.title="Update My Information";
			params.height=350;
			params.width=450;
			params.buttons= { 'Update Info': function() {
			 $('iframe[name=thisIframe]').contents().find('input#getQuoteButton').click();},
			'Cancel': function() { $(this).dialog('close');}};
			params.iframeScroll = 'auto';
			break;
		case "/home/modals/resetpassword.jsp":
		case "/individual/modals/resetpassword.jsp":
			params.width=450;
			params.height=487;
			params.title="Reset Your Password";
			break;
		case "/home/modals/chat.jsp":  		
		case "/individual/modals/chat.jsp":  		
			params.title="Chat";
			params.height=150;
			params.width=300;
			params.buttons= { 'Submit Request' : function() {
			$('iframe[name=thisIframe]').contents().find('input#chat_submit').click();},
			'Close': function() { $(this).dialog('close'); } };
			break;
		case "/home/modals/advisor/startHere.html":
		case "/individual/modals/advisor/startHere.html":
			params.height=515;
			params.width=985;
			params.dialogClass="advisor";
			delete params.title;
			delete params.buttons;
			break;
		default:
			break;
		}
				
		return params;
} 

function demographics(zip, demographicString){
 	
	this.zipcode=zip;
	// The following parsing is based on how the demographic
	// cookie is parsed on the Java side.
	// NOTE: Always ensure this parsing matches the Java parsing
	var demographicsList = demographicString.split('|');
	this.ages = demographicsList[0].split('#');
	this.ages.pop(); // remove last element due to parsing issue
	this.genders = demographicsList[1].split('#');
	this.genders.pop(); // remove last element due to parsing issue
	this.relations = demographicsList[2].split('#');
	this.relations.pop(); // remove last element due to parsing issue
	this.smokers = demographicsList[3].split('#');
	this.smokers.pop(); // remove last element due to parsing issue
}

function writeSearchURL () {
	var providerlink;
	providerlink = $('a#networkDoctors').attr('href');
	$('a#search_provider_link').attr('href', providerlink);
}

// DLS: format currency
// to grab as int use:
// var something = parseFloat(formatPrice(something));
function formatPrice(num) {
	var y = num.replace(/[^0-9\.]+/g,"");
	return parseFloat(y);
}

// DLS: moved from product.js to global.js
function TRG_numbersOnly( thisString ) {
	return thisString.replace(/[^0-9]/g, "");
}

// SALO: determine to show oep message
function showOEP() {
	$("#getQuoteButton").click(function () {
     	//if($("#applicant1").length > 0){
		//	$.cookie("showOEP", "true", { path: '/' });
		//} else {
			$.cookie("showOEP", "false", { path: '/' });
		//}
    });
}

// SALO: show the producer opt-in message
function agentMessage() {
	var agentid = getUrlVars()["agentid"];
	var url = document.location.toString();
	if (typeof agentid == 'undefined'){
		// do nothing	
	}else if (url.match(/index.jsp/)){
		(agentid != '')?getProducer(agentid):'';
	} else {
		return false; // do nothing
	}
}

function getProducer(id) {
	$.ajax({
		url: "/producerContactService.do?agentid="+id+"",
		type: 'GET',
		dataType: 'xml',
		success: function(data){
			var producer = $.xml2json(data);
			var name = producer.name;
			var email = producer.email;
			var phone = producer.phone;
			var agency = producer.agency; // change this to producer.agency when xml is ready
			agency = (agency == "")?"":"with "+agency;
			var width = (producer.value == 'ERROR')?400:600;
			var height = (producer.value == 'ERROR')?300:400;
			$.colorbox({
				transition:'none', 
				speed:500,
				title:'Producer Notice',
				overlayClose: false,
				initialHeight:height,
				initialWidth:width,
				innerHeight:height,
				innerWidth:width,
				href:"/individual/producer-opt-in.jsp",
				open:true,
				onOpen:function(){  },
				onLoad:function(){  },
				onComplete:function(){ 
					bindButtons(producer.value);
					(producer.value == 'ERROR')?showError():showProducerInfo(name, email, phone, agency);
				 },
				onCleanup:function(){  },
				onClosed:function(){  }
			});
		}
	});
}

function showError() {
	$("#producerInfo").hide();
	$(".producerError").show();
}

function showProducerInfo(name, email, phone, agency) {
	$("#name").html(name);
	$("#email").html(email);
	$("#phoneno").html(phone);
	$("#agency").html(agency);
	$(".producerError").hide();
	$("#producerInfo").show();
}

function bindButtons(producer) {
	// @todo, can rewrite this when more permanent rules come in
	var ref = document.referrer;
	if (ref == '') {
		//alert('DEBUG: no history');
		// IF NO HISTORY
		$("#continue_btn").click(function () {
			//location.href = "http://www.regence.com";
			$.colorbox.close();
		});
		if (producer == 'ERROR'){
			$("#cboxClose").click(function () {
				location.href = (pCode == 'AS')?"http://asuris.com":"http://www.regence.com";
			});
		} else {
			$("#cboxClose").click(function () {
				location.href = (pCode == 'AS')?"http://asuris.com":"http://www.regence.com";
			});
		}
		$("#continue_btn_error").click(function () {
			location.href = (pCode == 'AS')?"http://asuris.com":"http://www.regence.com";
		});
	} else {
		// IF HISTORY PRESENT
		//alert('DEBUG: history '+ref);
		$("#continue_btn").click(function () {$.colorbox.close();});
		if (producer == 'ERROR'){
			$("#cboxClose").click(function () {
				location.href = ref;
			});
		} else {
			$("#cboxClose").click(function () {
				location.href = ref;
			});
		}
		$("#continue_btn_error").click(function () {
			location.href = ref;
		});
	}
}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
		if (hash[0].toLowerCase() == 'agentid') { hash[0] = 'agentid'; }
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}


// SALO: short term coverage
function showShortTerm() {
	var url = document.location.toString();
	var title = $("#short_term").attr('title');
	var open = (url.match(/#shortTerm/)) ? true : false;
	var openDialog = $("#short_term").dialog({
		autoOpen:open,
		width:535,
		height:275,
		modal:true,
		title:title,
		buttons: { "Continue": function() { parent.location.href = "https://secure.regencelife.com/section.cfm?wSectionID=30" } }
	});
	(url.match(/#shortTerm/)) ? openDialog : "";
}

// IDAHO under 19 stand alone messaging
function idahoHSA(url) {
	$.colorbox({
		transition:'none', 
		speed:500,
		title:'IDAHO under 19 applicant',
		overlayClose: false,
		initialHeight:400,
		initialWidth:400,
		innerHeight:400,
		innerWidth:400,
		href:"/individual/idahoHSA-message.jsp",
		open:true,
		onOpen:function(){  },
		onLoad:function(){  },
		onComplete:function(){ 
			buttonConfig(url);
			$.cookie("PLANCODE", "ID", {path: '/', expires: 0} );
		 },
		onCleanup:function(){  },
		onClosed:function(){  }
	});
}

function buttonConfig(url) {
	$("#continue_btn").click(function () {
		if(demomodal == true){
			parent.location.href = url;
		} else {
			location.href = url;
		}
	});
}

function modalMessage(arr) {
	// define defualts
	var url = arr['url'];
	var file = arr['file'];
	var title = arr['title'];
	$.colorbox({
		transition:'fade',
		speed:200,
		title:title,
		width:670,
		height:500,
		href:"/individual/"+file,
		scrolling: false,
		overlayClose: false,
		onComplete:function () {
			$(".cancel").click(function () {
				$.colorbox.close();
			});
			($("#mainText").length == 0)?"":scrollBottom("#mainText");
			// bind button
			$("#btnContinue").attr("href", url);
		}
	});
	
	// HACK until I can move the edit information modal into colorbox	
	$.cookie('showrbsoep', 'false', { path: "/" });
	
	function scrollBottom(elem) {
		var elem = $(elem);
		var padding = elem.padding().top + elem.padding().bottom;
		elem.scroll(function () {
			if(elem.scrollTop() == elem[0].scrollHeight - elem.height() - padding ) {
				$("#button-transparent").remove();
			}
		});
	}
}

function linkRBSOEP() {
	$(".info").click(function () {
		var url = window.location.pathname;
		modalMessage({
			url:url,
			file:"information_modal.jsp",
			title:"Important Information for Applicants Under 19"
		})
	});
}


$(document).ready(function(){ 
	// HACK until I can move the edit information modal into colorbox
	($.cookie('showrbsoep') == 'true')?showRBSOEP():"";
	function showRBSOEP() {
		var url = $.cookie('oepURL');
		modalMessage({
			url:url,
			file:"information_modal.jsp",
			title:"Important Information for Applicants Under 19"
		});
	}
	
	linkRBSOEP();
	
	
	
	$.ajaxSetup ({cache: false}); 
	agentMessage();
	showShortTerm();
	showOEP();

	writeSearchURL();
	
	$(".validateMe").each(function () {  					
 		var idString;
		idString =  $(this).attr("id");
		
		// 2009.10.06 KJD: Ok, if we're going to do it this way, skip this one
		if( idString != 'getQuoteForm' )	{		$("#"+idString).validate();	}
		
		//TODO: Place on page and modal
		$(this).prepend("<div class='formErrors'>Form Errors:<br /><div class='errorIds' ><span style='color:red;'></span></div></div>");	
		$(this).prepend("<div class='formWarning'></div>");			   	
     });

	$.ui.dialog.defaults.bgiframe = true;

	// 2009.10.06 KJD: Added for zip validation
	if(jQuery().validate){
	$('#getQuoteForm')
		.validate({
			onsubmit: true,
			onfocusout: false,
			onkeyup: false,
			onclick: false,
			//errorElement: "div",
        	//wrapper: "div",  // a wrapper around the error message
        	errorPlacement: function(error, element) {
        	//$(".formWarning").remove();
            //offset = element.offset();
            error.appendTo(".formErrors");
            // error.insertBefore(".formErrors");
            error.addClass('errorMessage');  // add a class to the wrapper
            // error.css('display', 'none');
        },

			submitHandler: function(form)
			{		 
				// Show the spinner
				
				$("#getQuoteForm").attr('style','visibility:hidden').after('<div class="spinner" style="margin:-200px 0 0 200px;position:absolute;"></div>');
				
				// 2009.10.08 KJD: Ajax validation of zip
				$.ajax({
					   type: "POST",
					   url: "/planCodeService.do",
					   data: "zip=" + $("#ZipCode").val(),
					   success: function( xmlDoc )
					   {
						 $(xmlDoc).find("plancode").each(function()
						 {
						 	var planValue = $( this ).attr( 'value' );
						 	var planArea = $( this ).attr( 'area' );
						 	//alert(planValue);
						 	var quoteAgeAllowed;
						 	quoteAgeAllowed = true;
						 	
						 	// IDAHO applicants temp not availalbe online
						 	//if( $( this ).attr( 'value' ) == 'ID') {
							//	$(".formErrors")
							//		.replaceWith( "<div class='formErrors' style='display: block;'>Placeholder text for Idaho outage</div>" )
							//		.show( 500 );
							//	$("#getQuoteForm").removeAttr('style');
							//	$('.spinner').remove();
							//	
							//	return false;
							//}
						 	
						 	// DLS: Check if values are not empty or == ERROR
						 	if( $( this ).attr( 'value' ) == '' || $( this ).attr( 'value' ) == 'ERROR' ) {
								$(".formErrors")
									.replaceWith( "<div class='formErrors' style='display: block;'>Form Errors:<br>Sorry, this zip code is outside of our service area</div>" )
									.show( 500 );
								$("#getQuoteForm").removeAttr('style');
								$('.spinner').remove();
								
								return false;
							}
							
							if ( pCode == 'AS' && planValue != 'ASURIS'){
								$(".formErrors")
									.replaceWith("<div class='formErrors' style='display: block;'>Form Errors:<br>Sorry, that zip code is outside of our service area.  You can apply online for coverage through our affiliate, <a href='http://www.regence.com/individual/medical/index.jsp' target='_blank'>Regence BlueShield</a>.</div>")
					  				.show( 500 );
					  				$("#getQuoteForm").removeAttr('style');
					  				$(".spinner").remove();
					  				return false;
					  	
				  			} 
				  			
				  			if ( pCode != 'AS' && planValue == 'ASURIS'){
				  				$(".formErrors")
									.replaceWith("<div class='formErrors' style='display: block;'>Form Errors:<br>Sorry, that zip code is outside of our service area.  You can apply online for coverage through our affiliate, <a href='http://web.asuris.com/individual/medical/AS/index.jsp' target='_blank'>Asuris</a>.</div>")
					  				.show( 500 );
					  				$("#getQuoteForm").removeAttr('style');
					  				$(".spinner").remove();
					  				return false;
					  		}
							
							// DLS: 03.29.2010 Redirect for medicare applicants
							var agemax = $('input#age0').val();
							redirectMedicareApplicant(agemax);
							
							function redirectMedicareApplicant(age){
								if ( age >= 65){
									var errorMessageAge;
									// DLS: set zip cookie to carry over to medicare
									var zip = $( '#ZipCode' ).val();
									setZipCookie(zip);
									if(planValue == 'ASURIS'){
										errorMessageAge = "<div class='formErrors' style='display: block;'>Form Errors:<br>Our individual health plans only cover applicants under the age of 65. If you are applying for coverage for yourself, please visit our <a href='http://asuris.com/needCoverage/medicare/' target='_blank'>Medicare page</a> to learn about your coverage options.</div>";
									} else {
										errorMessageAge = "<div class='formErrors' style='display: block;'>Form Errors:<br>Our individual health plans only cover applicants under the age of 65. If you are applying for coverage for yourself, please visit our <a href='/"+planValue+"/products/medicare/index.jsp' target='_blank'>Medicare page</a> to learn about your coverage options.</div>";
									}
									quoteAgeAllowed = false;
									$(".formErrors")
						 			.replaceWith( errorMessageAge )
									.show( 500 );
									$("#getQuoteForm").removeAttr('style');
									$('.spinner').remove();
								}
							}
							
							function setZipCookie(zip) {
								$.cookie("ZIP", zip, {path: '/', expires: 0} );
							}
							
							
							// 2009.12.08 DLS: Set age limits for each region
						 	// errorMessageAge in each condition for seperate wording for each region
						 	if( planValue == 'ASURIS' ) {
						 		// AS age limit
						 		var agelimit = 26;
						 		var errorMessageAge = "<div class='formErrors' style='display: block;'>Form Errors:<br> Dependents must be less than " + agelimit + " years old, except in the case of disability. If you would like to apply for coverage that includes a legally disabled dependent, call Asuris directly at 1-888-344-5593 or local 509-922-8072.</div>";
						 	} else if( planValue == 'OR' ) {
						 		// OR age limit
						 		var agelimit = 26;
						 		var errorMessageAge = "<div class='formErrors' style='display: block;'>Form Errors:<br> Dependents must be less than " + agelimit + " years old, except in the case of disability. If you would like to apply for coverage that includes a legally disabled dependent, call Regence directly at 888-734-3623.</div>";
						 	} else if( planValue == 'UT' ) {
						 		// UT age limit
						 		//var agelimit = 26;
						 		//var errorMessageAge = "<div class='formErrors' style='display: block;'>Form Errors:<br> Dependents must be less than " + agelimit + " years old, except in the case of disability. If you would like to apply for coverage that includes a legally disabled dependent, call Regence directly at 888-734-3623.</div>";
						 	} else {
						 		// Set Default
						 		var agelimit = 26;
						 		var errorMessageAge = "<div class='formErrors' style='display: block;'>Form Errors:<br> Dependents must be less than " + agelimit + " years old, except in the case of disability. If you would like to apply for coverage that includes a legally disabled dependent, call Regence directly at 888-734-3623.</div>";
						  	}
						  	
						  	$('input.plancode').each(function(){
						  		if(planValue == 'ASURIS'){
						  			$(this).val('asuris');
						  			
						  		} else {
						  			$(this).val('non-asuris');
						  		}
						  	});
						 	
						 	// 2010.01.11 DLS: Validation for zip code and dependent age
						 	function validateDependentAge(recipient, age){
						 		if( recipient == 'd' && age >= agelimit ){
						 			quoteAgeAllowed = false;
						 			errorDependentAge();
									return false;
						 		} else {
						 			quoteAgeAllowed = true;
						 			//alert(quoteAgeAllowed);
						 		}
						 	}
						 	
						 	function errorDependentAge(){
						 		//alert(errorMessageAge);
						 		$(".formErrors")
						 			.replaceWith( errorMessageAge )
									.show( 500 );
									$("#getQuoteForm").removeAttr('style');
									$('.spinner').remove();
							}
						 	
						 	// IDAHO under 19, colorbox to inform applicant they may only apply for HSA $3500
						 	if (planValue == 'ID' && $('#age0').val() < 19 && $('.addedApplicant').length == 0){
						 		var zip = $("#ZipCode").val();
						 		var age = $('#age0').val();
						 		var gender = $('#gender0').val();
						 		var tab = $('#tobacco0').attr( 'checked' );
						 		var urlId = "/viewProduct.do?zip="+zip+"&t0="+tab+"&g0="+gender+"&a0="+age+"&r0=s&id=01t400000013smgAAA";
						 		idahoHSA(urlId);
						 		$('.spinner').remove();
						 		$("#getQuoteForm").removeAttr('style');
						 		quoteAgeAllowed = false;
						 		return false;
						 	}
							
							if( $('select#relationship1').val() == 'd'){
						 		var recipient = 'd';
						 		var age = $('input#age1').val();
						 		validateDependentAge(recipient, age);
						 	}
						 	
						 	$('div.dependent').each(function (i) {
						 		var recipient = 'd';
						 		var age;
						 		var min = 2;
						 		var id = min + i;
						 		age = $('input#age'+id).val();
								validateDependentAge(recipient, age);
						 	});
						 	
						 	// 2010.08.26 SALO: Adding to the chaos that is this function
						  	// Temp to disallow applicants to apply at specified age
						  	$("input.quoteAge").each(function () {
								var inputAge = $(this).val();
								if ( inputAge < 19){
									
									// separate subscriber vs dependent
									var parentID = $(this).parent().attr('id');
									var regionName;
									var phoneNo;
									var eMessage;
									// SALO: when will this ever be global, no one knows... no one knows...
									// get plan name and phone number for Regence/Asuris
									if ( planValue == 'ASURIS' ){ regionName = 'Asuris'; phoneNo = '1 (866) 704-2708';} else { regionName = 'Regence'; phoneNo = '1 (888) 734-3623'; }
									
									
									if ( planValue == 'OR' && planArea != 'clark_co'){
										
										if ( parentID == 'applicant0') {
											// main applicant
											//eMessage = "<div class='formWarning' style='display: block;'>Regence is no longer accepting applications for individual coverage from applicants under 19 years of age. For more information or to see if you qualify for an exemption to this rule, please call our Sales department toll-free at 1 (888) 734-3623.</div>";
											//$(".formWarning")
											//.show( 500 )
											//.replaceWith( eMessage );
											//$("#getQuoteForm").removeAttr('style');
											//$('.spinner').remove();
											//quoteAgeAllowed = false;
											//return false;
										} else {
											//eMessage = "<div class='formWarning' style='display:block;'><b>You may enroll eligible family members who are under age 19 at the open enrollment period defined in state or federal law.  The annual enrollment periods are currently </b>February 1st<b> through </b>February 28th<b> each year for an effective date of </b>March 1st<b> and </b>August 1st<b> through </b>August 31st<b> each year for an effective date of </b>September 1st<b>.  For more information or to see if there are exceptions to this open enrollment period for which you may qualify, please contact your Producer or call our Sales department toll-free at 1-888-REGENCE.</b></div>";
											//$(".formWarning")
											//.show( 500 )
											//.replaceWith( eMessage );
											//$("#getQuoteForm").removeAttr('style');
											//$('.spinner').remove();
											//quoteAgeAllowed = false;
											//return false;
										}
									} else if ( planValue == 'UT' ){
										if ( parentID == 'applicant0' || $('#age0').val() < 19) {
											$.cookie("uhipMessage", "true", { path: '/' });
										} else {
											$.cookie("uhipMessage", "false", { path: '/' });
										}	
									} else if (planValue == 'WARBS' || planArea == 'clark_co' || planValue == 'ASURIS') {
										//$.cookie("showOEP", "true", { path: '/' });	
										// 2011.06.29 SALO: Remove blocking under 19 applicants, show limitions in colorbox message
										if ( parentID == 'applicant0') {
											// main applicant
											//eMessage = "<div class='formWarning' style='display: block;'><b>Applicants and family members who are under age 19 may enroll during the open enrollment period defined by state or federal law.  The open enrollment periods are </b>March 15, 2011<b> through </b>April 30, 2011<b> and </b>September 15, 2011<b> through </b>October 31, 2011.<b>  For more information or to see if there are exceptions to this open enrollment period for which you may be qualified, please contact your agent or call our Sales department toll-free at "+phoneNo+".</b></div>";
											//$(".formWarning")
											//.show( 500 )
											//.replaceWith( eMessage );
											(demomodal == true)?backToIndex():messaging();
											quoteAgeAllowed = false;
											return false;
										} else {
											//eMessage = "<div class='formWarning' style='display: block;'><b>Applicants and family members who are under age 19 may enroll during the open enrollment period defined by state or federal law.  The open enrollment periods are </b>March 15, 2011<b> through </b>April 30, 2011<b> and </b>September 15, 2011<b> through </b>October 31, 2011.<b>  For more information or to see if there are exceptions to this open enrollment period for which you may be qualified, please contact your agent or call our Sales department toll-free at "+phoneNo+".</b></div>";
											//$(".formWarning")
											//.show( 500 )
											//.replaceWith( eMessage );
											(demomodal == true)?backToIndex():messaging();
											quoteAgeAllowed = false;
											return false;
										}
									
										
									} else {
										// do nothing
									}
									
								}
							});
							
							// Hack for the modal until I can get it over to colorbox - messaging(); and backToIndex();
							function messaging() {
								$("#getQuoteForm").removeAttr('style');
								$('.spinner').remove();
								var url = "/listPlans.do?" + $("#getQuoteForm").serialize();
								modalMessage({
									url:url,
									file:"information_modal.jsp",
									title:"Important Information for Applicants Under 19"
								});
							}
							
							function backToIndex() {
								// set cookie
								var url = "/listPlans.do?";
								var formValues	= $("#getQuoteForm").serialize();
								$.cookie('showrbsoep', 'true', { path: "/" });
								$.cookie('oepURL', url+formValues, { path: "/" });
								// kick back to index
								parent.window.location = "/individual/medical/index.jsp";
							}
							
							var whereFrom = document.referrer;
							
						 	if( quoteAgeAllowed == true ){ 
							
								var cookieString = "{'zip':'" + $( '#ZipCode' ).val() + "','age0':'" + $( '#age0' ).val() + "','gender0':'" + $( '#gender0' ).val() + "','tobacco0':" + $( '#tobacco0' ).attr( 'checked' ) + "}";
								if(demomodal == true){
									// remember me is not currently an option in the demographic modal
								} else {
								$.cookie("rememberMe", ( ($( '#rememberMe' ).attr( 'checked' ))?cookieString:null ) );
								}
								// 2009.10.12 KJD: Everything looks good, so create the url based on entries
								// 2010.01.14 DLS: If demomodal is true then needs to be sent to parent
								if(demomodal == true && whereFrom.indexOf("listPlans.do") > -1) {
									parent.location.href	= "/listPlans.do?" + $("#getQuoteForm").serialize();
								} else if(demomodal == true && whereFrom.indexOf("listProducts.do") > -1) {
									parent.location.href = "/updateDemographics.do?" + $("#getQuoteForm").serialize();
								} else if(demomodal == true && whereFrom.indexOf("/updateDemographics.do") > -1){
								    parent.location.href = "/updateDemographics.do?" + $("#getQuoteForm").serialize();
								} else if(demomodal == true && whereFrom.indexOf("/plan-finder.jsp") > -1){
								    location.href = "/updateDemographics.do?" + $("#getQuoteForm").serialize();
								} else if(demomodal == true && whereFrom.indexOf("/cost-calculator.jsp") > -1){
									location.href = "/updateDemographics.do?" + $("#getQuoteForm").serialize();
								} else if(demomodal == true && whereFrom.indexOf("/viewProduct.do") > -1){
								    parent.location.href = "/updateDemographics.do?" + $("#getQuoteForm").serialize();
								} else if(demomodal == true && whereFrom.indexOf("/comparison.jsp") > -1){
								    parent.location.href = "/listPlans.do?" + $("#getQuoteForm").serialize();
								}
								else {
									location.href	= "/listPlans.do?" + $("#getQuoteForm").serialize();
								}
								//return false;
							}
						 });
				   
					   }
				});
			}
		});
	}	
		
	$("#getQuoteForm > div:nth-child(even)").addClass("odd");
	$("#getQuoteForm > div:nth-child(odd)").addClass("even");
						   
						   
	$("#nav-primary li").hoverClass("sfhover");
	$("#nav-plans > li a").append('<span class="ui-icon-triangle-1-s ui-icon"></span>')
	$("#nav-plans li").hoverClass("sfhover");
	
	//tried using fillSpace but it added scrollbar
	$(".accordion").accordion({animated:false,autoHeight:true});
	$('#care-packages > ul li:first-child').addClass('first');
	
	$("ul.rightMenu li:first-child").addClass('first');
	
	$('ul[class^=tabs]').parent().tabs();
	//nth-child index is one, not zero based
	$("#inner-tabs tr:nth-child(even)").addClass("odd");
	$("#inner-tabs tr:nth-child(odd)").addClass("even");
	$('#expandedCart tr:nth-child(even)').find('td').addClass("alt");
	$('div[class*=truncate]').each(function(){
		$(this).truncate();
	});
	
	var n = $('#deductibles div').length;
	c = 'd'+n;
	$("#deductibles").attr("class",c);
    //parseQueryString(window.location.search.toString());
	$(".box").wrapInner('<div class="l"><div class="r"><div class="inner"></div></div></div>').prepend('<div class="t"><div>').append('<div class="b"><div>');
	//initialize tips
	$("#overview #coverage td a").each(function(){
	 	var t = $(this).attr('title');
		$(this).attr('title','Click to explain this term');
		$(this).parent().parent().after('<tr class="termHelp hidden '+$(this).parent().parent().attr('class')+'"><td colspan="2"><div><div>'+t)
	});
	// toggle tips - individual
	$("#overview #coverage td a").click(function(){
		$(this).parent().parent().toggleClass('open');
		$(this).parent().parent().next().toggleClass('open').toggle();
	});
	// toggle tips - all
	$('#overview #explain').click(function(){
		var innerH = $(this).find('a').html();
		if (innerH == 'Explain these terms') {
			$('#coverage .termHelp').show();
			$('#coverage tr').addClass('open');
			$(this).find('a').html('Hide explanations')
		} else {
			$('#coverage .termHelp').hide();
			$('#coverage tr').removeClass('open');
			$(this).find('a').html('Explain these terms')
		}
		$(this).find('span').toggleClass('ui-icon-circlesmall-plus').toggleClass('ui-icon-circlesmall-minus');
	});
	$('#editDemo a').click(function(){
		$(this).prev().toggleClass("ui-icon-triangle-1-e").toggleClass("ui-icon-triangle-1-s");
		$(this).parent().next().toggle();
	});
	$('#toggleDependents a').click(function(){
		$(this).prev().toggleClass("ui-icon-triangle-1-e").toggleClass("ui-icon-triangle-1-s");
		$(this).parent().next().toggle();
	});
	
	$('#addApplicant').click(function(){
				var i = $('#applicants div');
				i = i.index($('#applicants div:last'))+1;
				var applicount;
				applicount = i+1;
	
				var iMinus = i - 1;
				
					if (i < 10) {
								if (i==1){
								  	$("#applicant" + iMinus).after("<div id='applicant"+ i +"' class='addedApplicant'><select name='r"+i+"' id='relationship"+i+"' class='quoteRelationship'><option value='p'>Spouse</option><option value='o'>Domestic Partner</option><option value='d'>Dependent</option></select>\n<input name='a"+ i +"' id='age"+ i +"' type='text' class='required digits text-field quoteAge' minlength='1' maxlength='2'  min='0' title='Age Of Applicant " + applicount + "'/>\n<select name='g"+ i +"' id='gender"+ i +"' class='required quoteGender' title='Gender Of Applicant " + applicount + "'>\n<option value=''></option><option value='f'>Female</option><option value='m'>Male</option></select>\n<input name='t"+ i +"' id='tobacco"+ i +"' type='checkbox' value='on' class='quoteTobacco' />\n<a id='removeApplicant"+ i +"' href='javascript:removeApplicant("+ i +")'>[x]</a></div>");
								}else{
									$("#applicant" + iMinus).after("<div id='applicant"+ i +"' class='addedApplicant dependent'><label name='r"+i+"' id='relationship"+i+"' class='quoteRelationship'>Dependant</label><input type='hidden' value='d' name='r"+i+"' class='hidden'/>\n<input name='a"+ i +"' id='age"+ i +"' class='required digits text-field quoteAge' minlength='1' maxlength='2'  min='0' title='Age Of Applicant " + applicount + "'/>\n<select name='g"+ i +"' id='gender"+ i +"' class='required quoteGender' title='Gender Of Applicant " + applicount + "'>\n<option value=''></option><option value='f'>Female</option><option value='m'>Male</option></select>\n<input name='t"+ i +"' id='tobacco"+ i +"' type='checkbox' value='true' class='quoteTobacco' />\n<a id='removeApplicant"+ i +"' href='javascript:removeApplicant("+ i +")'>[x]</a></div>"); 
								}
						
						} 
						else {
							
							alert('You can only add 10 applicants');
		
						}
				
			});
		
	// 2009.10.14 KJD: Get/set values for remember me checkbox
	$( '#rememberMe' )
		.each(function(){
			
			$( this ).attr( 'checked',$.cookie("rememberMe") );
		
			
			
			
			if( $.cookie("rememberMe") )
			{
				var cookieVals = eval( "(" + $.cookie("rememberMe") + ")" );
				// 2010.01.13 DLS: Ug!, we only use this to set the zip, the rest is being populated by the DEMOGRAPHICS coookie.
				$( '#ZipCode' 	).val( cookieVals['zip'] );
				// $( '#age0' 		).val( cookieVals['age0'] );
				// $( '#gender0' 	).val( cookieVals['gender0'] );
				// $( '#tobacco0' 	).attr( 'checked', cookieVals['tobacco0'] );
			}
		});
});

function setPlancodeCookie(region) {
	$.cookie('PLANCODE', ( region ), {path: '/', expires: 30});
}


function modalFunction(){
	
	var i = $('.modal-window .selfGuided .getQuote .getQuoteForm div .applicants div');
				
				i = i.index($('.modal-window .selfGuided .getQuote .getQuoteForm div .applicants div:last'))+1;
				var applicount;
				applicount = i
				var iMinus = i - 1
				
					if (i < 10) {
						
						$(".modal-window .selfGuided .getQuote .getQuoteForm div .applicants .applicant" + iMinus).after("<div id='applicant"+ i +"'><span>Applicant</span>\n<input name='age"+ i +"' id='age"+ i +"' type='text' class='text-field quoteAge' title='Age Of Applicant " + applicount +"/>\n<select name='gender"+ i +"' id='gender"+ i +"' class='quoteGender'>\n<option value='none'></option><option value='Female'>Female</option><option value='Male'>Male</option></select>\n<input name='tobacco"+ i +"' id='tobacco"+ i +"' type='checkbox' value='true' class='quoteTobacco' />\n<a id='removeApplicant"+ i +"' href='javascript:removeApplicant("+ i +")'>Remove</a></div>");
						
					} else {
						
						alert('You can only add 10 applicants');
	
					}
	
	
	
}

function removeApplicant(indexValue)
{ 
	$('#applicant' + indexValue).remove();
	$('#applicants div.addedApplicant').each(function(i){
		i=i+1;

		this.id = "applicant" + i;

		if ($(this).attr('class') != 'addedApplicant dependent') {
			$('#applicants div:eq('+i+') select:eq(0)').attr("id","relationship" + i);
			$('#applicants div:eq('+i+') select:eq(0)').attr("name","r" + i);
			$('#applicants div:eq('+i+') select:eq(1)').attr("id","gender" + i);
			$('#applicants div:eq('+i+') select:eq(1)').attr("name","g" + i);
			//$('#applicants div:eq('+i+') input:eq(0)').attr("name","r" + i);
			$('#applicants div:eq('+i+') input:eq(0)').attr("id","age" + i);
			$('#applicants div:eq('+i+') input:eq(0)').attr("name","a" + i);
			$('#applicants div:eq('+i+') input:eq(1)').attr("id","tobacco" + i);
			$('#applicants div:eq('+i+') input:eq(1)').attr("name","t" + i);
			$('#applicants div:eq('+i+') a').attr("id","removeApplicant"+i);
			$('#applicants div:eq('+i+') a').attr("href","javascript:removeApplicant("+ i +")");
		}

		if ($(this).attr('class') == 'addedApplicant dependent'){
			$('#applicants div:eq('+i+') label:eq(0)').attr("id","relationship" + i);
			$('#applicants div:eq('+i+') label:eq(0)').attr("name","r" + i);
			$('#applicants div:eq('+i+') select').attr("id","gender" + i);
			$('#applicants div:eq('+i+') select').attr("name","g" + i);
			$('#applicants div:eq('+i+') input:eq(0)').attr("name","r" + i);
			$('#applicants div:eq('+i+') input:eq(1)').attr("id","age" + i);
			$('#applicants div:eq('+i+') input:eq(1)').attr("name","a" + i);
			$('#applicants div:eq('+i+') input:eq(2)').attr("id","tobacco" + i);
			$('#applicants div:eq('+i+') input:eq(2)').attr("name","t" + i);
			$('#applicants div:eq('+i+') a').attr("id","removeApplicant"+i);
			$('#applicants div:eq('+i+') a').attr("href","javascript:removeApplicant("+ i +")");
		} 
	});
} 

// 2010.03.11 PJC functions to show session timout warning modal window
// Put StartSessionTimer(); in the document.ready to enable in a page

// this integer governs the appearance of the session timeout warning dialog
// 12 mins = 720000
var intitalTimeout = 720000;
// final timeout kicks session back to home 
// 2 mins = 120000
var finalTimeout = 120000;
// this is a numeric handle that is as part of the 'turn off the modal' processs
var timeoutHandle = 0;
// if all participating pages are using the same home page then you can set it here
// this establishes the scope for 
var homePage = "";


// starts the session time out timer and calls the first parameter when timeout occurs
function StartSessionTimer(){

    $("#sessionDialog").hide();
    $("#sessionDialog").dialog({ autoOpen: false, modal: true});
    timeoutHandle = setTimeout("ShowSessionTimeout()", intitalTimeout);

	// if the user hits the X then they go back to the main page
	$("#sessionDialog").bind('dialogclose', function(event, ui) {
	  window.location = homePage;
	});
    
}

// this is called by the timeout dialog in response to the user clicking the 
// continue with this session 
function ResetSession(){
    
	$("#resetButton").hide();
	$("#resetMessage").show();
	document.location = document.URL;
}

// clears the timeout and shows the modal dialog
// sets the final timer that goes back to the index page
function ShowSessionTimeout() {
    clearTimeout(timeoutHandle);
	$("#sessionDialog").show();	
	$("#sessionDialog").dialog("open");
	
	timeoutHandle = setTimeout("ResetToHome()", finalTimeout);
	$("#resetMessage").hide();
}

// set the home page navigation on the individual pages.
function ResetToHome(){
	document.location = homePage;
}

// 2009.10.13 KJD: Create the webTrend links.  Called from footer due to timing issues
// NB: Edits to this function need to be made to /individual/js/global.js also!
function TRG_setWebTrends()
{
	$('.webTrends').each(function(){

		// 2009.10.13 KJD: Create the absolute URL
		var strUrl	= $(this).attr('href');
		if(	( strUrl.length > 0 ) && ( "/" == strUrl.substr(0, 1) )	)	{	strUrl=window.location.protocol+"//" + window.location.host+strUrl;	}
		
		var relArray	= $( this ).attr( 'rel' );

		$( this )
			.attr({
				// 'href'		: strUrl,
				'onClick'	: "dcsMultiTrack('DCS.dcsuri','" + strUrl + "','WT.ti'," + ( ( relArray.indexOf( "'" ) > -1 )? relArray :"'" + relArray + "'" ) + ");"
			});
	});
}

// Jquery sizes

/*!
 * JSizes - JQuery plugin v0.33
 *
 * Licensed under the revised BSD License.
 * Copyright 2008-2010 Bram Stein
 * All rights reserved.
 */
/*global jQuery*/
(function ($) {
	var num = function (value) {
			return parseInt(value, 10) || 0;
		};

	/**
	 * Sets or gets the values for min-width, min-height, max-width
	 * and max-height.
	 */
	$.each(['min', 'max'], function (i, name) {
		$.fn[name + 'Size'] = function (value) {
			var width, height;
			if (value) {
				if (value.width !== undefined) {
					this.css(name + '-width', value.width);
				}
				if (value.height !== undefined) {
					this.css(name + '-height', value.height);
				}
				return this;
			}
			else {
				width = this.css(name + '-width');
				height = this.css(name + '-height');
				// Apparently:
				//  * Opera returns -1px instead of none
				//  * IE6 returns undefined instead of none
				return {'width': (name === 'max' && (width === undefined || width === 'none' || num(width) === -1) && Number.MAX_VALUE) || num(width), 
						'height': (name === 'max' && (height === undefined || height === 'none' || num(height) === -1) && Number.MAX_VALUE) || num(height)};
			}
		};
	});

	/**
	 * Returns whether or not an element is visible.
	 */
	$.fn.isVisible = function () {
		return this.is(':visible');
	};

	/**
	 * Sets or gets the values for border, margin and padding.
	 */
	$.each(['border', 'margin', 'padding'], function (i, name) {
		$.fn[name] = function (value) {
			if (value) {
				if (value.top !== undefined) {
					this.css(name + '-top' + (name === 'border' ? '-width' : ''), value.top);
				}
				if (value.bottom !== undefined) {
					this.css(name + '-bottom' + (name === 'border' ? '-width' : ''), value.bottom);
				}
				if (value.left !== undefined) {
					this.css(name + '-left' + (name === 'border' ? '-width' : ''), value.left);
				}
				if (value.right !== undefined) {
					this.css(name + '-right' + (name === 'border' ? '-width' : ''), value.right);
				}
				return this;
			}
			else {
				return {top: num(this.css(name + '-top' + (name === 'border' ? '-width' : ''))),
						bottom: num(this.css(name + '-bottom' + (name === 'border' ? '-width' : ''))),
						left: num(this.css(name + '-left' + (name === 'border' ? '-width' : ''))),
						right: num(this.css(name + '-right' + (name === 'border' ? '-width' : '')))};
			}
		};
	});
})(jQuery);


 
