var activeSection = "accomodation";
var action = "";
var txBooking = new Object();

function initBookingForm() {
	
	if ($(".bookingForm")) {
		setLanguage(epLanguage);
		addCommonListeners();
		addAccomodationListeners();
		addLiftPassListeners();
		addSkiRentalListeners();
		addCustomerListeners();
	}
}

function setLanguage(language) {
	
	if (epLanguage == "en")
	{
		txBooking.antallHeiskort = "Please select number of lift passes.";	
		txBooking.alleFelt = "All fields are required.";	
		txBooking.datoTilEtterDatoFra = "To date cannot be before from date."
		txBooking.vilDuFjerneProdukt = "Are you sure you want to want to remove this product?";	
		txBooking.ja = "Yes";	
		txBooking.nei = "No";	
		txBooking.fortsettUtenHeiskort = "Continue without lift passes";	
		txBooking.fortsettUtenSki = "Continue without skis";	
		txBooking.fortsett = "Continue";	
		txBooking.endreBesilling = "Make changes";	
		txBooking.bekreftBestilling = "Confirm booking";	
		txBooking.dinBestilling = "Your booking";
		txBooking.oppdatererHandlekurv = "Updating cart";
		txBooking.maksAntallPersoner = "Maximum 7 persons per appartment.";
		txBooking.velg = "Select";
		
		txBooking.januar = "January";
		txBooking.februar = "February";
		txBooking.mars = "March";
		txBooking.april = "April";
		txBooking.mai = "May";
		txBooking.juni = "June";
		txBooking.juli = "July";
		txBooking.august = "August";
		txBooking.september = "September";
		txBooking.oktober = "October";
		txBooking.november = "November";
		txBooking.desember = "December";
	}
	else 
	{
		txBooking.antallHeiskort = "Du må velge antall heiskort";
		txBooking.alleFelt = "Alle felt må fylles ut";
		txBooking.datoTilEtterDatoFra = "Til-dato kan ikke være tidligere enn fra-dato."		
		txBooking.vilDuFjerneProdukt = 	"Er du sikker på at du vil fjerne dette produktet fra handlekurven?";
		txBooking.ja = "Ja";	
		txBooking.nei = "Nei";	
		txBooking.fortsett = "Fortsett";	
		txBooking.fortsettUtenHeiskort = "Fortsett uten heiskort";	
		txBooking.fortsettUtenSki = "Fortsett uten skiutstyr";	
		txBooking.endreBesilling = "Endre bestilling";	
		txBooking.bekreftBestilling = "Fullfør bestilling";	
		txBooking.dinBestilling = "Din bestilling";	
		txBooking.oppdatererHandlekurv = "Oppdaterer handlekurv";
		txBooking.maksAntallPersoner = "Maks 7 personer pr leilighet.";
		txBooking.velg = "Velg";
		
		txBooking.januar = "Januar";
		txBooking.februar = "Februar";
		txBooking.mars = "Mars";
		txBooking.april = "April";
		txBooking.mai = "Mai";
		txBooking.juni = "Juni";
		txBooking.juli = "Juli";
		txBooking.august = "August";
		txBooking.september = "September";
		txBooking.oktober = "Oktober";
		txBooking.november = "November";
		txBooking.desember = "Desember";	
	}		
}

function addCommonListeners() {
	
	$("select.updateQuantity").unbind("change");
	$("select.updateQuantity").change(function(){
		
		var id = $(this).parents("tr").attr("id");
		var lineTotal = $(this).parents("tr").find("td.total");
		var quantity = $(this).val();
		
		var product = new Object();
		product.orderLineId = id;
		product.quantity = quantity;
		
		addServiceLoading(lineTotal);
		disableForm();
		
		updateProduct(product);
		
		return false;
	});

	$("td.delete a.delete").unbind("click");
	$("td.delete a.delete").click(function(){
		
		var id = $(this).parents("tr").attr("id");
		var td = $(this).parents("td");
		createDeleteConfirmation(td);
		return false;
	});	
	
	$("td.delete a.cancel").unbind("click");
	$("td.delete a.cancel").click(function(){
		removeDeleteConfirmation();
		return false;
	});	
	
	$("td.delete a.confirm").unbind("click");
	$("td.delete a.confirm").click(function(){
		var id = $(this).parents("tr").attr("id");
		var lineTotal = $(this).parents("tr").find("td.total");
		
		var product = new Object();
		product.orderLineId = id;
		addServiceLoading(lineTotal);
		disableForm();
		deleteProduct(product);
		removeDeleteConfirmation();
		return false;
	});
}

function showUpdatedRows() {
	
	$("tr.updated td").animate(
		{backgroundColor: "#FFAC88"}, 100, 
		function(){
			$(this).animate({backgroundColor: "#FFFFFF"}, 800)
		}
	);
}


function addAccomodationListeners() {
	
	var fieldset = $("fieldset.accomodation");
	fieldset.find(".buttonsNext button").click(function(){
		
		if ($('fieldset.liftpass').size() == 1) {
			setActiveSection("liftpass", 2);
		}
		else {
			setActiveSection("customer", 2);
		}
		
		$("fieldset.accomodation p.info").removeClass("infoActive");
		$(this).hide();
		return false;
		}
	);
	
	fieldset.find(".apt select").change(validateAndUpdateNumberOfPersons);
	$("fieldset.next .buttonsNext button").click(function(event){
		event.stopPropagation();

		if ($('fieldset.liftpass').size() == 1) {
			setActiveSection("liftpass", 2);
		}
		else {
			setActiveSection("customer", 2);
		}

		return false;
	});
}


function addLiftPassListeners() {
	
	$("#liftpass_age").change(function()
		{
			var age = $(this).val();
			updateLiftPassPrices(age);
		}	
	);
	
	$("fieldset.liftpass td.add button").click(function()
		{
			var product = new Object();
			product.type = "liftpass";
			product.id = getLiftpassValue("id", null);
			product.quantity = $("#liftpass_quantity").val();
			product.age = $("#liftpass_age").val();
			product.days = getLiftpassValue("days", null);
			
			if (product.quantity == 0)
			{
				showErrorMessage("liftpass", txBooking.antallHeiskort);
				return false;
			}

			hideErrorMessage();
			addLoadingRow("liftpass");
			updateNextButton("");
			
			addProduct(product);
			return false;
		}
	);
}

function addSkiRentalListeners() {
	
	$("fieldset.skirental td.add button").click(function() {
		var product = new Object();
		product.type = "skirental";
		product.quantity = $("#skirental_quantity").val();
		product.id = $("#skirental_product").val();
		product.from = $("#skirental_from").val();
		product.to = $("#skirental_to").val();
		
		if (product.quantity == 0 || product.id == 0 || product.from == 0 || product.to == 0)
		{
			showErrorMessage("skirental", txBooking.alleFelt);
			return false;
		}
		
		if (product.to < product.from)
		{
			showErrorMessage("skirental", txBooking.datoTilEtterDatoFra);
			return false;
		}
		
		hideErrorMessage();
		addLoadingRow("skirental");
		updateNextButton("");
		
		addProduct(product);
		return false;
	});
	
	$("#skirental_from").change(function()
	{
		var value = $(this).val();
		$("#skirental_to").find("option").each(function() {
			if ($(this).attr("value") < value)
				$(this).hide();
			else
				$(this).show();
		});
		
		if ($("#skirental_to").val() < value)
			$("#skirental_to").val(value);
	});
}

function addCustomerListeners() {
	
	$("fieldset.customer .buttonsNext button.next").click(function(event){		
		event.stopPropagation();
		
		if (activeSection == "customer" && $("form.bookingForm").valid())
		{	
			var customer = new Object();
			customer.name = $("#contactName").val();
			customer.address = $("#contactAddress").val();
			customer.zip = $("#contactZip").val();
			customer.city = $("#contactCity").val();
			customer.country = $("#contactCountry").val();
			customer.email = $("#contactEmail").val();
			customer.phone = $("#contactPhone").val();
			customer.comment = $("#contactRequest").val();
			
			updateCustomer(customer);
			activeSection = "confirmation";
		}
		
		else if (activeSection == "confirmation")
		{
			completeOrder();
		}
		
		return false;
	});
	
	$("fieldset.customer .buttonsNext button.change").click(function(){
		hideConfirmation();
		return false;
	});	
}

function enableForm()
{
	$(".bookingForm").find("input,select,button,textarea").removeAttr("disabled");
}

function disableForm()
{
	$(".bookingForm").find("input,select,button,textarea").attr("disabled", "disabled");
}


function setActiveSection(sectionId)
{
	activeSection = sectionId;
	var section = $("fieldset." + sectionId);
	section.show();
	
	$("fieldset.next .buttonsNext button").unbind("click");
	
	switch (activeSection)
	{
		case "liftpass":
			updateNextButton(txBooking.fortsettUtenHeiskort);
			$("fieldset.next .buttonsNext button").click(function(event){
				event.stopPropagation();
				$("fieldset.liftpass p.info").removeClass("infoActive");
				setActiveSection("skirental");
				return false;
			});
			break;

		case "skirental":
			updateNextButton(txBooking.fortsettUtenSki);
			$("fieldset.next .buttonsNext button").click(function(event){
				event.stopPropagation();
				$("fieldset.skirental p.info").removeClass("infoActive");
				setActiveSection("customer");
				$(this).hide();
				return false;
			});
			break;				
	}
}

function updateNextButton(text)
{	
	var button = $("fieldset.next .buttonsNext button");	
	if (text == ""){
		button.html(txBooking.fortsett);
		button.removeClass("passive");
		return;
	}
	
	button.html(text);
	button.addClass("passive");
}


function validateAndUpdateNumberOfPersons()
{	
	var children = parseInt($("select#children").val());
	var adults = parseInt($("select#adults").val());
	var message = null;
	
	if ((adults + children) > 7)
		message = txBooking.maksAntallPersoner;
	
	if (message != null)
	{
		showErrorMessage("accomodation", message);
		disableForm();
		$("#children, #adults").removeAttr("disabled");
		return false;
	}
	
	hideErrorMessage();
	
	product = new Object();
	product.adults = adults;
	product.children = children;
	product.orderLineId = $("select#adults").parents("tr").attr("id");	
	updateNumberOfPersons(product);
	
	$("select#adults").after($("#ajaxLoader").clone().addClass("updating"));	
	return true;
}

function numberOfPersonsUpdated()
{
	$(".updating").remove();
	enableForm();
}

function updateLiftPassPrices(age) {	
	$("#liftpass_type option").each(function() 
		{
			var text = new String($(this).html());
			var startPos = text.lastIndexOf("(");
			text = text.substr(0, startPos);
						
			var price = getLiftpassValue(age, $(this).val());
			
			text = text + " (" + price + ",-)";
			$(this).html(text);
		}		
	);
}

function getLiftpassValue(field, values)
{
	var fieldNo = 0;
	
	switch (field)
	{
		case "id":
			fieldNo = 0;
			break;
		case "days":
			fieldNo = 1;
			break;
		case "child":
			fieldNo = 2;
			break;
		case "adult":
			fieldNo = 3;
			break;
	}
	
	if (values == null)
		values = new String($("#liftpass_type").val());
	
	return values.split(';')[fieldNo];
}

function addProduct(product)
{
	updateCart(product, "add");
}

function updateProduct(product)
{
	updateCart(product, "update");
}

function deleteProduct(product)
{
	updateCart(product, "delete");
}

function updateCart(product, operation)
{
	var postData = {
		operation: operation + "Product",
		data: JSON.stringify(product)
	};
	
	disableForm();
	
	$.ajax({
		type: "POST",
		url: onlineBookingUrl,
		data: postData,
		dataType: "html",
		success: updateCartFromJSON,
		error: function(XMLHttpRequest, textStatus, errorThrown){ displayAjaxErrorMessage(XMLHttpRequest, textStatus, errorThrown, "Feil i addProduct");}
	});
}

function updateNumberOfPersons(product)
{
	var postData = {
		operation: "updateAccomondation",
		data: JSON.stringify(product)
	};
		
	disableForm();
		
	$.ajax({
		type: "POST",
		url: onlineBookingUrl,
		data: postData,
		dataType: "html",
		success: numberOfPersonsUpdated,
		error: function(XMLHttpRequest, textStatus, errorThrown){ displayAjaxErrorMessage(XMLHttpRequest, textStatus, errorThrown, "Feil i addProduct");}
	});
}

function updateCustomer(customer)
{	
	var postData = {
		operation: "addPersonalDetails",
		data: JSON.stringify(customer)
	};
	
	disableForm();
	
	action = "customer";
		
	$.ajax({
		type: "POST",
		url: onlineBookingUrl,
		data: postData,
		dataType: "html",
		success: updateCartFromJSON,
		error: function(XMLHttpRequest, textStatus, errorThrown){ displayAjaxErrorMessage(XMLHttpRequest, textStatus, errorThrown, "Feil i addProduct");}
	});
}

function completeOrder()
{	
	action = "complete";

	var postData = {
		operation: "completeOrder"
	};
	
	$.ajax({
		type: "POST",
		url: onlineBookingUrl,
		data: postData,
		dataType: "html",
		success: orderCompleted,
		error: function(XMLHttpRequest, textStatus, errorThrown){ displayAjaxErrorMessage(XMLHttpRequest, textStatus, errorThrown, "Feil i addProduct");}
	});
}

function updateCartFromJSON(data, textStatus) {
	enableForm();
	buildFormFromAjax(JSON.parse(data));
	addCommonListeners();
	
	if (action == "customer")
	{
		showConfirmation();
	}
	
	action = "";
}

function orderCompleted(data) {
	
	if (data != "false")
	{
		data = new String(data);
		data = data.substring(1, data.length-2);
		data = data.replace("\n", "");
		data = data.replace("\\", "");
		$(".form").html(data);
	}
}

function showConfirmation() {
	
	hideErrorMessage();
	$("td.delete").hide();
	$("table.product").hide();
	$("p.info").hide();
	
	if ($("fieldset.liftpass table.cart tr").size() == 0) {
		($("fieldset.liftpass table.cart")).before($("<p>").addClass("confirmation").append("Heiskort ikke valgt."))
	}

	if ($("fieldset.skirental table.cart tr").size() == 0) {
		($("fieldset.skirental table.cart")).before($("<p>").addClass("confirmation").append("Skiutstyr ikke valgt."))
	}
	
	$("table.cart .updateQuantity").each(function(){
		addConfirmationSpan($(this));
		$(this).hide();
	});
	
	$("table.apt select").each(function(){
		addConfirmationSpan($(this));
		$(this).hide();		
	});	
	
	$("fieldset.customer input").each(function(){
		addConfirmationSpan($(this));
		$(this).hide();
	});

	$("fieldset.customer textarea").each(function(){
		addConfirmationSpan($(this));
		$(this).hide();
	});
	
	$("h3 span").hide();
	$("fieldset.accomodation h3").addClass("orderConfirmation");
	$("fieldset.liftpass h3").addClass("orderConfirmation");
	$("fieldset.skirental h3").addClass("orderConfirmation");
	$("fieldset.accomodation h3").before($("<h3>").addClass("confirmation").append(txBooking.dinBestilling));
	
	$("#contactTermsConditions").parents("div.field").hide();
	
	$(".buttonsNext button.change").show();
	$(".buttonsNext button.next").html(txBooking.bekreftBestilling);
	
	$(".infoBooking").hide();
	$(".infoConfirmation").show();
	
	activeSection = "confirmation";
	
	$.scrollTo(0,1200);
}

function addConfirmationSpan(input) {
	
	input.after(
			$("<span>")
				.addClass("confirmation")
				.append(nl2br(input.val() + "&nbsp;"))
		);
}


function nl2br(text) {
	var text = new String(text);
	var breakTag = "<br />";
	return text.replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
}

function hideConfirmation() {
	$("td.delete").show();
	$("table.product").show();
	$("p.info").show();
	
	$(".confirmation").remove();
	$(".buttonsNext button.change").hide();
	
	$("table.cart .quantity select").show();
	$("table.apt select").show();
	$("fieldset.customer input").show();
	$("fieldset.customer textarea").show();	
	$("#contactTermsConditions").parents("div.field").show();
	$(".orderConfirmation").removeClass("orderConfirmation");
	$(".buttonsNext button.next").html(txBooking.fortsett);
	
	$(".infoBooking").show();
	$(".infoConfirmation").hide();

	activeSection = "customer";
	$.scrollTo(0,1200);
}

function displayAjaxErrorMessage(XMLHttpRequest, textStatus, errorThrown, msg)
{
	alert(msg);
	alert(textStatus);
	alert(errorThrown);
	enableForm();
	action = "";
}

function addLoadingRow(fieldsetId)
{
	$("tr.loading").remove();

	var fieldset = $("fieldset." + fieldsetId); 
	addTableBodyIfEmpty(fieldset.find("table.cart"));
	var tbody = fieldset.find("table.cart tbody");	
	tbody.append(
		$("<tr>")
			.addClass("loading")
			.css("display", "none")
			.append($("<td>")
				.addClass("quantity")
				.append($("#ajaxLoader").clone())
			)
			.append($("<td>")
					.attr("colspan", getColCount(tbody.parent()) - 1)
					.append(txBooking.oppdatererHandlekurv + "...")
				)
		);
	
	$("tr.loading").fadeIn(50)
}

function removeLoadingRow()
{
	$("tr.loading").remove();
}

function addServiceLoading(cell)
{
	cell.html($("#ajaxLoader").clone());
}

function showErrorMessage(fieldsetId, message)
{	
	hideErrorMessage()
	var fieldset = $("fieldset." + fieldsetId);
	
	var table = null;
	
	if (fieldsetId == "accomodation")
		table = fieldset.find("table:first");
	else
		table = fieldset.find("table.product");
	
	table.after(
		$('<p>')
			.addClass("error")
			.append(message)
	);
}

function hideErrorMessage()
{
	$("p.error").remove();
}

function addTableBodyIfEmpty(table)
{
	if (table.find("tbody").size() == 0)
	{
		table.append("<tbody>");
	}
}

function getColCount(table)
{
	var row = table.find("tr:first");
	
	if (row.size() == 0)
		return 1;
	
	var colCount = 0;
	row.find("td").each(function(){
		colspan = parseInt($(this).attr("colspan"));
		colCount += (colspan > 0) ? colspan : 1;
	})
	
	return colCount;
}

function buildFormFromAjax(data) {
	
	
	for (var n=0; n<data.items.length; n++)
	{
		switch (data.items[n].name)
		{
			case "service":
				updateServicesTable(data.items[n].lines);
				break;
			case "liftcard":
				buildLiftPassTable(data.items[n].lines);
				break;
			case "skirental":
				buildSkiRentalTable(data.items[n].lines);
				break;
		}
				
	}
	
	$("fieldset.orderTotal td.total").html(data.totalFormatted);
	enableForm();
	showUpdatedRows();
}

function updateServicesTable(data) {

	if (data.length == 0)
		return;

	var fieldset = $("fieldset.accomodation");
	var table = fieldset.find("table.cart:last-child");
	
	for (var n=0; n<data.length; n++)
	{
		var line = data[n];		
		var row = table.find("#" + line.orderLineId);
		
		row.find("select").val(line.qty);
		row.find("td.total").html(line.totalFormatted);		
	}
	
}

function buildLiftPassTable(data) {
		
	var fieldset = $("fieldset.liftpass");
	var table = fieldset.find("table.cart");
	
	// nullstiller
	table.find("tbody").remove();

	if (data.length == 0)
	{
		$("fieldset.liftpass p.cart").css("display: block");
		return;
	}
	
	addTableBodyIfEmpty($("fieldset.liftpass table.cart"));
	var tbody = table.find("tbody");

	for (var n=0; n<data.length; n++)
	{
		var line = data[n];
		var changedCss = (data[n].changed) ? "updated" : "";
		tbody.append(
			$("<tr>")
				.addClass(changedCss)
				.attr("id", "" + line.orderLineId)
				.append($("<td>")
					.addClass("quantity")
					.append(createQuantityDropdown(0, Math.max(8, parseInt(line.qty) + 4),line.qty))
				)
				.append($("<td>")
					.addClass("name")
					.append(line.name)
				)
				.append($("<td>")
					.addClass("unitPrice")
					.append("" + line.priceFormatted)
				)
				.append($("<td>")
					.addClass("total")
					.append("" + line.totalFormatted)
				)
				.append($("<td>")
					.addClass("delete")
					.append($("<a>")
							.addClass("delete")
							.attr("href", "#")
							.append("<span>X</span>")
					)
				)
			);
	}
	
}

function buildSkiRentalTable(data) {
		
	var fieldset = $("fieldset.skirental");
	var table = fieldset.find("table.cart");
	
	// nullstiller
	table.find("tbody").remove();
	
	if (data.length == 0)
	{
		$("fieldset.skirental p.cart").css("display: block");
		return;
	}
	
	addTableBodyIfEmpty($("fieldset.skirental table.cart"));
	var tbody = table.find("tbody");

	for (var n=0; n<data.length; n++)
	{
		var line = data[n];		
		var period = (line.from != line.to) ? line.fromFormatted + " - " + line.toFormatted : line.fromFormatted;
		var changedCss = (data[n].changed) ? "updated" : "";
		
		tbody.append(
			$("<tr>")
				.addClass(changedCss)
				.attr("id", "" + line.orderLineId)
				.append($("<td>")
					.addClass("quantity")
					.append(createQuantityDropdown(0, Math.max(8, parseInt(line.qty) + 4),line.qty))
				)
				.append($("<td>")
					.addClass("name")
					.append($("<span>")
						.addClass("productGroup")
						.append(line.groupName))
					.append("<br />")
					.append(line.name)
				)
				.append($("<td>")
					.addClass("from")
					.append(period)
				)
				.append($("<td>")
					.addClass("unitPrice")
					.append("" + line.priceFormatted)
				)
				.append($("<td>")
					.addClass("total")
					.append("" + line.totalFormatted)
				)
				.append($("<td>")
					.addClass("delete")
					.append($("<a>")
							.addClass("delete")
							.attr("href", "#")
							.append("<span>X</span>")
					)
				)
			);
	}
	
}

function createQuantityDropdown(min, max, selected) {

	var select = $('<select>').addClass("updateQuantity");
	for (var n=min; n<=max; n++)
	{
		var option = $('<option>').attr("value", n).append(n);
		if (n == selected)
			option.attr("selected", "selected");
		
		select.append(option);
	}
	
	return select;
}


function createDeleteConfirmation(td) {
	
	removeDeleteConfirmation();
	
	td.append($("<div>")
		.addClass("confirmation")
		.append($("<p>")
			.append($("<span>")
				.append(txBooking.vilDuFjerneProdukt)
			)
			.append($("<span>")
				.addClass("buttons")
					.append($("<a>")
						.attr("href", "#")
						.addClass("confirm")
						.append(txBooking.ja)
					)
					.append($("<a>")
							.attr("href", "#")
							.addClass("cancel")
							.append(txBooking.nei)
						)
				)
		)
	);
	
	$("body").click(function(){
		removeDeleteConfirmation();
		}
	);
	
	$('div.confirmation').click(function(event){
	     event.stopPropagation();
	 });
	
	addCommonListeners();
}

function removeDeleteConfirmation() {
	$("div.confirmation").remove();	
}


function calPrevMonth() {
	var nextMonth = calendarMonth-1;
	var nextYear = calendarYear;
	
	if (nextMonth == 0)
	{
		nextYear--;
		nextMonth = 12;
	}
	
	calShowMonth(nextMonth, nextYear);
	return false;
}

function calNextMonth() {
	
	var nextMonth = calendarMonth+1;
	var nextYear = calendarYear;
	
	if (nextMonth == 13)
	{
		nextYear++;
		nextMonth = 1;
	}
	
	calShowMonth(nextMonth, nextYear);
	return false;
}

function calShowMonth(month, year)
{

	var monthNames = new Array("", txBooking.januar, txBooking.februar, txBooking.mars, txBooking.april, txBooking.mai, txBooking.juni, txBooking.juli, txBooking.august, txBooking.september, txBooking.oktober, txBooking.november, txBooking.desember);
	
	if ($("#calMonth" + year + month).size() > 0) {
		$(".monthFrame").stop().scrollTo("#calMonth" + year + month, 1000);
		calendarMonth = month;
		calendarYear = year;
		
		$(".calendar h3 span").html("" + monthNames[month] + " " + year);
		
		return true;
	}
	return false;
}

function initBookingSearch()
{
	setLanguage(epLanguage);

	$("#bookingWeek").click(function(event)
	{
		event.stopPropagation();
		toggleCalendar();
		hidePeriod();
	});
	
	$("#bookingPeriod").click(function(event)
	{
		event.stopPropagation();
		togglePeriod();
		hideCalendar();
	});

	$(".monthFrame").stop().scrollTo(0, 0);
	
	$(".weekPicker span.available").click(function()
	{
		var dateId = $(this).attr("id");
		var date = $(this).attr("title");
		$("#bookingWeek").html(date);
		$("#date").val(dateId);

		$("#bookingPeriod").html(txBooking.velg);
		$("#period").val('');
		
		$(".periodPicker li").hide();

		if ($(this).hasClass("sunsun"))
			$("#period_sunsun").show();
		
		if ($(this).hasClass("sunfri"))
			$("#period_sunfri").show();

		if ($(this).hasClass("frisun"))
			$("#period_frisun").show();

		if ($(this).hasClass("friwed"))
			$("#period_friwed").show();

		if ($(this).hasClass("wedsun"))
			$("#period_wedsun").show();

		if ($(this).hasClass("thusun"))
			$("#period_thusun").show();
		
		$(".weekPicker").hide();
	});

	$("div:not(.periodOffer) div.periodPicker li").click(function()
	{		
		var selPeriodData = new String($(this).attr("id")).split("_");
		var periodId = selPeriodData[1];
		var periodName = $(this).attr("title");
		
		$("#bookingPeriod").html(periodName);
		$("#period").val(periodId);
		
		$(".periodPicker").hide();
	});
}

function toggleCalendar() {
	$(".weekPicker").slideToggle();
	
	if ($(".weekPicker:visible").size() > 0)
	{
		$("body").click(function(){
			hideCalendar();
			$("body").unbind('click', hideCalendar);
			}
		);
		
		$('.weekPicker').click(function(event){
		     event.stopPropagation();
		 });
	}
}

function hideCalendar() {
	$(".weekPicker").slideUp();
}

function togglePeriod() {
	$(".periodPicker").slideToggle(200);
	
	if ($(".periodPicker:visible").size() > 0)
	{
		$("body").click(function(){
			hidePeriod();
			$("body").unbind('click', hidePeriod);
			}
		);
		
		$('.periodPicker').click(function(event){
		     event.stopPropagation();
		 });
	}
}

function hidePeriod() {
	$(".periodPicker").slideUp(200);
}

$(document).ready(function(){
	initBookingSearch();
});
