/*
 * MooTools
 * versie 1.11
 * used for site interactivity
*/

if (typeof($pick) == 'undefined') {
	$pick = function (obj, picked){
		return $defined(obj) ? obj : picked;
	};
}

Element.implement({
    hide: function() {
        return this.setStyle('opacity',0);
    },

    show: function() {
        return this.setStyle('opacity',0.9);
    }
});


/**
 * Bookingsmodule countrycode and languagecode
 */
var currentCountryCode = 'NL'; // <========= CHANGE THIS =====
if (currentCountryCode == 'NL') {
	var currentLanguageCode = 'NLD';
} else {
	var currentLanguageCode = currentCountryCode;
}

window.addEvent('load', function(){
	var homeMenuButton = $('home');
	if ($chk(homeMenuButton)) {
		if (window.location.protocol == 'https:') {
			homeMenuButton.href = 'http://' + window.location.host + window.location.pathname;
		}
	}
});

var DropdownMenu = new Class({
    initialize: function(element) {
        $A($(element).childNodes).each(function(el) {
            if(el.nodeName.toLowerCase() == 'li')
            {
                $A($(el).childNodes).each(function(el2)
                {
                    if(el2.nodeName.toLowerCase() == 'ul')
                    {
                        $(el2).hide();

                        el.addEvent('mouseover', function() {
                            el2.show();
                            this.getFirst().setStyles({
                                color: '#ff0000',
                                background: 'url(/images/siteimages/icon-main-navigation-active.jpg) left no-repeat'
                            });
                            return false;
                        });

                        el.addEvent('mouseout', function() {
                            el2.hide();
                            //keep parent class selected
                            if (this.getFirst().hasClass('selected')){
                                return false;
                            }
                            this.getFirst().setStyles({
                                color: '#223f86',
                                background: 'url(/images/siteimages/icon-main-navigation.jpg) left no-repeat'
                            });
                            return false;
                        });

                        new DropdownMenu(el2);
                    };
                });
            };
        });
        return this;
    }
});

function slider() {
    if ($chk($('loginButton'))) {
        var controlElement = $('loginButton');
        var toggleElement = $('loginBar');
        var barElement = $('mottoAndLanguageBar');

        //add unobtrusive javascript for onclick event to <a> tag that toggles sliding login panel
        var loginSlider = new Fx.Slide(toggleElement, {duration: 1000}).hide();
        controlElement.removeAttribute("href");
        controlElement.addEvent("click", function(event) {
            if (toggleElement.getStyle('margin-top') == '0px') {
                controlElement.setHTML('Login');
                controlElement.setStyle('background', 'url(/images/siteimages/button-login.jpg) right top no-repeat');
                barElement.setStyle('background', 'url(/images/siteimages/background-header.jpg) left top no-repeat');
                controlElement.setStyle('color', '#ffffff');
            }
            else {
                controlElement.setHTML('Logged in');
                controlElement.setStyle('background', 'url(/images/siteimages/button-login-active.jpg) right top no-repeat');
                barElement.setStyle('background', 'url(/images/siteimages/background-header-squared.jpg) left top no-repeat');
                controlElement.setStyle('color', '#666666');
            };
            loginSlider.toggle();
        });
    };
};

function tooltip(text) {
    var tipFavorites = new Tips($$('#favoritesTab'), {
        initialize:function(){
            this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0);
        },
        onShow: function(toolTip) {
            this.fx.start(1);
        },
        onHide: function(toolTip) {
            this.fx.start(0);
        }
    });
};

function popup() {
    if ($chk($('closeButton'))) {
        var controlElement = $('closeButton');

        //add unobtrusive javascript for onclick event to <a> tag that closes popup
        controlElement.removeAttribute("href");
        controlElement.addEvent("click", function(event) {
            window.close();
        });
    };
    self.resizeTo(500, 630);
    var offSet = getScrollWidth() - getWidth();
    self.resizeTo(500 + offSet, 630);
}

function imageMapDestinations() {
    if ($chk($('imageMapDestinations'))) {
        var updateEffect = new Fx.Styles($E('table', 'destinations'), {duration: 1000,transition: Fx.Transitions.linear});
        var countryHotSpots = $$('#mapEurope area');

        for (var i = 0; i < countryHotSpots.length; i++) {
            countryHotSpots[i].removeProperty('href');
            countryHotSpots[i].addEvent("click", function(event) {
                //alert('ajax call for country ISO: ' + this.getProperty('alt')); // <- Wat is dit?
                /********************************************************************************************
                * event: geklikt op land in kaart europa in destinations page (dp.html)
                * actie: ajax call om tabel met bestemmingen (div#destinations tabel) te updaten
                ********************************************************************************************/

                //opacity from 100% to 0% and back again for visual cue user
                updateEffect.start({
                    'opacity': [1,0]
                }).chain(function(){
                    updateEffect.start({
                    'opacity': [0,1]
                    });
                });
            });
        };
    };
};


function unselectMenus(){
    var menuElements = $$('#dropdownMenu li a');
    //alert(menuElements.length);
    for (var i = 0; i < menuElements.length; i++) {
        menuElements[i].removeClass('selected');
    }
}

function emptyFieldsOnFocus() {
    var inputElements = $$('input');

    if (inputElements.length > 0) {
        //add unobtrusive javascript for onclick event to <input> tag that empties field on entry
        for (var i = 0; i < inputElements.length; i++){
            inputElements[i].onfocus = function(event) {
                  this.value = '';
            };
        };
    };
};

function alignRightSubmenu(){
    var uls = $$('li ul'), Auls;
    if (uls.length > 0) {
        Auls = $A(uls);
		
        if (Auls) {
            //try {
                Auls.getLast().addClass('rightItem');
           // } catch(e) {}
        }
    }
}

function initMenu() {
	menu = $('dropdownMenu');
	if ($chk(menu)){
		new DropdownMenu($('dropdownMenu'));
		alignRightSubmenu();
	}
}

window.addEvent('domready', initMenu.bind(window));


/**
 * Will switch the site language
 *
 * @param {String} isoCode
 * @param {Boolean} siteContainsLanguage
 * @todo Implement location/ dhtml swap rules. Now only redirects to home
 */
function switchSiteLanguage(isoCode, siteContainsLanguage) {	
	window.location = "/?lang=" + isoCode;
}

function ShowBookingsModuleOffline(message) {
	try {
		if (typeof(BookingsModule) == "undefined"
            || BookingsModule.online == true) {

            // NB: don't set BookingsModule.online == false, main bookingsmodule js might not be included
            if (typeof(BookingsModule) != "undefined") {
                BookingsModule.online = false
            }

            if (typeof(BookingsModule) == "undefined"
                || BookingsModule.domReady == true) {
                doShowBookingsModuleOffline(message);
            } else {
            	
                window.addEvent('domready', doShowBookingsModuleOffline.bind(window, message));
            }
        }
		} catch(ex) {
				
			  // something went wrong, let's not make it worse... 
		}
}

function doShowBookingsModuleOffline(message) {
    try {
	      var bmDiv = $('bookingsModule');
	      var messageDiv = $('bmOffline');
	      if (!$chk(bmDiv) || !$chk(messageDiv)) {
		        return;
	      }
	      bmDiv.getChildren().each(function(elt){
		        elt.setStyle('display', 'none');
	      });
	      bmDiv.adopt(messageDiv);
	      try {
		        messageDiv.setStyle('display', 'block');
	      } catch (ex) {
		        messageDiv.style.display = 'block';
	      }
	      messageDiv.setProperty('title', 'Error: ' + message);
		} catch(ex) {
			  // something went wrong, let's not make it worse... 
		}
}

/**
 * Check for global EURO namespace
 */
if(!$chk(EURO)) {
    var EURO = {};
}

/**
 * Redirect for the banners
 * Small correction: if the banners have a frame as target the modal window will be shown.
 *
 * @param {String} destination
 * @param {String} target
 */
EURO.redirect = function(destination, target) {
	if (target == 'frame') {
		destination = convertAnchorUrl(destination);
		modalWindow.showUrl(destination);
		return false;
	}
	window.open(destination, target);
	return false;
}

function popitup(url) {
	if (url.indexOf('?ispopup=true')== -1) {
		url += '?ispopup=true';
	}
	modalWindow.showUrl(url);
	return false;
//		var newwindow = window.open(url,'name','height=520,width=500,resizable=1,scrollbars=1');
//    //newwindow=window.open(url,'name','resizable=1,scrollbars=1');
//    if (newwindow.focus) { newwindow.focus() }
//    return false;
}
function checkForCCPopups(){
	// anchors with onclick="window.open('/popup.php?popup=popup.travel_documents&lang=NLD','','width=300,height=500,toolbar=0,location=0,menubar=0,directories=0,scrollbars=1');" 
	// have to be modified
}
/**
 * Container for debug functionality
 */
var debug = {};

/**
 * Used to log debug messages
 * If 'window.console.log' exists it will be used.
 * Else msg will be alerted if boolShowAlertAlternative is set to true
 *
 * @param {Mixed} msg
 * @param {Boolean} boolShowAlertAlternative
 */
debug.log = function(msg, boolShowAlertAlternative) {
	if ($chk(window.console)) {
		//window.console.log(arguments.callee);
		window.console.log(msg);
	} else if (boolShowAlertAlternative === true) { // only show alternative if forced
        alert(msg);
    }
	return;
}

/**
 * Check all anchors with a CSS-class '_tobelayered'
 * These anchors will be modified to be shown in a modal window 
 * 
 * @return void
 */
function checkLinksToBeLayered() {
	var links = $$("a");
	if (links.length > 0) {
		links.each( function(el) {
			var target= el.getProperty('target');
			var ref = el.getProperty('href');
			if ((el.hasClass('_tobelayered') || target == 'frame') && ref != '#'){
				var ref = convertAnchorUrl(el.href);
				el.href = "#";
				el.setProperty('target', null);
				el.addEvent('click', function() {modalWindow.showUrl(ref);});
			}
		});
	}
}

function convertAnchorUrl(ref) {
	
	/**
	 * If no ispopup is present, it will be added
	 */
	if (ref.indexOf('?ispopup=true')== -1) {
		ref_extra = '';
		/**
		 * Check links for occurence of #
		 * If that's present, the ispopup-variable will be merged before the #
		 */
		if (ref.indexOf('#') != -1) {
			ref = ref.split('#');
			ref_extra = ref[1];
			ref = ref[0];
		}
		var separator = ref.indexOf('?') == -1 ? '?' : '&'; 
		ref += separator + 'ispopup=true#' + ref_extra;
	}
	return ref;
}

/**
 * ModalWindow - a JS class to control a built in modal window.
 * HTML prerequisites: 
 * - underlay to mask the rest of the site
 * - window - the container
 * - content - an HTML container to put content as a string
 * - iframe - to show a page in. 
 * They're accessed by ID. Id's are stored within the options-object used on initialisation
 * 
 * Relevant methods: 
 *  - showURL to show a page within the iframe-object
 *  - showContent to show content - passed as a string.
 *  
 * @author Bart Stroeken
 */
var ModalWindow = new Class({
	
	Implements: new Options(),
	
	/**
	 * Config
	 */
	options: {
		containers: {
			underlay : 'modalUnderlay',
			window : 'modalWindow',
			content : 'modalContent',
			iframe : 'modalIframe'
		},
		
		spacing: {
			// 210: 160 (boven en onder 80 px), + 50 voor de header + knop
			height: 210
		}
	},
	
	/**
	 * Setup all containers, store the body's and html-object's overflow
	 * add an eventhandler to the iframe to resize the modalWindow
	 * 
	 */
	initialize: function(options){

		this.setOptions(options);
		
		this.obj = $(this.options.containers.window);
		
		this.contentdiv = $(this.options.containers.content);
		this.iframe = $(this.options.containers.iframe);
		if ($chk(this.iframe)){
			this.iframe.addEvent('load', this.resize.bind(this));
		}

		this.overlay.object = $(this.options.containers.underlay);
	},

	/**
	 * Overlay-object 
	 * to be shown and to be hidden.
	 */
	overlay : {
		object: null,
		
		display: function(){
			this.object.removeClass('hidden');
			var selects = $$('select');
			selects.each(function(el){ el.addClass('hidden');});
			this.checkBodyStyles();
			this.documentbody.setStyle('overflow', 'hidden');
		},
		
		checkBodyStyles: function(){
			if (!$chk(this.documentbody)){
				this.documentbody = $(window.document.body);
				this.documenthtml = $(window.document.html);

				this.flowStyles = {
					body: this.documentbody.getStyle("overflow"),
					html: this.documenthtml.getStyle("overflow")
				}; 		
				
			}
			
		},
		
		hide : function(){
			var selects = $$('select');
			selects.each(function(el){ el.removeClass('hidden');});
			this.object.addClass('hidden');
			this.documentbody.setStyle('overflow', this.flowStyles.body);
//			this.documenthtml.setStyle('overflow',  this.flowStyles.html);
		}
	},
	
	/**
	 * Display a page in the modalwindow
	 * Start observing the window's resize-event for resizing the modalWindow along
	 */
	showUrl: function(url){
		this.overlay.display();
		this.iframe.setProperty('src', url);
		this.obj.show();
		if (this.obj.hasClass('hidden')){
			this.obj.removeClass('hidden');
		}
		
		this.active = 'iframe';
		this.resize();
		window.addEvent('resize', this.resize.bind(this));
	},
	
	/**
	 * Display a string of content within the modalwindow
	 * Start observing the window's resize-event for resizing the modalWindow along
	 */
	showContent: function(content){
		this.overlay.display();
		this.contentdiv.set('html', content);
		this.obj.show();
		if (this.obj.hasClass('hidden')){
			this.obj.removeClass('hidden');
		}
		this.active = 'content';
		this.resize();
		window.addEvent('resize', this.resize.bind(this));
	},
	
	/**
	 * Resize the modalWindow
	 * The width is set by CSS - the height is calculated
	 */
	resize: function(){
		size = this.obj.getSize();
		var maxheight = document.body.clientHeight - this.options.spacing.height;
		w =  -(size.x/2) + 'px';
		
		if (this.active == 'iframe'){
			this.iframe.setStyle('height', maxheight + 'px');
			this.contentdiv.setStyle('height', '0px');
		} else {
			this.iframe.setStyle('height', '0px');
			this.contentdiv.setStyle('height', maxheight + 'px');
		}
		this.obj.setStyles({
			'marginLeft' : w,
			'marginTop' : - (size.y/2) + 'px'
		});
	},
	
	/**
	 * - Hide the overlay
	 * - clear the content's HTML
	 * - removes the iframe's src
	 * - removes the resize-observer
	 */
	hide: function(){
		this.overlay.hide();
		this.contentdiv.set('html', '');
		this.iframe.removeProperty('src');
		window.removeEvent('resize', this.resize.bind(this));
		this.obj.hide();
	}
});

var modalWindow;
window.addEvent('domready', function(){
	modalWindow = new ModalWindow();
	checkLinksToBeLayered();
});

function displayError(field, errormessage) {
	var error_container = $('errorTooltip');
	var error_content = $('errorContent');
	var target = $(field);
	if (!$chk(error_container) || !$chk(error_content) || !$chk(target)) {
		alert(errormessage);
		return;
	}
	error_content.set('html',errormessage);
	/**
	 * Position the bastard
	 */
	var target_x = target.getCoordinates().left + target.getSize().x;
	var target_y = target.getCoordinates().top;
	error_container.setStyles( {
		position: 'absolute',
		top: target_y + 'px',
		left: target_x + 'px',
		display: 'block'
	})
}

if (!$chk(Util)) {
	var Util = {};
}

Util.urlParameters = {
	
	parameters: null,
	
	setup: function(){
		var url = window.location.href;
		var params = url.substr(url.indexOf('?')+1);
		parametersets = $A(params.split('&'));
		this.parameters = $H();
		parametersets.each(function(value, index){
			var array = value.split('=');
			this.parameters.set(array[0], array[1]);
		}.bind(this));
	},
	
	get: function(index){
		if (!$chk(this.parameters)){
			this.setup();
		}
		return this.parameters.get(index);
	}
};


/**
 * Update the GoogleMaps-url for a frame. If set, a dummy is used for when no content is found.
 * 
 * @param string value
 * @param Element frame
 * @param Element dummy
 */
function updateMap(value, frame, dummy){
	newval = '';
	if ($chk(dummy)) {
		dummy.setStyle('display', 'none');
	}

	frame.setStyle('display', 'none');
	var maps_pattern = /http\:\/\/maps\.google/;
	if (!$chk(value.match(maps_pattern))){
		value = '';
	}
	if (value != '' && value != ' '  ) {
		frame.setStyle('display', 'block');
		frame.src = value.replace(/&amp;/gi, '&');
	}
}

/*
---

script: URI.js

name: URI

description: Provides methods useful in managing the window location and uris.

license: MIT-style license

authors:
  - Sebastian Markbåge
  - Aaron Newton

requires:
  - Core/Selectors
  - /String.QueryString

provides: [URI]

...
*/
var URI = new Class({

	Implements: Options,

	options: {
		/*base: false*/
	},

	regex: /^(?:(\w+):)?(?:\/\/(?:(?:([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)?(\.\.?$|(?:[^?#\/]*\/)*)([^?#]*)(?:\?([^#]*))?(?:#(.*))?/,
	parts: ['scheme', 'user', 'password', 'host', 'port', 'directory', 'file', 'query', 'fragment'],
	schemes: {http: 80, https: 443, ftp: 21, rtsp: 554, mms: 1755, file: 0},

	initialize: function(uri, options){
		this.setOptions(options);
		var base = this.options.base || URI.base;
		if(!uri) uri = base;
		
		if (uri && uri.parsed) this.parsed = $unlink(uri.parsed);
		else this.set('value', uri.href || uri.toString(), base ? new URI(base) : false);
	},

	parse: function(value, base){
		var bits = value.match(this.regex);
		if (!bits) return false;
		bits.shift();
		return this.merge(bits.associate(this.parts), base);
	},

	merge: function(bits, base){
		if ((!bits || !bits.scheme) && (!base || !base.scheme)) return false;
		if (base){
			this.parts.every(function(part){
				if (bits[part]) return false;
				bits[part] = base[part] || '';
				return true;
			});
		}
		bits.port = bits.port || this.schemes[bits.scheme.toLowerCase()];
		bits.directory = bits.directory ? this.parseDirectory(bits.directory, base ? base.directory : '') : '/';
		return bits;
	},

	parseDirectory: function(directory, baseDirectory) {
		directory = (directory.substr(0, 1) == '/' ? '' : (baseDirectory || '/')) + directory;
		if (!directory.test(URI.regs.directoryDot)) return directory;
		var result = [];
		directory.replace(URI.regs.endSlash, '').split('/').each(function(dir){
			if (dir == '..' && result.length > 0) result.pop();
			else if (dir != '.') result.push(dir);
		});
		return result.join('/') + '/';
	},

	combine: function(bits){
		return bits.value || bits.scheme + '://' +
			(bits.user ? bits.user + (bits.password ? ':' + bits.password : '') + '@' : '') +
			(bits.host || '') + (bits.port && bits.port != this.schemes[bits.scheme] ? ':' + bits.port : '') +
			(bits.directory || '/') + (bits.file || '') +
			(bits.query ? '?' + bits.query : '') +
			(bits.fragment ? '#' + bits.fragment : '');
	},

	set: function(part, value, base){
		if (part == 'value'){
			var scheme = value.match(URI.regs.scheme);
			if (scheme) scheme = scheme[1];
			if (scheme && !$defined(this.schemes[scheme.toLowerCase()])) this.parsed = { scheme: scheme, value: value };
			else this.parsed = this.parse(value, (base || this).parsed) || (scheme ? { scheme: scheme, value: value } : { value: value });
		} else if (part == 'data') {
			this.setData(value);
		} else {
			this.parsed[part] = value;
		}
		return this;
	},

	get: function(part, base){
		switch(part){
			case 'value': return this.combine(this.parsed, base ? base.parsed : false);
			case 'data' : return this.getData();
		}
		return this.parsed[part] || '';
	},

	go: function(){
		document.location.href = this.toString();
	},

	toURI: function(){
		return this;
	},

	getData: function(key, part){
		var qs = this.get(part || 'query');
		if (!$chk(qs)) return key ? null : {};
		var obj = qs.parseQueryString();
		return key ? obj[key] : obj;
	},

	setData: function(values, merge, part){
		if (typeof values == 'string'){
			data = this.getData();
			data[arguments[0]] = arguments[1];
			values = data;
		} else if (merge) {
			values = $merge(this.getData(), values);
		}
		return this.set(part || 'query', Hash.toQueryString(values));
	},

	clearData: function(part){
		return this.set(part || 'query', '');
	}

});

URI.prototype.toString = URI.prototype.valueOf = function(){
	return this.get('value');
};

URI.regs = {
	endSlash: /\/$/,
	scheme: /^(\w+):/,
	directoryDot: /\.\/|\.$/
};

URI.base = new URI(document.getElements('base[href]', true).getLast(), {base: document.location});

String.implement({

	toURI: function(options){
		return new URI(this, options);
	}

});

