try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

/**
 * static object that handles page logic
 */
var logic = function($){
	/**
	 * private methods and variables
	 */
	var priv = {
		debug	: (resources.debugmode == 'true'),		//enables/disables the error logging
		debugSeverity : 0,	//level of error logging
		console	: $("<ul>").addClass("debug-console"),
		tooltipText : null,
		toolTipWidth : null,
		toolTipBodyWidth : null,
		toolTipHeight : null,
		toolTipBodyHeight : null,
		openPopupId : null,
		showRibbon : false,
				
		initConsole	: function(){
			//if the console has not yet been added to the document, do so now
			if(!priv.console.parentNode){
				$("body").append(priv.console);
			} 
		},
		
		onResizePopup : function() {
		    var width = $(window).width();
		    
            if($('#popupOverlay').length > 0){
                // set width of overlay
                $('#popupOverlay').width(width);
            }
            
            if($('#'+priv.openPopupId).length > 0){
                var topPopup = logic.getCurrentCenterHeight()-($('#'+priv.openPopupId).height()/2);
                if(topPopup < 0) {
                    topPopup = 10;
                }
                $('#'+priv.openPopupId).css({'top':topPopup+'px','left':((width/2)-($('#'+priv.openPopupId).width()/2))+'px'});
            }
        },
		
		setShades : function($addShadows){
			//dynamically write the shades to all the main-content items
			logic.writeDebug('writing shades');
			
			// set shadows to a specific element or to all divs with the shadow class
			if($addShadows == null){
			    $addShadows = $("div.shadow");
			}
            
            $addShadows.each(
				function(i) {
				    //if there are already shades, do nothing
				    if($(this).parent().find("div.shade-top").attr("class")){
				        logic.writeDebug($(this).parent().find("div.shade-top").attr("class"));
				        return;
				    }
				    		
				    if($(this).parent().length != 0 && $(this).parent().css("display") != "none"){
					     //first remove extra margin, for placing
			            $(this).css("margin", "0px");
			            
			            var newWidth = $(this).width();
    					var newHeight = $(this).height();
					    
					    $(this).before(
						    $('<div>').addClass('shade-top-left'),
						    $('<div>').addClass('shade-top').width(newWidth),
						    $('<div>').addClass('shade-top-right'),
						    $('<div>').addClass('clear-both'),
						    $('<div>').addClass('shade-left').height(newHeight)
					    );
					    $(this).after(
						    $('<div>').addClass('shade-right').height(newHeight),
						    $('<div>').addClass('clear-both'),
						    $('<div>').addClass('shade-bottom-left'),
						    $('<div>').addClass('shade-bottom').width(newWidth),
						    $('<div>').addClass('shade-bottom-right')
					    );
					}
				}
			);
		},
		
		correctShades : function($correctShadowsElement){
			logic.writeDebug('correcting shades');
			
			$divShadeLeft = null;
			$divShadeRight = null;
			if($correctShadowsElement != null){
			    $divShadeLeft = $("div.shade-left", $correctShadowsElement);
			    $divShadeRight = $("div.shade-right", $correctShadowsElement);
			} else {
			    $divShadeLeft = $("div.shade-left");
			    $divShadeRight = $("div.shade-right");
			}
			
			var newHeight = 0;
			$divShadeLeft.each(
				function(i){
					$(this).height($(this).next().height());
				}
			);
			
			$divShadeRight.each(
				function(i){
					$(this).height($(this).prev().height());
				}
			);
		},
		
		setRoundedCorners	: function(){
			//create the elements for the general list-rounded class
			$("ul.list-rounded, div.list-rounded").append("<div class='top-left'>").append("<div class='top-right'>").append("<div class='bottom-left'>").append("<div class='bottom-right'>");
			
			//add some styles for the list-promos first-child for older browser support
			$("ul.list-promos>li:first-child").css("border", "none");
			$("ul.list-promos>ul>li:first-child div.top-left, ul.list-promos>ul>li:first-child div.top-right").css("display", "none");
		},
		
		//sets fading borders where elements have class .fading-borders
		setFadingBorders    : function() {
            var localTimer = new Timer();
            $("div.fading-borders").not(".no-script").each(
		        function(i){
		            try {
		                var tmpWidth = $(this).width();
		                var fadeSize = "";
		                var $tmpContent = $("<div class='fade-content'>").css("margin-left", "1px");
		                if(tmpWidth){
		                    $tmpContent.width(tmpWidth - 2);   
		                }
    		            
		                while($(this).children().length > 0){
		                    $tmpContent.append($(this).children()[0]);
		                }
    		            		            
		                //check what size the fades should have
		                if($(this).hasClass("small")){
		                    fadeSize += "-small";
		                }
		                else if($(this).hasClass("med")){
		                     fadeSize += "-med";
		                }
                        
                        //set the borders if width is available
                        if(tmpWidth){
		                    $(this).append("<div class='top-left'>").append("<div class='top-right'>").append(
		                        $("<div class='fade-right" + fadeSize + "'>").width(tmpWidth).append(
		                            $("<div class='fade-left" + fadeSize + "'>").width(tmpWidth - 1).append(
		                                $tmpContent
		                            )
		                        )
		                    );
		                }
		                else {
		                    //if the with is not available
		                     $(this).append("<div class='top-left'>").append("<div class='top-right'>").append(
		                        $("<div class='fade-right" + fadeSize + "'>").append(
		                            $("<div class='fade-left" + fadeSize + "'>").append(
		                                $tmpContent
		                            )
		                        )
		                    );
		                }
		             }
		             catch(err){
		                logic.writeDebug("Error setting fading borders: " + err, 0);
		             }      
		        }
		    );
		    logic.writeDebug("setFadingBorders script time was: " + (localTimer.Stop()) + " ms", -1);
		},
		
		setAlternating	: function(){
			$("ul.alternating>li:nth-child(even), table.alternating>tr:nth-child(even)").addClass("even");
			$("ul.alternating>li:nth-child(odd), table.alternating>tr:nth-child(odd)").addClass("odd");
		}
		
		
	};
	
	/**
	 * public methods
	 */
	return {
		//prefix that should be used when setting cookies
		CookiePrefix	: resources.cookie_prefix,
		
		/**
		 * initializes the page logic
		 * to be called on $(document).ready
		 */
		OnReady	: function(){
			//add trim method to the string object
			String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g,"");}
			String.prototype.trimBetween = function(){
		        var vals = this.split(" ");
		        var newString = '';
		        for(var i=0;i<vals.length;i++) { 
		            var s = vals[i];
			        if(s.trim().length > 0){
				        newString += s + " ";
			        }
		        }
		        return newString.trim().replace(/\n/g,'');
			}
			String.prototype.stripTags = function() {return this.replace(/<(.|\n)*?>/g, "");}
			String.format = function()
            {
                if( arguments.length == 0 )
                    return null;

                var str = arguments[0];
                for(var i=1;i<arguments.length;i++)
                {
                    var re = new RegExp('\\{' + (i-1) + '\\}','gm');
                    str = str.replace(re, arguments[i]);
                }

                return str;
            }            
            
            $('#country-links-btn').toggle(function(){                
                $('#country-links').css({display:'none'});
                $('#bottom').css({height:'27px'});  
                priv.correctShades();
            },
            function(){                
                $('#country-links').css({display:'block'});
                $('#bottom').css({height:'50px'});                    
                priv.correctShades();
            }
            );
            $('#country-links-btn').trigger('click');
            
			var personalItemsTimer = new Timer();
			//load and show the personal item links
			personalItems.Load("alreadyviewed");
			personalItems.Load("favorites");
			personalItems.ShowItemLinks();
			logic.writeDebug("personalItems script time was: " + (personalItemsTimer.Stop()) + " ms", -1);
		    		    
			//initialize the resultList
			if(typeof(resultList) != "undefined"){
			    var ResultListTimer = new Timer();
				resultList.OnReady();
				logic.writeDebug("resultList script time was: " + (ResultListTimer.Stop()) + " ms", -1);
			}
			
			//initialize the accoDetails
			if(typeof(accoDetails) != "undefined"){
				var AccoDetailsTimer = new Timer();
				accoDetails.OnReady();
				logic.writeDebug("accoDetails script time was: " + (AccoDetailsTimer.Stop()) + " ms", -1);
			}
			
			//initialize the location
			if(typeof(locDetails) != "undefined"){
				var LocDetailsTimer = new Timer();
				locDetails.OnReady();
				logic.writeDebug("locDetails script time was: " + (LocDetailsTimer.Stop()) + " ms", -1);
			}
			
			//initialize the home
			if(typeof(homePage) != "undefined"){
				homePage.OnReady();
			}
			
			//initialize the travelers
			if(typeof(travelers) != "undefined"){
			    var travelersTimer = new Timer();
				travelers.OnReady();
				logic.writeDebug("travelers script time was: " + (travelersTimer.Stop()) + " ms", -1);
			}
			
			//initialize the resultList
			if(typeof(promotions) != "undefined"){
			    var promotionsTimer = new Timer();
				promotions.OnReady();
				logic.writeDebug("promotions script time was: " + (promotionsTimer.Stop()) + " ms", -1);
			}
			
			if(typeof(compareList) != "undefined"){
			    var compareListTimer = new Timer();
				compareList.OnReady();
				logic.writeDebug("compareList script time was: " + (compareListTimer.Stop()) + " ms", -1);
			}
			
			if(typeof(imageCreator) != "undefined"){
			    var imageCreatorTimer = new Timer();
				imageCreator.OnReady();
				logic.writeDebug("imageCreator script time was: " + (imageCreatorTimer.Stop()) + " ms", -1);
			}
			
			//for the PromoPage pages
			if(typeof(PromoPage) != "undefined"){
			    PromoPage.OnReady();
			}
			
			//for the booking pages
			if(typeof(bookingLogic) != "undefined"){
			    bookingLogic.OnReady();
			}
						
			//Some generic list styles and classes that should be added			
			//setFading
			//priv.setFadingBorders();
			//set alternating rows
			
			//set events to promotions that could be on the page
			//bind events
            $('ul.promotion-blocks').children("li").hover(
                function(){$(this).addClass("hover");},
		        function(){$(this).removeClass("hover");}
            ).bind("click",
                function(){
                    //redirect to the correct page
                    var url = $(this).find(".promo-acco-name a").attr("href");
                    
                    document.location.href = url;
                    //prevent event bubbling
                    return false;
                }
            );
            
            $(priv.freeTextInputElement).bind("keydown", 
			    function(evt){
			        if(evt.keyCode == 27){
			            logic.hidePopup();
			        }
			    }
			);
			
			$('div.directto select').bind('change',
			    function(){
			        var nValue = $(this).val();
			        if(nValue != null && nValue != '-1' && nValue != ''){
			            var rel = $(':selected', this).attr('rel')
			            if(rel != null && rel != '' ){
			                var type = '&type=search';
			                if(location.href.indexOf('offers.aspx') != -1 || location.href.indexOf('lastminutes.aspx') != -1){
		                        type = '&type=offers';
		                    }
			                var response = $.ajax({
                            url: resources.path_prefix + '/utilpages/checkquery.ashx',
                            data:   $('#hidQueryString').attr('rel')+'&rel='+rel+type,
                            async: false}).responseText;
                            
                            if(response == '1'){
                                var hidQueryString = $('#hidQueryString').attr('rel');
                                var curNvalue = logic.getURLParamFromString('N', '?'+hidQueryString);
                                hidQueryString = logic.removeURLParam(hidQueryString, 'N');
                                hidQueryString = 'N='+curNvalue+'+'+nValue+'&'+hidQueryString.replace('&&','&');
                                if(location.href.indexOf('offers.aspx') != -1 || location.href.indexOf('lastminutes.aspx') != -1){
			                        location.href = resources.path_prefix+'/lastminutes.aspx?'+hidQueryString;
			                    } else {
			                        location.href = resources.path_prefix+'/search.aspx?'+hidQueryString;
			                    }
                            } else {
                                var confirmMessage = response;
                                confirmMessage = confirmMessage.replace(/{bestemming}/g, $(':selected', this).text().trim());
                                var allSearchOptions = $('#result-properties table td.txt');
                                var searchOptions = $(allSearchOptions.get(0)).text().replace(/\(wis\)/g,'').trimBetween();
                                var departureOptions = $(allSearchOptions.get(1)).text().trimBetween();
                                departureOptions = departureOptions.substring(0, departureOptions.indexOf('(')).trim();
                                if(searchOptions == 'Selecteer aan linkerkant')
                                    searchOptions = '';
                                else 
                                    searchOptions = searchOptions + ', ';
                                confirmMessage = confirmMessage.replace(/{zoekopties}/g, '('+searchOptions+departureOptions+')');
                                if(confirm(confirmMessage)){
                                    if(location.href.indexOf('offers.aspx') != -1 || location.href.indexOf('lastminutes.aspx') != -1){
			                            location.href = resources.path_prefix+'/lastminutes.aspx?N='+nValue;
			                        } else {
			                            location.href = resources.path_prefix+'/search.aspx?N='+nValue;
			                        }
                                } else {
                                    resultList.selectDirectTo();
                                }
                            }
			            } else {
			                if(location.href.indexOf('offers.aspx') != -1 || location.href.indexOf('lastminutes.aspx') != -1){
			                    location.href = resources.path_prefix+'/lastminutes.aspx?N='+nValue;
			                } else {
			                    location.href = resources.path_prefix+'/search.aspx?N='+nValue;
			                }
			            }
			        }
			    }
			);
			
			//corrects the shades when the the page is fully loaded
			//sometimes images can stretch the page height and additional correction is needed
			//if(!jQuery.browser.msie || 
			//    (jQuery.browser.msie && parseInt(jQuery.browser.version)>=7 ))
			$(window).bind("load",
				function() {
					//sets the shades			        
			        if(logic.getURLParam("view") != "prices"){
                        priv.setShades();
                    }
			        priv.setRoundedCorners();
			        priv.setAlternating();

				}
			);
			
			//show the "new site ribbon", exept on the reservation pages, and popups
			if(priv.showRibbon && document.location.href.indexOf("/reservation") == -1 && document.location.href.indexOf("/popup") == -1){
			    //define the set of <div>s that hold the click events
			    var clickDivsHtml = "";
			     			    
			    for(var i=1; i<=5; i++){
			        clickDivsHtml += "<div class='img-" + i + "'></div>";
			    }
			    
			    $("body").append($("<div id='ribbon-tag'>").html(clickDivsHtml).bind("click", 
			        function(evt){
			            //navigate home
			            document.location.href = resources.path_prefix + "/default.aspx";
			        }
			    ));
			    $("#ribbon-tag div").bind("click",
			        function(evt){
			            formsubmit.showSendReactionPopup();
			            return false;
			        }
			    );
			}
		},
				
		OnResize	: function(){
			//triggered on resize
			priv.onResizePopup();
		},
		
		CorrectShades   : function(){
		    priv.correctShades();
		},
		
		getJsParams : function (javascriptfile){
            var params = new Object();

            javascriptfile = javascriptfile + '?';
            var tags = document.getElementsByTagName('script');
            for (var n = 0; n < tags.length; n++)
            {
                var startIndex = tags[n].src.indexOf(javascriptfile);
                if(startIndex != -1){
                   var urlparams = tags[n].src.substring(javascriptfile.length+startIndex);
                   var params = urlparams.split('&');
                   for(var i = 0;i<params.length;i++){
                     var param = params[i].split('=');
                     if(param[1] != null && param[1] != ''){
                        params[param[0]] = param[1];
                     }
                   }
                }
            }
            
            return params;
        },
        
        NewWindow   : function(mypage,myname,w,h,pos,infocus){
            var win=null;
            if(pos=="random"){
                myleft = (screen.width)?Math.floor(Math.random()*(screen.width-w)):100;mytop=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;
            }
            if(pos=="center"){
                myleft=(screen.width)?(screen.width-w)/2:100;mytop=(screen.height)?(screen.height-h)/2:100;
            }
            else if((pos!='center' && pos!="random") || pos==null){
                myleft=0;mytop=20
            }
            settings="width=" + w + ",height=" + h + ",top=" + mytop + ",left=" + myleft + ",scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes";win=window.open(mypage,myname,settings);
            win.focus();
        },

        getURLParam : function (strParameterName)
        {
            var strURL = location.href;
            
            var splitChar = '?';
            if ( strURL.indexOf (splitChar) == -1 )
                splitChar = '#';
                
            if ( strURL.indexOf (splitChar) > 0 )
            {
                var strParameters = strURL.split (splitChar) [1].split ("&");
                for ( i = 0; i < strParameters.length; i++ )
                {
                    if ( strParameters [i].indexOf ("=") > 0 )
                    {
                        var strParameterValue = strParameters [ i ].split ("=");
                        if ( strParameterValue [0] == strParameterName )
                            return strParameterValue [1].split('#')[0];
                    }
                }
            }
            return "";
        },
        
        removeURLParam : function (strURL, strParameterName)
        {                            
            var newUrl = '';
            var strParameters = strURL.split ("&");
            for ( i = 0; i < strParameters.length; i++ )
            {
                if (strParameters[i].indexOf("=") > 0 && strParameters[i].indexOf(strParameterName+"=") == -1)
                {
                    var strParameterValue = strParameters [ i ].split ("=");
                    if(i == 0){
                        newUrl += strParameterValue[0] + '=' +strParameterValue[1];
                    } else {
                        newUrl += '&'+strParameterValue[0] + '=' +strParameterValue[1];
                    }
                }
            }
            
            return newUrl;
        },
        
        getURLParamFromString : function (strParameterName, strURL)
        {
            var strURL = strURL;
            
            var splitChar = '?';
            if ( strURL.indexOf (splitChar) == -1 )
                splitChar = '#';
                
            if ( strURL.indexOf (splitChar) > -1 )
            {
                var strParameters = strURL.split (splitChar) [1].split ("&");
                for ( i = 0; i < strParameters.length; i++ )
                {
                    if ( strParameters [i].indexOf ("=") > 0 )
                    {
                        var strParameterValue = strParameters [ i ].split ("=");
                        if ( strParameterValue [0] == strParameterName )
                            return strParameterValue [1];
                    }
                }
            }
            return "";
        },        
        
        urlEncode : function (urlToEncode)
        {
	        // The Javascript escape and unescape functions do not correspond
	        // with what browsers actually do...
	        var SAFECHARS = "0123456789" +					// Numeric
					        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					        "abcdefghijklmnopqrstuvwxyz" +
					        "-_.!~*'()";					// RFC2396 Mark characters
	        var HEX = "0123456789ABCDEF";

	        var plaintext = urlToEncode;
	        var encoded = "";
	        for (var i = 0; i < plaintext.length; i++ ) {
		        var ch = plaintext.charAt(i);
	            if (ch == " ") {
		            encoded += "+";				// x-www-urlencoded, rather than %20
		        } else if (SAFECHARS.indexOf(ch) != -1) {
		            encoded += ch;
		        } else {
		            var charCode = ch.charCodeAt(0);
			        if (charCode > 255) {
			            alert( "Unicode Character '" 
                                + ch 
                                + "' cannot be encoded using standard URL encoding.\n" +
				                  "(URL encoding only supports 8-bit characters.)\n" +
						          "A space (+) will be substituted." );
				        encoded += "+";
			        } else {
				        encoded += "%";
				        encoded += HEX.charAt((charCode >> 4) & 0xF);
				        encoded += HEX.charAt(charCode & 0xF);
			        }
		        }
	        } // for

	        return encoded;
        },
        
        getCurrentCenterHeight : function () {
            var myHeight = 0;
            if( typeof( window.innerWidth ) == 'number' ) {
                //Non-IE
                myHeight = window.innerHeight;
            } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
                //IE 6+ in 'standards compliant mode'
                myHeight = document.documentElement.clientHeight;
            } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                //IE 4 compatible
                myHeight = document.body.clientHeight;
            }
            
            var scrOfY = 0;
            if( typeof( window.pageYOffset ) == 'number' ) {
                //Netscape compliant
                scrOfY = window.pageYOffset;
            } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
                //DOM compliant
                scrOfY = document.body.scrollTop;
            } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
                //IE6 standards compliant mode
                scrOfY = document.documentElement.scrollTop;
            }
            
            myHeight = (myHeight/2) + scrOfY;
            
            return myHeight;
        },
        
        getBottomPage : function () {
            var myHeight = 0;
            if( typeof( window.innerWidth ) == 'number' ) {
                //Non-IE
                myHeight = window.innerHeight;
            } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
                //IE 6+ in 'standards compliant mode'
                myHeight = document.documentElement.clientHeight;
            } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                //IE 4 compatible
                myHeight = document.body.clientHeight;
            }
            
            var scrOfY = 0;
            if( typeof( window.pageYOffset ) == 'number' ) {
                //Netscape compliant
                scrOfY = window.pageYOffset;
            } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
                //DOM compliant
                scrOfY = document.body.scrollTop;
            } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
                //IE6 standards compliant mode
                scrOfY = document.documentElement.scrollTop;
            }
            
            myHeight = myHeight + scrOfY;
            
            return myHeight;
        },
        
        /**
		 * ajaxParams is a function which takes an array of keys and values and generates a string jQuery understands to send as parameters
		 * @param {Array} names Array with parameter names
		 * @param {Array} values Array with parameter values
		 */
        ajaxParams : function (names, values){
			
			if(names.length < 1) return '';
			if(values.length < 1) return '';
			
			var dataString = '{';
			for(x = 0; x < names.length; x++){
				if(typeof(values[x]) == 'string'){
					dataString += '"' + names[x].replace('"', '\\"') + '": "' + values[x].replace('"', '\\"') + '",';
				}
				else {
					dataString += '"' + names[x] + '": "' + values[x] + '",';
				}
			}
			
			dataString = dataString.substring(0, dataString.length - 1);
			dataString += '}';
			return dataString;
		},
        
        /**
		 * shows an tooltip when hovered over the element(s)
		 * @param {jQuery object} $element
		 * @param {Int} altOrTitle: 0 - tooltip from alt, 1 - tooltip from title
		 */
        toolTip : function($element, altOrTitleOrFile, loadUrl, leftMargin) {           
            if(leftMargin == null)
                leftMargin = 10;
            if(altOrTitleOrFile == null)
                altOrTitleOrFile = 1;
            
            $element.mousemove(function(e){
                var toolTipId = '#info_tooltip2';
                if(altOrTitleOrFile < 2) {
			        toolTipId = '#info_tooltip'; 
			    } 	
			    
			    var left = 0;
		        if(priv.toolTipBodyWidth < (e.pageX+leftMargin+priv.toolTipWidth)){
                   left = (e.pageX-leftMargin-priv.toolTipWidth);
                } else {
                   left = (e.pageX+leftMargin);
                }
                var top = 0;
                if(priv.toolTipBodyHeight < (e.pageY+10+priv.toolTipHeight)){
                   top = (e.pageY-10-priv.toolTipHeight);
                } else {
                   top = (e.pageY+10);
                }
                
                $(toolTipId).css({'top':top+'px','left':left+'px'});
            });
            
            $element.hover(
                function (e) {
                    priv.toolTipBodyHeight = logic.getBottomPage();
                    priv.toolTipBodyWidth = $('body').width();
                    if(altOrTitleOrFile < 2){
                        // normal tooltip
                        if(altOrTitleOrFile == null || altOrTitleOrFile == 0){
                            priv.tooltipText = this.alt;
                            this.alt = '';
                        } else {
                            priv.tooltipText = this.title;
                            this.title = '';
                        }
                        
                        if(priv.tooltipText != ''){
                            if($('#info_tooltip').length == 0){
			                    $('#site-container').append($('<div id="info_tooltip">').css('position','absolute'));
			                    $('#info_tooltip').html(priv.tooltipText);
			                } else {
			                    $('#info_tooltip').html(priv.tooltipText);
			                    $('#info_tooltip').show();
			                }
			            }
			            
			            priv.toolTipWidth = $('#info_tooltip').width();
			            priv.toolTipHeight = $('#info_tooltip').height();
			        } else {
			            if($('#info_tooltip2').length == 0){
			                $('#site-container').append($('<div id="info_tooltip2">').css('position','absolute'));
			            } 
			            $('#info_tooltip2').load(loadUrl, null, null);
			            $('#info_tooltip2').show();
			            			            
			            priv.toolTipWidth = $('#info_tooltip2').width();
			            priv.toolTipHeight = 222;
                        // make daterange dropdown invisible if IE
                        if (($.browser.msie))
                        {
                            if(priv.toolTipBodyHeight < (e.pageY+10+priv.toolTipHeight))
                            {   
			                    var dropdown = $('select.daterange');
			                    if (dropdown != null)
			                    {
			                        dropdown.css("visibility", "hidden")
    			                }                        
			                }
                        }	
			        }
                },
                function () {
                    
                    if(altOrTitleOrFile < 2){
                        // normal tooltip
                        $('#info_tooltip').hide();
                        
                        if(altOrTitleOrFile == null || altOrTitleOrFile == 0){
                            this.alt = priv.tooltipText;
                        } else {
                            this.title = priv.tooltipText;
                        }
                    } else {
                        $('#info_tooltip2').html('');
                        // make daterange dropdown visible if IE
                        if (($.browser.msie))
                        {   
			                var dropdown = $('select.daterange');
			                if (dropdown != null)
			                {
			                    dropdown.css("visibility", "visible")
    			            }                        
			            }
                        
                        $('#info_tooltip2').hide();
                    }
                }
            );
        },
        
        showPopup : function (popupId, showOverlay, popupWidth, popupPadding, preloader) {
            $('object').hide();
            
            // set default parameters
            if(showOverlay == null){
                showOverlay = true;
            }
            if(popupWidth == null){
                popupWidth = 500;
            }
            if(popupPadding == null){
                popupPadding = 10;
            }
            
            if(priv.openPopupId != null){
                $('#'+priv.openPopupId).hide();
            }
            
            var screenWidth = $(window).width();
            var screenHeight = $(window).height();
            var scrollY = $(document).scrollTop();
            var pageX = $(document).width();
            var pageY = $(document).height();
            
            var opacity = (!preloader)? 7 : 3;
            if(showOverlay != null && showOverlay == true){
                // create page overlayDiv if it doesnt exist
                if($('#popupOverlay').length == 0){
                    $('body').append($('<div id="popupOverlay">'));
                    $('#popupOverlay').css({'z-index':'999','background-color':'#4d4d4d','position':'absolute','top':'0','left':'0','opacity':'.' + opacity,'filter':'alpha(opacity=70)'});
                }
                // set heigth and width of overlay
                $('#popupOverlay').width(pageX);
                $('#popupOverlay').height(pageY);
                if(!preloader)
                    $('#popupOverlay').bind("click", 
			            function(){
			                logic.hidePopup();
			            }
			        );
            }
            
            // initialize popup
            var wrapperWidth = popupWidth+20+(popupPadding*2);
            if($('#'+popupId).attr('class').indexOf('initialized') == -1){
                $('#'+popupId).css({'width':wrapperWidth+'px'});

                // add padding and width and closebutton
                if(popupWidth == null) {
                    popupWidth = 400;
                }
                if(popupPadding == null) {
                    popupPadding = 10;
                }
                var $curPopup = $('.shadow:eq(0)', '#'+popupId);
                var popupHtml = $curPopup.html();
                var $closeButton = $('<a href="javascript:void(0);">' + resources.closeWindow + '</a>').addClass('remove').css({'position':'absolute'});
                if(!preloader)
                $closeButton.bind("click",
				    function(){
					    logic.hidePopup();
				    }
			    );
			    
                var $newDiv = $('<div>').css({'width':popupWidth+'px','padding':popupPadding+'px', 'position' : 'relative'});
                $newDiv.html(popupHtml);
                if(!preloader)
                    $newDiv.prepend($closeButton);
                $curPopup.html('');
                $curPopup.append($newDiv);             
                
                $('body').append($('#'+popupId));
                
                $('a.pCancel', $curPopup).bind("click",
				    function(){
					    logic.hidePopup();
				    }
			    ); 
			    $('#'+popupId).addClass('initialized');
            }
            
            // set position of popup
            var topPopup = ((screenHeight/2) + scrollY)-($('#'+popupId).height()/2);
            if(topPopup < 0) {
                topPopup = 10;
            }
            $('#'+popupId).css({'top':topPopup+'px','left':((screenWidth/2)-(popupWidth/2))+'px'});
            
            // show overlay if necessary
            if(showOverlay){
                $('#popupOverlay').show();
            }
            
            // show the popup
            $('#'+popupId).show();
            if($('.shade-top-left', '#'+popupId).length == 0){
                priv.setShades($('.shadow', '#'+popupId));
            }
            
            priv.openPopupId = popupId;
        },
        
        /**
        * Renders a popup containing the HTML from all the DIV elements of a given page
        **/
        showDynamicPopup : function (htmlPath, linkObj) {
	        //create the popup element if it does not already exist
	        if(!$("#dynamic-popup").get(0)){
	            var popupHTML = "" + 
	                "<div id='dynamic-popup' class='popup'>" + 
	                    "<div class='shadow'>" + 
	                        "<div class='heading'></div>" + 
	                        "<div class='content'></div>" + 
	                        "<div style='padding-top:10px; padding-bottom:10px; padding-left:10px;'><strong><a href='javascript:logic.hidePopup(\"pSubscribe\")' id='remove2'>" + resources.closeWindow + "</a></strong></div>" + 
	                    "</div>" + 
	                "</div>";
	            var popupDiv = document.createElement("DIV");
	            popupDiv.innerHTML = popupHTML;
	            $("BODY").append(popupDiv);
	        }
	        
	        $('#dynamic-popup div.content').html('&nbsp;');
	        logic.resizePopup();
            logic.showPopup('dynamic-popup', true, 623, 0);
            $('#dynamic-popup div.heading').html($(linkObj).html());
            $('#dynamic-popup div.content').load(htmlPath + " div", null, logic.callBackResizePopup);
	    },
        
        hidePopup : function () {
            if(priv.openPopupId == 'pSunwebVideo'){
                accoVideo.Remove();
                $('#videodiv').html('');
            }
            $('#popupOverlay').hide();
            $('#'+priv.openPopupId).hide();
            $('object').show();
            priv.openPopupId = null;
        },
        
        callBackResizePopup : function () {
            priv.correctShades($('#'+priv.openPopupId)); 
            
            var topPopup = logic.getCurrentCenterHeight()-($('#'+priv.openPopupId).height()/2);
            if(topPopup < 0) {
                topPopup = 10;
            }
            $('#'+priv.openPopupId).css({'top':topPopup+'px'});
        },
        
        resizePopup : function (resizePopupId) {
            if(resizePopupId != null) {
                priv.correctShades($('#'+resizePopupId));
            } else {
                priv.correctShades($('#'+priv.openPopupId));
            }
        },
        
        findPosX : function (obj)
        {
            var curleft = 0;
            if(obj.offsetParent)
                while(1) 
                {
                  curleft += obj.offsetLeft;
                  if(!obj.offsetParent)
                    break;
                  obj = obj.offsetParent;
                }
            else if(obj.x)
                curleft += obj.x;
            return curleft;
        },

        findPosY : function(obj)
        {
            var curtop = 0;
            if(obj.offsetParent)
                while(1)
                {
                  curtop += obj.offsetTop;
                  if(!obj.offsetParent)
                    break;
                  obj = obj.offsetParent;
                }
            else if(obj.y)
                curtop += obj.y;
            return curtop;
        },
        		
		/**
		 * handles the writing of debug messages
		 * @param {String} msg
		 * @param {Int} severity: 0 info, 1 wanring, 2 error, 3 critical
		 */
		writeDebug	: function(msg, severity){
			if(typeof(severity) == "undefined"){
				severity = 0;
			}
			
			if(priv.debug && severity <= priv.debugSeverity){
				//check whether debug console exists
				if(typeof(console) != "undefined" && console.log){
					console.log(msg);
				}
				//if no debug console exists: create debug div
				else {
					priv.initConsole();
					$(priv.console).append(
						$("<li>").html(msg)
					);
				}
			}
		}
	}
}(jQuery);

var formsubmit = function($){
	/**
	 * private methods and variables
	 */
	var priv = {
	
	    sendAccoClicked : false,
	    addReviewClicked : false,
	    addMagazineClicked : false,
	    sendReactionClicked : false,
	    sendCancellationClicked : false,
	    sendPreBookingClicked : false,
	    
	    showSubscribeError : function(errorMsg){
	        $('#subscribe-errormsg').show();
	        $('#subscribe-errormsg').html(errorMsg);
	        logic.resizePopup();
	    },
	    
	    successSubscribeNewsletter : function (result){
	        $('#un-or-subscribe-newsletter').hide();
	        
	        if( result == "1" )
	        {	         
	            $('#subscribe-succeeded').show();
	            logic.showPopup('subscribe-succeeded', true, 500, 0);
	        }
	        if( result == "0" )
	        {
	            $('#subscribe-allreadydone').show();
	            logic.showPopup('subscribe-allreadydone', true, 500, 0);
	        }        
            
            logic.resizePopup();	        
	    },
	    
	    successUnsubscribeNewsletter : function (result){
	        $('#un-or-subscribe-newsletter').hide();
	        $('#unsubscribe-succeeded').show();
            logic.showPopup('unsubscribe-succeeded', true, 500, 0);
            logic.resizePopup();	        
	    },	    
	    
	    errorUnOrSubscribeNewsletter : function (result){
	        $('#un-or-subscribe-newsletter').hide();
	        $('#un-or-subscribe-failed').show();
	        //logic.writeDebug("Submit error: " + result, 2);
	        //priv.showSubscribeError('Er is een fout opgetreden');
            logic.showPopup('un-or-subscribe-failed', true, 500, 0);
            logic.resizePopup();	        
	    },
	    
	    showReviewError : function(errorMsg){
	        priv.addReviewClicked = false;
	        $('#review-errormsg').show();
	        $('#review-errormsg').html(errorMsg);
	        logic.resizePopup();
	    },

	    successAddReviewAcco : function (result){
	        priv.addReviewClicked = false;
	        $('#review-email').val('');
	        $('#review-name').val('');
	        $('#review-text').val('');
	        $('#review-errormsg').hide();
	        
	        $('#addreview-content').hide();
	        $('#addreview-send').show();
	        logic.resizePopup();
	    },
	    
	    errorAddReviewAcco : function (result){
	        priv.addReviewClicked = false;
	        logic.writeDebug("Submit error: " + result);
	        priv.showReviewError('Er is een fout opgetreden');
	    },
	    
	    showSendAccoError : function(errorMsg){
	        priv.sendAccoClicked = false;
	        $('#send-errormsg').show();
	        $('#send-errormsg').html(errorMsg);
	        logic.resizePopup();
	    },
	    
	    successSendAcco : function (result){	        
	        // reset input boxes
	        $('#toEmails').val('');
            $('#txtMessage').val('');
            $('#txtFromName').val('');
            $('#txtFromEmail').val('');
	        $('#sendAccoContent').hide();
	        $('#sendAccoMessage').show();
	        logic.resizePopup();
	        
	        priv.sendAccoClicked = false;
	    },
	    
	    errorSendAcco : function (result){
	        priv.showSendAccoError('Er is een fout opgetreden');
	        
	        priv.sendAccoClicked = false;
	    },
	    
	    successCancellation : function (result) {
	        // reset input boxes
	        //$('#sendCancellationContent').hide();
	        //$('#sendCancellationMessage').show();
	        //logic.resizePopup();
	        window.location = resources.path_prefix + '/html/sendSuccess.aspx?type=cancellation';
	        priv.sendCancellationClicked = false;
	    },
	    
	    errorCancellation : function (result) {
	        priv.showCancellationError('Er is een fout opgetreden');
	        priv.sendCancellationClicked = false;
	    },
	    
	    showCancellationError : function (errorMsg) {
	        priv.sendCancellationClicked = false;
	        $('#cancellation-send-errormsg').show();
	        $('#cancellation-send-errormsg').html(errorMsg);
	        logic.CorrectShades();	        
	    },
	    
	    successPrebooking : function (result) {
	        window.location = resources.path_prefix + '/html/sendSuccess.aspx?type=prebook';
	        priv.sendPrebookingClicked = false;
	    },
	    
	    errorPrebooking : function (result) {
	        priv.showPreBookError('Er is een fout opgetreden');
	        priv.sendPrebookingClicked = false;
	    },
	    
	    showPreBookError : function (errorMsg) {
	        priv.sendPreBookingClicked = false;
	        $('#prebook-send-errormsg').show();
	        $('#prebook-send-errormsg').html(errorMsg);
	        logic.CorrectShades();
	    },
	    
	    showSendReactionError : function(errorMsg){
	        priv.sendReactionClicked = false;
	        $('#sendreaction-errormsg').show();
	        $('#sendreaction-errormsg').html(errorMsg);
	        logic.resizePopup();
	    },
	    
	    successSendReaction : function (result){	        
	        // reset input boxes
            $('#reaction-txtMessage').val('');
            $('#reaction-txtFromName').val('');
            $('#reaction-txtFromEmail').val('');
	        $('#sendReactionContent').hide();
	        $('#sendReactionMessage').show();
	        logic.resizePopup();
	        
	        priv.sendReactionClicked = false;
	    },
	    
	    errorSendReaction : function (result){
	        priv.showSendReactionError('Er is een fout opgetreden');
	        
	        priv.sendReactionClicked = false;
	    },
	    
	    showMagazineError : function(errorMsg){
	        $('#magazine-send-errormsg').show();
	        $('#magazine-send-errormsg').html(errorMsg);
	        logic.resizePopup();
	        priv.addMagazineClicked = false;
	        $('#btn-brochure').removeAttr('disabled');
	    },
	    
	    successMagazine : function (result){	        
            // redirect to thankyou page
	        window.location = resources.path_prefix + '/html/companyinfo.aspx?option=thankyou-brochure';
	        
	        $('#btn-brochure').removeAttr('disabled');
	        priv.addMagazineClicked = false;
	    },
	    
	    errorMagazine : function (result){
	        priv.showMagazineError('Er is een fout opgetreden');
	        priv.addMagazineClicked = false;
	    }
	};
	
	/**
	 * public methods
	 */
	return {
	    showSendReactionPopup : function(){
	        $('#sendReactionContent').show();
	        $('#sendReactionMessage').hide();
	        logic.showPopup('pSendMessage', true, 625, 0);
	    },

        checkPostalCode : function() {
                var postal = $('#mag-postal').val();
                if(postal.length == 6){
                    $('#mag-street').val('');
                    $('#dd-mag-street').empty();
                    var response = $.ajax({
                                      url: resources.path_prefix + '/utilpages/postaladdress.ashx',
                                      data:   'country='+$('#mag-country').val()+
		                                      '&postal='+postal,
                                      async: false
                                     }).responseText;
                    if(response.split('|').length == 2){
                        $('#dd-mag-street').hide();
                        $('#mag-street').show();
                        $('#mag-city').val(response.split('|')[0]);
                        $('#mag-street').val(response.split('|')[1]);
                        $('#magazine-send-errormsg').hide();
                    }
                    else if(response.split('|').length > 2){
                        $('#mag-city').val(response.split('|')[0]);
                        $('#dd-mag-street').show();
                        $('#mag-street').hide();
                        var options = '';
                        var returnValue = response.split('|');
                        for(var j=1;j<returnValue.length;j++){
                            if(j%2==1){
                                options += '<option value="'+returnValue[j]+'">'+returnValue[j]+'</option>';
                            }
                        }
                        $('#dd-mag-street').append(options);
                        $('#magazine-send-errormsg').hide();
                    }
                    else {
                        $('#dd-mag-street').hide();
                        $('#mag-street').show();
                        $('#magazine-send-errormsg').show().html('De postcode is onbekend, weet u zeker dat deze correct is?');
                    }
                }      
        },
	
	    showMagazinePopup : function () {
	        if($('#pMagazine').html() == ''){
	            $('#pMagazine').load(resources.path_prefix + '/html/magazinepopup.aspx #popup', null, function(){
                    formsubmit.showMagazinePopup();
                });
            } else {
                $('#sendMagazineContent').show();
	            $('#sendMagazineMessage').hide();
	            logic.showPopup('pMagazine', true, 750, 0);
	            logic.resizePopup();

	            $('#mag-postal').keyup(function(e){
                    var postal = $('#mag-postal').val();
                    if(postal.length == 6){
                        $('#mag-street').val('');
                        $('#dd-mag-street').empty();
                        var response = $.ajax({
                                          url: resources.path_prefix + '/utilpages/postaladdress.ashx',
                                          data:   'country='+$('#mag-country').val()+
			                                      '&postal='+postal,
                                          async: false
                                         }).responseText;
                        if(response.split('|').length == 2){
                            $('#dd-mag-street').hide();
                            $('#mag-street').show();
                            $('#mag-city').val(response.split('|')[0]);
                            $('#mag-street').val(response.split('|')[1]);
                            $('#magazine-send-errormsg').hide();
                        }
                        else if(response.split('|').length > 2){
                            $('#mag-city').val(response.split('|')[0]);
                            $('#dd-mag-street').show();
                            $('#mag-street').hide();
                            var options = '';
                            var returnValue = response.split('|');
                            for(var j=1;j<returnValue.length;j++){
                                if(j%2==1){
                                    options += '<option value="'+returnValue[j]+'">'+returnValue[j]+'</option>';
                                }
                            }
                            $('#dd-mag-street').append(options);
                            $('#magazine-send-errormsg').hide();
                        }
                        else {
                            $('#dd-mag-street').hide();
                            $('#mag-street').show();
                            $('#magazine-send-errormsg').show().html('De postcode is onbekend, weet u zeker dat deze correct is?');
                        }
                    }
                });
	        }
	    },
	    
	    sendMagazine : function () {
	        priv.addMagazineClicked = true;
	        var title = $('#mag-title').val();              // * verplicht
	        var firstletter = $('#mag-firstletter').val();  // * verplicht
	        var middlename = $('#mag-middlename').val();
	        var lastname = $('#mag-lastname').val();        // * verplicht
	        var birthday = $('#mag-birthday').val(); 
	        var birthmonth = $('#mag-birthmonth').val(); 
	        var birthyear = $('#mag-birthyear').val(); 
	        var street = $('#mag-street').val();            // * verplicht
	        if(street == ''){
	            street = $('#dd-mag-street').val();
	        }
	        var streetnr = $('#mag-streetnr').val();        // * verplicht
	        var streetnrext = $('#mag-streetnrext').val();
	        var postal = $('#mag-postal').val();            // * verplicht
	        var city = $('#mag-city').val();                // * verplicht
	        var country = $('#mag-country').val();          // * verplicht
	        var phoneprivate = $('#mag-phoneprivate').val();
	        var phonework = $('#mag-phonework').val();
	        var email = $('#mag-email').val();              // * verplicht
	        var agree = $('#mag-agree')[0].checked;
	        
	        var correctEmail = true;	        
	        var reg = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	        if (agree) {
	            correctEmail = reg.test(email);
	        }
	        
	        reg = /^([0-9]{4}[a-z]{2})$/i;
	        var correctPostal = reg.test(postal);
	        
	        if(title == '0') {
	            priv.showMagazineError('Er is geen aanhef ingevuld');
	        } else if(firstletter == '') {
	            priv.showMagazineError('Er zijn geen voorletters ingevuld');
	        } else if(lastname == '') {
	            priv.showMagazineError('Er is geen achternaam ingevuld');
	        } else if(street == '') {
	            priv.showMagazineError('Er is geen straatnaam ingevuld');
	        } else if(streetnr == '' || isNaN(streetnr)) {
	            priv.showMagazineError('Er is geen of een onjuist huisnummer ingevuld');
	        } else if(!correctPostal) {
	            priv.showMagazineError('Er is geen of een onjuiste postcode ingevuld');
	        } else if(city == '') {
	            priv.showMagazineError('Er is geen woonplaats ingevuld');
	        } else if(!correctEmail) {
	            priv.showMagazineError('Er is een ongeldig emailadres ingevuld');
	        } else if(  (birthday != '0' || birthmonth != '0' || birthyear != '0') &&
	                    (birthday == '0' || birthmonth == '0' || birthyear == '0')) {
	            priv.showMagazineError('Er is een ongeldige geboortedatum ingevuld');
	        } else {
	            // everything ok
	            //priv.showMagazineError('Even geduld alstublieft...');
	            
	            $('#btn-brochure').attr('disabled',true);
	            $.ajax({
		            type: "POST",
		            url: resources.path_prefix + '/utilpages/addbrochure.ashx',
			        data:   'title='+title+
			                '&firstletter='+firstletter+
			                '&middlename='+middlename+
			                '&lastname='+lastname+
			                '&birthday='+birthday+
			                '&birthmonth='+birthmonth+
			                '&birthyear='+birthyear+
			                '&street='+street+
			                '&streetnr='+streetnr+
			                '&streetnrext='+streetnrext+
			                '&postal='+postal+
			                '&city='+city+
			                '&country='+country+
			                '&phoneprivate='+phoneprivate+
			                '&phonework='+phonework+
			                '&email='+email+
			                '&agree='+agree,
			        async: true,
    				
		            success : priv.successMagazine,
			        error : priv.errorMagazine
		        });
	        }
	    },

	    switchEmailMandatory : function () {
	        var agree = $('#mag-agree')[0].checked;
	        
	        if (agree) {
	            $('#mag-emailmandatorysymbol').css("display", "");
	        }
	        else
	            $('#mag-emailmandatorysymbol').css("display", "none");
	    },

	    showCancellationPopup : function () {
	        if($('#pCancellation').html() == ''){
	            $('#pCancellation').load(resources.path_prefix + '/html/cancellationpopup.aspx #popup', null, function(){
                    formsubmit.showCancellationPopup();
                });
            } else {
                $('#sendCancellationContent').show();
	            $('#sendCancellationMessage').hide();
	            logic.showPopup('pCancellation', true, 710, 0);
	            logic.resizePopup();
	        }
	    },
	    
	    sendCancellation : function () {
	        priv.sendCancellationClicked = true;
	        var title = $('#canc-title').val();              // * verplicht
	        var firstletter = $('#canc-firstletter').val();  // * verplicht
	        var middlename = $('#canc-middlename').val();
	        var lastname = $('#canc-lastname').val();        // * verplicht
	        var birthday = $('#canc-birthday').val(); 
	        var birthmonth = $('#canc-birthmonth').val(); 
	        var birthyear = $('#canc-birthyear').val(); 
	        var street = $('#canc-street').val();            // * verplicht
	        var streetnr = $('#canc-streetnr').val();        // * verplicht
	        var streetnrext = $('#canc-streetnrext').val();
	        var postal = $('#canc-postal').val();            // * verplicht
	        var city = $('#canc-city').val();                // * verplicht
	        var country = $('#canc-country').val();          // * verplicht
	        var phoneprivate = $('#canc-phoneprivate').val();
	        var phonework = $('#canc-phonework').val();
	        var email = $('#canc-email').val();             // * verplicht
	        var resnr = $('#canc-resnr').val();             // * verplicht
	        var accountnr = $('#canc-accountnr').val();         // * verplicht
	        var depdate =  $('#canc-depdate').val();
	        var party1 =  $('#canc-party1').val();
	        var party2 =  $('#canc-party2').val();
	        var party3 =  $('#canc-party3').val();
	        var party4 =  $('#canc-party4').val();
	        var party5 =  $('#canc-party5').val();
	        var party6 =  $('#canc-party6').val();
	        var party7 =  $('#canc-party7').val();
	        var party8 =  $('#canc-party8').val();
	        var dest =  $('#canc-dest').val();
	        var acco =  $('#canc-acco').val();
	        var reason =  $('#canc-reason').val();
	        var reasonextra =  $('#canc-reason-extra').val();
	        var bankname =  $('#canc-bankname').val();
	        var accountname = $('#canc-accountname').val();
	        var accountcity = $('#canc-accountcity').val();
	        var aanspraak = $('#canc-redenaanspraak').val();
	        var bijzonderheden = $('#canc-bijzonderheden').val();
	        var gogo = $('.canc-gogoverz:checked').val();
	        var cancellationfor = $('.allereizigers:checked').val();
	        var cancellationforsome = $('#annreizigers').val();
	        
	        var reg = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	        var correctEmail = reg.test(email);
	        
	        if(title == '0') {
	            priv.showCancellationError('Er is geen aanhef ingevuld');
	        } else if(firstletter == '') {
	            priv.showCancellationError('Er zijn geen voorletters ingevuld');
	        } else if(lastname == '') {
	            priv.showCancellationError('Er is geen achternaam ingevuld');
	        } else if(street == '') {
	            priv.showCancellationError('Er is geen straatnaam ingevuld');
	        } else if(streetnr == '') {
	            priv.showCancellationError('Er is geen of een onjuist huisnummer ingevuld');
	        } else if(postal == '') {
	            priv.showCancellationError('Er is geen postcode ingevuld');
	        } else if(city == '') {
	            priv.showCancellationError('Er is geen woonplaats ingevuld');
	        } else if(phoneprivate == '') {
	            priv.showCancellationError('Er is geen telefoonnummer ingevuld');
	        } else if(resnr == '') {
	            priv.showCancellationError('Er is geen reserveringsnummer ingevuld');
	        } else if(accountnr == '') {
	            priv.showCancellationError('Er is geen rekeningnummer ingevuld');
	        } else if(email == '') {
	            priv.showCancellationError('Er is geen emailadres ingevuld');
	        } else if(email != '' && !correctEmail) {
	            priv.showCancellationError('Er is een ongeldig emailadres ingevuld');
	        } else if(  (birthday != '0' || birthmonth != '0' || birthyear != '0') &&
	                    (birthday == '0' || birthmonth == '0' || birthyear == '0')) {
	            priv.showCancellationError('Er is een ongeldige geboortedatum ingevuld');
	        } else {
	            // everything ok
	            
	            $.ajax({
		            type: "POST",
		            url: resources.path_prefix + '/utilpages/sendcancellation.ashx',
			        data:   'title='+title+
			                '&firstletter='+firstletter+
			                '&middlename='+middlename+
			                '&lastname='+lastname+
			                '&birthday='+birthday+
			                '&birthmonth='+birthmonth+
			                '&birthyear='+birthyear+
			                '&street='+street+
			                '&streetnr='+streetnr+
			                '&streetnrext='+streetnrext+
			                '&postal='+postal+
			                '&city='+city+
			                '&country='+country+
			                '&phoneprivate='+phoneprivate+
			                '&phonework='+phonework+
			                '&resnr='+resnr+
			                '&accountnr='+accountnr+
			                '&depdate='+depdate+
	                        '&party1='+party1+
	                        '&party2='+party2+
	                        '&party3='+party3+
	                        '&party4='+party4+
	                        '&party5='+party5+
	                        '&party6='+party6+
	                        '&party7='+party7+
	                        '&party8='+party8+
	                        '&dest='+dest+
	                        '&acco='+acco+
	                        '&reason='+reason+
	                        '&reasonextra='+reasonextra+
	                        '&bankname='+bankname+
	                        '&accountname='+accountname+
	                        '&accountcity='+accountcity+
	                        '&aanspraak='+aanspraak+
	                        '&bijzonderheden='+bijzonderheden+
	                        '&gogo='+gogo+
	                        '&cancellationfor='+cancellationfor+
	                        '&cancellationforsome='+cancellationforsome+	                        
			                '&email='+email,
			        async: true,
    				
		            success : priv.successCancellation,
			        error : priv.errorCancellation
		        });
	        }
	    },	    
	    
	    cancellationSkip : function(id)
	    {
            var question = $('#vraag'+id);  
            var answer = $('#antwoord'+id); 
            if ($('.'+id+':checked').val() == "ja")
            {
                question.css("display", "none");
                question.css("visibility", "hidden");
                answer.css("display", "none");
                answer.css("visibility", "hidden");
            }
            else 
            {
                question.css("display", "block");
                question.css("visibility", "visible");
                answer.css("display", "block");
                answer.css("visibility", "visible");
    	        logic.CorrectShades();	        
            }
	    },
	    
	    prebookingShowCompanions : function(nr)
	    {
	        // set divcompanion with display: block to display:none
	        for (j=1; j<=7; j++)
	        {
	            $('#divcompanion' + j).css("display","none");
	        }
	        if (nr > 1)
            {
	            for (i=2; i <= nr ; i++)
	            {
	                $('#divcompanion' + (i-1)).css("display","block");
	            }
	            logic.CorrectShades();
            }	      
	    },
	    
	    sendPreBooking : function()
	    {
	        priv.sendPreBookingClicked = true;
	        
	        var phonehomestay = $('#prebook-phonehomestay').val();

	        var destination = $('#prebook-destination').val();  // * verplicht
	        var acconame = $('#prebook-acconame').val();        // * verplicht
	        var accotype = $('#prebook-accotype').val();        // * verplicht
	        var hosttype =  $('#prebook-hosttype').val();       // * verplicht
	        var nrpersons =  $('#prebook-nrpersons').val();     // * verplicht
	        var depday =  $('#prebook-depday').val();           // * verplicht
	        var depmonth =  $('#prebook-depmonth').val();       // * verplicht
	        var depyear =  $('#prebook-depyear').val();         // * verplicht
	        var nrdays =  $('#prebook-nrdays').val();           // * verplicht
	        var remarks =  $('#prebook-remarks').val();
            
            var error = 'false';
            for (i=0; i<nrpersons; i++)
            {   var reg = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	            var correctEmail = reg.test($('#prebook-email' + i).val());

	            if($('#prebook-title' + i).val() == '0') {
	                priv.showPreBookError('Er is geen aanhef ingevuld');
	                error = 'true';
	            } else if($('#prebook-firstletter' + i).val() == '') {
	                priv.showPreBookError('Er zijn geen voorletters ingevuld');
	                error = 'true';
	            } else if( $('#prebook-lastname' + i).val() == '') {
	                priv.showPreBookError('Er is geen achternaam ingevuld');
	                error = 'true';
	            } else if( $('#prebook-street' + i).val() == '') {
	                priv.showPreBookError('Er is geen straatnaam ingevuld');
	                error = 'true';
	            } else if($('#prebook-streetnr' + i).val() == '') {
	                priv.showPreBookError('Er is geen of een onjuist huisnummer ingevuld');
	                error = 'true';
	            } else if($('#prebook-postal' + i).val() == '') {
	                priv.showPreBookError('Er is geen postcode ingevuld');
	                error = 'true';
	            } else if($('#prebook-city' + i).val() == '') {
	                priv.showPreBookError('Er is geen woonplaats ingevuld');
	                error = 'true';
	            } else if($('#prebook-phoneprivate' + i).val() == '') {
	                priv.showPreBookError('Er is geen telefoonnummer ingevuld');
	                error = 'true';
	            } else if($('#prebook-email0').val() == '') {
	                priv.showPreBookError('Emailadres is verplicht voor hoofdboeker');
	                error = 'true';
	            } else if( $('#prebook-email' + i).val() != '' && !correctEmail) {
	                priv.showPreBookError('Er is een ongeldig emailadres ingevuld');
	                error = 'true';
                } else if ($('#prebook-birthday' + i).val() == '0' || $('#prebook-birthmonth' + i).val() == '0' || $('#prebook-birthyear' + i).val() == '0') {	
                    priv.showPreBookError('Er is geen geboortedatum ingevuld');            
	                error = 'true';
	            } else if(  ($('#prebook-birthday' + i).val() != '0' || $('#prebook-birthmonth' + i).val() != '0' || $('#prebook-birthyear' + i).val() != '0') &&
	                        ($('#prebook-birthday' + i).val() == '0' || $('#prebook-birthmonth' + i).val() == '0' || $('#prebook-birthyear' + i).val() == '0')) {
	                priv.showPreBookError('Er is een ongeldige geboortedatum ingevuld');
	                error = 'true';
                }
            }

            if (error == 'true') {
                error = 'true';
            } else if (destination == '') {
	            priv.showPreBookError('Er is geen bestemming ingevuld');
	        } else if (acconame == '') {
	            priv.showPreBookError('Er is geen accommodatienaam ingevuld');
	        } else if (accotype == '0') {
	            priv.showPreBookError('Er is geen accommodatietype ingevuld');
	        } else if (hosttype == '0') {
	            priv.showPreBookError('Er is geen verzorginstype ingevuld');
	        } else if (nrpersons == '0') {
	            priv.showPreBookError('Aantal personen is niet ingevuld');
	        } else if (nrdays == '0') {
	            priv.showPreBookError('Aantal dagen is niet ingevuld');
	        } else if (depday == '0' || depmonth == '0' || depyear == '0') {
	            priv.showPreBookError('Er is geen vertrekdatum ingevuld');
	        } else if ((depday != '0' || depmonth != '0' || depyear != '0') &&
	                   (depday == '0' || depmonth == '0' || depyear == '0')){
	            priv.showPreBookError('Er is een ongeldige vertrekdatum ingevuld');
	        } else {
	            // everything ok
	            var title = '';
	            var firstletter = '';
	            var middlename = '';
	            var lastname = '';
	            var birthday = '';
	            var birthmonth = '';
	            var birthyear = '';
	            var street = '';
	            var streetnr = '';
	            var streetnrext = '';
	            var postal = '';
	            var city = '';
	            var phoneprivate = '';
	            var phonework = '';
	            var email = '';
	            var cancellation = '';
	            var insurance = '';
	            
	            for (i=0; i<nrpersons; i++)
	            {
	                title += $('#prebook-title' + i).val() + ';';              // * verplicht
	                firstletter += $('#prebook-firstletter' + i).val()+ ';';  // * verplicht
	                middlename += $('#prebook-middlename' + i).val()+ ';';
	                lastname += $('#prebook-lastname' + i).val()+ ';';        // * verplicht
	                birthday += $('#prebook-birthday' + i).val()+ ';';        // * verplicht
	                birthmonth += $('#prebook-birthmonth' + i).val()+ ';';    // * verplicht
	                birthyear += $('#prebook-birthyear' + i).val()+ ';';      // * verplicht
	                street += $('#prebook-street' + i).val()+ ';';            // * verplicht
	                streetnr += $('#prebook-streetnr' + i).val()+ ';';        // * verplicht
	                streetnrext += $('#prebook-streetnrext' + i).val()+ ';';
	                postal += $('#prebook-postal' + i).val()+ ';';            // * verplicht
	                city += $('#prebook-city' + i).val()+ ';';                // * verplicht
	                phoneprivate += $('#prebook-phoneprivate' + i).val()+ ';';// * verplicht
	                phonework += $('#prebook-phonework' + i).val()+ ';';
	                email += $('#prebook-email' + i).val()+ ';';              // * verplicht
	                cancellation += $('.prebook-cancellation'+i+':checked').val()+ ';';
	                insurance += $('.prebook-insurance'+i+':checked').val()+ ';';
	            }
	            
	            $.ajax({
		            type: "POST",
		            url: resources.path_prefix + '/utilpages/sendprebooking.ashx',
			        data:   'destination='+destination+
			                '&acconame='+acconame+
			                '&accotype='+accotype+
	                        '&hosttype='+hosttype+
	                        '&nrpersons='+nrpersons+
	                        '&depday='+depday+
	                        '&depmonth='+depmonth+
	                        '&depyear='+depyear+
	                        '&nrdays='+nrdays+
	                        '&remarks='+remarks+
                            '&title='+title+
		                    '&firstletter='+firstletter+
		                    '&middlename='+middlename+
		                    '&lastname='+lastname+
		                    '&birthday='+birthday+
		                    '&birthmonth='+birthmonth+
		                    '&birthyear='+birthyear+
		                    '&street='+street+
		                    '&streetnr='+streetnr+
		                    '&streetnrext='+streetnrext+
		                    '&postal='+postal+
		                    '&city='+city+
		                    '&phoneprivate='+phoneprivate+
		                    '&phonework='+phonework+                          
		                    '&email='+email+   
		                    '&cancellation='+cancellation+
		                    '&insurance='+insurance+                       
	                        '&phonehomestay='+phonehomestay,
			        async: true,
    				
		            success : priv.successPrebooking,
			        error : priv.errorPrebooking
		        });	 
           
	        }
	        
	    },
	    
	    showPopupOrNot : function()
	    {
	        var email = $('#pre-subscribe-email').val();
	        if (email != null && email != '' && email != 'email@adres.nl')
	        {
	            location.href = resources.path_prefix+'/newsletterupdate.aspx?ID=UcSMUmNN7UUUUr';
	            //formsubmit.unOrSubscribeNewsletter('aanmelden');
	        }
	        else
	        {
	            location.href = resources.path_prefix+'/newsletterupdate.aspx?ID=UcSMUmNN7UUUUr';
	            //logic.showPopup('un-or-subscribe-newsletter', true, 750, 0);
	        }
	    },

	    unOrSubscribeNewsletter : function (fid) {
	        // for testing purposes use local send newsletter page below
	        //var ajaxUrl = resources.path_prefix + '/testpages/sendnewsletter.aspx'
	        var ajaxUrl = resources.path_prefix + '/utilpages/addnewsletter.ashx';
	        switch(fid)
	        {
	            case 'aanmelden':
	                var email = $('#subscribe-email').val();
	                if (email == '')
	                {
    	                var email = $('#pre-subscribe-email').val();
	                }
	                break;
                case 'afmelden':
	                var email = $('#unsubscribe-email').val();
	                break;
	        }
	        //var email = $('#subscribe-email').val();
            if(email == 'email@adres.nl'){
                email = '';
            }
	        if(email == ''){
	            priv.showSubscribeError('Gelieve een correct emailadres in te vullen.');
	        } else {
	            var reg = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
                if (!reg.test(email)) {
                    priv.showSubscribeError('Gelieve een correct emailadres in te vullen.');
                } else {
                    // if email is valid submit
                    //priv.showSubscribeError('Even geduld alstublieft...');
	                switch(fid)
	                {
	                    case 'aanmelden':
	                        $.ajax({
			                    type: "POST",
			                    url: ajaxUrl,
				                data: 'email='+email+'&fid='+fid,
				                async: true,
                				
			                    success : priv.successSubscribeNewsletter,
				                error : priv.errorUnOrSubscribeNewsletter
			                });
			                break;
                        case 'afmelden' :			            
	                        $.ajax({
			                    type: "POST",
			                    url: ajaxUrl,
				                data: 'email='+email+'&fid='+fid,
				                async: true,
                				
			                    success : priv.successUnsubscribeNewsletter,
				                error : priv.errorUnOrSubscribeNewsletter
			                });
    			            break;
	                }
                }
	        }
	    },
	    
	    addReviewAcco : function () {
	        if(!priv.addReviewClicked){
	            priv.addReviewClicked = true;
	            
	            var ajaxUrl =  $('#review-url').val();
	            var reviewemail = $('#review-email').val();
	            var reviewname = $('#review-name').val().stripTags();
	            var reviewtext = $('#review-text').val().stripTags();
	            var accoid = $('#review-accoid').val();
	            if(reviewname == ''){
	                priv.showReviewError('Gelieve een naam in te vullen.');
	            }
	            else if(reviewtext == ''){
	                priv.showReviewError('Gelieve een bericht in te vullen.');
	            }
	            else if(reviewemail == ''){
	                priv.showReviewError('Gelieve een correct emailadres in te vullen.');
	            } else {
	                var reg = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
                    if (!reg.test(reviewemail)) {
                        priv.showReviewError('Gelieve een correct emailadres in te vullen.');
                    } else {
                        // if email is valid submit
	                    var dataStr = "reviewemail=" + reviewemail + "&reviewname=" + reviewname + "&reviewtext=" + reviewtext + "&accoid=" + accoid;
    	                
	                    $.ajax({
			                type: "POST",
			                url: ajaxUrl,
				            data: dataStr,
				            async: true,
            				
			                success : priv.successAddReviewAcco,
				            error : priv.errorAddReviewAcco
			            });
                    }
	            }
	        }	   
         },
         
         sendAccommodation : function(accoId){
            if(!priv.sendAccoClicked){ // make sure the email isnt send multiple times
                priv.sendAccoClicked = true;
                
                // input values
                var toEmails = $('#toEmails').val();
                var message = $('#txtMessage').val();
                var fromName = $('#txtFromName').val();
                var fromEmail = $('#txtFromEmail').val();
                
                // email regex
                var reg = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
                var incorrectEmail = false;
                var arrtoEmails = toEmails.split(',');
                for(var i=0;i<arrtoEmails.length;i++){
                    if (arrtoEmails[i] != '' && !reg.test(arrtoEmails[i].trim())) {
                        incorrectEmail = true;
                        break;
                    }
                }
                
                if(toEmails == '' || incorrectEmail){
	                priv.showSendAccoError('Het veld "stuur naar email" is niet correct ingevuld. Er mogen alleen letters en cijfers in en geen andere tekens.');
	            }
	            else if(fromEmail == '' || !reg.test(fromEmail)){
	                priv.showSendAccoError('Het veld "uw email" is niet correct ingevuld. Er mogen alleen letters en cijfers in en geen andere tekens.');
	            }
	            else {
	                $.ajax({
		                type: "POST",
		                url: resources.path_prefix + '/utilpages/sendaccommodation.ashx',
			            data: 'toEmails='+toEmails+'&message='+message+'&fromName='+fromName+'&fromEmail='+fromEmail+'&accoId='+accoId,
			            async: true,
        				
		                success : priv.successSendAcco,
			            error : priv.errorSendAcco
		            });
	            }
	        }
         },
         
         sendReaction : function(){
            if(!priv.sendReactionClicked){ // make sure the email isnt send multiple times
                priv.sendReactionClicked = true;
                
                // input values

                var message = $('#reaction-txtMessage').val();
                var fromName = $('#reaction-txtFromName').val();
                var fromEmail = $('#reaction-txtFromEmail').val();
                
                var reg = new RegExp("^[A-Za-z0-9._%-]+@(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,8}$");
                
	            if(fromEmail == '' || !reg.test(fromEmail)){
	                priv.showSendReactionError('Het veld "uw email" is niet correct ingevuld. Er mogen alleen letters en cijfers in en geen andere tekens.');
	            }
	            else {
	                $.ajax({
		                type: "POST",
		                url: resources.path_prefix + '/utilpages/sendreaction.ashx',
			            data: 'message='+message+'&fromName='+fromName+'&fromEmail='+fromEmail,
			            async: true,
        				
		                success : priv.successSendReaction,
			            error : priv.errorSendReaction
		            });
	            }
	        }
         }
	}
}(jQuery);

var Timer = function(){
    var priv = {
        startTime : new Date(),
        endTime   : null
    };
        
    return {
        Start   : function(){
            priv.startTime = new Date();
        },
        
        Stop    : function(){
            priv.endTime = new Date();
            return (priv.endTime - priv.startTime);
        },
        
        ShowIntermediate : function(){
            var intermediateTime = new Date();
            return (intermediateTime - priv.startTime); 
        },
        
        GetStartTime   : function(){
            return priv.startTime;
        }
    };
};

/**
 * Initiate onload methods and functions
 */
$(document).ready(
	function(){
	    var TotalOnreadyTime = new Timer();
		logic.OnReady();
		logic.writeDebug("script time was: " + (TotalOnreadyTime.Stop()) + "ms ", -1);
		
		// set first time cookie
		var firstTimeCookie = $.cookie(logic.CookiePrefix + "firsttime");
		if (!firstTimeCookie || firstTimeCookie.length == 0){
		    logic.showPopup('intro-movie-popup', true, 660, 0);
	        
	        // object are hidden when popups are shown; show object in intro-movie-popup
	        $('#intro-movie-popup object').show();
	        
	        logic.resizePopup();  	        
		}
		$.cookie(logic.CookiePrefix + "firsttime", "true", { expires: 30 });
		
		// set cookie for enquete
        //var cookieStr = $.cookie(logic.CookiePrefix + "enquete");
        //if(!cookieStr || cookieStr.length == 0){
        //    $.cookie(logic.CookiePrefix + "enquete", "true", { expires: 62, path: '/' });
        //}
	}
);


/**
 * Bind resize eventes
 */
$(window).bind('resize', 
	function(){
		logic.OnResize();
});

function open_popup(pagina, w, h)  {
	var parameters = "width=" + w + ", height=" + h + ", left=100, top=50, toolbar=0, location=0, directories=0, status=0, menubar=0, scrollbars=1, resizable=1";
	var winpopup = window.top.winpopup;
	
	window.top.winpopup = window.open(pagina, '_blank', parameters);
	window.top.winpopup.focus()
}