var fromLtu = false;
var getUrl = '';
var urlArray = [];
var fadingArray = [];
var interrupt = false;
var fading = true;
var TinyMceActivated = false;
var showQueue = new Array();
var nextToShow = 0;
var galleryItemsToHide = [];
var weekday = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];

jQuery(document).ready(function()
{
	// Create dropdown menu
	jQuery('#dropdown').ptMenu();	

	jQuery.get('/load.php?ip_is_ltu','',function(result)
	{
		// Fade and change the header img
		if (result == 'true')
			fromLtu = true;
		else
		{
			jQuery('#top_spacer').css('background-image','url(/img/site/top_spacer.png)');
			jQuery('body').css('background-image', 'url(/img/site/background.jpg)');
		}

		initHeaderImages();
	});

	// Load the availability widget
	loadAvailabilityWidget();
});

function setLanguageText()
{
	var lang = (!get('lang') ? defaultLanguage : get('lang'));

	jQuery.each(languageArray[lang],function(i,item)
	{

		if(jQuery('.langItem'+i).hasClass('button'))

		{

			jQuery('.langItem'+i).html(item);

		}

		else

			jQuery('.langItem'+i).html(item);			

	});

	

	jQuery.datepicker.setDefaults(jQuery.datepicker.regional[(!get('lang') ? defaultLanguage : get('lang'))]);

	jQuery("#widget_datepicker").datepicker("setDate",jQuery("#widget_datepicker").datepicker("getDate"));
	
	switch(lang)
	{
		case 'nl':
		{
			jQuery.extend(jQuery.validator.messages,
			{
				required: "Dit veld is verplicht.",
				maxlength: jQuery.format("U kunt niet meer dan {0} karakters invoeren."),
				minlength: jQuery.format("U dient minimaal {0} karakters in te voeren."),
				rangelength: jQuery.format("U dient minimaal {0} en maximaal {1} karakters in te voeren."),
				email: "Voer alstublieft een geldig e-mail adres in.",
				url: "Voer alstublieft een geldig web adres in.",
				date: "Voer alstublieft een geldige datum in.",
				number: "Voer alstublieft een geldig getal in.",
				digits: "Gebruik alleen cijfers.",
				equalTo: "Herhaal de invoer nogmaals.",
				range: jQuery.format("U dient een waarde tussen {0} en {1} in te voeren."),
				max: jQuery.format("U dient een waarde kleiner dan of gelijk aan {0} in te voeren."),
				min: jQuery.format("U dient een waarde groter dan of gelijk aan {0} in te voeren.")
			});
			break;
		}
		case 'gb':
		{
			jQuery.extend(jQuery.validator.messages,
			{
				required: "This field is required.",
				remote: "Please fix this field.",
				email: "Please enter a valid email address.",
				url: "Please enter a valid URL.",
				date: "Please enter a valid date.",
				number: "Please enter a valid number.",
				numberDE: "Bitte geben Sie eine Nummer ein.",
				digits: "Please enter only digits",
				creditcard: "Please enter a valid credit card number.",
				equalTo: "Please enter the same value again..",
				accept: "Please enter a value with a valid extension.",
				maxlength: jQuery.format("Please enter no more than {0} characters."),
				minlength: jQuery.format("Please enter at least {0} characters."),
				rangelength: jQuery.format("Please enter a value between {0} and {1} characters long."),
				range: jQuery.format("Please enter a value between {0} and {1}."),
				max: jQuery.format("Please enter a value less than or equal to {0}."),
				min: jQuery.format("Please enter a value greater than or equal to {0}.")
			});
			break;
		}
		case 'de':
		{
			jQuery.extend(jQuery.validator.messages,
			{
				required: "Dieses Eingabefeld ist verpflichtet.",
				maxlength: jQuery.format("Sie k&ouml;nnen nicht mehr als {0} Zeichen eingeben."),
				minlength: jQuery.format("Sie sollen mindestens {0} Zeichen eingeben."),
				rangelength: jQuery.format("Sie sollen minimal {0} und maximal {1} Zeichen eingeben."),
				email: "Bitte geben Sie eine g&uuml;ltige E-Mail-Adresse ein.",
				url: "Bitte geben Sie eine g&uuml;ltige Internet-Adresse ein.",
				date: "Bitte geben Sie ein g&uuml;ltiges Datum ein.",
				number: "geben Sie eine g&uuml;ltige Zahl ein.",
				digits: "Bitte nur Zahlen eingeben.",
				equalTo: "Wiederholen Sie bitte Ihre Eingabe.",
				range: jQuery.format("Sie sollen eine Zahl von {0} bis {1} eingeben."),
				max: jQuery.format("Sie sollen eine Zahl kleiner als oder gleich {0} eingeben."),
				min: jQuery.format("Sie sollen eine Zahl gr&ouml;&szlig;er als oder gleich {0} eingeben.")
			});
			break;
		}
		case 'ltu':
		{
			jQuery.extend(jQuery.validator.messages,
			{
				required: "&#352;is laukelis privalomas.",
				maxlength: jQuery.format("Negalite ivesti daugiau nei {0} &#382;enklu."),
				minlength: jQuery.format("Privalote ivesti ma&#382;iausiai {0} &#382;enklu."),
				rangelength: jQuery.format("Privalote ivesti ma&#382;iausiai {0} ir daugiausiai {1} &#382;enklu."),
				email: "Pra&#353;ome ivesti galiojanti el. pa&#353;to adresa.",
				url: "Pra&#353;ome ivesti galiojanti interneto adresa.",
				date: "Pra&#353;ome ivesti teisinga data.",
				number: "Pra&#353;ome ivesti teisinga skaiciu.",
				digits: "Naudokite tik skaicius.",
				equalTo: "Iveskite informacija dar karta",
				range: jQuery.format("Privalote ivesti verte nuo {0} iki {1}."),
				max: jQuery.format("Privalote ivesti verte, ma&#382;esne arba lygia {0} vertei."),
				min: jQuery.format("Privalote ivesti verte, didesne arba lygia {0} vertei.")
			});
			break;
		}
		case 'ru':
		{
			jQuery.extend(jQuery.validator.messages,
			{
				required: "Это поле обязано к заполнению.",
				maxlength: jQuery.format("Вы не можете ввести больше знаков чем {0}."),
				minlength: jQuery.format("Вы должны ввести минимально {0} знаков."),
				rangelength: jQuery.format("Вы должны ввести минимально {0} и максимально {1} знаков."),
				email: "Введите, пожалуйста, правильный адрес электронной почты.",
				url: "Введите, пожалуйста, правильный адрес сайта.",
				date: "Введите, пожалуйста, правильную дату.",
				number: "Введите, пожалуйста, правильную цифру.",
				digits: "Введите только цифры.",
				equalTo: "Введите информацию еще раз.",
				range: jQuery.format("Введите стоимость между {0} и {1}."),
				max: jQuery.format("Введите стоимость, ниже или ровную {0}."),
				min: jQuery.format("Введите стоимость, выше или ровную {0}.")
			});
			break;
		}
	}
}

// Function called when the processing of the url is done
function processingReady()
{	
	showAjaxLoader(2);
	
	// After processing, if get('admin') is set show the login form
 	if(get('admin',false))activateDialogWindow('edit_dialog','login');

	loadSiteMenu(get('edit',false));
	
	jQuery.datepicker.setDefaults(jQuery.datepicker.regional[(!get('lang') ? defaultLanguage : get('lang'))]);
	
	// If extend processing is defined, execute it
	if(typeof extendProcessingReady != 'undefined')extendProcessingReady();	
}



function loadBooking()
{
	jQuery('#booking').load('/modules/booking/index.php','',function(){});	
}



function loadTestimonial()

{

	jQuery.getJSON('/load.php?testimonial&lang='+(!get('lang') ? defaultLanguage : get('lang')),'',function(testimonial)

	{

		jQuery('#quote_content').html('<img src="img/site/testimonial_first.png"/>' + URLDecode(testimonial.catchphrase) + '<img src="img/site/testimonial_last.png"/>');		

		jQuery('#quote_name').text(URLDecode(URLDecode(testimonial.name)));

		jQuery('#quote_holder').show();

		

		var quoteHeight = jQuery('#quote_holder').height();

		

		switch(quoteHeight)

		{

			case quoteHeight > 29 && quoteHeight < 59:

			{

				jQuery('#testimonial_message').css('max-height', '167px');

				break;

			}

			case quoteHeight > 58 && quoteHeight < 84:

			{

				jQuery('#testimonial_message').css('max-height','137px');

				break;

			}

			case quoteHeight > 83 && quoteHeight < 109:

			{

				jQuery('#testimonial_message').css('max-height','113px');

				break;

			}

			case quoteHeight > 108:

			{

				jQuery('#testimonial_message').css('max-height', '87px');

				break;

			}

		}

		

		jQuery('#testimonial_catchphrase').html('<img src="img/site/testimonial_first.png"/>' + URLDecode(testimonial.catchphrase) + '<img src="img/site/testimonial_last.png"/>');

		jQuery('#testimonial_message').text(str_replace('\\\'','\'',URLDecode(testimonial.message)));		

		jQuery('#testimonial_footer').text(URLDecode(URLDecode(testimonial.name)));

	});

}



function loadAvailabilityWidget(callback)

{

	jQuery.getJSON('/load.php',{accommodations : 'all', language : (!get('lang') ? defaultLanguage : get('lang'))},function(data)

	{

		jQuery.each(data,function(i,item)

		{

			jQuery('#accommodation_select').append('<option value="'+item.name+'">'+item.name+'</option>');

		});

		

		jQuery('#accommodation_select').change(function()

		{

			jQuery('#widget_datepicker').datepicker('destroy');

			createDatepicker();

		});

				

		createDatepicker();

		loadGalleryWidget(4000, true);

	});

}



	var createDatepicker = function()
	{
		jQuery('#widget_datepicker').datepicker
		({
			showOtherMonths: true,
			beforeShow: function()
			{
				if(jQuery(this).datepicker('getDate') != null)
				{
					date = jQuery(this).datepicker('getDate');
					checkAvailability(jQuery('#accommodation_select').val(), date.getFullYear(), date.getMonth()+1);
				}
			},
			beforeShowDay: function(date)
			{
				return [false,''];
			},
			onChangeMonthYear: function(year, month, inst)
			{
				checkAvailability(jQuery('#accommodation_select').val(), year, month, '#widget_datepicker');
			}
		});
	}



// Function that checks the availability, and adds a 'ui-state-booked' class for the days that are booked.
function checkAvailability(accommodation, year, month, div, period_of_stay)
{	
	if(!isdefined(div))div = '#ui-datepicker-div';
	if(!isdefined(period_of_stay))period_of_stay = -1;

	// Load the page (if no language is set, use the default language)
	jQuery.getJSON('/load.php',{availability : 'check', accommodation : accommodation ,year : year, month : month, next_month : ((period_of_stay == -1 || period_of_stay < 2) ? false : true)},function(data)
	{
		var lang = (!get('lang') ? defaultLanguage : get('lang'));
		
		// Check if the period of stay is smaller then 2. If the period_of_stay is -1 or 1, then all dates can be shown.
		if(period_of_stay < 2)
		{
			// Check every datepicker date
			jQuery(div).find('.ui-state-default').each(function(i,item)
			{
				var element = jQuery(this);
				element.attr('title',languageArray[lang][24]);
				
				if(data.length > 0)
				{
					// Compare the current date, with dates from the loaded data
					jQuery.each(data,function(d,date)
					{
						// If the dates match, add a 'ui-state-boocked' class and break (return false) the loop
						if(date.day == element.html())
						{
							element.addClass('ui-state-booked');

							if(date.special == 'end')
							{
								element.parent().addClass('ui-state-end');
								element.attr('title',languageArray[lang][58]);
							}
							else
							{
								if(date.special == 'start')
									element.parent().removeClass('ui-state-end');

								element.parent().attr('onclick','return false;');
								element.attr('onclick','return false;');
								element.attr('title',languageArray[lang][25]);
								return false;
							}
						}
					});
				}
			});
		}
		else
		{
			var visibleDays = [];
			
			// Check the dates based on the period_of_stay
			if(period_of_stay == 2 || period_of_stay == 9)
			{
				// Only friday
				visibleDays.push('friday');
			}
			else if(period_of_stay == 4 || period_of_stay == 11)
			{
				// Only monday
				visibleDays.push('monday');
			}
			else if(period_of_stay == 7 || period_of_stay == 14)
			{
				// Both monday and friday
				visibleDays.push('monday');
				visibleDays.push('friday');
			}
			
			// Check every datepicker date
			jQuery(div).find('.ui-state-default').each(function(i, item)
			{
				var element = jQuery(this);
				
				// Fill the date object
				var dateObj = new Date();	
				// months are zero indexed!
				dateObj.setMonth(month - 1);
				dateObj.setYear(year);
				dateObj.setDate(parseInt(element.html()));
				
				// Get the day
				var day = weekday[dateObj.getDay()];
				
				if(in_array(day, visibleDays))
				{				
					var dateIterator = dateObj;
					element.parent().attr('title',languageArray[lang][24]);
					
					for(j = 0; j < period_of_stay; j++)
					{
						// Check if the current element is booked or not
						jQuery.each(data, function(d, date)
						{
							if(date.day == dateIterator.getDate() && (date.month == dateIterator.getMonth() + 1))
							{								
								element.parent().addClass('ui-state-booked');
								
								if(j == 0 && date.special == 'end')
								{
									element.parent().addClass('ui-state-end');
									element.parent().attr('title',languageArray[lang][58]);
								}
								else
								{
									if(j == 0 && date.special == 'start')
										element.parent().removeClass('ui-state-end');

									if(j != 0)
									{
										element.parent().addClass('ui-state-not-bookable');
										element.parent().attr('title',languageArray[lang][65]);
									}
									else
										element.parent().attr('title',languageArray[lang][25]);

									element.parent().removeAttr('onclick');									
									element.parent().html(element.html());
									return false;
								}
							}
						});
						
						// Increase the start date with one day
						dateIterator.setDate(dateIterator.getDate() + 1);
					}
				}
				else
				{
					// The current day is not one of the possible days (based on period_of_stay), so disable
					element.parent().removeAttr('onclick').css('color','#999').css('font-weight','bold').css('cursor','default');
					element.parent().html(element.html());
				}
			});
		}
	});
}



// Function that initializes the header images

function initHeaderImages()

{

	var currentImage = 1;

	fadingArray = fadingImages;

	

	if(fromLtu)

		fadingArray = fadingLtuImages;

	

	jQuery.each(fadingArray, function(i, image)

	{

		var display = 'none';

		

		if(i == 0)

			display = 'inline';

			

		jQuery('#header').append('<img style="display: ' + display + '" id="header-img-' + (i+1) + '" src="' + image + '"/>');

		

		jQuery('#header-img-' + (i+1)).load(function()

		{

			if (i == (fadingArray.length - 1))

				setImage(fadingArray, 2, true);

		});

	});

}



// Function that sets the obj image to a random src

function setImage(array, index, start)

{

	var execute = function()

	{

		if(!interrupt && fading)

		{

			if(index == array.length + 1) index = 1;

			

			if (index != currentImage)

			{

				jQuery('#header-img-' + index).fadeIn(1000);

				jQuery('#header-img-' + currentImage).fadeOut(1000);

			}

			

			currentImage = index;

			index += 1;

			

			// Recursive call of set image

			setImage(array, index);

		}

	}

	

	// If not interrupted, proceed as normal. Else load Google maps

	if(!interrupt && fading)

	{

		// If route map exists, fade it out and remove it

		if(jQuery('#route_map').exists())

		{

			jQuery('#route_map').fadeOut(1000,function()

			{

				jQuery(this).remove();

				execute();

			});

		}

		else

		{

			if (isdefined(start)) 

				execute();

			else

			{

				jQuery(this).timeOut(8000, function(){execute();});

			}

		}

	}

	else if(fading)

	{

		jQuery('#header').append

		(

				'<div id=\"route_map\">'

			+		'<iframe width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"http://maps.google.com/maps/ms?hl=nl&amp;ie=UTF8&amp;msa=0&amp;msid=117327317922011868682.00046b83e425a1d4a321d&amp;ll=55.103516,21.730957&amp;spn=2.841231,17.666016&amp;z=6&amp;output=embed\">'

			+		'</iframe>'

			+	'</div>'

		);

		

		/*if(GBrowserIsCompatible())

		{

			var map = new GMap2(document.getElementById('route_map'));

			map.addControl(new GMenuMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(30,5)));

			map.addControl(new GSmallZoomControl3D(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5,4)));

			map.setCenter(new GLatLng(37.4419, -122.1419), 13);

		}

		*/

		

		jQuery('#header').find('img').each(function(i,img)

		{

			if(jQuery(this).css('display') == 'inline')

				jQuery(this).fadeOut(1000);

		});



		jQuery('#route_map').fadeIn(1000);

	}

	

	if(!fading)fading = true;

}



function loadGalleryWidget(TimeOut, start)

{

	if(typeof(start) == "undefined")

		start = false;



	if (start)

	{

		nextToShow = 0;

		jQuery('#thumb_holder').empty().load('/load.php?accommodation_widget', function()

		{

			jQuery('#thumb_holder .visible-holder').each(function(i,item)

			{

				jQuery(this).find('img').load();

			});

			

			jQuery('.image_holder a').lightBox();

			var widgetThumb = nextToShow;

			for (var i = 0; i < 6; i++)

			{

				fadeInGalleryImage(i, widgetThumb, TimeOut);

				

				if (widgetThumb == jQuery('#thumb_holder .image_holder').length - 1) 

					widgetThumb = 0;

				

				widgetThumb++;

			}

		});

	}

	
	if(!fromLtu)
	{
		for (var i = 0; i < jQuery('#thumb_holder .visible-holder').length; i++)
		{

			if(i == 0)
				galleryItemsToHide = jQuery('#thumb_holder .visible-holder');

		

			setTimeout("fadeOutGalleryImage("+start+","+TimeOut+","+i+")", i * 500);
		}
	}

}



function fadeOutGalleryImage(start, TimeOut, index)

{

	var elmToHide = galleryItemsToHide[(galleryItemsToHide.length - 1) - index];

	jQuery(elmToHide).hide();

	

	if (!start && (index == jQuery('#thumb_holder .visible-holder').length - 1))

	{

		jQuery('#thumb_holder .visible-holder').find('span').removeClass('mask1');

		jQuery('#thumb_holder .visible-holder').find('span').removeClass('mask2');

		jQuery('#thumb_holder .visible-holder').removeClass('visible-holder');

		

		var widgetThumb = nextToShow;

		for (var j = 0; j < 6; j++)

		{

			setTimeout("fadeInGalleryImage("+j+","+widgetThumb+","+TimeOut+")", 500 + (j * 500));

			

			widgetThumb++;

			

			if (widgetThumb == jQuery('#thumb_holder .image_holder').length)

				widgetThumb = 0;

		}

	}

}

	

function fadeInGalleryImage(i, j, TimeOut)

{

	if(i < 3)

		jQuery('#widget_thumb'+j).find('span').addClass('mask1');

	else

		jQuery('#widget_thumb'+j).find('span').addClass('mask2');

			

	jQuery('#widget_thumb'+j).fadeIn('fast',function()

	{

		jQuery(this).addClass('visible-holder');



		if(i == 5 && !fromLtu)

		{

			nextToShow = j + 1;

			

			jQuery(this).timeOut(TimeOut, function()

			{

				loadGalleryWidget(TimeOut);

			});

		}

	});

}



// If Array.indexOf function does not exist (IE) create it

if(!Array.indexOf)

{

    Array.prototype.indexOf = function(obj)

	{

        for(var i=0; i<this.length; i++)

		{

            if(this[i]==obj)return i;

        }

    }

}



// Function to center the object

jQuery.fn.centerScreen = function()

{

	var obj = this;

	obj.css('top', jQuery(window).height()/2-this.height()/2);

    obj.css('left', jQuery(window).width()/2-this.width()/2);

    jQuery(window).resize(function(){obj.centerScreen();});

}



// Function that gives a delay on the object

jQuery.fn.timeOut = function(time, callback)

{

	if(!isdefined(callback))callback = function(){};

	var obj = this; 

    obj.queue(function(){setTimeout(function(){obj.dequeue();callback();}, time)});

};



// Function checks if element exists

jQuery.fn.exists = function()

{

	return jQuery(this).length > 0;

}



// Get & set current page plugin

function setCurrentPagePlugin(Plugin, callback)

{

	if(typeof callback == "undefined")callback = function(){};

	CurrentPagePlugin = Plugin;

	

	callback();

}

function getCurrentPagePlugin()

{

	return CurrentPagePlugin;

}



// Load dialog

function loadDialog(div,content_url,icon,name,callback,login,width)

{

	if (typeof callback == "undefined")callback = function(){};

	if (typeof width == "undefined")width = 700;

	

	setDialogWidth(div, width);

	jQuery('#'+div+'_content').empty().load(content_url,'',function(){callback();activateDialogWindow(div,login);});

	jQuery('#'+div+'_title').html(name);

	setDialogWindowIcon(div,icon+'.png','/img/framework/dialog_icons/'+icon+'.png');

}



function setDialogWidth(div, width)

{

	jQuery('#'+div).width(width);

}



// Activates the dialog window and deactivates the main menu

function activateDialogWindow(div,login)

{

	if(typeof login == "undefined" || login == null)

	{

		if(jQuery('#framework_menu').is(':visible'))

		{

			hideMainMenu();

		}	

	}

	showDialogWindow(div);

}



// Shows the dialog window

function showDialogWindow(div)

{

	scroll(0,0);

	showFade('fade', 0.7);

	jQuery('#'+div).centerScreen();

	jQuery('#'+div).mb_open();

}



// Hides the dialog window

function hideDialogWindow(div)

{

	jQuery('#'+div).mb_close();

	jQuery('#'+div).unbind();

}



// Set new dialog window icon

function setDialogWindowIcon(div, icon_name, icon_path)

{

	jQuery('#'+div).attr('icon',icon_name).find('.icon').attr('src',icon_path);

}



// Shows the ajax loader (position = 1 || 2)

function showAjaxLoader(position)

{

	switch(position)

	{

		case 1:

			//jQuery('#ajax_loader').css('margin-left','-'+(jQuery('#ajax_loader').width()/2)+'px').show('fast');

			jQuery('#ajax_loader').fadeIn('fast').timeOut(1200);

			break;

		case 2:

			//jQuery('#ajax_loader').css('margin-left','-'+((jQuery('#ajax_loader').width()/2)+107)+'px').show('fast');

			jQuery('#ajax_loader').fadeIn('fast').timeOut(1200);

			break;

	}

}



// Shows the site submenu

function showSubmenu(div)

{

	var slide_height = '30';

	//jQuery('#'+div).css('height', '0px').animate({height: slide_height+'px'},'fast');

}



// Hides the site submenu

function hideSubmenu(div)

{	

	if(jQuery('#'+div).is(':visible'))

	{

		//jQuery('#'+div).animate({height: '0px'},'fast',function(){jQuery('#'+div).hide();});

	}

}



// Shows the fade overlay

function showFade(div,transparency)

{

	if(jQuery('#'+div).exists() && jQuery('#'+div).is(':hidden'))

	{

		jQuery('#'+div).css('display','block').css('opacity', 0).fadeTo('fast', transparency);

	}

}



// Hides the fade overlay

function hideFade(div)

{

	if(jQuery('#'+div).exists() && jQuery('#'+div).is(':visible'))

	{

		jQuery('#'+div).fadeTo('fast', 0,function(){jQuery('#'+div).hide()});

	}

}



// Load the site menu
function loadSiteMenu(edit)
{
	if(!isdefined(edit))edit = false;

	jQuery('#main_menu #dropdown').fadeOut('fast').empty()
	jQuery.getJSON('/load.php?main_menu=get&language='+(!get('lang') ? defaultLanguage : get('lang')), '', function(pages)
	{
		var language = (!get('lang') ? defaultLanguage : get('lang'));
		var main_menu = '';
		var extra = '';
	
		if (edit) 
			extra = 'edit/';
	
		jQuery.each(pages, function(p, page){
			if (page.in_menu == 1) {
				var has_children = false;
			
				if (page.children.length >= 1) 
					has_children = true;
			
				if (!has_children) 
					main_menu += '<li onclick="jQuery(this).find(\'a\').click();"><span class="outer"><span class="l"></span><span class="r"></span></span><a href="/strt/' + extra + 'lang/' + language + '/page/' + page.true_name + '" rel="address:/' + extra + 'lang/' + language + '/page/' + page.true_name + '" id="page_' + page.page_id + '" class="main_menu_item">';
				else 
					main_menu += '<li onclick="jQuery(this).find(\'a .head\').click();"><span class="outer"><span class="l"></span><span class="r"></span></span><a href="/strt/' + extra + 'lang/' + language + '/page/' + page.true_name + '" rel="address:/' + extra + 'lang/' + language + '/page/' + page.true_name + '" id="page_' + page.page_id + '" class="main_menu_item head">';
			
				main_menu += URLDecode(page.name) + '</a>';
				
				if (has_children) {
					main_menu += '<ul>';
				
					jQuery.each(page.children, function(c, child){
						if (child.in_menu == 1) 
							main_menu += '<li onclick="jQuery(this).find(\'a\').click();"><a href="/strt/' + extra + 'lang/' + language + '/page/' + page.true_name + '/sub/' + child.true_name + '" rel="address:/' + extra + 'lang/' + language + '/page/' + page.true_name + '/sub/' + child.true_name + '" id="page_' + child.page_id + '" class="main_menu_item">' + URLDecode(child.name) + '</a></li>';
					});
				
					main_menu += '</ul>';
				}
			
				main_menu += '</li>';
			}
		});
	
		var menuElement = jQuery('#main_menu #dropdown');
		menuElement.append(main_menu);
		
		// Create the dropdown menu 
		menuElement.ptMenu();
		jQuery('.main_menu_item').address();		
		/*
		.address(function()
		{
			return menuElement.attr('href').replace('/strt', '');
		});
		*/
		

		menuElement.fadeIn('fast');
	});
}



// Load site submenu

function loadSiteSubmenu(div,parent_id)

{

	jQuery('#'+div).load('/modules/edit_page/load.php?item=submenu&id='+parent_id,'',function()

	{

		showSubmenu(div);

		

		// Set all sub items to have font-weight normal, and the active one to have font-weight bold

		jQuery('.sub_item').each(function()

		{

			jQuery(this).css('font-weight','normal');

			

			var split = jQuery(this).attr('id').split('sub_item');

			

			if(split[1] == currentPageID)

			{

				jQuery(this).css('font-weight','bold');				

			}

		});

	});	

}



// Function that loads the page and sets the content
function loadPage()
{
	//showAjaxLoader(2);

	// Hide and empty the page assets
	jQuery('#normal_content').hide('fast').empty();
	jQuery('#plugin_top').hide('fast').empty();
	jQuery('#plugin_bottom').hide('fast').empty();
	jQuery('#booking').hide('fast').empty();
	
	if(jQuery('.mceEditor').css('display') == 'none')
		jQuery('.mceEditor').show();
	
	// Hide TinyMCE text area's
	jQuery('.tiny_mce_textarea').hide('fast');

	// Retrieve get_page and get_sub(page)
	var get_page	= get('page');
	var get_sub		= get('sub');
	
	if(!get_page)
	{
		// No page is set, use the homepage
		var page = homePage;
	}
	else if(!get_sub)
	{
		// No subpage is set, so load the set page
		var page = get_page;
	}
	else
	{
		// A page and subpage have been set, load the subpage
		var page = get_sub;
	}	

	// Pages with a space in the name, have a _ in stead, so replace them
	page = str_replace('_',' ',page);
	
	if(page == 'beschikbaarheid')
		jQuery.address.value('/lang/'+(!get('lang') ? defaultLanguage : get('lang'))+'/booking');
	else
	{
		if(page == 'route')
		{
			interrupt = true;
			setImage(fadingArray,0);
		}
		else
		{
			if(interrupt)
			{
				interrupt = false;
				fading = true;
			}
			else
				fading = false;	

			setImage(fadingArray,0);
		}

		// After processing, if get('booking') is set, load the booking module
		if(get('booking',false))
		{
			jQuery('#quote_holder').hide();		
			loadBooking();
			jQuery.address.title(siteTitle + 'Boeken');
		}
		else
		{
			// Load the page (if no language is set, use the default language)
			jQuery.getJSON('/load.php',{page : page, language : (!get('lang') ? defaultLanguage : get('lang'))},function(page)
			{
				// Set the page title
				jQuery.address.title(siteTitle + URLDecode(page.name));			

				jQuery('.main_menu_item').removeClass('active');
				jQuery('#page_'+page.id).addClass('active');
				
				currentPageID = page.id;
				textPosition = page.text_position;			

				// Load the submenu
				/*
				if(has_children == 'true')
				{
					loadSiteSubmenu('submenu',id);

				}

				*/

				

				if(jQuery('#holder').is(':hidden'))

					showQueue[showQueue.length] = '#holder';

					

				if(jQuery('#widgets').is(':hidden'))
					showQueue[showQueue.length] = '#widgets';
				
				if(get('home',false) || URLDecode(page.name) == homePage || URLDecode(page.name).toLowerCase() == 'pradžia' || URLDecode(page.name).toLowerCase() == 'начало')
					loadTestimonial();
				else
					jQuery('#quote_holder').hide();			

				

				// Check if there is a page plugin

				if(page.plugin_id != -1)

				{

					// There is a page plugin, so load it

					jQuery.ajax

					({

						type: 'GET',

						url: '/modules/'+page.plugin_name+'/index.php',

						data: '',

						success: function(data)

						{	          			

							if(textPosition == 'bottom')

							{

								// Set the page content

								setPageContent(page.content, function()

								{

									showQueue[showQueue.length] = '#plugin_top';

									jQuery('#plugin_top').html(data);

								});

							}

							else if(textPosition == 'top')

							{

								// Set the page content

								setPageContent(page.content, function()

								{

									showQueue[showQueue.length] = '#plugin_bottom';

									jQuery('#plugin_bottom').html(data);

								});

							}

							else

							{

								// Text Position is set to none

								showQueue[showQueue.length] = '#plugin_top';

								jQuery('#plugin_top').html(data);

								

								jQuery('.mceEditor').hide();

							}

						}

					});

				}

				else

				{

					// Set the page content

					setPageContent(page.content, function()

					{

						setLanguageText();

						// After the setPageContent function is done show each item in the show queue

						jQuery.each(showQueue,function(i,item)

						{

							jQuery(item).show('fast');

						});

						// Empty showQueue

						showQueue = [];

						// When done hide the ajax loader

						jQuery('#ajax_loader').fadeOut('fast');

					});				

				}

			});

		}
	}
}



// Function that sets the page content (page = page data(json))

function setPageContent(page_content, callback)

{

	jQuery.datepicker.regional[(!get('lang') ? defaultLanguage : get('lang'))];

	

	// Check if in edit mode

	if(!TinyMceActivated && !get('edit',false))

	{

		// Add the site content div to the show queue

		showQueue[showQueue.length] = '#normal_content';

		// Set the page content

		jQuery('#normal_content').html(stripslashes(URLDecode(page_content)));

		

		jQuery('#normal_content a').each(function()

		{

			if(jQuery(this).attr('rel') == 'lightbox')

				jQuery(this).lightBox();

		});

	}

	else

	{

		// DYNAMIC TINYMCE INSTANCES

		var ed = tinyMCE.get('page_content');

		

		// Set page content

		ed.setContent(stripslashes(URLDecode(page_content)));

				

		// If a page plugin is active, load the tab

		handlePluginTab();

	}

	

	// If a callback is set, execute it

	if(isdefined(callback))callback();

}



// Function that sets the new language

function setLanguage(language)

{

	// Set new lang, assamble the new url, reload page

	jQuery.address.value(set('lang',language,true));

	

	loadSiteMenu();

}



// Function that processes/extracts the url (used after reload)

function processUrl(url)

{

	// Set the getUrl variable to the given url

	getUrl = url;

	

	// If url is defined, transform the url string into an url array

	if(isdefined(url))urlArray = getUrl.split('/');

}



// Function that will return the value of the given item

function get(item, next)

{

	if(!isdefined(next))next = true;

	

	// The urlArray contains all the url items. If next is true, it looks as follows:

	// urlArray['page','2','product','5']

	// So the item name will always precede it's value

	// If next is false, we're looking for an item without a specific value

	

	// Check if the item exists in the urlArray

	if(in_array(item, urlArray))

	{

		if(next)

		{

			// If the item exists and next is true, fetch the item it's value

			return urlArray[urlArray.indexOf(item)+1];

		}

		else

			return true;

	}

	else

	{

		// If not, return false

		return false;

	}

}



// Function that will set the value of the requested item

// (if assemble is true, it will create a new url and return it)

function set(item, value, assemble, inFront)

{

	// If assemble isn't defined, it is false

	if(!isdefined(assemble))assemble = false;

	if(!isdefined(inFront))inFront = false;

	

	// The urlArray contains all the url items. If next is true, it looks as follows:

	// urlArray['page','2','product','5']

	// So the item name will always precede it's value

	// If next is false, we're setting an item without a value

	

	// Check if the item exists in the urlArray

	if(!in_array(item, urlArray))

	{

		if(inFront)

		{

			if(value != '')

				// If there is a value set it to the first item

				urlArray[0] = value;

			else

				// If there is no value remove the first item

				urlArray.splice(0,1);

			

			// Add the new item in front of the array

			urlArray.unshift(item);

		}

		else

		{

			// If the item doesn't exist create the item

			urlArray[urlArray.length] = item;

		}

	}

	

	if(!inFront && value != '')

	{

		// Set the item it's value

		urlArray[urlArray.indexOf(item)+1] = value;

	}

	

	if(assemble)

	{

		return assambleUrlArray();

	}

}



function assambleUrlArray()

{

	var newUrl = '';

	for(i in urlArray)

	{

		if(urlArray[i] != '')

			newUrl += '/'+urlArray[i];

	}		

	return newUrl;

}



// Adress event handlers

// To debug for search engine (without javascript) put .change event into .internalChange and empty .init

jQuery.address

	.init(function(event)

	{

		// When init, and 'strt' is in the url, replace it with a # for the functioning of the address script

		var initUrl = window.location.href;

	    if(initUrl.indexOf('strt') > -1)

	    {

	    	window.location.href = window.location.href.replace('strt','#');

    	}

	})

	.change(function(event)

	{

		// After the reload process the new url

	    processUrl(event.value);

	    

	    // After processing, handle the page loading

		if(get('edit',false) && !TinyMceActivated && loggedIn == 'true')

    	{

    		// Activate edit mode and load the edit menu

			activateTopbar();

		}

	    else

	    {

	    	// Load the page

	    	loadPage();

    	}

	})

	.internalChange(function(event){})

	.externalChange(function(event)

	{
		// If the change is external, execute processing ready after processing

		processingReady();

	});
