jQuery(document).ready(function ($) {

	var messages = {
		'priceCalculatorTypeEsweMessage': $("#priceCalculatorTypeEsweMessage").dialog({
			autoOpen: false,
			modal: true,
			buttons: {
				Ok: function () {
					$(this).dialog("close");
				}
			},
			open: function () {
				$(this).removeClass('hideme');
			}
		}),
		'priceCalculatorTypeNotSuppliedMessage': $("#priceCalculatorTypeNotSuppliedMessage").dialog({
			autoOpen: false,
			modal: true,
			buttons: {
				Ok: function () {
					$(this).dialog("close");
				}
			},
			open: function () {
				$(this).removeClass('hideme');
			}
		}),
		'priceCalculatorInvalidZipMessage': $("#priceCalculatorInvalidZipMessage").dialog({
			autoOpen: false,
			modal: true,
			buttons: {
				Ok: function () {
					$(this).dialog("close");
				}
			},
			open: function () {
				$(this).removeClass('hideme');
			}
		}),
		'priceCalculatorInvalidNumberMessage': $("#priceCalculatorInvalidNumberMessage").dialog({
			autoOpen: false,
			modal: true,
			buttons: {
				Ok: function () {
					$(this).dialog("close");
				}
			},
			open: function () {
				$(this).removeClass('hideme');
			}
		}),
		'priceCalculatorNoDataMessage': $("#priceCalculatorNoDataMessage").dialog({
			autoOpen: false,
			modal: true,
			buttons: {
				Ok: function () {
					$(this).dialog("close");
				}
			},
			open: function () {
				$(this).removeClass('hideme');
			}
		}),
		'invalidConsumptionRange': $("#validConsumptionRange").dialog({
			autoOpen: false,
			modal: true,
			buttons: {
				Ok: function () {
					$(this).dialog("close");
				}
			},
			open: function () {
				$(this).removeClass('hideme');
			}
		})
	};

	/**
	 * Set visibility of user interface with respect to checked energy type
	 * radio button.
	 */
	var electricityInterface = $("#pricecalculator .energy-type-switch-electricity");
	var gasInterface = $("#pricecalculator .energy-type-switch-gas");
	var electricityIsChecked = $("#energyTypeElectricity").is(":checked");
	electricityInterface[electricityIsChecked ? "show" : "hide"]();
	gasInterface[electricityIsChecked ? "hide" : "show"]();
	$("#electricityConsumptionPerYearInKwh").val(electricityConsumptionPerYearRates[0]);
	$("#gasConsumptionPerYearInKwh").val(gasConsumptionPerYearRates[0]);

	/**
	 * Slider default image opacity
	 */
	$("#pricecalculator-slider .slider-items img").each(function () {
		$(this).animate({opacity: 0.5}, 0);
	});
	$("#pricecalculator-slider .slider-items img:first-child").each(function () {
		$(this).animate({opacity: 1.0}, 0);
	});

	/**
	 * Slider: "Number of residents (electricity)"
	 */
	$(function () {
		var values = [0, 19, 37, 56, 73];
		var slider = $("#numberOfResidentsSlider").slider({
			slide: function (event, ui) {
				var includeLeft = event.keyCode != $.ui.keyCode.RIGHT;
				var includeRight = event.keyCode != $.ui.keyCode.LEFT;
				var nearestValue = findNearest(includeLeft, includeRight, ui.value, values);
				var index = $.inArray(nearestValue, values);
				slider.slider('option', 'value', nearestValue);
				$("#electricityConsumptionPerYearInKwh").val(electricityConsumptionPerYearRates[index]);
				$("#pricecalculator-slider .pricecalculator-slider-electricity .slider-items img").each(function (iteration, element) {
					if (iteration <= index) {
						$(this).animate({opacity: 1.0}, 0);
					} else {
						$(this).animate({opacity: 0.5}, 0);
					}
				});
				return false;
			}
		});
	});

	/**
	 * Slider: "Square meters (gas)"
	 */
	$(function () {
		var values = [0, 18, 37, 59, 82];
		var slider = $("#squareMetersSlider").slider({
			slide: function (event, ui) {
				var includeLeft = event.keyCode != $.ui.keyCode.RIGHT;
				var includeRight = event.keyCode != $.ui.keyCode.LEFT;
				var nearestValue = findNearest(includeLeft, includeRight, ui.value, values);
				var index = $.inArray(nearestValue, values);
				slider.slider('option', 'value', nearestValue);
				$("#gasConsumptionPerYearInKwh").val(gasConsumptionPerYearRates[index]);
				$("#pricecalculator-slider .pricecalculator-slider-gas .slider-items img").each(function (iteration, element) {
					if (iteration == index) {
						$(this).animate({opacity: 1.0}, 0);
					} else {
						$(this).animate({opacity: 0.5}, 0);
					}
				});
				return false;
			}
		});
	});

	/**
	 * Hide "Switch To" link
	 */
	$("#switchToLink").animate({
		top: '-46px'
	});

	/**
	 * Result "class"
	 */
	Result = function() {
		this.supplyArea = null;
		this.checkedEnergyType = null;
		this.consumption = null;
		this.vatFactor = null;
		this.basicRate = null;
		this.energyRate = null;
		this.bonus = null;
		this.rate = null;
	};
	Result.prototype.evaluate = function () {
		this.retrieveCheckedEnergyType();
		this.setConsumption();
		this.validateConsumption();
		this.analyzeSupplyAreaEnergyType();
	};
	Result.prototype.retrieveCheckedEnergyType = function () {
		this.checkedEnergyType = $("#pricecalculator-energy-type > input:radio[name*=energyType]:checked").val();
	};
	Result.prototype.setConsumption = function () {
		this.consumption = $("#" + this.checkedEnergyType + "ConsumptionPerYearInKwh").val();
	};
	Result.prototype.validateConsumption = function () {
		if (parseInt(this.consumption) != this.consumption) {
			throw "priceCalculatorInvalidNumberMessage";
		}
		if (this.consumption < consumptionMinimumValues[this.checkedEnergyType] || 
			this.consumption > consumptionMaximumValues[this.checkedEnergyType]) {
			$("#validMinimumConsumptionRange").text(consumptionMinimumValues[this.checkedEnergyType]);
			$("#validMaximumConsumptionRange").text(consumptionMaximumValues[this.checkedEnergyType]);
			throw "invalidConsumptionRange";
		}
	};
	Result.prototype.analyzeSupplyAreaEnergyType = function () {
		var supplyAreaEnergySupplyState, rate, bonus;
		supplyAreaEnergySupplyState = this.supplyArea[this.checkedEnergyType + "SupplyType"];
		if (supplyAreaEnergySupplyState == "ESWE") {
			throw "priceCalculatorTypeEsweMessage";
		} else if (supplyAreaEnergySupplyState == "NOT_SUPPLIED") {
			throw "priceCalculatorTypeNotSuppliedMessage";
		} else if (supplyAreaEnergySupplyState == "") {
			throw "priceCalculatorInvalidZipMessage";
		} else if (this.supplyArea.length == 0) {
			throw "priceCalculatorInvalidZipMessage";
		} else {
			this.evaluateVatFactor();
			this.extractRates();
			this.calculate();
			this.output();
		}
	};
	Result.prototype.evaluateVatFactor = function() {
		this.vatFactor = 1 + this.supplyArea[this.checkedEnergyType + "Rate"].vat/100;
	};
	Result.prototype.extractRates = function() {
		this.basicRate = this.supplyArea[this.checkedEnergyType + "Rate"].basicRate;
		this.energyRate = this.supplyArea[this.checkedEnergyType + "Rate"].energyRate;
		this.bonus = this.supplyArea[this.checkedEnergyType + "Rate"].bonus;
	};
	Result.prototype.calculate = function () {
		var basicRate, energyRate, bonus, rate;
		if (this.supplyArea[this.checkedEnergyType + "Rate"] == undefined) {
			throw "priceCalculatorNoDataMessage";
		}
		this.rate = (this.basicRate + this.energyRate/100 * this.consumption) * this.vatFactor - this.bonus * this.vatFactor;
	};
	Result.prototype.output = function() {
		var basicRate, energyRate, bonus, rate;
		basicRate = this.formatPrice(this.basicRate * this.vatFactor);
		energyRate = this.formatPrice(this.energyRate * this.vatFactor);
		bonus = this.formatPrice(this.bonus * this.vatFactor);
		rate = this.formatPrice(this.rate);
		$("#pricecalculator-tooltip-basicrate").text(basicRate);
		$("#pricecalculator-tooltip-energyrate").text(energyRate);
		$("#pricecalculator-tooltip-bonus").text(bonus);
		$("#bonus").text(bonus);
		$("#rate").val(rate);
		$("#switchToLink").animate({
			top: '-5px'
		});
	};
	Result.prototype.formatPrice = function(price) {
		return price.toFixed(2).toString().replace('.', ',');
	};

	/**
	 * Bind radio buttons
	 */
	$("#energyTypeElectricity").bind("click", function () {
		$("#pricecalculator .energy-type-switch-electricity").show();
		$("#pricecalculator .energy-type-switch-gas").hide();
		resetCalculator();
	});
	$("#energyTypeGas").bind("click", function () {
		$("#pricecalculator .energy-type-switch-gas").show();
		$("#pricecalculator .energy-type-switch-electricity").hide();
		resetCalculator();
	});

	/**
	 * Create result object
	 */
	result = new Result();

	/**
	 * Bind Submit button
	 */
	$("#search").bind("click", function () {
		resetCalculator();
		fillResult(result);
		try {
			result.evaluate();
		}
		catch (exception) {
			messages[exception].dialog("open");
		}
	});

	/**
	 * Clean result field
	 */
	function resetCalculator() {
		$("#bonus").text("0");
		$("#rate").val("");
		$("#switchToLink").animate({
			top: '-46px'
		});
	}

	/**
	 * AJAX Request
	 */
	function fillResult(result) {
		if (result.supplyArea == null || result.supplyArea.zip != $("#zip").val()) {
			$.ajax({
				async: false,
				type: "POST",
				url: "index.php",
				data: {
					"type": "5000",
					"tx_pteswepricecalculator_pi1[controller]": "SupplyArea",
					"tx_pteswepricecalculator_pi1[action]": "search",
					"tx_pteswepricecalculator_pi1[format]": "JSON",
					"tx_pteswepricecalculator_pi1[demand][zip]": $("#zip").val()
				},
				dataType: "json",
				success: function (response) {
					result.supplyArea = response;
				}
			});
		}
	}

	/**
	 * Find nearest dedicated value of actual slider value
	 */
	function findNearest(includeLeft, includeRight, value, values) {
		var nearest = null;
		var diff = null;
		for (var i = 0; i < values.length; i++) {
			if ((includeLeft && values[i] <= value) || (includeRight && values[i] >= value)) {
				var newDiff = Math.abs(value - values[i]);
				if (diff == null || newDiff < diff) {
					nearest = values[i];
					diff = newDiff;
				}
			}
		}
		return nearest;
	}
	
	/**
	 * hide page header at the thx page
	 */
	$(function () {
		if ($(".formhandler-without-page-header").length) {
			$("h2.csc-firstHeader").parent("div.csc-default").hide();
		}
	});

	// Information-Tooltip
	$("#pricecalculator-tooltip-trigger").tooltip();

});

