var tarifValidatorConf = {
	message : '<div/>',
	position : 'center right',
	lang : 'de',
	offset : [ 0, 0 ],
	inputEvent : 'submit',
	messageClass : 'tarif-error'
};

$(document).ready(function() {
	// only validate zip field
	// use of .cockpit-zip crashes with service page
	jQuery('.zip').validator(tarifValidatorConf).defineOnFailBehaviour().ajaxStart(function() {
		$('.next_btn').attr("disabled", "disabled").css("color", "#cccccc");
	}).ajaxComplete(function() {
		$('.next_btn').removeAttr("disabled").css("color", "#000000");
	});

	$('#jetzt').click(function() {
		return $('#mform').find('.cockpit_zip').data("validator").checkValidity();
	})
	// attach listener to send total volume of tarif to salesfunnel
	// ajaxSuccess is the only event that gets fired when boxes are drawn
	.ajaxSuccess(function() {
		$('.button').each(function() {
			$(this).click(function() {
				ersparnis = false;
				umsatz = 0;
				if ($(this).parent().parent().find(".saving_save")) {
					ersparnis = true;
				}
				umsatz = $(this).parent().parent().find(".price").html();
				umsatz = parseInt(umsatz.replace(/¬|\s|,|\./g, "")) * 100;
				// save cookie with tarifs id
				tarifID = $(this).parent().find("[name=tariffId]").val();
				$.cookie("productID", normalizeTarifID(tarifID), {
					path : '/'
				});
				salesFunnel.tarifAuswahlTracking(ersparnis, umsatz);
			});
		});
	});

	// switch for geschäfts/privatkunden
	$('#mform').submit(function() {
		target = "";
		$('#mform').find("[type=radio]").each(function() {
			if ($(this).attr("checked")) {
				if ($(this).val() == "pk") {
					target = "gas-privatkunden/gaspreisrechner-gaspreisvergleich/";
				} else if ($(this).val() == "gk") {
					target = "gas-geschaeftskunden/gastarifrechner-gas-preisvergleich/";
				}
			}
		});
		$(this).attr("action", target);
	});

	// tarif validator validate only zip
	$('#mform').find('.cockpit_zip').each(function() {

		if ($('#mform').hasClass("gg_tarifform")) {
			tarifValidatorConf.effect = 'wall';
		}
		$(this).validator(tarifValidatorConf);

		var ggTarifError = "gg_tarif-error";
		$.tools.validator.addEffect("wall", function(errors, event) {
			$('#postcode').css("border-color", "#cb3830").css("background-color", "#efb69e");
			$("." + ggTarifError).remove();
			var wall = $(document.createElement("div")).insertAfter($('#mform'));
			wall.addClass(ggTarifError);
			// add new ones
			$.each(errors, function(index, error) {
				wall.append("<p>" + error.messages[0] + "</p>");
			});
		}, function(inputs) {
			$('#postcode').css("background-color", "#fff").css("border-color", "#CDCDCD");
			$("." + ggTarifError).remove();
		});

	});

});

function normalizeTarifID(id) {
	switch (id) {
	case "82":
		return "0";
	case "7":
		return "1";
	case "83":
		return "3";
	case "8":
		return "2";
	case "4":
		return "4";
	default:
		return "";
	}
}

