﻿function SidebarQuickSearch(fields)
{
	this.fields = fields;
	this.clearSelection();
	this.bindOnChangeEventHandler();
}

SidebarQuickSearch.serviceUrl = "/services/QuickSearchDestinations.aspx";
SidebarQuickSearch.instance = null;

SidebarQuickSearch.prototype.bindOnChangeEventHandler = function()
{
	var $this = this;
	this.fields.bind("change", function()
	{
		$this.clearSelectionFromFollowingFields(this);
		$this.reloadOptions(this);
	});
};

SidebarQuickSearch.prototype.clearSelection = function()
{
	this.fields.each(function()
	{
		if ("" !== $(this).val())
			$(this).val("")
	});
};

SidebarQuickSearch.prototype.performActionOnFollowingFields = function(field, action)
{
	var performAction = false;
	this.fields.each(function()
	{
		if (performAction)
		{
			action(this);
		}
		if (null == field || this == field)
		{
			performAction = true;
		}
	});
}

SidebarQuickSearch.prototype.clearSelectionFromFollowingFields = function(field)
{
	this.performActionOnFollowingFields(field, function(elem)
	{
		$(elem).val("");
	});
}

SidebarQuickSearch.prototype.reloadOptions = function(field)
{
	var url = this.getReloadOptionsUrl();
	// disable further selections
	this.fields.attr("disabled", "disabled");
	// get new destination data
	var $this = this;

	$.ajax({
		url: url,
		dataType: "json",
		success: function(data)
		{
			// update selection values, for all following fields
			$this.performActionOnFollowingFields(field, function(elem)
			{
				var fieldName = $(elem).attr("name");
				$this.updateField(fieldName, data);
			});
		},
		complete: function()
		{
			// enable further selections
			$this.fields.attr("disabled", "");
		}
	});
};

SidebarQuickSearch.prototype.getReloadOptionsUrl = function()
{
	var options = this.fields.serialize();
	if ("" == options)
	{
		this.fields.attr("disabled", "");
		options = this.fields.serialize();
		this.fields.attr("disabled", "disabled");
	}
	return SidebarQuickSearch.serviceUrl + "?" + this.fields.serialize();
};

SidebarQuickSearch.prototype.updateField = function(name, data)
{
	// abort if no matching field is found
	var field = this.fields.filter("[name='" + name + "']");
	if (1 != field.length)
		return;

	// determine if current field is selected
	var isSelected = ("" !== field.val());

	// crop dropdown and insert new values
	field[0].options.length = 1;
	var options = data[name];
	for (var index in options)
	{
		var option = options[index];
		var elem = $("<option></option>").attr("value", option.id).html(option.name);
		// select first item, if previously selected
		if (isSelected)
			elem.attr("selected", "selected");
		field.append(elem);
	}
};

SidebarQuickSearch.setup = function()
{
	var quicksearch = $(".quickSearch");
	var fields = $(".country select, .area select, .location select", quicksearch);
	if (3 == fields.length)
	{
		SidebarQuickSearch.instance = new SidebarQuickSearch(fields);
	}
};

function SidebarDestinations() { }

SidebarDestinations.cookie = new Cookie("skiaAreaSelector", 365);
SidebarDestinations.active = null;
SidebarDestinations.onclick = function(elem)
{
	var active = $(SidebarDestinations.active);
	if (active !== null)
	{
		active.removeClass("active");
		var content = $(active.parent().next("div")[0]);
		content.addClass("hide");
	}
	if (elem !== SidebarDestinations.active)
	{
		$(elem).addClass("active");
		var content = $($(elem).parent().next("div")[0]);
		content.removeClass("hide");
		SidebarDestinations.active = elem;
	}
	else
	{
		SidebarDestinations.active = null;
	}

	var activeCountry = SidebarDestinations.active != null
		? $(elem).attr("class").match(/\d+/)
		: -1;
	SidebarDestinations.cookie.set(activeCountry);
};

SidebarDestinations.updateActiveFromCookie = function(anchors)
{
	var cookieValue = SidebarDestinations.cookie.get();
	if (cookieValue == -1 && SidebarDestinations.active != null)
	{
		$(SidebarDestinations.active).click();
	}
	else
	{
		var className = ".country" + cookieValue;
		var countryFromCookie = $(anchors).filter(className);
		var countryFromCookieIsUnselected = 0 < countryFromCookie.length && SidebarDestinations.active != countryFromCookie[0];
		if (countryFromCookieIsUnselected)
		{
			countryFromCookie.click();
		}
	}
}

SidebarDestinations.setup = function()
{
	var anchors = $(".sidebar_destinations h5 a");
	anchors.bind("click", function() { SidebarDestinations.onclick(this); });

	var active = $(anchors).filter(".active");
	SidebarDestinations.active = active.length !== 0 ? active[0] : null;
	SidebarDestinations.updateActiveFromCookie(anchors);
};

function Discount() { }

Discount.setup = function()
{
	var discounts = $(".highlights .highlight:not(.highlightfull), .highlights-type2 .highlight-type2:not(.highlightfull-type2)");
	var popups = $(".highlights .highlightfull, .highlights-type2 .highlightfull-type2");
	discounts.bind("click", function()
	{
		$(this).next(".highlightfull, .highlightfull-type2").show();
	});
	popups.bind("click", function()
	{
		$(this).hide();
	});
};

function MenuTextImage() { }

MenuTextImage.setHoverTextImage = function(e)
{
	var menuitem = MenuTextImage.getHoveredItem(e);
	if (null == menuitem)
		return;

	MenuTextImage.changeImageSource(menuitem, true);
};

MenuTextImage.setNormalTextImage = function(e)
{
	var menuitem = MenuTextImage.getHoveredItem(e);
	if (null == menuitem)
		return;

	MenuTextImage.changeImageSource(menuitem, false);
};

MenuTextImage.getHoveredItem = function(e)
{
	var items = $(e.target).parents("li:not(.active)");
	return 0 < items.length ? items[0] : null;
};

MenuTextImage.regexAppendHover = /(\/textimage)(\/[^\/]+\/[^\/]+.gif)/;
MenuTextImage.regexRemoveHover = /(\/textimage)\/hover(\/[^\/]+\/[^\/]+.gif)/;

MenuTextImage.changeImageSource = function(menuitem, hover)
{
	var label = $("img", menuitem);
	var source = label.attr("src");
	var newSource = hover
		? source.replace(MenuTextImage.regexAppendHover, "$1/hover$2")
		: source.replace(MenuTextImage.regexRemoveHover, "$1$2");
	label.attr("src", newSource);
};

MenuTextImage.setup = function()
{
	var menus = $(".navBalk .subnav:has(img), .navBalk .mainnav:has(img)");
	if (0 < menus.length)
	{
		menus.bind("mouseover", MenuTextImage.setHoverTextImage);
		menus.bind("mouseout", MenuTextImage.setNormalTextImage);
	}
};


function Preloader() { }

Preloader.load = function(src, elem)
{
	var preloader = new Image();
	if (elem)
	{
		preloader.onload = function() { $(elem).attr("src", src); };
	}
	preloader.src = src;
};

function Carrousel(container, imagelist)
{
	this.container = container;
	this.imagelist = imagelist;
	this.index = 0;
	this.slideshowTimer = null;
	this.elements = {
		container: this.container,
		image: $(".photo img", this.container),
		link: $(".photo a", this.container),
		overlay: $(".clickOverlay", this.container),
		caption: $("div.caption", this.container),
		counter: $(".controls span.index", this.container),
		next: $(".navigationBar a.next", this.container),
		previous: $(".navigationBar a.previous", this.container)
	};
	this.attachEvents();
	this.start();
}

Carrousel.SlideshowDisplayTime = 5000;

Carrousel.prototype.attachEvents = function()
{
	var $this = this;
	this.elements.next.bind("click", function() { $this.next(); });
	this.elements.previous.bind("click", function() { $this.previous(); });
	if ($.browser.msie)
	{
		this.elements.overlay.bind("click", function()
		{
			$this.elements.link[0].click();
			return false;
		});
	}
};


Carrousel.prototype.next = function()
{
	var isSlideshowRunning = this.stop();

	this.index = this.index + 1;
	if (this.imagelist.length <= this.index)
		this.index = 0;
	this.update();

	if (isSlideshowRunning)
		this.start();
};

Carrousel.prototype.previous = function()
{
	var isSlideshowRunning = this.stop();

	this.index = this.index - 1;
	if (this.index < 0)
		this.index = this.imagelist.length - 1;
	this.update();

	if (isSlideshowRunning)
		this.start();
};

Carrousel.prototype.update = function() {
    var image = this.imagelist[this.index];
    var target = image.url.indexOf("http://") == 0 ? "_blank" : "_top";

    /* Ampersands get encoded twice, once in code behind once here. The replace function corrects this */
    var captionWithCorrectAmpersand = image.caption.replace("&amp;", "&");
    this.elements.caption.text(captionWithCorrectAmpersand);

    this.elements.link.attr("href", image.url);
    this.elements.link.attr("target", target);
    this.elements.counter.text(this.index + 1);
    Preloader.load(image.src, this.elements.image);
};

Carrousel.prototype.isStarted = function()
{
	return this.slideshowTimer != null;
};

Carrousel.prototype.start = function()
{
	if (false === this.isStarted())
	{
		var $this = this;
		this.slideshowTimer = setTimeout(function() { $this.next(); }, Carrousel.SlideshowDisplayTime);
		return true;
	}
	return false;
};

Carrousel.prototype.stop = function()
{
	if (this.isStarted())
	{
		clearTimeout(this.slideshowTimer);
		this.slideshowTimer = null;
		return true;
	}
	return false;
};

Carrousel.instances = [];
Carrousel.setup = function(id, imagelist)
{
	var container = $(".carrousel." + id);
	if (container.length === 1)
	{
		var index = Carrousel.instances.length;
		Carrousel.instances[index] = new Carrousel(container, imagelist);
	}
};

function TabControl(elemObj)
{
	var switchGrPath = "#{0}_tabcontrol > .tabswitch";
	var blockGrPath = "#{0}_tabpages > .tabpage";
	var switchPath = "tabswitch_{0}";
	var blockPath = "tab_{0}";

	var ctrl = this;
	if (elemObj.id.match(/(.*)_(?:tabcontrol)/))
	{
		this.id = elemObj.id;
		this.name = RegExp.$1;
		this.switchPath = switchPath;
		this.blockPath = blockPath;
		this.switchGrPath = switchGrPath.format(this.name);
		this.blockGrPath = blockGrPath.format(this.name);
		$(this.switchGrPath).each(function()
		{
			if (this.id.match(/^tabswitch_(.*)/))
			{
				this.name = RegExp.$1;
				var link = this.tagName == "A" ? this : $("a", this)[0];
				if (link != null)
				{
					link.name = this.name;
					link.onclick = function()
					{
						if (ctrl.showTab(this.name))
							return false;
						else
							return true;
					};
				}
			}
		});
	}
}

TabControl.prototype.showTab = function(itemName)
{
	var targetID = this.blockPath.format(itemName);
	if ($("#" + targetID).length != 0)
	{
		$(this.blockGrPath).each(function()
		{
			if (this.id == targetID)
				$(this).addClass("active");
			else
				$(this).removeClass("active");
		});

		var targetSwitchID = this.switchPath.format(itemName);
		$(this.switchGrPath).each(function()
		{
			if (this.id == targetSwitchID)
				$(this).addClass("active");
			else
				$(this).removeClass("active");
		});

		$(this).trigger("switch", { item: itemName });
		return true;
	}
	else
		return false;
}

TabControl.instances = {};
TabControl.setup = function()
{
	var elems = $(".tabcontrol");
	if (elems.length != 0)
	{
		for (var i = 0; i < elems.length; i++)
		{
			TabControl.instances[elems[i].id] = new TabControl(elems[i]);
		}
	}
}

function SearchRefinement() {};

SearchRefinement.toggleShowAllPopup = function(elem)
{
	var popup = $(elem).parent().next();
	if (popup.hasClass("hide"))
		popup.removeClass("hide");
	else
	    popup.addClass("hide");
};

SearchRefinement.setup = function()
{
	var links = $(".refine .category a.readMore");
	if (links.length != 0)
	{
		links.bind("click", function() { SearchRefinement.toggleShowAllPopup(this); });
	}
};

function PriceTable(container) {
	var $this = this;
	this.container = container;
	this.prices = $(".prices", container);
	this.months = $(".maanden li", container);
	this.loader = $("#loader, #loading", container);
	this.isLoading = false;
	this.isWaiting = false;

	this.months.find("a").bind("click", function() {
		var anchor = $(this);
		return $this.onMonthClicked(anchor);
	});
	this.bindPriceTableFilterButtons();
}

PriceTable.instance = null;
PriceTable.serviceUrl = "/services/PriceTable.aspx?id={0}&month={1}&{2}&{3}";
PriceTable.monthFinder = /[?&]month=(\d+)/;
PriceTable.durationCategoryFinder = /[?&](durationcategory=\d+)/;
PriceTable.packageTypeFinder = /[?&](packagetype=\d+)/;

PriceTable.prototype.isLoadingFinished = function() {
	return (false === this.isLoading && false === this.isWaiting);
};

PriceTable.prototype.showContent = function(html) {
	this.isLoading = false;
	this.prices.html(html);
	this.bindPriceTableFilterButtons();
	if (this.isLoadingFinished())
		this.loader.hide();
};

PriceTable.prototype.showError = function() {
	var message = "Het is op dit moment helaas niet mogelijk de data & prijzen van de geselecteerde maand te tonen. Probeer het later nog eens.";
	var html = '<p class="error">{0}</p>'.format(message);
	this.isLoading = false;
	this.isWaiting = false;
	this.showContent(html);
};

PriceTable.prototype.onMonthClicked = function(anchor) {
	var parent = anchor.parent();
	if (parent.hasClass("active") || false === this.isLoadingFinished())
		return false;

	// select active menu item
	this.months.removeClass("active");
	parent.addClass("active");

	return this.loadPriceTable(anchor);
};

PriceTable.prototype.onPriceTableFilterButtonClicked = function(anchor) {
	return this.loadPriceTable(anchor);
};

PriceTable.prototype.loadPriceTable = function(anchor) {
	if (false === this.isLoadingFinished())
		return false;

	this.isLoading = true;
	this.isWaiting = true;

	// load pricetable html
	var $this = this;
	this.loader.show();
	$.ajax({
		url: $this.getServiceUrl(anchor),
		timeout: 15000,
		dataType: "html",
		success: function(html) { $this.showContent(html) },
		error: function() { $this.showError(); }
	});

	// schedule hiding of loader after specific timespan
	setTimeout(function() {
		$this.isWaiting = false;
		if ($this.isLoadingFinished())
			$this.loader.hide();
	}, 500);

	return false;
};

PriceTable.prototype.getServiceUrl = function(anchor) {
	var id = $("#accommodationId").val();
	var url = anchor.attr("href");
	PriceTable.monthFinder.exec(url);
	var month = RegExp.$1;
	var durationCategory = PriceTable.durationCategoryFinder.exec(url) !== null ? RegExp.$1 : '';
	var packageType = PriceTable.packageTypeFinder.exec(url) !== null ? RegExp.$1 : '';

	return PriceTable.serviceUrl.format(id, month, durationCategory, packageType);
};

PriceTable.prototype.bindPriceTableFilterButtons = function() {
	var $this = this;
	$(".pricetable_filter a", this.container).bind("click", function() {
		var anchor = $(this);
		return $this.onPriceTableFilterButtonClicked(anchor);
	});
};

PriceTable.setup = function() {
	var container = $("#prijzen");
	if (container.length != 0) {
		PriceTable.instance = new PriceTable(container);
	}
};

var Reservation = {};

Reservation.setup = function() {
    $(".show-more-rooms").click(function() {
        $("table.booking tr.hide").removeClass("hide");
        $(this).hide();
        return false;
    });
    $("table.booking tr.hide select").each(function() {
        if ($(this).val() > 0) {
            $(this).parents("tr.hide").removeClass("hide");
        };
    });
    if ($("table.booking tr.hide").length == 0) {
        $(".show-more-rooms").addClass("hide");
    } else {
        $(".show-more-rooms").removeClass("hide");
    };
    $("span.error").each(function() {
        if ($(this).css("visibility") != "hidden" && $(this).css("display") == "none") {
            $(this).css("display", "block");
        };
    });
    var fnCountryId = function() { Reservation.toggleForeignCountryWarning($(this).val() != 17); }; //17=netherlands
    $(".countryId").bind("change", fnCountryId);
    $(".countryId").bind("keyup", fnCountryId);
    Reservation.toggleForeignCountryWarning($(".countryId").val() != 17);

    var fnProducts = function() { Reservation.toggleCustomValues($(this)); };
    $(".products").bind("change", fnProducts);
    $(".products").bind("keyup", fnProducts);
    $(".products").each(function() { Reservation.toggleCustomValues($(this)); });
};

Reservation.toggleForeignCountryWarning = function(on) {
    if (on) { 
        $("#foreignCountryWarning").show();
    } else {
        $("#foreignCountryWarning").hide();
    };
};

Reservation.toggleCustomValues = function(products) {
    var customValues = products.parents().children(".tblCustomValue").eq(0);
    if (products.val() > 0 && customValues.length != 0) {
        customValues.removeClass("hide");
    } else {
        customValues.addClass("hide");
    };
};

// global initialization
$(document).ready(function()
{
	SidebarQuickSearch.setup();
	SidebarDestinations.setup();
	MenuTextImage.setup();
	SearchRefinement.setup();
	TabControl.setup();
	Discount.setup();
	PriceTable.setup();
	Reservation.setup();
});



