/*
 * 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);
    }
});

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();
});
