/*
 * croatiadivers.com - Price calculator
 */

// On load
$(document).ready(function(){
	
	// Configure date picker date format
	$.extend(DateInput.DEFAULT_OPTS, {
	  stringToDate: function(string) {
	    var matches;
	    if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
	      return new Date(matches[1], matches[2] - 1, matches[3]);
	    } else {
	      return null;
	    };
	  },
	
	  dateToString: function(date) {
	    var month = (date.getMonth() + 1).toString();
	    var dom = date.getDate().toString();
	    if (month.length == 1) month = "0" + month;
	    if (dom.length == 1) dom = "0" + dom;
	    return dom + "-" + month + "-" + date.getFullYear()
	  }
	});
	
	// Alias seasons in hotel prices
	for (var hotel in hotelPrices){
		hotelPrices[hotel]["season_9"] = hotelPrices[hotel]["season_1"];
		hotelPrices[hotel]["season_8"] = hotelPrices[hotel]["season_2"];
		hotelPrices[hotel]["season_7"] = hotelPrices[hotel]["season_3"];
		hotelPrices[hotel]["season_6"] = hotelPrices[hotel]["season_4"];
	}
	
	// Init date picker
	$("#arrival-date").date_input();
	
	
	// Add event listeners
	$("#price-form").bind("submit", onSubmit);
	$("#price-form").bind("reset", onReset);
	$("#num-people").bind("change", onChangeNumPeople);
	
	// Ensure form is reset
	$("#price-form")[0].reset();
});


// On clicking submit button, validates user input and calculates a price
function onSubmit(e) {
	
	// Stop HTML form submission
	e.preventDefault()
	
	// If form is invalid, return.
	if(!validateForm()){
		return;
	}
	
   /*
	* Calculate season
	*/
	var season = null;
	var selectedDate = new Date();
	var thisYear = selectedDate.getFullYear();
	selectedDate.setFullYear(thisYear, parseDate(month) - 1, parseDate(day));
	var startDate = new Date();
	var endDate = new Date();	
	
	// Before first season, show error message
	startDate.setFullYear(thisYear, parseDate(seasons.season_1_start.split("-")[1]) - 1, parseDate(seasons.season_1_start.split("-")[0]));
	if (selectedDate < startDate){
		displayMessage(userMessages.dateBeforeSeason + seasons.season_1_start + "-" + year);
		return;
	}
	
	// After last season, show error message
	endDate.setFullYear(thisYear, parseDate(seasons.season_9_end.split("-")[1]) - 1, parseDate(seasons.season_9_end.split("-")[0]));
	if (selectedDate > endDate){
		displayMessage(userMessages.dateAfterSeason + seasons.season_9_end + "-" + year);
		return;
	} 
	
	// Else, get season
	for (var s=1; s<=9; s++){
		startDate.setFullYear(thisYear, parseDate(seasons["season_" + s + "_start"].split("-")[1]) - 1, parseDate(seasons["season_" + s + "_start"].split("-")[0]));
		endDate.setFullYear(thisYear, parseDate(seasons["season_" + s + "_end"].split("-")[1]) - 1, parseDate(seasons["season_" + s + "_end"].split("-")[0]));
		if (selectedDate >= startDate && selectedDate <= endDate){
			season = "season_" + s;
		}
	}
	
	// If season was not calculated, an error occurred because there's a gap between seasons
	if (!season){
		displayMessage(userMessages.seasonCalculationError);
		return;
	}
	
	
	// If no accommodation or diving was selected, inform user
	if (userInput.accommodation == "None" && userInput.diving == "None"){
		displayMessage(userMessages.noDivingOrAccommodation);
		return;
	}
	
	
	/*
	 * Calculate price
	 */
	var price = 0;
	
	// For each person
	$(".diver select").each(function (i){
		
		// Calculate diving price
		if (this.value != "None"){
			price += divingPrices[this.value];
		}
		
		// Calculate accommodation price
		if (userInput.accommodation != "None"){
			price += hotelPrices[userInput.accommodation][season][userInput.numNights] * userInput.numNights;
			
			// If person is a non-diver
			if (this.value == "None" || this.value == "passenger"){
				// Add accommodation overhead
				price += nonDiverAccomodationOverhead * userInput.numNights;
			}
		}		
	});
	
	
	// Display price
	displayMessage("The total cost for your selection is " + (Math.round(price*100)/100).toFixed(2) + " euros" + "\n\n" + termsMessage);
};


// Parse a day or month to an integer
function parseDate(date){
	return parseInt(date.replace(/^0+/, ""));
}

// On clicking reset button, resets form
function onReset() {
	$("#divers").empty();
};

// Validates user input in form. If invalid, reports errors.
function validateForm(){
	var errMsg, valid = false;
	
	// Store form values
	userInput = {};
	
	userInput.arrivalDate = $("#arrival-date").val();
	userInput.numNights = $("#num-nights").val();
	userInput.accommodation = $("#accommodation").val();
	userInput.numOfPeople = $("#num-people").val();
	
	if (!userInput.accommodation) {
		errMsg = userMessages.noAccommodation;
	} else if (userInput.accommodation == "None") {
		valid = true;
	} else if (!userInput.arrivalDate){
		errMsg = userMessages.noArrivalDate;
	} else if (!userInput.arrivalDate.match(/^\d{2}-\d{2}-\d{4}$/)){
		errMsg = userMessages.invalidArrivalDate;
	} else if (!userInput.numNights) {
		errMsg = userMessages.noNumNights;
	} else if (!userInput.numOfPeople) {
		errMsg = userMessages.noNumPeople;		
	} else {
		valid = true;
	}
	
	
	// Check each diver input
	$(".diver select").each(function (i){
		if (!this.value){
			errMsg = userMessages.noDiving;
			valid = false;
		}
	});
	
	// Extract and validate arrival date
	if (valid) {
		date = userInput.arrivalDate.split("-");
		day = date[0];
		month = date[1];
		year = date [2];
		now = new Date();
		thisYear = now.getFullYear();
		if (year < thisYear) {
			errMsg = userMessages.yearIsPast;
			valid = false;
		} 
	}
	
	if (errMsg){
		displayMessage(errMsg);
	}
	
	return valid;
}

// Displays a message to the user
function displayMessage(msg){
	alert (msg);
}

// Called on changing number of people in group
function onChangeNumPeople(){
	
	var newNum = $("#num-people").val();
	var currNum = $(".diver").length;
	
	if (!newNum){
		$("#num-people").val(currNum);
		return;
	}else if (newNum > currNum){
		// Add divers
		var addNum = newNum - currNum;
		for (var i=0; i<addNum; i++){
			var clonelist = $("#diving-").clone();
			var clone = clonelist[0];
			$("#divers").append(clone);
			var num = currNum + (i+1)
			clone.id += num;
			clone.className += " diver";
			var label = clonelist.find("label");
			label[0].innerHTML += num;
		}
	}else if (newNum < currNum){
		// Remove divers
		while ($(".diver").length > newNum){
			var r = $("#diving-" + $(".diver").length)[0];
			r.parentNode.removeChild(r);
		}
	}
}
