// JavaScript Document

// >>>>>>> DEFAULTS <<<<<<<<<<<<<<<<<<<<

// NOTE - in the Document.ready() script, events MUST be assigned BEFORE any "set defaults" stuff gets called.
// This is because setdefaults may trigger an event in order to calculate initial dynamic values.

var baseURL = "/~/products/productdata.ashx";
var requestTracker = new Array();
	requestTracker['quote'] = false;
	requestTracker['shortContent'] = new Array;
	requestTracker['shortContent']['hospital'] = false;
	requestTracker['shortContent']['extras'] = false;
	requestTracker['shortContent']['benefit'] = false;
	requestTracker['longContent'] = false;

function populateDefaults(args)
{
	// populate form elements from dynamically written associative JS array called "defaults"
	$(args).each(function(){
		if($(".qq_" + this).attr("type") == "radio")
		{
			// for radio buttons, find element and set 'checked' (A similiar method will 
			// be needed if checkboxes are introduced later)
			$(".qq_" + this + ":[value='" + defaults[this] + "']").attr("checked", "checked");
			
			// raise the click event - data will have changed.
			// This is why you need to bind event listeners before calling this function.
			$(".qq_" + this + "[value='" + defaults[this] + "']").trigger("click");
			
		}else{
			
			// for everything else, set value
			$(".qq_" + this).val(defaults[this]);
		}
	});
	getNewPrice({});
}

function activateDefaultSideTab()
{
	$("#" + defaults['selectedItem']).trigger("click");
}


// >>>>>>> SET LISTENERS <<<<<<<<<<<<<<<<<<<<

function setPriceChangeEvent(args)
{
	// set event listeners for the price change
	// Note the IE hack. We must use the 'click event' for radio buttons 
	// in IE, because change does not register correctly for radio buttons, 
	// but we cannot use 'click' for select boxes, because the event would 
	// occur BEFORE the value has changed. Therefore  the click event is used 
	// for radio buttons in IE ONLY, and the change event is used otherwise.
	$(args).each(function(){
			$(".qq_" + this).bind(($.browser.msie && $(".qq_" + this).attr("type") == "radio")? "click" : "change", getNewPrice); 
	});
}

function setContentChangeEvent(args)
{
	// set event listeners for dynamically loaded content
	$(args).each(function(){
		$(".qq_" + this[0]).bind("click", {callData:this}, getNewContent); 
		$(".qq_" + this[0]).bind("click", {callData:this}, displayReferrerOffers); 
	});
}

function setSideTabActivation(args)
{
	// set event listeners for dynamically loaded content
	$(args).each(function(){
			$("#" + this).bind("click", {active:this, set:args}, showSideTab); 
	});
}	

function setTopTabActivation(args)
{
	// set event listeners for dynamically loaded content
	$(args).each(function(){
			//alert("bind - " + args);
			$(".qq_link_" + this).bind("click", {active:this, set:args}, showTopTab); 
	});
}

// >>>>>>> HANDLE LISTENERS <<<<<<<<<<<<<<<<<<<<

function showSideTab(event)
{

	//deactivate all tabs
	$(event.data.set).each(function(){
			$("#" + this).parent().parent().removeClass("productDetailsOptions_selected");
			$("#" + this).parent().parent().addClass("productDetailsOptions");					
	});
	
	// activate selected tab
	$("#" + event.data.active).parent().parent().removeClass("productDetailsOptions");
	$("#" + event.data.active).parent().parent().addClass("productDetailsOptions_selected");
	
	// force reload of main page content - it's changed.
	$(".qq_link_" + getSection()).trigger("click");
	
}

function showTopTab(event)
{
	// deactivate all tabs
	$(event.data.set).each(function(){
			$(".qq_link_" + this).parent().removeClass(this + "_selected");
			$(".qq_link_" + this).parent().addClass(this);					
	});
	
	// activate selected tab.
	$(".qq_link_" + event.data.active).parent().removeClass(event.data.active);
	$(".qq_link_" + event.data.active).parent().addClass(event.data.active + "_selected");
	
	// request new main tab content.
	changeMainContent(event.data.active, $("." + getProduct() +":checked").attr("name"), $("." + getProduct() +":checked").val());
}

function setBenefitShowHide(args)
{
	// set event listeners for dynamically loaded content
	$(args).each(function(){
			$("#" + this[0]).bind("click", {shown:this[1]}, showHideBenefits); 
	});
}

// >>>>>>> MAKE AJAX CALLS <<<<<<<<<<<<<<<<<<<<

function getNewPrice(event)
{
	// check for, and abort any existing request.
	if(requestTracker['quote'])
	{
		requestTracker['quote'].abort();
		requestTracker['quote'] = false
	}
	
	var qs;
	qs = "m=getQuote&h=" + $(".qq_hospital:checked").val()  + "&e=" + $(".qq_extras:checked").val()  + "&b=" + $(".qq_benefit:checked").val()  + "&s=" + $(".qq_state").val() + "&c=" + $(".qq_situation").val() + "&a=" + $(".qq_maxage").val();
	
	$(".qq_price").html("<img src='/images/spinnerPrice.gif' align='center'>");

	$('#futureRate').hide();
	
	requestTracker['quote'] = $.ajax({
		type: "GET",
		url: baseURL,
		data: qs,
		success: function(msg) {
			msg = msg + "";

			var currentRate = msg.split('|')[0];
			var qqWeeklyPrice = parseFloat(currentRate.substr(1, msg.length - 1));

			var futureRate = msg.split('|')[1];
			var futureWeeklyPrice = parseFloat(futureRate.substr(1, msg.length - 1));


			//populate qq_price
			var elementDuration = $("input:radio:checked.qq_duration ");

			// handle the duration for the quote (ie week, month, year)
			var strDuration = (elementDuration.val() + "").toLowerCase();

			var qqPrice;
			var futurePrice;

			if (strDuration == "month") {
				qqPrice = (qqWeeklyPrice * 52) / 12;
				futurePrice = (futureWeeklyPrice * 52) / 12;
			}
			else if (strDuration == "year") {
				qqPrice = (qqWeeklyPrice * 52);
				futurePrice = (futureWeeklyPrice * 52);
			}
			else {
				qqPrice = qqWeeklyPrice;
				futurePrice = futureWeeklyPrice;
			}


			var annualDiscount = "";

			// if they get a discount
			if (qq_isCombinationDiscountAvailable()) {
				$(".snippet").show();
				var nDiscountPercentage = qq_discountPercent();
				if (nDiscountPercentage > 0) {

					var dAnnualDiscount = (qqWeeklyPrice * 52) * (nDiscountPercentage / 100);
					annualDiscount = "$" + dAnnualDiscount.toFixed(2);

					var dDiscount = qqPrice * (nDiscountPercentage / 100);
					qqPrice = qqPrice - dDiscount;

					var futureDiscount = futurePrice * (nDiscountPercentage / 100);
					futurePrice = futurePrice - futureDiscount;
				}
			}
			else {
				$(".snippet").hide();
			}

			//populate price
			$(".qq_price").html("$" + qqPrice.toFixed(2));

			//populate annual discount
			$("#annualSaving").html(annualDiscount);

			//populate future rate
			$("#futureRate .quote").html("$" + futurePrice.toFixed(2));
			$('#futureRate').show();

			requestTracker['quote'] = false;
		}
	});
}

function getNewContent(event)
{
	// check for, and abort any existing request.
	if(requestTracker['shortContent'][event.data.callData[0]])
	{
		requestTracker['shortContent'][event.data.callData[0]].abort();
		requestTracker['shortContent'][event.data.callData[0]] = false
	}
	
	// request new dynamic content from the server (proxied through localhost for development)
	var qs = "m=" + event.data.callData[1] + "&p=" +event.data.callData[0]+ "&o="+$(event.target).val().toLowerCase()+"";
	var desc = $("." + event.data.callData[2]);
	
	// Set the loading spinner. Inactive spinner is only used on the details page
	// where the class is productDetailsOptions. the normal spinner is used in all other cases
	// ie - every prod box on first screen, active box on second screen
	if($("#qq_" + event.data.callData[0]).hasClass("productDetailsOptions"))
	{
		desc.html("<img src='/images/spinnerInactive.gif' align='center'>");
	}else{
		desc.html("<img src='/images/spinner.gif' align='center'>");
	}
	
	requestTracker['shortContent'][event.data.callData[0]] =  $.ajax({
									   type: "GET",
									   url: baseURL,
									   data: qs,
									   success: function(msg){
										   //alert(msg)
										 desc.html(msg);
										 try{
										 	requestTracker['shortContent'][event.data.callData[0]] = false;
										 }catch(err){/*drop IE6 jQuery scoping error quietly*/}
									   }
									 });
	
	// re-request the top tab section data - it's changed
	$(".qq_link_" + getSection()).trigger("click");
}


function changeMainContent(tab, product, option)
{
	var method;
	switch(tab.toString())
	{
	case 'productDetails':
		method = "GetDetail";
	break;
	case 'productSummary':
		method = "GetSummary"
	break;
	case 'termsConditions':
		method = "GetTC";
	break;
	default:
	}
	// check for, and abort any existing request.
	if(requestTracker['longContent'])
	{
		requestTracker['longContent'].abort();
		requestTracker['longContent'] = false
	}
	var qs = "m=" + method + "&p=" +product+ "&o=" + option;
	$(".mainframe").html("<img src='/images/spinner.gif' align='center'>");
	requestTracker['longContent'] =  $.ajax({
									   type: "GET",
									   url: baseURL,
									   data: qs,
									   success: function(msg){
										   //alert(msg)
										 $(".mainframe").html(msg);
										 requestTracker['longContent'] = false;
									   }
									 });
}

function showHideBenefits(event)
{
	if(event.data.shown)
	{
		$("#qq_benefit").show(500);
		/*
		$(".qq_benefit").removeAttr("disabled");
		$("#benefit_50percent_label").show()
		$("#benefit_80percent_label").show()
		*/
	}else{
		$("#qq_benefit").hide(1000);
		/*
		$(".qq_benefit").attr("disabled", "disabled");
		$("#benefit_50percent_label").hide()
		$("#benefit_80percent_label").hide()
		*/
	}
}

// >>>>>>> UTILITY FUNCTIONS <<<<<<<<<<<<<<<<<<<<

function getProduct()
{
	
	return $(".productDetailsOptions_selected").attr('id');
}

function getSection()
{
	var testarray = ["productSummary", "productDetails", "termsConditions"];
	var sel
	$(testarray).each(function(){
		if($("#tab_" + this).hasClass(this + "_selected")){sel =this;}
	});
	return(sel);
}

// ##### Original functions for radio button graphical effects.
//       Below code is purely display logic

function setSelectedRadioStyleForHospitalCover(selectedElement, callingElement)
{
	
	var arrHospitalCover = new Array('hospitalCover_noCover','hospitalCover_good','hospitalCover_better', 'hospitalCover_best');
	
	var i=0;

	for (i=0; i < arrHospitalCover.length; i++)
	{
		if ((arrHospitalCover[i] + "_label") != selectedElement)
		{
			//we can't set the background position to 0, this means that the hover won't work.  so let's just remove the inline styling.
			document.getElementById(arrHospitalCover[i] + "_label").style.cssText = '';
			//alert("calling element was not selected element")

		}
		else //set the backgroundPosition to the 'selected' position
		{
			if (callingElement == 'quickQuote') {
				document.getElementById(selectedElement).style.cssText = 'background-position: 0px -214px';
				//alert("quickquote was calling element - " + arrHospitalCover[i] + " - " + $("#" + arrHospitalCover[i]).attr("checked"));
				$("#" + arrHospitalCover[i]).attr("checked", "checked");
			}
			else { //callingElement == 'productDetails'
				document.getElementById(selectedElement).style.cssText = 'background-position: 0px -44px';
				//alert("quickquote was NOT calling element");
			}
		}
	}
	
}

function setSelectedRadioStyleForExtrasCover(selectedElement, callingElement)
{
	var arrExtrasCover = new Array('extrasCover_noExtras_label','extrasCover_some_label','extrasCover_lots_label');
	
	var i=0;

	for (i=0; i < arrExtrasCover.length; i++)
	{
		if (arrExtrasCover[i] != selectedElement)
		{
			//we can't set the background position to 0, this means that the hover won't work.  so let's just remove the inline styling.
			document.getElementById(arrExtrasCover[i]).style.cssText = '';
		}
		else //set the backgroundPosition to the 'selected' position
		{
			if (callingElement == 'quickQuote') {
				document.getElementById(selectedElement).style.cssText = 'background-position: 0px -214px';
			}
			else { //callingElement == 'productDetails'
				document.getElementById(selectedElement).style.cssText = 'background-position: 0px -44px';
			}
		}
	}
}

function setSelectedRadioStyleForBenefit(selectedElement, callingElement)
{
	var arrBenefit = new Array('benefit_50percent_label','benefit_80percent_label');
	
	var i=0;

	for (i=0; i < arrBenefit.length; i++)
	{
		if (arrBenefit[i] != selectedElement)
		{
			//we can't set the background position to 0, this means that the hover won't work.  so let's just remove the inline styling.
			document.getElementById(arrBenefit[i]).style.cssText = '';
		}
		else //set the backgroundPosition to the 'selected' position
		{
			if (callingElement == 'quickQuote') {
				document.getElementById(selectedElement).style.cssText = 'background-position: 0px -142px';
			}
			else { //callingElement == 'productDetails'
				document.getElementById(selectedElement).style.cssText = 'background-position: 0px -44px';
			}
		}
	}
}

function setSelectedRadioStyleForSortOfCover(selectedElement, callingElement)
{
	var arrSortOfCover = new Array('sortOfCover_singles_label','sortOfCover_couples_label','sortOfCover_family_label');
	
	var i=0;

	for (i=0; i < arrSortOfCover.length; i++)
	{
		if (arrSortOfCover[i] != selectedElement)
		{
			//we can't set the background position to 0, this means that the hover won't work.  so let's just remove the inline styling.
			document.getElementById(arrSortOfCover[i]).className = '';
		}
		else //set the backgroundPosition to the 'selected' position
		{
			if (callingElement == 'quickQuote') {
				document.getElementById(selectedElement).className = 'active';
			}
			else { //callingElement == 'productDetails'
				document.getElementById(selectedElement).className = '';
			}
		}
	}
}

// returns if this is a combination quote.  This is when they have selected both hospital and extras
function qq_isCombinationQuote()
{
    var strHospitalValue = $(".qq_hospital:checked").val().toLowerCase();
    var strExtrasValue = $(".qq_extras:checked").val().toLowerCase();
    
    var bHasHospital = (strHospitalValue == "good" || strHospitalValue == "better" || strHospitalValue == "best");
    var bHasExtras = (strExtrasValue == "some" || strExtrasValue == "themost");
    
    return (bHasHospital && bHasExtras);
}

function qq_isCombinationDiscountAvailable()
{
    return qq_isCombinationQuote() && qq_includeDiscount(); // under construction. make dynamic from sitecore
}

function qq_includeDiscount()
{
    return window.qq_valiable_includeDiscount === true;
}

function qq_discountPercent()
{
    var x = window.qq_valiable_discountPercent; 
    return (((typeof x) == "number") ? x : 0);
}

function quickQuoteSnippet_Goto()
{
    var url = "/QuickQuote/QuickQuoteRedirect.aspx";

    try
    {
        var state = $(".qq_state").val();
        var situation = $(".qq_situation").val();
        var age = $(".qq_maxage").val();
        url += "?state=" + state + "&situation=" + situation + "&age=" + age;
    }
    catch(ex)
    {
        alert(ex.message)
    }
    
    // redirect to the required page
    window.location.replace(url);
}

