(function($){
	var URL_ROOT = $('script[url-root]').attr('url-root');
	$.CMS = {
		URL_ROOT : URL_ROOT,
		URL_DATA : URL_ROOT+'cms-data/'
	};
	
	$.easing.easeInExpo = function (x, t, b, c, d) {
		return (t===0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	};
	$.easing.easeOutExpo = function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	};
	
	$.fx.interval = 40;
	
	var SMALL = $(window).width() <= 480,
		panelSpeed = 500,
		pageSpeed = 800,
		sidebar = $('#sidebar'),
		content = $('#content'),
		footer = $('#footer'),
		sidebarRight,
		contentLeft,
		background = $('#background'),
		contentBackground = $('#content-background'),
		curBG = background.find('div').css('background-image'),
		tooltip = $('#bg-tooltip'),
		ttTarget = { left : 0, top : 0 },
		ttPos = { left : 0, top : 0 },
		slided = false,
		ttin = false;
		
	// Init some stuff on content
	function initContent() {
		/* Enable forms */
		$('#content-inner form[data-action]').each(function() {
			$(this).attr('action', $(this).attr('data-action'));
		});
		
		/* Enable placeholders */
		$('#content-inner [placeholder]').focus(function() {
			var that = $(this);
			if(that.is('.placeholder')) {
				that.removeClass('placeholder').val('');
			}
		}).blur(function() {
			var that = $(this), placeholder = that.data('placeholder');
			if(!that.val() && placeholder) {
				that.addClass('placeholder').val(placeholder);
			}
		}).each(function() {
			var that = $(this), placeholder = that.attr('placeholder');
			that.data('placeholder', placeholder).attr('placeholder', '');
			if(!that.val()) {
				that.addClass('placeholder').val(placeholder);
			}
		});
		
		if(!SMALL) {
			/* Scrollbars */
			$('#content-inner .content-padding:not(.jspaned)').css('overflow', 'auto').addClass('jspaned').jScrollPane({
				showArrows : true,
				autoReinitialise : true,
				verticalGutter : 10,
				horizontalGutter : 0,
				verticalDragMinHeight : 14,
				verticalDragMaxHeight : 14,
				speed : 60
			});
			$('.popup').each(function() {
				$(this).css('top', 263 - $(this).height() / 2);
			});
			$('.popup-content:not(.jspaned)').css('overflow', 'auto').addClass('jspaned').jScrollPane({
				showArrows : true,
				autoReinitialise : true,
				verticalGutter : 10,
				horizontalGutter : 0,
				verticalDragMinHeight : 14,
				verticalDragMaxHeight : 14,
				speed : 60
			});
		}
		
		$('#content-inner iframe.autoresize').load(function() {
			var that = $(this);
			try {
				that.height(that.contents().height());
			} catch(ex) {}
		});
	}
	initContent();
	if(SMALL) {
		footer.insertAfter(content).find('a[title]').text(function(){
			return $(this).attr('title');
		});
		$('#contacts,#social').insertAfter(content);
		$('.gallery,.popup').remove();
		
		$('#menu>ul,#lngmenu').hide();
		sidebar.append($('<div id="small-title"></div>').text(sidebar.find('a.this').text()));
	} else {
		$('#content-inner .content-padding').focus();
		footer.find('a[title]').attr('title', '');
	}
	
	// Clean up content
	function cleanupContent(animate) {
		if(!SMALL) {
			if(animate) {
				showFooter();
			} else {
				footer.css({
					marginBottom : 0,
					opacity : 1
				});
			}
		}
		$('.panel.open .close').click();
		if(!SMALL) {
			$('.gallery').animate({
				marginLeft : '100%'
			}, animate ? panelSpeed : 0, 'easeOutExpo', function() {
				$(this).remove();
			});
			$('#gmaps').animate({
				marginLeft : '100%'
			}, animate ? panelSpeed : 0, 'easeOutExpo');
		}
		$('.submenu').remove();
		$('.popup').remove();
	}
	// Hide footer
	function hideFooter(callback) {
		if(SMALL) {
			return;
		}
		footer.animate({
			marginBottom : -30,
			opacity : 0
		}, panelSpeed, 'easeOutExpo', callback);
	}
	// Show footer
	function showFooter() {
		if(SMALL) {
			return;
		}
		footer.animate({
			marginBottom : 0,
			opacity : 1
		}, panelSpeed, 'easeOutExpo');
	}
	
	if(!SMALL) {
		$('#background').click(function(e) {
			if(!sidebarRight) {
				sidebarRight = sidebar.css('margin-right');
				contentLeft = content.css('margin-left');
			}
			sidebar.animate({
				marginRight : slided ? sidebarRight : '50%'
			}, 700, 'easeOutExpo');
			content.animate({
				marginLeft : slided ? contentLeft : '50%'
			}, 700, 'easeOutExpo');
			slided = !slided;
			tooltip.toggleClass('slided', slided);
		});
		$('body').delegate('#sidebar,#content', 'mouseleave', function() {
			if(!ttin) {
				tooltip.stop().hide().fadeTo(1);
				ttin = true;
			}
		}).delegate('#sidebar,#content', 'mouseenter', function() {
			if(ttin) {
				tooltip.hide();
				ttin = false;
			}
		}).delegate('#background', 'mousemove', function(e) {
			ttTarget = {
				left : 20 + e.pageX,
				top : 20 + e.pageY
			};
		}).delegate('.popup-close', 'click', function() {
			var popup = $(this).closest('.popup').hide(), url = popup.attr('data-hide');
			if(url) {
				$.post(url);
			}
		});
		setInterval(function() {
			if(!ttin) {
				return;
			}
			var offset = tooltip.offset(),
				dx = (ttTarget.left - ttPos.left) * 0.2,
				dy = (ttTarget.top - ttPos.top) * 0.2;
			if(Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) {
				return;
			}
			ttPos = {
				left : ttPos.left + dx,
				top : ttPos.top + dy
			};
			tooltip.css(ttPos);
		}, 50);
	}
	
	if(SMALL) {
		/* Showing and hiding panels */
		$('body').delegate('.panel-show', 'click', function() {
//			console.debug($($(this).attr('href')).addClass('open').show());
			return false;
		});
		$('body').delegate('.panel .close', 'click', function() {
			$(this).closest('.panel').hide();
			return false;
		}).delegate('#small-title', 'click', function() {
			$(this).remove();
			$('#menu>ul,#lngmenu').show();
		});
	} else {
		/* Showing and hiding panels */
		content.delegate('.panel-show', 'click', function() {
			var panel = $($(this).attr('href')).addClass('open');
			if(panel.is('.bottom')) {
				panel.show().css({
					opacity : 0,
					marginBottom : -panel.outerHeight()
				});
				panel.animate({
					opacity : 1,
					marginBottom : 0
				}, panelSpeed, 'easeOutExpo');
			} else {
				panel.show().css({
					opacity : 0,
					marginRight : -panel.outerWidth()
				});
				panel.animate({
					opacity : 1,
					marginRight : 0
				}, panelSpeed, 'easeOutExpo');
			}
			return false;
		});
		content.delegate('.panel .close', 'click', function() {
			var panel = $(this).closest('.panel');
			if(!panel.is('.open')) {
				return false;
			}
			panel.removeClass('open');
			if(panel.is('.bottom')) {
				panel.animate({
					opacity : 0,
					marginBottom : -panel.outerHeight() - 1
				}, panelSpeed, 'easeOutExpo');
			} else {
				panel.animate({
					opacity : 0,
					marginRight : -panel.outerWidth() - 1
				}, panelSpeed, 'easeOutExpo');
			}
			return false;
		});
	}
	
	// Treatments
	content.delegate('.treatment.closed', 'click', function() {
		$('.content', this).slideDown();
		$(this).removeClass('closed').addClass('open');
	}).delegate('.treatment.open', 'click', function() {
		$('.content', this).slideUp();
		$(this).removeClass('open').addClass('closed');
	});
	
	// Special offers
	content.delegate('.offer.closed', 'click', function() {
		$('.text', this)[SMALL ? 'show' : 'slideDown']();
		$('.pic', this).animate(SMALL ? {} : {
			width : 193,
			height : 193,
			marginRight : 20,
			marginTop : 13
		}, 'swing');
		$(this).removeClass('closed').addClass('open');
	}).delegate('.offer.open', 'click', function() {
		$('.text', this)[SMALL ? 'hide' : 'slideUp']();
		$('.pic', this).animate(SMALL ? {} : {
			width : 45,
			height : 45,
			marginRight : 10,
			marginTop : 0
		}, 'swing');
		$(this).removeClass('open').addClass('closed');
	});
	
	// Gallery
	if(!SMALL) {
		content.delegate('a.open-gallery', 'click', function(e) {
			e.preventDefault();
			var clicked = $(this),
				clickedHref = clicked.attr('href'),
				gallery = $('.gallery'),
				picOut = $('<img>').appendTo($('.gallery-pic-out').empty()),
				picIn = $('<img>').appendTo($('.gallery-pic-in').empty()),
				prev = $('.gallery-prev'),
				next = $('.gallery-next'),
				back = $('.gallery-back'),
				pos = 0,
				pics = $('[rel='+clicked.attr('rel')+']'),
				n = pics.length;
		
			function showPic(p) {
				pos = p;
				picOut.attr('src', picIn.attr('src') || '').fadeTo(0, 1).fadeTo(500, 0);
				picIn.attr('src', pics.eq(pos).attr('href')).fadeTo(0, 0).fadeTo(500, 1);
			}
		
			prev.toggle(n > 1);
			next.toggle(n > 1);
	
			pics.each(function() {
				$('<img>').attr('src', $(this).attr('href'));
			});
		
			$('<img>').attr('src', clickedHref);
			pics.each(function() {
				if($(this).attr('href') == clickedHref) {
					return false;
				}
				pos++;
			});
	
			prev.click(function() {
				showPic((pos + n - 1) % n);
				return false;
			});
			next.click(function() {
				showPic((pos + 1) % n);
				return false;
			});
			back.click(function() {
				prev.unbind();
				next.unbind();
				back.unbind();
			
				$('.content-padding').animate({
					marginLeft : 0
				}, panelSpeed, 'easeOutExpo', function() {
					showFooter();
				});
				gallery.animate({
					marginLeft : '100%'
				}, panelSpeed, 'easeOutExpo');
						
				return false;
			});
		
			hideFooter(function() {
				showPic(pos);
				$('.content-padding').animate({
					marginLeft : '-100%'
				}, panelSpeed, 'easeOutExpo');
				gallery.animate({
					marginLeft : 0
				}, panelSpeed, 'easeOutExpo');
			});
			return false;
		});
	}
	
	/* Map */
	var map;
	if(!SMALL) {
		content.delegate('a.map-link[data-coords]', 'click', function(e) {
			e.preventDefault();
			var that = $(this),
				coords = that.attr('data-coords').split(';'),
				myLatLng;
	
			if(coords.length != 2) {
				return;
			}
			try {
				myLatLng = new google.maps.LatLng(coords[0], coords[1]);
			} catch(ex) {
				return;
			}
			if(!map) {
				var myOptions = {
					zoom: 15,
					center: myLatLng,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				};
				map = new google.maps.Map(document.getElementById('map'), myOptions);
	
				var marker = new google.maps.Marker({
					position: myLatLng,
					map: map,
					title: 'Hotel Telegraaf'
				});
			}
	
			hideFooter(function() {
				$('.content-padding').animate({
					marginLeft : '-100%'
				}, panelSpeed, 'easeOutExpo');
				$('#gmaps').animate({
					marginLeft : 0
				}, panelSpeed, 'easeOutExpo');
			});
	
			return false;
		});
		content.delegate('#close-map', 'click', function() {
			$('.content-padding').animate({
				marginLeft : 0
			}, panelSpeed);
			$('#gmaps').animate({
				marginLeft : '100%'
			}, panelSpeed, 'easeOutExpo', function() {
				showFooter();
			});
			return false;
		});
	}
	
	
	/* Changing pages */
	var mainmenu = $('#menu ul'),
		loadedMain = mainmenu.find('a.this').attr('href'),
		loadedSub = $('.submenu a.this').attr('href'),
		cache = {};
	
	function loadPage(state) {
		if(state === null) {
			return;
		}
		var gotData = false,
			timeout = false,
			fullChange = state.main != loadedMain,
			noFullAnim = navigator.userAgent.match(/iPad|Android/i);
			
		if(loadedMain == state.main && loadedSub == state.sub) {
			return;
		}
		
		function loaded(data) {
			var current = $('.content-padding:last');
			cleanupContent(!fullChange);
			
			// Update window title
			document.title = data.match(/<title>([^<]*)<\/title>/i)[1];
			$('title').text(document.title);
			
			data = $(data.replace(/^[\s\S]*<body[^>]*>|<\/body>[\s\S]*$|<script[^<]*<\/script>|<style>[\s\S]*<\/style>|<!--[\s\S]*-->|\n\s*(:?\n)/ig, '').replace(/\n\s*/g, "\n").replace('<script class="preserve" src=', '<div class="preserved-script" style="display:none" data-src=').replace('</script>', '</div>')).wrapAll('<div>').parent();
						
			if(SMALL) {
				// Switch content
				data.find('.submenu').insertBefore(current);
				data = data.find('.content-padding');
				current.replaceWith(data);
				initContent();
				
				$('#menu>ul,#lngmenu').hide();
				content.show();
				if($('.submenu a.this').length && $('#small-title').length) {
				} else {
					$('#small-title').remove();
					sidebar.append($('<div id="small-title"></div>').text(sidebar.find('a.this').text()));
				}
				window.scrollTo(0, 0);
				
			} else {
				// Change background
				var newBG = data.find('#background').children().css('background-image'),
					newContentBG = data.find('#content-background').children().css('background-image');
				
				if(newBG != curBG) {
					var bgTest = $('<img>').attr('src', newBG.replace(/^url\(["']?|["']?\)$/g, '')),
						bgTest2 = $('<img>').attr('src', newContentBG.replace(/^url\(["']?|["']?\)$/g, ''));
					
					if(noFullAnim) {
						var removingBG = background.find('div');
						$('<div>').css('background-image', newBG).appendTo(background);
						setTimeout(function() {
							removingBG.remove();
						});
					} else {
						setTimeout(function() {
							background.find('div:not(.removing)').addClass('removing').stop().fadeTo(1500, 0, function() {
								$(this).remove();
							});
							$('<div>').css('background-image', newBG).fadeTo(0, 0).appendTo(background).fadeTo(1500, 1);
							contentBackground.find('div:not(.removing)').addClass('removing').stop().fadeTo(1500, 0, function() {
								$(this).remove();
							});
							$('<div>').css('background-image', newContentBG).fadeTo(0, 0).appendTo(contentBackground).fadeTo(1500, 1);
						}, 2 * pageSpeed);
					}
					
					curBG = newBG;
				}
				
				// Import gmaps and gallery
				if(!$('#gmaps').length) {
					data.find('#gmaps').insertAfter(current);
				}
				data.find('.gallery, .submenu, .popup').insertAfter(current);
			
				// Switch content
				data = data.find('.content-padding');
			
				current.after(data);
				if(fullChange) {
					current.remove();
				} else {
					current.animate({
						marginLeft : '-100%'
					}, pageSpeed, 'easeOutExpo', function() {
						$(this).remove();
					});
				}
			
				if(!fullChange) {
					data.css('margin-left', '100%').animate({
						marginLeft : 0
					}, pageSpeed, 'easeOutExpo');
					$('#content-inner .content-padding').focus();
				}
				initContent();
			
				if(fullChange) {
					if(noFullAnim) {
						$('#content-inner .content-padding').focus();
					} else {
						content.css('top', '-50%').animate({
							top : '50%'
						}, pageSpeed, 'easeOutExpo', function() {
							$('#content-inner .content-padding').focus();
						});
					}
				}
			}
		}
		function tryLoaded(haveData) {
			if(haveData) {
				if(timeout) {
					loaded(haveData);
				} else {
					gotData = haveData;
				}
			} else {
				if(gotData) {
					loaded(gotData);
				} else {
					timeout = true;
				}
			}
		}
		
		if(state.type) {
			var prev = mainmenu.find('.this').removeClass('this').parents('li').children('ul'),
				next = mainmenu.find('a[href='+state.main+']:last').addClass('this').parents('li').children('ul');
			
			if(SMALL) {
				if(cache[state.href]) {
					loaded(cache[state.href]);
				} else {
					$.get(state.href, function(data) {
						cache[state.href] = data;
						loaded(data);
					}, 'html');
				}
			} else {
				if(prev[0] !== next[0]) {
					if(prev.length) {
						prev.slideUp(function() {
							next.slideDown();
						});
					} else {
						next.slideDown();
					}
				}
			
				if(fullChange) {
					if(noFullAnim) {
						tryLoaded();
						if(cache[state.href]) {
							tryLoaded(cache[state.href]);
						} else {
							$.get(state.href, function(data) {
								cache[state.href] = data;
								tryLoaded(data);
							}, 'html');
						}
					} else {
						content.stop().animate({
							top : '150%'
						}, pageSpeed, 'easeInExpo', function() {
							tryLoaded();
						});
				
						if(cache[state.href]) {
							tryLoaded(cache[state.href]);
						} else {
							$.get(state.href, function(data) {
								cache[state.href] = data;
								tryLoaded(data);
							}, 'html');
						}
					}
				} else {
					if(cache[state.href]) {
						loaded(cache[state.href]);
					} else {
						$.get(state.href, function(data) {
							cache[state.href] = data;
							loaded(data);
						}, 'html');
					}
				}
			}
			loadedMain = state.main;
			loadedSub = state.sub;
		}
	}
	
	
	// Browsers that support HTML5 history.pushState() are modern enough
	var modern = history && history.pushState;
	
	if(modern) {
		$(window).bind('popstate', function(e) {
			loadPage(e.originalEvent.state);
		});
	} else {
/*		$(window).bind('hashchange', function(e) {
			var state = $.bbq.getState();
			loadPage(state.href ? state : null);
		}).trigger('hashchange');*/
	}
	
	function setState(data, title, url) {
		try{
			if(modern) {
				history.pushState(data, title, url);
			} else {
//				$.bbq.pushState(data, 2);
			}
			loadPage(data);
			
			/* Google analytics tracking */
			if(window._gaq) {
				window._gaq.push(['_trackPageview', url]);
			}
			/* Snoobi */
			if(window.snoobi) {
				snoobi.trackPageView(url);
			}
			
			return false;
		} catch(ex) {
		}
	}
	
	if(modern) {
		$('#menu').delegate('ul a, #logo', 'click', function(e) {
			var link = $(this),
				href = link.attr('href'),
				data = {
					type : 'main',
					main : href,
					href : href
				};
			if(href.match(/https?:\/\//)) {
				link.attr('target', '_blank');
				return;
			}
			if(loadedMain != href || loadedSub) {
				return setState(data, link.text(), href);
			} else {
				return false;
			}
		});
		content.delegate('.submenu a', 'click', function() {
			var link = $(this),
				href = link.attr('href'),
				data = {
					type : 'sub',
					main : loadedMain,
					sub : href,
					href : href
				};
			if(href.match(/https?:\/\//)) {
				link.attr('target', '_blank');
				return;
			}
			if(loadedSub != href) {
				return setState(data, link.text(), href);
			} else {
				return false;
			}
		});
	}
})(jQuery);

jQuery(function($){
});


