// JavaScript Document

// ---------------- 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],30);
	}
	if (document.referrer != '') {
		var urlDomain = document.referrer.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 "/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);
}

$(document).ready(function(){ 

	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();	}
		
		// 2009.10.06 KJD: AH! Really?!, why isn't this just added to the page?
		$(this).prepend("<div class='formErrors'>Form Errors:<br /><div class='errorIds' ><span style='color:red;'></span></div></div>");				   	
     });

	$.ui.dialog.defaults.bgiframe = true;

	// 2009.10.06 KJD: Added for zip validation
	if(jQuery().validate){
	$("#getQuoteForm")
		.validate({
			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 quoteAgeAllowed;
						 	quoteAgeAllowed = true;
						 	
						 	
						 	// 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 = 25;
						 		var errorMessageAge = "<div class='formErrors' style='display: block;'> 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 = 23;
						 		var errorMessageAge = "<div class='formErrors' style='display: block;'> 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;'> 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 = 25;
						 		var errorMessageAge = "<div class='formErrors' style='display: block;'> 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.getPlanCode').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(){
						 		$(".formErrors")
						 			.replaceWith( errorMessageAge )
									.show( 500 );
									$("#getQuoteForm").removeAttr('style');
									$('.spinner').remove();
							}
						 	
						 	// Check if values are not empty or == ERROR
						 	if( $( this ).attr( 'value' ) == '' || $( this ).attr( 'value' ) == 'ERROR' ) {
								$(".formErrors")
									.replaceWith( "<div class='formErrors' style='display: block;'>Sorry, this zip code is outside of our service area</div>" )
									.show( 500 );
								$("#getQuoteForm").removeAttr('style');
								$('.spinner').remove();
								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);
						 	});
						 	
						 	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("/viewProduct.do") > -1){
								    parent.location.href = "/updateDemographics.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'>Dependant</option></select>\n<input name='a"+ i +"' id='age"+ i +"' type='text' class='required digits text-field quoteAge' minlength='1' maxlength='2'  min='0' max='64' 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' max='64' 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 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 +")");
		} 
	});
} 

// 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 + "'" ) + ");"
			});
	});
}


 