var application = {};

function getNumFeatures() {
	var nc = application.checkboxes.length;
	
	var numChecked = 0;
	
	for (i=0; i < nc; i++) {
		if (application.checkboxes[i].checked) {
			numChecked++;
		}
	}
	
	return numChecked;
}

/** Returns Bell a-la-carte pricing based on features selected.
 */
function getIncrementalPricing(provider) {
	var price = 0;
	var nc = application.checkboxes.length;
	for (i=0; i < nc; i++) {
		if (application.checkboxes[i].checked) {
			//alert("Fetching config.bell.featuresIncremental[" + application.checkboxes[i].id + "]");
			price += config[provider].featuresIncremental[application.checkboxes[i].id]
		}
	}
	return price;
}

function getBellLD() {
	for (var key in config.bell.ld)
		if ($("bell_ld_" + key).checked)
			return key;
			
	return "unlimited";
}

function setDetailsLD(key) {
	var str = "";
	if (config.bell.ld[key].fee) {
		// Any fee is included in total price, so we have to separate them for details display.
		str += config.bell.ld[key].name + ": $";
		str += roundNumber(config.bell.ld[key].price - config.bell.ld[key].fee, 2, true);
		str += "<br />Monthly Service Fee: $" + config.bell.ld[key].fee;
	} else {
		var str = config.bell.ld[key].name + ": $" + roundNumber(config.bell.ld[key].price, 2, true);
	}
	
	$("bell_ld_details_lite").innerHTML = str;
	$("bell_ld_details_basic").innerHTML = str;
	$("bell_ld_details_choice").innerHTML = str;
}

function calculateBellPlans(numFeatures) {
	if (!numFeatures) {
		numFeatures = getNumFeatures();
	}

	// This way we can work on only the plans we need, but still
	// run the numbers through our lowest-price algorithm.
	var litePrice = 9999999;
	var basicPrice = 9999999;
	var choicePrice = 9999999;
	
	if (numFeatures == 0) {
		// Home Phone Lite plan.
		litePrice = config.bell.lite.basePrice;
	} else if (numFeatures == 1) {
		// Home Phone Lite plan + incremental price of feature
		litePrice = config.bell.lite.basePrice + getIncrementalPricing("bell");		
	} else if (numFeatures == 2) {
		if ($("call_waiting").checked && $("call_display").checked) {
			// Home Phone Basic plan.
			basicPrice = config.bell.basic.basePrice;
		} else {
			//   Home Phone Lite plan + incremental price of features
			litePrice = config.bell.lite.basePrice + getIncrementalPricing("bell");
			
			//   Home Phone Choice plan
			choicePrice = config.bell.choice.basePrice;
		}
	} else if (numFeatures == 6) {
		// Home Phone Choice plan + 6.95 (minimum a-la-carte pricing)
		choicePrice = config.bell.choice.basePrice + 6.95;
	} else {
		// Home Phone Choice plan
		choicePrice = config.bell.choice.basePrice;
	}

	if (litePrice < basicPrice) {
		finalPrice = litePrice;
		finalPlan = config.bell.lite;
	} else {
		finalPrice = basicPrice;
		finalPlan = config.bell.basic;
	}
	
	if (choicePrice <= finalPrice) {
		finalPrice = choicePrice;
		finalPlan = config.bell.choice;
	}
	
	var ldKey = getBellLD();
	
	finalPrice += config.bell.ld[ldKey].price;
	setDetailsLD(ldKey);
	
	return {
		"name": finalPlan.name,
		"price": roundNumber(finalPrice, 2, true),
		"keyword": finalPlan.keyword
	};

}

function calculateAliantPlans(numFeatures, province, rogersPlanKeyword) {
	if (!numFeatures) {
		numFeatures = getNumFeatures();
	}

	// This way we can work on only the plans we need, but still
	// run the numbers through our lowest-price algorithm.
	var basicPrice = 9999999;
	var regularPrice = 9999999;
	var localPrice = 9999999;
	
	if (rogersPlanKeyword == "extras")
		comparePlan = config.aliant[province].local;
	else
		comparePlan = config.aliant[province].regular;
		
	if (numFeatures == 0) {
		// Regular basic plan.
		basicPrice = config.aliant[province].basic.basePrice;
	} else if (numFeatures <= 2) {
		//   Basic plan + incremental price of features
		basicPrice = config.aliant[province].basic.basePrice + getIncrementalPricing("aliant");
		basicPrice += 12.50;	// extra long distance pricing to ensure a correct 
								// comparison with Rogers Classic plan

		regularPrice = config.aliant[province].regular.basePrice;
	} else if (numFeatures == 3) {
		regularPrice = config.aliant[province].regular.basePrice;
	} else {
		localPrice = config.aliant[province].local.basePrice
	}

	//alert("basicPrice: " + basePrice + ", comparePrice: " + comparePrice);

	if (basicPrice < regularPrice) {
		finalPrice = basicPrice;
		finalPlan = config.aliant[province].basic;
	} else {
		finalPrice = regularPrice;
		finalPlan = config.aliant[province].regular;
	}
	
	if (localPrice <= finalPrice) {
		finalPrice = localPrice;
		finalPlan = config.aliant[province].local;
	}
		
	return {
		"name": finalPlan.name,
		"price": roundNumber(finalPrice, 2, true),
		"keyword": finalPlan.keyword
	};
}

/** Find the difference between the two values, and rounds it to two decimal places.
 */
function fancyDiff(one, two) {
	var diff;
	
	if (one > two)
		diff = one - two;
	else
		diff = two - one;
	
	return roundNumber(diff, 2, true)
}

function setRogersPlanDisplay(plan) {
	$("recommend_basic").style.display = "none";
	$("recommend_classic").style.display = "none";
	$("recommend_extras").style.display = "none";

	if (plan == "classic") {
		$("recommend_classic").style.display = "block";
	} else if (plan == "extras") {
		$("recommend_extras").style.display = "block";
	} else {
		$("recommend_basic").style.display = "block";
	}
	
	$("current_rogers_plan").value = plan;
}


function updatePricing() {
	var numFeatures = getNumFeatures();

	if (numFeatures == 0) {
		if ($("bell_250_min_wrap").style.display == "none") {
			$("bell_250_min_wrap").style.display = "list-item";
			$("bell_ld_250min").checked = true;
		}
	} else {
		if ($("bell_ld_250min").checked)
			$("bell_ld_unlimited").checked = true;
		
		$("bell_250_min_wrap").style.display = "none";
	}

	var rogersPlan = calculateRogersPlans(numFeatures);

	setRogersPlanDisplay(rogersPlan.keyword);
	
	// Adjust for differences in regional 911 fees.
	var region = getRegion();
	if (region != "on") {
		rogersPlan.price = roundNumber(rogersPlan.price * 1 + config.rogers.differentials[region], 2, true);
	}
	
	setCost("rogers", rogersPlan.price);
	$("rogers_plan").innerHTML = rogersPlan.name;
	$("invoice_rogers_" + rogersPlan.keyword).innerHTML = rogersPlan.price;
	
	var bellPlan = calculateBellPlans(numFeatures);

	setCost("bell", bellPlan.price);
	$("bell_plan").innerHTML = bellPlan.name;
	$("current_bell_plan").value = bellPlan.keyword;
	$("invoice_bell_" + bellPlan.keyword).innerHTML = bellPlan.price;
	
	$("bell_savings_value").innerHTML = fancyDiff(rogersPlan.price, bellPlan.price);
	
	var aliantPlanNB = calculateAliantPlans(numFeatures, "nb", rogersPlan.keyword);
	$("aliant_nb_plan").innerHTML = aliantPlanNB.name;
	setCost("aliant_nb", aliantPlanNB.price);
	$("aliant_nb_savings_value").innerHTML = fancyDiff(rogersPlan.price, aliantPlanNB.price);
	$("current_aliant_nb_plan").value = aliantPlanNB.keyword;
	
	if (aliantPlanNB.keyword == "basic") {
		$("invoice_aliant_nb_basic").innerHTML = aliantPlanNB.price;
	}
	
	var aliantPlanNF = calculateAliantPlans(numFeatures, "nf", rogersPlan.keyword);
	$("aliant_nf_plan").innerHTML = aliantPlanNF.name;
	setCost("aliant_nf", aliantPlanNF.price);
	$("aliant_nf_savings_value").innerHTML = fancyDiff(rogersPlan.price, aliantPlanNF.price);
	$("current_aliant_nf_plan").value = aliantPlanNF.keyword;
	
	if (aliantPlanNF.keyword == "basic") {
		$("invoice_aliant_nf_basic").innerHTML = aliantPlanNF.price;
	}
	
	if (numFeatures == 0) {
		$("aliant_nb_basic_carte").style.display = "none";
		$("aliant_nf_basic_carte").style.display = "none";	
		
		$("aliant_nb_ld_500").style.display = "none";
		$("aliant_nf_ld_500").style.display = "none";
		$("aliant_nb_ld_250").style.display = "inline";
		$("aliant_nf_ld_250").style.display = "inline";
	} else {
		$("aliant_nb_basic_carte").style.display = "inline";
		$("aliant_nf_basic_carte").style.display = "inline";	

		$("aliant_nb_ld_250").style.display = "none";
		$("aliant_nf_ld_250").style.display = "none";
		$("aliant_nb_ld_500").style.display = "inline";
		$("aliant_nf_ld_500").style.display = "inline";
	}
	
	updateDetailsPaneIfNecessary();
	
	return true;
}

function switchCompetitor(newComp) {
	if (!newComp)
		newComp = "bell";
	
	$("bell_calc_wrapper").style.display = "none";
	$("aliant_nb_calc_wrapper").style.display = "none";
	$("aliant_nf_calc_wrapper").style.display = "none";
	$(newComp + "_calc_wrapper").style.display = "block";

	$("bell_savings").style.display = "none";
	$("aliant_nb_savings").style.display = "none";
	$("aliant_nf_savings").style.display = "none";
	$(newComp + "_savings").style.display = "inline";

	// Change default selections if applicable.
	if (getNumFeatures() == 2) {
		if (newComp == "bell" && $("home_away_voicemail").checked && $("call_display").checked) {
			$("home_away_voicemail").checked = false;
			$("call_waiting").checked = true;
		} else if (newComp != "bell" && $("call_waiting").checked && $("call_display").checked) {
			$("home_away_voicemail").checked = true;
			$("call_waiting").checked = false;
		} 
	}
}

function getRegion() {
	if ($("province_NB").checked)
		return "nb";
	else if ($("province_NF").checked)
		return "nf"
	
	return "on";
}

function getCompetitor() {
	if ($("province_ON").checked)
		return "bell";
	else if ($("province_NB").checked)
		return "aliant_nb";
	else if ($("province_NF").checked)
		return "aliant_nf";
	
	return "bell";
}

function switchRegion() {
	switchCompetitor(getCompetitor());
	
	updateFees();

	updatePricing();	
	
	if (getRegion() == "on")
		$("bell_ld_wrap").style.display = "block";
	else
		$("bell_ld_wrap").style.display = "none";

}

function updateFees() {
	var region = getRegion();
	var fees = 0.41;
	
	if (region == "nb")
		fees = 0.72;
	else if (region == "nf")
		fees = 0.19;
	
	$("details_rogers_basic_fees").innerHTML = fees;
	$("details_rogers_classic_fees").innerHTML = fees;
	$("details_rogers_extras_fees").innerHTML = fees;
}

function detailsOn() {
	var provider = this.id.slice(8);

	// If the user clicked the current provider's details button again, turn the details pane off.
	// If they clicked the other provider's details button, switch to the other provider's details pane.
	if ($("recommend_wrapper").style.display == "none") {
		var np = application.detailPanes.length;
		for (i=0; i < np; i++) {
			if (application.detailPanes[i].style.display == "block") {
				if (application.detailPanes[i].id.indexOf(provider) >= 0) {
					detailsOff();
					return false;
				}
			}
		}
	}
		
	$("recommend_wrapper").style.display = "none";
	closeAllDetailPanes();
	$("details_" + provider + "_" + $("current_" + provider + "_plan").value).style.display = "block";
	
	return false;
}

function detailsOff() {
	closeAllDetailPanes();
	$("recommend_wrapper").style.display = "block";
	
	return false;
}

/** To be used if the user changes feature or location options when the details pane is open
 */
function updateDetailsPaneIfNecessary() {
	if ($("recommend_wrapper").style.display == "none") {
		var np = application.detailPanes.length;
		for (i=0; i < np; i++) {
			if (application.detailPanes[i].style.display == "block") {
				var specs = application.detailPanes[i].id.split("_");
				var provider = "rogers";
				if (specs[1] != "rogers") {
					provider = getCompetitor();
				}
				closeAllDetailPanes();
				$("details_" + provider + "_" + $("current_" + provider + "_plan").value).style.display = "block";
			}
		}
	}	
}


addLoadEvent(function() {
	application.detailPanes = getElementsByClassName("details_pane");
	closeAllDetailPanes();

	application.checkboxes = getElementsByClassName("feature");
	var nc = application.checkboxes.length;
	
	for (i=0; i < nc; i++) {
		application.checkboxes[i].onchange = updatePricing;
		application.checkboxes[i].onclick = updatePricing;
	}
	
	$("province_ON").onchange = switchRegion;
	$("province_NB").onchange = switchRegion;
	$("province_NF").onchange = switchRegion;
	$("province_ON").onclick = switchRegion;
	$("province_NB").onclick = switchRegion;
	$("province_NF").onclick = switchRegion;
	
	switchRegion();
	updatePricing();

	var details = getElementsByClassName("details_toggle");
	var nd = details.length;
	for (i=0; i < nd; i++) {
		details[i].onclick = detailsOn;
	}	

	var detailsClose = getElementsByClassName("details_close");
	var nd = detailsClose.length;
	for (i=0; i < nd; i++) {
		detailsClose[i].onclick = detailsOff;
	}	

	var bellLD = getElementsByClassName("bell_ld_select");
	var nld = bellLD.length;
	for (i=0; i < nld; i++) {
		bellLD[i].onclick = updatePricing;
		bellLD[i].onchange = updatePricing;
	}	
	
});

function closeAllDetailPanes() {
	var np = application.detailPanes.length;
	
	for (i=0; i < np; i++) {
		application.detailPanes[i].style.display = "none";
	}
}