//http://www.adamcoulombe.info/lab/jquery/select-box/customSelect.jquery.js
(function($){
 $.fn.extend({
 
 	customStyle : function(options) {
	  if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
	  return this.each(function() {			
			var currentSelected = $(this).find('option:selected').text();
			$(this).after('<span class="customStyleSelectBox"><span class="customStyleSelectBoxInner">'+currentSelected+'</span></span>').css({position:'absolute', opacity:0,fontSize:$(this).next().css('font-size')});
			var selectBoxSpan = $(this).next();
			var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) -parseInt(selectBoxSpan.css('padding-right'));			
			//var selectBoxSpanInner = selectBoxSpan.find(':first-child');
			var selectBoxSpanInner = selectBoxSpan.find(':first-child');
			selectBoxSpan.css({display:'inline-block'});
			selectBoxSpanInner.css({width:selectBoxWidth, display:'inline-block'});
			var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
			$(this).height(selectBoxHeight).change(function(){
				selectBoxSpanInner.text($(this).find('option:selected').text()).parent().addClass('changed');
			});
			
	  });
	  }
	}
 });
})(jQuery);


/* custom script*/
$(document).ready(function(){
	//"top menu" right margin
	$("#nav-top li:last").addClass("last");

	//"select state" menu styling
	$('.styleBox').customStyle();
	
	//hilight the current page's nav label
	var thisNav = $('div#main').attr("class");
	$('li a[id='+thisNav+']').parent('li').addClass('at');

	//"select state" menu function - top, home
	$("#btn-state-selector a").click(function(e){
		e.preventDefault();
		var src = $("option:selected", "select.selectState").val();
		if(src != ""){
			if(src == "/aetna/online-quote-apply"){
				var expirationDate = { path: '/', expires: 30 };
				$.cookie("FORMATTEDSTATENAME", "Arizona", expirationDate);
				$.cookie("STATELIST", "arizona", expirationDate);
			}
			window.location = src;
		}
	});

	//"select state" menu function - bottom
	$("a#select-bottom").click(function(e){
		e.preventDefault();
		var src = $("option:selected", "select.selectState2").val();
		if(src != ""){
			if(src == "/aetna/online-quote-apply"){
				var expirationDate = { path: '/', expires: 30 };
				$.cookie("FORMATTEDSTATENAME", "Arizona", expirationDate);
				$.cookie("STATELIST", "arizona", expirationDate);
			}
			window.location = src;
		}
	});	

	//plan choice - header
	$(".choice-tool .left h2 a").click(function(e){
		e.preventDefault();
	}); 

	/*$("select.selectState").change(function() {
		var src = $("option:selected", this).val();
		window.location = src;
        var src = $("option:selected", this).val();
		var redirectionStates = new Array;
		redirectionStates = ["alabama", "hawaii", "idaho", "iowa", "Minnesota", "montana", "new-hampshire", "new-mexico", "north-dakota", "oregon", "puerto-rico", "rhode-island", "south-dakota", "utah", "vermont", "washington", "wisconsin"];	
		var redirect = -1;
		for (i = 0; i < redirectionStates.length;i++){
			checkString = src.indexOf(redirectionStates[i]);
			if(checkString >= 0){
				redirect = 1;
				break;
			}
		}
		
		if(redirect == 1){
			var url = src+"?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=360&width=630&modal=true";
			//var url = "04_ehealthmodal.html?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=360&width=630&modal=true";
			tb_show("Ehealth", url);	
		}else{
			window.location = src;
		}
	});*/
	
	//home image rotation
	var COOKIE_NAME = 'aetnaIVLHomeImage';
	var imgNum = 8;
    var options = { path: '/', expires: 30 };
	if ($("#content-home-learn-more").length){
		var ckvalue = $.cookie(COOKIE_NAME);
		if(ckvalue == null){
			$.cookie(COOKIE_NAME, 1, options);
		}else{
			ckvalue = parseInt(ckvalue) + 1;
			if(ckvalue == 9){
				ckvalue = 1;	
			}
			$.cookie(COOKIE_NAME, ckvalue, options);
			var imageName = 'home_rotate_'+ ckvalue +'.jpg';
			$('#content-home-learn-more').css({"background-image":"url(/images/"+imageName+")"});
		}
	}
	
	// Tabs
	if ($("#tabs").length){
		$('#tabs').tabs();
		/*for (var i = 1;i< 20;i++){
			$('#tabs'+i).tabs();
		}*/
	}
	// Accordion
	$('#accordion h3').next().css({"display":"none"});
	$('#accordion h3:first').not('#accordion.how-to-buy h3:first').addClass('active');
	$('#accordion h3:first').not('#accordion.how-to-buy h3:first').next().css({"display":"block"});

	$('#accordion h3').click(function(e){
		if($(this).is('.active')){
			e.preventDefault();
			$(this).next().slideUp('fast');
			$(this).removeClass('active');
			$(this).css({"background-position":"0px 0px"});
		}else{
			e.preventDefault();
			$(this).next().slideDown('fast');
			$(this).addClass('active');
			$(this).css({"background-position":"0px -48px"});
		}
	});

	//popup window
	$('a.simple').click(function(e) {
		e.preventDefault();
		var page = this.href;
		window.open(page, '_blank', 'width=800,height=600,location=no,scrollbars=yes,resizable=yes,menubar=yes,status=yes,toolbar=yes,titlebar=yes,left=0,top=0,screenX=0,screenY=0');
    });

	$('a.jellyvision').click(function(e) {
		e.preventDefault();
		var page = "/media/virtual-benefits-advisor.html";
		window.open(page, '_blank', 'width=935,height=575,location=no,scrollbars=no,resizable=no,menubar=no,status=no,toolbar=no,titlebar=no,left=0,top=0,screenX=0,screenY=0');
    });

	$('a[rel="external"]').click(function(e) {
        e.preventDefault();
		var page = this.href;
		window.open(page, '_blank', 'width=800,height=600,location=yes,scrollbars=yes,resizable=yes,menubar=yes,status=yes,toolbar=yes,titlebar=yes,left=0,top=0,screenX=0,screenY=0');
    });

	$('a[target="_blank"][rel!="external"]').click(function(e) {
        e.preventDefault();
		var page = this.href;
		window.open(page, '_blank', 'width=800,height=600,location=yes,scrollbars=yes,resizable=yes,menubar=yes,status=yes,toolbar=yes,titlebar=yes,left=0,top=0,screenX=0,screenY=0');
    });

	$('a[target="blank"]').click(function(e) {
        e.preventDefault();
		var page = this.href;
		window.open(page, '_blank', 'width=800,height=600,location=yes,scrollbars=yes,resizable=yes,menubar=yes,status=yes,toolbar=yes,titlebar=yes,left=0,top=0,screenX=0,screenY=0');
    });
	
	//contact us
	$('a[href="/aetna-insurance/contact-us"]').click(function(e) {
        e.preventDefault();
		var page = this.href;
		window.open(page, '_blank', 'width=800,height=600,location=yes,scrollbars=yes,resizable=yes,menubar=yes,status=yes,toolbar=yes,titlebar=yes,left=0,top=0,screenX=0,screenY=0');
    });

	//read more
	$('.plan-read-more').click(function(e){
		e.preventDefault();
		$(this).hide();
		$(this).next('div.plan-details-snippet').fadeIn();
	});

	//definition popup
	$(".definition-popup").click(function(e){
		e.preventDefault();
		$(this).blur();
		//set datafile url
		urlVar = $(this).attr("href");
		//set empty popwindow
		if($("body").find("div.definition-popup-window").length){
			$("body").find("div.definition-popup-window").remove();
		}
		$("body").prepend('<div class="definition-popup-window"><div id="close"><a href="#">Close</a></div><h2></h2><div class="definition-popup-content"><img src="/images/ajax-loader-green.gif" /></div></div>');
		windowBlock = $("body").find("div.definition-popup-window");
		h2Block = $("body").find("div.definition-popup-window h2");
		contentBlock = $("body").find("div.definition-popup-window div.definition-popup-content");
		
		if(e.pageX > ($(window).width())/2){
			var tPosX = e.pageX-340;
		}else{
			var tPosX = e.pageX+40;
		}
		var tPosY = e.pageY;
		windowBlock.css({left: tPosX, top: tPosY});
		windowBlock.css({display:"block"});

		// get data, populate window 
		$.getJSON(urlVar, function(json){
			h2Block.html(json.h2);
			contentBlock.html(json.content);
			var tPosY = e.pageY-windowBlock.height()+35;
			windowBlock.css({top:tPosY}); 
		});
		
		//bind close button event
		$("div.definition-popup-window #close a").bind('click', function(e){
			e.preventDefault();
			$(this).parent().closest("div.definition-popup-window").remove();
		});
		
	});

	//plan choice tool
	if ($("#choice-tool-form").length){
		
		/*---------------PLAN CHOICE TOOL FORM FUNCTIONALITY------------------------*/
		
		$(window).load(function() {
			$('input[name=choice]').attr('checked', false);
			/*$('input[name=choice]').next('span').removeClass('blue');
			$("span.feedback").hide();
			checkedNum = 0;
			$("#plan-choice-submit").attr('src', "/images/btn_form_submit_grey.gif");
			$("#plan-choice-submit").removeClass('active');
			
			$("div.choice-tool").show();
			$("div.choice-tool li").show();
			$(this).parent().hide();*/
		});


		//form box - open/close
		$('#btn-plan-choice-tool a').click(function(e){
			if($(this).is('.active')){
				e.preventDefault();
				$("#choice-tool-form-arrow").hide();
				$("#choice-tool-form").slideUp('fast');
				$(this).removeClass('active');
				
			}else{
				e.preventDefault();
				$("#choice-tool-form-arrow").show();
				$("#choice-tool-form").slideDown('fast');
				$(this).addClass('active');
			}
		});

		var checkedNum = 0;
		var planAndScore = new Array();

		//selected check box count, submit button color change
		$("input.plan-choice-check").click(function(e){
			$("span.feedback").hide();
			if($(this).next('span').is('.blue')) {
				$(this).next('span').removeClass('blue');
			}else{
				$(this).next('span').addClass('blue');
			}
			checkedNum = $("input.plan-choice-check:checked").length;
			if(checkedNum == 3){
				$("#plan-choice-submit").attr('src', "/images/btn_form_submit.gif");
				$("#plan-choice-submit").addClass('active');
				$("span.feedback-error").hide();
			}else{
				$("#plan-choice-submit").attr('src', "/images/btn_form_submit_grey.gif");
				$("#plan-choice-submit").removeClass('active');
			}
		});

		//reset
		$("#choice-tool-form-reset img").click(function(e){
			//test
			$("#test li").remove();
			//------
			$('input[name=choice]').attr('checked', false);
			$('input[name=choice]').next('span').removeClass('blue');
			$("span.feedback").hide();
			checkedNum = 0;
			$("#plan-choice-submit").attr('src', "/images/btn_form_submit_grey.gif");
			$("#plan-choice-submit").removeClass('active');
			
			$("div.choice-tool").show();
			$("div.choice-tool li").show();
			$(this).parent().hide();
		});


		//calc
		$("#plan-choice-submit").click(function(e){
				//dataFileVar = "popup_sample.cfm";
				dataFileVar = $(this).parent().attr("action");
				if(checkedNum == 3){
					//test
					$("#test li").remove();
					//------
					$("div.choice-tool").hide();
					$("div.choice-tool li").hide();
					
					selectedBox0 = $("input[name=choice]:checked").eq(0).val();
					selectedBox1 = $("input[name=choice]:checked").eq(1).val();
					selectedBox2 = $("input[name=choice]:checked").eq(2).val();
	
					$.getJSON(dataFileVar, function(json){
						//$.each(json,function(key,value){
						for(var i in json){
							//alert(json[i].name);
							//$("#test").append("<li><strong>" +i +":" + json[i].name + "</strong></li>");
							tempScore = 0;
							for(var j in json[i].scores){
								//$("#test").append("&nbsp;&nbsp;<li>" +j+":"+ json[i].scores[j] +"</li>");
								if(j == selectedBox0 || j == selectedBox1 || j == selectedBox2){
									//tweaking weight for HSA plans
									if(j == 5 && json[i].scores[j] == 10){
										tempScore += 100;
									}else{
										tempScore += parseInt(json[i].scores[j]);
									}
								}	
							}
							planAndScore[i] = new Array();
							planAndScore[i][0] = json[i].id;
							planAndScore[i][1] = json[i].name;
							planAndScore[i][2] = tempScore;
						 }
						
						planAndScore = xsort(planAndScore, 2,-1);
						
						displayCount = 0;					
						for(var i = 0;i < planAndScore.length ;i++){
							//test
							$("#test").append("<li>"+planAndScore[i][0]+":"+planAndScore[i][1]+"-><b>"+planAndScore[i][2]+"</b></li>");
							//-----
							if(planAndScore[i][2] == planAndScore[0][2]){
								$("li#"+planAndScore[i][1]).closest("div.choice-tool").fadeIn('medium');
								$("li#"+planAndScore[i][1]).fadeIn('medium');
								displayCount++;
							}							
						}

						// min 4 plans should be listed.
						if(displayCount < 4){
							var isHSASelected = 0;
							// check if the HSA box is selected.
							if (selectedBox2 == 5){
								isHSASelected = 1;
							}
							$("#test").append("isHSASelected:"+isHSASelected+"<br>second item:"+planAndScore[displayCount][2]);
							
							// additional logic - if the HSA box is selected, the additional plan(s) should also be HSA compatible. 
							if( isHSASelected == 0 || (isHSASelected == 1 && planAndScore[0][2] < 100) || (isHSASelected == 1 && planAndScore[displayCount][2] > 100)){
								$("#test").append("<br>here");
								for(var i = displayCount; i< planAndScore.length; i++){
									if(planAndScore[i][2] == planAndScore[displayCount][2]){
										$("li#"+planAndScore[i][1]).closest("div.choice-tool").fadeIn('medium');
										$("li#"+planAndScore[i][1]).fadeIn('medium');
										//displayCount++;
									}
								}
							}					
						}
						// min 4 plans should be listed.
						/*if(planAndScore.length >= 10){
							if(displayCount < 4){
								for(var i = displayCount;i < displayCount + (4-displayCount) ;i++){
									//if(planAndScore[i][2] == planAndScore[0][2]){
										$("li#"+planAndScore[i][0]).closest("div.choice-tool").fadeIn('medium');
										$("li#"+planAndScore[i][0]).fadeIn('medium');
										displayCount++;
									//}
								}						
							}
						}*/
						//alert(displayCount);
						$("span.feedback-error").hide();
						$("span.feedback").show();
						$("#choice-tool-form-reset").show();
						
					});
		
				}else{
					$("span.feedback-error").show();
				}
		});
		/*--------------------------------------------------------------------*/
	}

	/*Dental Benefit*/
	//read more
	$('a.read-more').click(function(e){
		e.preventDefault();
		$(this).hide();
		$(this).parent().next('div.snippet').fadeIn();
	});
	// Email Form Validation
	if ($("#email-form").length){
		$("#email-form").validationEngine()
	}

	//tabs - unfocus
	$("#tabs ul li a").click(function(e){
		$(this).blur();
	});

	//accordion - unfocus
	$("#accordion div h3 a").click(function(e){
		$(this).blur();
	});

	//plan choice tool button - unfocus
	$("#btn-plan-choice-tool a").click(function(e){
		$(this).blur();
	});


	/*Footerlink 1 & Dental Link substitution*/
	var stateckvalue = $.cookie("STATELIST");
	var newLinkIndex = -1;
	var newURL = "";
	var oldURL = "";

	if(stateckvalue != "" && stateckvalue != null){
		$("ul#footer-link-1 li a").click(function(e){
			//e.preventDefault();
			oldURL = $(this).attr("href"); 
			for (i=0;i< footerlinks1.length;i++){
				if(footerlinks1[i] == oldURL){			
					newLinkIndex = i;
					break;
				}
			}
			if(stateckvalue == "arizona"){
				newURL = statefooterlinksarizona[newLinkIndex];
			}else{
				newURL = statefooterlinks1[newLinkIndex];
			}
			if (newURL == undefined){
				window.location = oldURL
			}else{
				window.location = "/state/"+ stateckvalue + newURL;
			}
			return false;
		});

		//dental link
		$("a#dental").click(function(e){
			var stateCKValue = $.cookie('STATELIST');
			if(stateCKValue == 'alabama'
			|| stateCKValue == 'colorado' 
			|| stateCKValue == 'hawaii'
			|| stateCKValue == 'idaho'
			|| stateCKValue == 'iowa'
			|| stateCKValue == "massachusetts"
			|| stateCKValue == 'minnesota'
			|| stateCKValue == 'montana'
			|| stateCKValue == 'new-hampshire'
			|| stateCKValue == 'new-mexico'
			|| stateCKValue == 'north-dakota'
			|| stateCKValue == 'oregon'
			|| stateCKValue == 'puerto-rico'
			|| stateCKValue == 'rhode-island'
			|| stateCKValue == 'south-dakota'
			|| stateCKValue == 'utah'
			|| stateCKValue == 'vermont'
			|| stateCKValue == 'washington'
			|| stateCKValue == 'wisconsin'
			){
				window.location = "/state/"+stateCKValue+"/individual-health-insurance/redirect";
			}else if(stateCKValue == "new-york"
			|| stateCKValue == "maine"
			|| stateCKValue == "new-jersey"
			){
				window.location = "/state/"+stateCKValue+"/individual-health-insurance";
			}else{
				window.location = "/dental/plus-dental";
			}
			return false;
		});
	}

	/*print button*/
	$("a#util-print").click(function(e){
		e.preventDefault();
		window.print();
	});

	/*prevent cache for saved-quote-apply*/
	$("a[href='/aetna/saved-quote-apply']").click(function(e){
		e.preventDefault();
		var last = new Date().getTime();
		window.location = "/aetna/saved-quote-apply?ts="+last;
	});
	
	
	/*email form*/
	$("#email-form").hide();
	$("#form-intro").hide();
	$("img#prescreen-continue").click(function(e){
		var prescreenVar = $('input[name=prescreen-button]:checked').val();									  
		if(prescreenVar == 'prescreen-member'){
			window.location = 'https://member.aetna.com/Member_Public/contactUs.jsp';
		}else if(prescreenVar == 'prescreen-nonmember'){
			$("#prescreen").hide();
			$("#email-form").fadeIn('slow');
			$("#form-intro").fadeIn('slow');
		}else{
		}									  									  
		
	});
	
});

/*Sort Function*/
function xsort(sqs,col,order){
    //function for sorting a multi-dementional array
    //sqs: name of array
	//col: specify "n"th col for sorting
    //order:1=ascending、-1=descending
    sqs.sort(function(a,b){
        return((a[col]-b[col])*order);
    });
    return(sqs);
}


/*addthis*/
var addthis_options = 'delicious, digg, favorites, google, twitter, yahoobkm';
var addthis_offset_top = -16;
var addthis_offset_left = 14;
var addthis_header_color = "#666666";
var addthis_header_background = "#ffffff";
