// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
	log.history = log.history || [];   // store logs to an array for reference
	log.history.push(arguments);
	if(this.console){
		console.log( Array.prototype.slice.call(arguments) );
	}
};

var wizard_url = '';

var wizard = (function(module) {

	var container, breadcrumb, questions, options, currentQuestion, answers = {};

	$(document).ready(function() {

		container = $("#wizard");
		breadcrumb = $("#breadcrumb", container);
		questions = $(".question", container);
		currentQuestion = $(".question_0", container);
		options = $(".option", container);


		options.click(function(e) {
			// Save their choice in the answers object
			var dataName = $(this).data("name");
			var dataValue = $(this).data("value");
			var dataTitle = $(this).data("title");
			var dataQuestion = $(this).data("question");
			answers[dataName] = dataValue;
			// Hide any bubbles that are siblings of this option
			$(".bubble", $(this).parent()).fadeOut();
			// Proceed to the next question
			nextQuestion();
			addBreadcrumbItem(dataTitle, dataName, dataQuestion);
		});

		// Climb up the answer tree until you find an unanswered question, then show it
		var nextQuestion = function() {
			currentQuestion.hide();
			switch (answers.insurance_type) {
				case 1 : // Go to Bijstandsverzekering
					switch (answers.travel_frequency) {
						case 1 : // tijdelijk
							if (answers.travel_persons) {
								if (answers.travel_country) {
									if (answers.travel_from && answers.travel_until) {
										if (answers.travel_car === 0 || answers.travel_car === 1) {
											endOfBranch();
										} else { // travel_country is null
											showQuestion(".question_1_1_1_1_1");
										}
									} else { // travel_from is null
										showQuestion(".question_1_1_1_1");
									}
								} else { // travel_country is null
									showQuestion(".question_1_1_1");
								}
							} else { // travel_persons is null
								showQuestion(".question_1_1");
							}
							break;
						case 2 : // jaarjilks
							if (answers.travel_persons) {
								if (answers.travel_duration) {
									if (answers.travel_car === 0 || answers.travel_car === 1) {
										endOfBranch();
									} else { // travel_car is null
										showQuestion(".question_1_2_1_1");
									}
								} else { // travel_duration is null
									showQuestion(".question_1_2_1");
								}
							} else { // travel_persons is null
								showQuestion(".question_1_2");
							}
							break;
						default : // travel_frequency is null
							showQuestion(".question_1");
					}
					break;
				case 2 : // Go to Annulatieverzekering
					switch (answers.travel_frequency) {
						case 1 : // 1 reis per jaar
							if (answers.travel_persons) {
								if (answers.travel_from && answers.travel_until) {
									if (answers.travel_baggage === 0 || answers.travel_baggage === 1) {
										endOfBranch();
									} else { // travel_baggage is null
										showQuestion(".question_2_1_1_1");
									}
								} else { // travel_from is null
									showQuestion(".question_2_1_1");
								}
							} else { // travel_persons is null
								showQuestion(".question_2_1");
							}
							break;
						case 2 : // meerdere reizen
							if (answers.travel_persons) {
								if (answers.travel_baggage === 0 || answers.travel_baggage === 1 || answers.travel_baggage === 2) {
									endOfBranch();
								} else { // travel_baggage is null
									showQuestion(".question_2_2_1");
								}
							} else { // travel_persons is null
								showQuestion(".question_2_2");
							}
							break;
						default : // travel_frequency is null
							showQuestion(".question_2");
					}
					break;
				case 3 : // Bijstand aan de woning, bijstand in thuiszorg
					switch (answers.home_type) {
						case 1 : // bijstand a/d woning
							endOfBranch();
							break;
						case 2 : // thuiszorg jaarkeuze
							if(answers.home_insurance_frequency == 1) {
								if(answers.home_insurance_from && answers.home_insurance_until) {
									if (answers.home_insurance_beneficiaries) {
										endOfBranch();
									} else {
										showQuestion(".question_3_3");
									}
								} else {
									showQuestion(".question_3_2_1");
								}
							} else if(answers.home_insurance_frequency == 2) {
								if (answers.home_insurance_beneficiaries) {
									endOfBranch();
								} else {
									showQuestion(".question_3_3");
								}
							} else {
								showQuestion(".question_3_2");
							}
							break;
						default : // home_type is null
							showQuestion(".question_3");
					}
					break;
				default : // insurance_type is null
					showQuestion(".question_0");
			}
		};

		// Leave a trail of bread so if we get lost we can follow it back home
		var addBreadcrumbItem = function(title, params) {
			$(".lastItem", breadcrumb).removeClass("lastItem").unbind("click");
			var breadcrumbItem = $('<div class="breadcrumbItem lastItem" data-params="' + params + '">' + title + '<div class="ir pointer">&nbsp;</div><div class="ir back">&nbsp;</div></div>');
			breadcrumbItem.click(removeLastBreadcrumbItem);
			breadcrumb.append(breadcrumbItem);
		};

		// Breadcrumb items have a data parameter called 'params', which stores a record of which answers were given at this question
		// Those answers should be deleted if we move back before this item
		var addParamsToLastBreadcrumbItem = function(params) {
			var lastBreadcrumbItem = $(".lastItem", breadcrumb);
			params += " " + lastBreadcrumbItem.data("params");
			lastBreadcrumbItem.data("params", params);
		};

		var removeLastBreadcrumbItem = function(e) {
			var params = $(this).data("params");
			var question = $(this).data("question");
			log("Delete these params because we are going back: "+params);
			var paramsArray = params.split(" ");
			for (var i=0, len=paramsArray.length; i<len; i++) {
				delete answers[paramsArray[i]];
			}
			// Remove this breadcrumb item
			$(this).remove();
			// Activate the new last breadcrumb item
			var newLast = $("#breadcrumb .breadcrumbItem:last");
			if (newLast.length > 0) {
				newLast.addClass("lastItem").click(removeLastBreadcrumbItem);
			}
			// Show the correct question
			nextQuestion();
		};

		var showQuestion = function(selector) {
			currentQuestion = $(selector, container).show();
		};

		// They have made it to the end of a branch, hooray!
		var endOfBranch = function() {
			$(".whiteblock").load('/ajax/wizard.php',answers);
			currentQuestion = $(".results", container).show();
		};

		// Text inputs for number of persons
		$(".subOption").click(function(e) {
			$(".bubble", $(this).parent()).fadeIn();
		});
		$(".bubble .btnArrow").click(function(e) {
			var input = $("input", $(this).parent());
			var error = $(".error", $(this).parent());
			if (input.val()) {
				answers.travel_persons = parseInt(input.val(), 10);
				nextQuestion();
				addBreadcrumbItem(answers.travel_persons + " " + input.data("title"), "travel_persons");
				error.hide();
			} else {
				error.show();
			}
		});

		$(".question_1_1_1 .btnRed").click(function(e) {
			var selectedCountry = $("#travel_country option:selected");
			if (selectedCountry.length > 0) {
				answers.travel_country = selectedCountry.val();
				addBreadcrumbItem(selectedCountry.text(), "travel_country");
				nextQuestion();
			}
		});

		$(".question_1_1_1_1 .btnRed").click(function(e) {
			if($('#travel_already_booked').css('display') != 'none') {
				if($('input[name="travel_already_booked"]:checked').length == 0) {
					$('#travel_already_booked').addClass('errorred');
					return false;
				} else {
					$('#travel_already_booked').removeClass('errorred');
				}
			}
			answers.travel_from = $.datepicker.formatDate('yy-mm-dd', $(".question_1_1_1_1 div[data-name='travel_from']").datepicker("getDate"));
			answers.travel_until = $.datepicker.formatDate('yy-mm-dd', $(".question_1_1_1_1 div[data-name='travel_until']").datepicker("getDate"));
			answers.travel_already_booked = $("#travel_already_booked").is(":checked") ? 1 : 0;
			if (!answers.travel_from || !answers.travel_until) {
				// Validation error, no dates selected
				return;
			}
			addParamsToLastBreadcrumbItem("travel_from travel_until travel_already_booked");
			nextQuestion();
		});

		$(".question_2_1_1 .btnRed").click(function(e) {
			answers.travel_from = $.datepicker.formatDate('yy-mm-dd', $(".question_2_1_1 div[data-name='travel_from']").datepicker("getDate"));
			answers.travel_until = $.datepicker.formatDate('yy-mm-dd', $(".question_2_1_1 div[data-name='travel_until']").datepicker("getDate"));
			if (!answers.travel_from || !answers.travel_until) {
				// Validation error, no dates selected
				return;
			}
			addParamsToLastBreadcrumbItem("travel_from travel_until");
			nextQuestion();
		});

		$(".question_3_2_1 .btnRed").click(function(e) {
			answers.home_insurance_from = $.datepicker.formatDate('yy-mm-dd', $(".question_3_2_1 div[data-name='home_insurance_from']").datepicker("getDate"));
			answers.home_insurance_until = $.datepicker.formatDate('yy-mm-dd', $(".question_3_2_1 div[data-name='home_insurance_until']").datepicker("getDate"));
			if (!answers.home_insurance_from || !answers.home_insurance_until) {
				// Validation error, no dates selected
				return;
			}
			addParamsToLastBreadcrumbItem("home_insurance_from home_insurance_until");
			nextQuestion();
		});

		$(".question_3_3 .btnRed").click(function(e) {
			var selectedItem = $(".question_3_3 input[name='home_insurance_beneficiaries']:checked");
			if (selectedItem.length > 0) {
				$(".question_3_3 .error").hide();
				answers.home_insurance_beneficiaries = selectedItem.val();
				addParamsToLastBreadcrumbItem("home_insurance_beneficiaries");
				nextQuestion();
			} else {
				$(".question_3_3 .error").show();
			}
		});

		$(".datepicker", container).datepicker({
			inline: true,
			changeMonth: true,
			changeYear: true,
			dateFormat: 'yy-mm-dd',
			onSelect: function( selectedDate ) {
				if($(this).attr('rel') == 'check_already_booked') {
					
					var now = new Date();
					var then = new Date(selectedDate);
					now = now.setDate(now.getDate()+31);
					
					if(then <= now) {
						$('#travel_already_booked').show();
						$('.question_1_1_1_1 #btnRed').addClass('validateAB');
					} else {
						$('#travel_already_booked').hide();
						$('.question_1_1_1_1 #btnRed').removeClass('validateAB');
					}
				}
			}
		});

	});

}(wizard || {}));


