var selectedBuiten;
var setTotal = function ($input) {
	var $row = $input.parents('tr');
	var $price = $('.price', $row);
	var $total = $('.total', $row);

	if ($total) {
		if ($input.hasClass('error')) {
			$total.html('-');
			$total.attr('data-price', '0');
		} else {
			var piece = $price.attr('data-price');
			var total = piece * $input.val();

			/*if (total > 0)*/$total.html('&euro; ' + (total.toFixed(2)).replace('.', ','));
			/*else $total.html('');*/
			$total.attr('data-price', total);
		}
	}


};
var setTotals = function () {
	var n = 0;
	$('.table:not(.month) tr:visible .total').each(function () {
		if ($(this).attr('data-price')) {
			n += 1 * $(this).attr('data-price');
		}

	});
	$('#priceyear').html('&euro; ' + (n.toFixed(2)).replace('.', ','));
	n = 0;
	$('.month tr:visible .total').each(function () {
		if ($(this).attr('data-price')) {
			n += 1 * $(this).attr('data-price');
		}

	});
	if (n == 0) $('#pricemonth').parents('.totalblock').hide();
	else $('#pricemonth').parents('.totalblock').show();
	$('#pricemonth').html('&euro; ' + (n.toFixed(2)).replace('.', ','));
};
$(document).ready(function () {

	$(document).pngFix(); // PNG fix for IE6
	openInNewWindow(); // Open links in new window
	$('body').addClass('domenabled');

	// Handje bij hover
	$(".partner").css("cursor", "pointer");
	// De complete div linken
	$(".partner").click(function () {
		window.location = $(this).find("a").attr("href"); return false;
	});

	if ($('#slideshow')) {
		$('#slideshow').fancyslideshow({
			slideshowNavigation: false,
			decimalNavigation: true,
			mousewheel: false,
			keyNavigation: false,
			startItem: 1,
			autoHeight: false,
			prevBtnTxt: 'Vorige bekijken',
			nextBtnTxt: 'Volgende bekijken',
			autoScroll: true,
			animationSpeed: 1500,
			delay: 12000
		});
	}
	// Remove footer border on first item
	$("#footer ul li:first-child").css("border-left", "none");

	$('label.pre').labelOver('over');

	// Rekenmodule
	if ($("#rekenmodule")) {

		if (false) {
			// mutual exclusive vervang auto buitenland
			var buiten1 = $('#rekenmodule label[for="vervang-auto-buitenland-1"]').parent();
			var html1 = buiten1.html();
			buiten1.html('<input type="radio" name="vervangauto" value="0" id="vervang-auto-buitenland-1" style="padding:0; margin:0 2px;" checked="checked" ></input>' + html1);

			var buiten2 = $('#rekenmodule label[for="extra-vervang-buitenland-1"]').parent();
			var html2 = buiten2.html();
			buiten2.html('<input type="radio" name="vervangauto" value="1" id="extra-vervang-buitenland-1" style="padding:0; margin:0 2px;"></input>' + html2);
			//buiten2.next().next().find('input.text').attr('disabled', 'disabled');

			var b1 = $('#rekenmodule label[for="vervang-auto-buitenland-1"]').parent().next().next().find('input.text');
			var b2 = $('#rekenmodule label[for="extra-vervang-buitenland-1"]').parent().next().next().find('input.text');

			buiten1.find('input').click(function () {
				if ($(this).val() == selectedBuiten) return;
				var b1 = $('#rekenmodule label[for="vervang-auto-buitenland-1"]').parent().next().next().find('input.text');
				var b2 = $('#rekenmodule label[for="extra-vervang-buitenland-1"]').parent().next().next().find('input.text');
				b1.show();
				b2.hide();
				b1.parent().parent().addClass('enabled');
				b2.parent().parent().removeClass('enabled');
				if (selectedBuiten != null) {
					b1.val(b2.val());
					b2.val('0');
				}
				selectedBuiten = $(this).val();
			});
			buiten2.find('input').click(function () {
				if ($(this).val() == selectedBuiten) return;
				var b1 = $('#rekenmodule label[for="vervang-auto-buitenland-1"]').parent().next().next().find('input.text');
				var b2 = $('#rekenmodule label[for="extra-vervang-buitenland-1"]').parent().next().next().find('input.text	');
				b2.show();
				b1.hide();
				b2.parent().parent().addClass('enabled');
				b1.parent().parent().removeClass('enabled');
				if (selectedBuiten != null) {
					b2.val(b1.val());
					b1.val('0');
				}
				selectedBuiten = $(this).val();

			});
			if (b1.val() != '0') {
				buiten1.find('input').click();
			} else if (b2.val() != '0') {
				buiten2.find('input').click();
			} else {
				buiten1.find('input').click();
			}
		}
		$("input[type=text]").focus(function () {
			$(this).select();
		});

		$('.text').each(function () {
			setTotal($(this));
		});

		// Pakketoverzicht uitleg
		$("#rekenmodule #main label a").click(function () {
			var id = $(this).parent().attr("for");
			var info = $("#uitleg p." + id).html();
			$("#sub .info p").html(info);
			//return false;
		});

		$('input[type="hidden"][value="' + $('#actionprice').text() + '"]').parents('tr').addClass('actionprice');

		if (window.rekengroups) {
			var total = $('.kenteken').length;

			var showBuitenland = false;
			for (name in window.rekengroups) {
				for (itemname in window.rekengroups[name]) {
					var item = window.rekengroups[name][itemname];

					if (item['amount'] == 0) {
						$('.itemid' + item['id']).hide();
					}
					if (item['amount'] == total) {
						$('.itemid' + item['id']).find('input').attr('checked', 'checked');
					}
					if (item['name'].indexOf('Voertuighulp Buitenlan') > -1) showBuitenland = true;
				}
			}
			if (!showBuitenland) $('#buitenlandOnderschrift').hide();

			$(".field input").click(function () {
				var parent = $(this).parent();
				var auto = $(this).parents('.autogegevens');
				var itemid = parent.attr('class').substring(6);
				var nrchecked = $('.' + itemid + ' input:checked').length;
				var rekenitem = findRekenitem(itemid.substring(6));

				if (rekenitem['amount'] == nrchecked) {
					$('.' + itemid + ' input:not(:checked)').attr('disabled', 'disabled');
					$('.' + itemid + ' input:not(:checked)').parent().css('color', '#ccc');
					$('.' + itemid + ' input:not(:checked)').addClass('amounthigh');
				} else {
					$('.' + itemid + ' input:not(:checked)').attr('disabled', '');
					$('.' + itemid + ' input:not(:checked)').parent().css('color', '#000');
					$('.' + itemid + ' input:not(:checked)').removeClass('amounthigh');
				}
				/*
				var other = 0;
				var otherName = '';
				if (compareBox[key]['exclusive'] == 'True') {
				for (a in compareBox) {
				if (a != key && compareBox[a]['key'] == compareBox[key]['key']) {
				other = parseInt($('.tbrm_' + a).val());
				otherName = compareBox[a]['name'];
				break;
				}	
				}			
				}
				args.IsValid = val+other <= nrofcars;
				*/
				var thiscompitem = compareBox[itemid.substring(6)];
				if (thiscompitem && thiscompitem['exclusive'] == 'True') {
					for (x in compareBox) {

						if (compareBox[x]['key'] == thiscompitem['key'] && x != itemid.substring(6)) {
							var other = auto.find('.itemid' + x + ' input');

							if ($(this).attr('checked') != '') {
								other.attr('checked', '');
								other.attr('disabled', 'disabled');
								other.parent().css('color', '#ccc');
								other.addClass('excluded');
							} else {
								other.attr('disabled', '');
								other.parent().css('color', '#000');
								other.removeClass('excluded');
							}

							break;
						}
					}
				}

				$(this).parents('.autogegevens').find(".field input:not(.amounthigh, .excluded)").each(function () {
					var parent = $(this).parent();
					var auto = $(this).parents('.autogegevens');
					var itemid = parent.attr('class').substring(6);
					var compitem = compareBox[itemid.substring(6)];
					if (compitem) {
						var compareParentId = compitem['parent'];
						var checkBoxParent = auto.find('.itemid' + compareParentId + ' input');
						if (checkBoxParent.attr('checked') == '') {
							$(this).attr('checked', '');
							$(this).attr('disabled', 'disabled');
							$(this).parent().css('color', '#ccc');
						} else {
							$(this).attr('disabled', '');
							$(this).parent().css('color', '#000');
						}
					}

				});
			});

			$(".field input").each(function () {
				var parent = $(this).parent();
				var auto = $(this).parents('.autogegevens');
				var itemid = parent.attr('class').substring(6);
				var compitem = compareBox[itemid.substring(6)];
				if (compitem) {
					var compareParentId = compitem['parent'];
					var checkBoxParent = auto.find('.itemid' + compareParentId + ' input');
					if (checkBoxParent.attr('checked') == '') {
						$(this).attr('disabled', 'disabled');
						$(this).parent().css('color', '#ccc');
					}
				}

			});
		}


		// Gegevens ANWB lid
		$("#geenlid, #correspondentie").hide();

		// If no is clicked then open fields
		$("#ledencheck input[type=radio]").click(function () {
			// Show subscribe fields
			if ($(this).val() == 'true') {
				$("#geenlid").css("display", "block");

				// Show the different address fields 
				$("#geenlid input.checkbox").click(function () {
					if ($(this).attr('checked') == true) {
						$("#correspondentie").css("display", "block");
					} else {
						$("#correspondentie").css("display", "none");
					}
				});

			} else {
				$("#geenlid").css("display", "none");
				$("#correspondentie").css("display", "none");
			}
		});

		$('input.text').change(function () {
			
			Page_ClientValidate('');
		});
	}

	// Kenteken kopieren
	$(".specialoptions a").click(function () {
		$(this).parent().parent().find("input[type=checkbox]").each(function () {
			if ($(this).attr("checked") == true) {
				var label = $(this).siblings("label").html();
				$(this).parent().parent().parent().next().find("label:contains(" + label + ")").siblings("input").attr("checked", "checked");
			}
		});
		return false;
	});

	// Faq page animations
	if ($("#faqMenu").length > 0) {
		var o2 = new Array();
		o2.push('ANWB_voor_bedrijven');
		o2.push('Wegenwacht_voor_bedrijven');
		o2.push('Voordeel_voor_bedrijven');
		o2.push('Mobiliteitskaart_voor_bedrijven');
		var o = new Array();
		$(".faq li").each(function () {
			var classes = $(this).attr("class").split(' ');
			for (i = 0; i < classes.length; i++) {
				if ($(o).index(classes[i]) == -1) o.push(classes[i]);
			}
		});
		o.sort();

		var cssClasses = { 'ANWB_voor_bedrijven': 0, 'Wegenwacht_voor_bedrijven': 3, 'Voordeel_voor_bedrijven': 2, 'Mobiliteitskaart_voor_bedrijven': 1 };
		var menu = "";
		for (i = 0; i < o2.length; i++) {
			if (o2[i].length > 0 && $(o).index(o2[i]) > -1) {

				menu += '<a href="#' + o2[i] + '" class="faqmenu-' + cssClasses[o2[i]] + '">' + o2[i].replace('_', ' ').replace('_', ' ') + '</a>';
			}
		}

		$('#faqMenu').html(menu);

		$('#faqMenu a:first').addClass('selected');
		var classSelector = '.' + $('#faqMenu a:first').attr('href').substring($('#faqMenu a:first').attr('href').indexOf('#') + 1);
		$('.faq li').not(classSelector).hide();
		$('.faq li' + classSelector).show();
		$('#faqMenu a').click(function () {
			$('#faqMenu a').removeClass('selected');
			$(this).addClass('selected');
			var classSelector = '.' + $(this).attr('href').substring($(this).attr('href').indexOf('#') + 1);

			$('.faq li').not(classSelector).hide();
			$('.faq li' + classSelector).show();

		});
	}
	$(".faq .link-list li>p, .faq .link-list li .faqBanner").hide();
	$(".faq .link-list li a").toggle(function () {
		// Stuff to do every *odd* time the element is clicked;
		//$(this).next("p").slideDown("fast");
		$(this).nextAll().fadeIn("slow");
	}, function () {
		// Stuff to do every *even* time the element is clicked;
		$(this).nextAll().fadeOut("slow");
	});
	//---------------------

	// Dries Roelvink
	// Headers
	$('.dries h2, .dries h3').css({
		display: 'block',
		height: '20px',
		textIndent: '-9999em'
	});
	$('.dries .video h2').css({
		width: '131px',
		backgroundImage: 'url("/include/images/header-bekijkvideo.gif")'
	});
	$('.dries .single h2').css({
		width: '149px',
		height: '20px',
		backgroundImage: 'url("/include/images/header-downloadgratis.gif")'
	});
	$('.dries .info h2').css({
		width: '188px',
		backgroundImage: 'url("/include/images/header-ANWB-voor-bedrijven-small.gif")'
	});

	// Form	
	$('.dries fieldset').hide();
	$('.dries a.star').click(function () {
		$(this).hide();
		$('.dries fieldset').fadeIn('slow');
	});
	//--------------------

});

function findRekenitem(id) {
	for (name in window.rekengroups) {
		for (itemname in window.rekengroups[name]) {
			var item = window.rekengroups[name][itemname];
			if (item['id'] == id) return item;
		}
	}
}

function setLidmaatschap(val) {
	var amount = parseInt(val);
	$('.lidmaatschapTable tr').each(function () {
		if ($(this).attr('class') != 'first') {
			var range = $(this).attr('class').substring('lidmaatschap_'.length);
			var from = parseInt(range.substring(0, range.indexOf('-')));
			var to = parseInt(range.substring(range.indexOf('-') + 1));

			if (amount >= from && amount <= to) {
				$(this).show();
			} else {
				$(this).hide();
			}
		}
	});

	setTotals();
	Page_ClientValidate('');

	$("td label:not(.notooltip)").simpletip({
		content: '<img src="/include/images/hover.png"/><div>Geen extra gegevens.</div>',
		onBeforeShow: function () {
			var tooltip = null;
			if (this.getParent().parents('tr').hasClass('disabled')) {
				tooltip = this.getParent().parents('tr').prev().find('.dependency').html();
			} else {
				tooltip = this.getParent().attr('data-tooltip');

			}
			if (tooltip) this.getTooltip().html('<img src="/include/images/hover.png"/><div>' + tooltip + '</div>');

		},
		position: ["70", "10"],
		fixed: true,
		showEffect: 'none'
	});

	$('td input.text').focus(function () {
		var tip = $(this).parents('tr').find('label:not(.notooltip)').simpletip();
		if (tip && tip.getTooltip) {
			tip.show();
			tip.update(tip.getTooltip().html());
		}

	});
	$('td input.text').blur(function() {
		var tip = $(this).parents('tr').find('label:not(.notooltip)').simpletip();
		if (tip) tip.hide();
	});
}
function openInNewWindow() {
	$("a[rel='blank']").each(function () {
		$(this).attr({
			href: "javascript:window.open('" + $(this).attr("href") + "');void(0);",
			title: "Link opent in een nieuw venster"
		});
	});
}
function LessThenLidmaatschap(args) {
	var val = parseInt(args.Value);
	var nrofcars = $('.amountofcars').val();
	return val <= nrofcars;
}
function CheckFieldLidmaatschap(sender, args) {
	args.IsValid = LessThenLidmaatschap(args);
}
function GetCompareItem(id, key) {

}

function CheckProductsGreaterEqualCars(sender, args) {
	var totalProducts = 0;
	for (product in window.productKeys) {
		totalProducts += parseInt($('.tbrm_' + window.productKeys[product]).val());
	}
	var nrofcars = parseInt($('.amountofcars').val());
	args.IsValid = totalProducts >= nrofcars;
}

function CheckDependency(sender, args) {
	var control = $('#' + sender.controltovalidate);

	
		var attr = control.attr('class');

		var key = attr.substring(10);
		if (compareBox[key]) {
			var val = parseInt(args.Value);
			var nrofcars = parseInt($('.tbrm_' + compareBox[key]['parent']).val());
			var other = 0;
			var otherName = '';
			if (compareBox[key]['exclusive'] == 'True') {
				for (a in compareBox) {
					if (a != key && compareBox[a]['key'] == compareBox[key]['key']) {
						other = parseInt($('.tbrm_' + a).val());
						otherName = compareBox[a]['name'];
						break;
					}

				}

			}

			if (nrofcars == 0) {
				control.parents('tr').addClass('disabled');
				control.parents('div').removeClass('active');
				control.val('0');
				val = 0;
			}
			else {
				control.parents('tr').removeClass('disabled');
			}

			args.IsValid = (val + other) <= nrofcars;
			if (other > 0) {
				sender.innerHTML = 'Aantal samen met ' + otherName + 'moet kleiner of gelijk zijn aan ' + compareBox[key]['child_name'];
			} else {
				sender.innerHTML = 'Om deze optie te gebruiken moet ook gekozen worden voor ' + compareBox[key]['child_name'];
			}

		} else {
			args.IsValid = true;
		}
	
	var isTheValid = !(LessThenLidmaatschap(args) && args.IsValid);
	if (!isTheValid) $('#' + sender.controltovalidate).addClass('error');
	else $('#' + sender.controltovalidate).removeClass('error');
	$('#' + sender.controltovalidate).toggleClass('error', isTheValid);

	var inputBox = control;
	if (!isNaN(inputBox.val())) {
		setTotal(inputBox);
		setTotals();
		var $table = inputBox.parents('table');
		var n = 0;
		$table.find('.text').each(function () { n += $(this).val() * 1; });
		if (n > 0) {
			$table.parents('div').addClass('active');
		} else {
			$table.parents('div').removeClass('active');
		}
	}
}

function CheckComplete(sender, args) {
	var txt = 'De volgende diensten zijn nog niet aan een kenteken toegewezen: <ul>';
	var wrongcount = 0;
	for (name in window.rekengroups) {
		for (itemname in window.rekengroups[name]) {
			var item = window.rekengroups[name][itemname];
			var nrofchecked = $('.itemid' + item['id']).find('input:checked').length;
			if (item['amount'] > 0 && item['amount'] != nrofchecked) {
				wrongcount++;
				txt += "<li>" + itemname + "(" + (item["amount"] - nrofchecked) + ")</li>";
			}
		}
	}
	sender.innerHTML = txt + "</ul>";
	if (wrongcount == 0) {
		args.IsValid = true;
	} else {
		args.IsValid = false;
	}
}
