
var cache = []; 

$(function()
{	
	var checkStyle = {
		fontWeight: "bold",
		fontSize: "14px",
		color: "#000000"
	}
	var reEditStyle = {
		fontWeight: "normal",
		fontSize: "12px",
		color: "#000000"
	}
	var sumBooking = 0;
	var sumAllSkipasses = 0;
	var sumDiscount = 0;
	
	/* preload gallery images for nicer transitions */
	$(".imageThumb").each(function(){
    	var cacheImage = document.createElement('img');
    	cacheImage.src = $(this).attr("id");
		cache.push(cacheImage);
	})
	
	var loadingAnimation = document.createElement("img");
	loadingAnimation.src = "https://secure.ski-france.com/images/loading.gif";
	cache.push(loadingAnimation);
	
	$(".imageThumb").click(function(){
		var path = $(this).attr("id");
		$("#imageBig").fadeOut("fast", function(){ 	
			$(this).attr("src", path);
			$(this).fadeIn("slow");
		});
		$("#imageBig").attr({
			"alt": $(this).attr("title"), 
			"title": $(this).attr("alt")
		});
		$("#imgBigTitle").html($(this).attr("title"));
	})
	
	function toggleCreditCardPaymentInfo()
	{
		var pm = $("select[name=obo_payment_method]").val();
		var ccp = $("#creditcardIcons");
		pm == "creditcard" ? ccp.show("slow") : ccp.hide("slow");
	}
	
	/* check if credit card payment is default because the booking date is too short before the */
	toggleCreditCardPaymentInfo();
	
	/* display payment infos according to selected payment method and show creditcard fields, if creditcard payment is selected */
	$("select[name=obo_payment_method]").change(toggleCreditCardPaymentInfo);
	
	/* toggle exotic skipasses */
	$(".toggleSps").click(function(){
		$(".toggleSps").toggle();
		$("#orderableSkipasses").slideToggle("slow");
	});
	
	$("#acceptAgbSubmitButton").click(function(event){
		event.preventDefault();
		/* default: confirm booking*/
		var exit = 0;
		
		/* check if required booking fields are emtpy */
		$(".required > span > input").each(function(){
			if ($(this).val() == "") {
				exit = 1;
				$("#message_" + $(this).attr("name")).show("slow");
			}
			else {
				$("#message_" + $(this).attr("name")).hide("slow");
			}
		});
		
		/* check if enterend email adress(es) are valid */
		$("input[name^='obo_email']").each(function(){
			var name = $(this).attr("name");
			var val = $(this).val();
			
			if (val && val.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) == null) {
				exit = 2;
				$("#message_wrong_email_" + name).show("slow");
			}
			else {
				$("#message_wrong_email_" + name).hide("slow");
			}
		});
		
		
		/* check if payment method is not selected */
		if ($("select[name=obo_payment_method]").val() == "null") {
			exit = 2;
			$("#missingPaymentMethodMessage").show("slow");
		}
		else {
			$("#missingPaymentMethodMessage").hide("slow");
		}
		
		/* check if language has to be selected and is not selected */
		if ($("select[name=lang_id]").val() == "null") {
			exit = 2;
			$("#message_lang_id").show("slow");
		}
		else {
			$("#message_lang_id").hide("slow");
		}
		
		/* check if AGBs are accepted */
		if ($("input[name=accept_agb]").attr("checked") != "checked") {
			exit = 2;
			$("#acceptAgbsMessage").show("slow");
		}
		else {
			$("#acceptAgbsMessage").hide("slow");
		}

		/* if required fields are empty, go to top */
		if (exit == 1) {
			/*$.scrollTo("a[name=top]", scroll);*/
		}
		else if (exit == 2) {
			/*$.scrollTo("a[name=bookingFormBottom]", scroll);*/
		}
		/* if everything is okay, confirm booking */
		else {
			/* build the skipass order table*/
			$(".orderableSkipass").each(function(){
				var amount  = $(this).find("input").val();
				var price = 0;
				var sum = 0;
				/* calculate the prices and discounts */
				if (amount > 0) {
					price = parseFloat($(this).find("#spValue > span").html());
					sum = amount * price;
					spInfoId = $("#skipass" + $(this).find("input").attr("name"));
					$(spInfoId).find("#skipassAmount").html(amount);
					$(spInfoId).find("#skipassSum").html(sum);
					$(spInfoId).find("#skipassSum").moneyFormat();
					$(spInfoId).show("slow");
					sumAllSkipasses += sum;
					sumDiscount += parseFloat($(this).find("#spgDiscount").html()) * amount;
				}
			});
			
			/* disable field for better readability */
			$(".booFormField > span > input, .booFormField > span > select, .booFormField > span > textarea, h2 > select, #languageSection > select").css(checkStyle);
			$(".booFormField > span > input, .booFormField > span > select, .booFormField > span > textarea, h2 > select, #languageSection > select").attr("disabled", "disabled"); 
									  
			/* toggle skipass button */
			$(".toggleSps").hide("slow");
			
			/* hide headlines  */
			$("#bookingForm > .colSection > h2").each(function(){
				if ($(this).attr("id") != "skipassBookingSummary" && $(this).attr("id") != "bookingSummary" && $(this).attr("id") != "paymentMethod"){
					$(this).hide("slow");
				}
			});
			
			/* show data headline*/
			/*$("#yoData").show("slow");*/
			
			/* if no skipasses are beeing ordered, also hide the skipass headline */
			if (sumAllSkipasses != 0)
			{
				var sumBooking = parseFloat($("span#apPrice").html().replace(".","").replace(",", ".")) + sumAllSkipasses + sumDiscount;
				$("#bookingSum > span").html(sumBooking).moneyFormat();
				$("#bookingDiscount > span").html(sumDiscount).moneyFormat();
				$("div#bookingSummary").show("slow");
				$("#anzahlungInfo").css("display", "none");
				$("div#skipassBookingSummary").show("slow");
			}
			/* hide all other messages and texts*/
			$("#agbs").hide("slow");
			$("#creditcardInfo").hide("slow");
			$("#securityNumberInfo").hide("slow");
			$("#missingPaymentMethodMessage").hide("slow");
			$("#message_lang_id").hide("slow");
			$("#orderableSkipasses").hide("slow");
			$("#seeSkipassInfosTerm").hide("slow");
			
			/* remove margin from colSections */
			$("div#commentSection, div#comFieldsSection").css("margin-bottom", "0px");
			
			/* show submit / cancel button and the famous "do you really want it?" question */
			$("#confirmBookingMessage").show("slow");
			$("#bookingSubmitButton").show("slow");
			$("#bookingCancelButton").show("slow");
		}
	});
		
	$("#bookingCancelButton").click(function(event){
		event.preventDefault();
		
		sumDiscount = 0;
		sumAllSkipasses = 0;
		sumBooking = 0;
		 
		$(".booFormField > span > input, .booFormField > span > select, .booFormField > span > textarea, h2 > select, , #languageSection > select").css(reEditStyle);
		$(":disabled").removeAttr("disabled");
		$("#bookingForm > .colSection > h2").show("slow");
		$("#agbs").show("slow");
		$("#hideSps").css("display", "inline");
		$("#orderableSkipasses").show("slow");
		$("#seeSkipassInfosTerm").show("slow");
		$(this).hide("slow");
		$("#checkInfo").hide("slow");
		$("#transferInfo").hide("slow");
		$("#creditcardPayment").hide("slow");
		$("#bookingSubmitButton").hide("slow");
		$("#confirmBookingMessage").hide("slow");
		$("#acceptAgbsMessage").hide("slow");
		$("#bookingSummary").hide("slow");
		$("div#skipassBookingSummary").hide("slow");
				
		/* restore original margin of colSections */
		$("div#commentSection, div#comFieldsSection").css("margin-bottom", "12px");
	});
	$(".booFormField > span > input").keypress(function(event) {
		if (event.which == "13") {
			event.preventDefault();
		}
	});
	$("#bookingSubmitButton").click(function(event){
		event.preventDefault();
		$(":disabled").removeAttr("disabled");
		$("#bookingForm").submit();
	});
	$(".goSubmitButton, #bookingSubmitButton").click(function() { 
		$.blockUI({
			message: $("#loadingAnimation"), 
			css: { 
				border: "none", 
	            padding: "15px", 
	            backgroundColor: "#fff", 
	            "-webkit-border-radius": "10px", 
	            "-moz-border-radius": "10px", 
				"border-radius": "10px",
	            opacity: 1, 
				border: "3px solid #aaa" 
	        }
		});
    });
	
	/*
	$("select").change(function() {
		$(this).closest("form").submit();
	});*/
	
	$("a.fancybox").fancybox({
		"overlayShow": true, 
		"overlayOpacity": 0.8, 
		"overlayColor": "#4a4b4b",
		"padding": 10, 
		"centerOnScroll": false, 
		"frameWidth": 755, 
		"frameHeight": 480
	});
	
	$("a.planFancybox").fancybox({
		"overlayShow": true, 
		"overlayOpacity": 0.8, 
		"overlayColor": "#4a4b4b",
		"padding": 10, 
		"centerOnScroll": false, 
		"frameWidth": 930, 
		"frameHeight": 480
	});
		
	/* toggle nav elementss */
	$("li.navArea > a").click(function(){
		$(this).parent().siblings().find("ul.navRegions").hide("slow");
		$("li.navArea > a").removeClass("clicked");
		$("li.navArea > a").removeAttr("id");
		$(this).addClass("clicked");
		$(this).siblings("ul.navRegions").slideToggle("slow");
	});
	
	$("li.navRegion > a").click(function(){
		$(this).siblings("ul.navResorts").show("slow");
		$(this).parent().siblings().find("ul.navResorts").hide("slow");
		$("li.navRegion > a").removeAttr("id");
		$(this).addClass("clicked");
	});
	
	$("li.navResort > a").click(function(){
		$("li.navResort > a").removeAttr("id");
		$(this).addClass("clicked");
	});
	
	$("li.navPage > a").click(function(){
		$("li.navPage > a").removeAttr("id");
		$(this).addClass("clicked");
	});
	
	var sorteds = [];
	$.each(regions, function() {
		if (this.resorts)
		{
			$.each(this.resorts, function() {
				sorteds.push(this);
	       	});
		}
   	});
	sorteds.sort(sortByName);
	
	function changeResorts() {
		var resortSelect = $("select[id=res_id]");
		var resVal = resortSelect.val();
		var regVal = $("select[id=reg_id]").val();
		
		resortSelect.find('option[value!=null]').remove();
				
		if (regVal.match(/null/)) {			
			$.each(sorteds, function() {
				var op = $("<option value='" + this.id + "'>" + this.name + "</option>");
				this.id == resVal ? op.attr("selected", "selected") : true;
				op.appendTo(resortSelect);
	       	});
		}
		else if (regVal.match(/in/)) {
			var ids = regVal.replace("in", "").replace("(", "").replace(")", "").replace(" ", "").split(",");
			
			$.each(sorteds, function() {
				for (var i=0; i<ids.length; i++)
				{
					if (ids[i] == this.parent)
					{
						var op = $("<option value='" + this.id + "'>" + this.name + "</option>");
						this.id == resVal ? op.attr("selected", "selected") : true;
						op.appendTo(resortSelect);
						break;
					}
				}
			});
		}	
		else {
			var id = regVal.replace("=","");
			$.each(regions[id].resorts, function() {
				var op = $("<option value='" + this.id + "'>" + this.name + "</option>");
				this.id == resVal ? op.attr("selected", "selected") : true;
				op.appendTo(resortSelect);
	       	});   
		}
    }
	
	$("#reg_id").change(changeResorts);
	changeResorts();
});	

function region(id, name) {
	this.id = id
	this.name = name;
	this.resorts = [];
}

function resort(id, name, parent) {
	this.id = id
	this.name = name;
	this.parent = parent;
}			

function sortByName(a, b) {
	var nameA = a.name.toLowerCase();
	var nameB = b.name.toLowerCase();
	return nameA.localeCompare(nameB);
}
