SR = window.SR || {
	navigationExtender: null,
	conf: {}
};


/** 
 * It's better to listen to the dom:loaded event, because this fires
 * before window.onload.
 *
 * Event.observe(window, "load", OnDocumentLoad); 
 */

document.observe("dom:loaded", OnDocumentLoad);


Event.observe(window, "unload", OnDocumentUnload);

function OnDocumentLoad ( evObj ) {
	
		var loadId = "home";
	
		SR.navigationExtender = new NavigatonExtender($("ReferenceNavigation"), $("footer"), new ReferenceContentLoader("Content", "backgroundContainer", loadId));
		
		
		// Add footer navigation visuals.
		jQuery('#footer li:not(:last)').append("<span>.</span>");
		
		jQuery.ifixpng("lib/images/pixel.gif");
				
		jQuery("#contentBottom").hover(
			  	function() { // mouseover
					clearTimeout(jQuery(this).data("timerID"))
		   		},
				function() { // mouseout
					var t = setTimeout(function() {
						SR.PageContent.hideBottomContainer();
					},500);
					jQuery(this).data("timerID",t);
				}
			);
	
	
		jQuery('#titleHeader img').ifixpng();   
		jQuery('.png').ifixpng();         
		setTimeout(function() {
			jQuery('#titleHeader img, #NavigationHeader img').ifixpng();              
		},100);
	
}

function OnDocumentUnload ( evObj )	{
}

/**
 * NavigatonExtender. 
 */
 
var NavigatonExtender = Class.create();
NavigatonExtender.prototype = {
	
	contentLoader: null, 
	
    initialize : function(list, footerNavigation, contentLoader) {
		this.ItemClicked = this.OnItemClicked.bindAsEventListener(this);
		this.ItemOver = this.OnItemOver.bindAsEventListener(this);
		this.ItemOut = this.OnItemOut.bindAsEventListener(this);
		this.list = $(list);
		this.footerNavigation = $(footerNavigation);
		this.contentLoader = contentLoader;
		
		var listItemsImages = this.list.select("li img");
		listItemsImages.each(function(el) { 
						Event.observe(el, "click", this.ItemClicked); 
						Event.observe(el, "mouseover", this.ItemOver); 
						Event.observe(el, "mouseout", this.ItemOut);
		}, this);
		
		var listItemsfooterNavigation = this.footerNavigation.select("ul li a");
		listItemsfooterNavigation.each(function(el) { 
				if (el.hasAttribute("class")) {
					// Only register navigation items which have a class attribute (01, 02, 03, ...)
					Event.observe(el, "click", this.ItemClicked); 
					Event.observe(el, "mouseover", this.ItemOver); 
					Event.observe(el, "mouseout", this.ItemOut);
				}
		}, this);
		
		Event.observe($$('#titleHeader img')[0], "click", this.ItemClicked);
		
		this.activeItem = null;
    },

    OnItemClicked : function(evObj) {
	
		var elem = evObj.target; //Event.element(evObj);
		this.doClick(elem);
		
    },

	doClick: function(elem) {

		// var itemNr = elem.getAttribute("class");
		var itemId = '';
		
		if (elem.tagName.toLowerCase() == 'a') {
			itemId = elem.getAttribute("rel");
		}
		else {
			itemId = elem.getAttribute("alt");
		}
		
		var itemNr = this.contentLoader.mainNavigationItems[itemId];
		if (!itemNr) itemNr = '99';

		if (SR.conf.sites[itemId] == 'bottom') {
			this.contentLoader.LoadBottomContent(itemId);
			return;
		}

    	this.contentLoader.LoadContent(itemId);
		
		var shadow = document.getElementById("shadow"+itemNr);
    	if (this.activeItem) {
			this.activeItem.src = this.activeItem.src.replace("_a", "_p");
			this.activeShadow.src = this.activeShadow.src.replace("_a", "_p");
		}

		var that = this;
		$$("#ReferenceNavigation [alt=" + itemId + "]").each(function (el) {

	    	that.activeItem = el;
			that.activeShadow = shadow;
		    that.activeItem.src = that.activeItem.src.replace("_o", "_a");
		    that.activeItem.src = that.activeItem.src.replace("_p", "_a");
			that.activeShadow.src = shadow.src.replace("_o", "_a");
			that.activeShadow.src = shadow.src.replace("_p", "_a");
		
		});
		
	},

    OnItemOver : function(evObj) {
		var itemNr = jQuery(evObj.target).attr("class");
		var shadow = document.getElementById("shadow"+itemNr);
		if (evObj.target.tagName.toLowerCase() == 'img') {
			Event.element(evObj).src = Event.element(evObj).src.replace("_p", "_o");
			shadow.src = shadow.src.replace("_p", "_o");
		}
    },
    OnItemOut : function(evObj) {
		var itemNr = jQuery(evObj.target).attr("class");
		var shadow = document.getElementById("shadow"+itemNr);
		if (evObj.target.tagName.toLowerCase() == 'img') {
		    Event.element(evObj).src = Event.element(evObj).src.replace("_o", "_p");
			shadow.src = shadow.src.replace("_o", "_p");
		}
    }
}

/**
 * ReferenceContentLoader.  
 */
 
var ReferenceContentLoader = Class.create();
ReferenceContentLoader.prototype = {
	
	/**
	 * Initialize id with -1, which will use to 
	 * determine if we're still loading the page,
	 * or just switching content.
	 */
	
	id: -1,
	
 	mainNavigationItems: {
		// Items in the main navigation with a predefined background.
		'home': 		'00',
		'sascha': 		'01',
		'news': 		'02',
		'sendungen': 	'03',
		'angebot': 		'04',
		'booking': 		'05'
	},

	initialize : function(contentHolder, backgroundContainer, id) {
		this.LinkOver = this.OnLinkOver.bindAsEventListener(this);
		this.LinkOut = this.OnLinkOut.bindAsEventListener(this);
		this.WindowResize = this.OnWindowResize.bindAsEventListener(this);
		this.backgroundContainer = $(backgroundContainer);
		this.contentHolder = $(contentHolder);
		this.viewportProperties = new ViewportProperties();
		this.LoadContent(id);
		Event.observe(window, "resize", this.WindowResize);
	},
	
	LoadContent : function(id) {
				
		if (id == this.id) {
			// Do not load the content again if it's already loaded.
			return;
		}


		var initialLoad = (this.id == -1);

		this.id = id;
		//changeTextAndImageForId(id, this, initialLoad);
		SR.PageContent.loadId(id, this, initialLoad);
	},
	
	LoadBottomContent: function(id) {
		
		SR.PageContent.loadBottomId(id, this);
		
	},
	
	ChangeBackground : function(id,initialLoad) {
		this.id = id;
		this.screenWidth = this.viewportProperties.WindowWidth;
		this.bgWidth = "1000";
		if (this.screenWidth >= 1000) {
			this.bgWidth = "1100";
		}
		if (this.screenWidth >= 1100) {
			this.bgWidth = "1200";
		}
		if (this.screenWidth >= 1200) {
			this.bgWidth = "1300";
		}
		if (this.screenWidth >= 1300) {
			this.bgWidth = "1400";
		}
		if (this.screenWidth >= 1400) {
			this.bgWidth = "1500";
		}
		if (this.screenWidth >= 1500) {
			this.bgWidth = "1600";
		}
		if (this.screenWidth >= 1600) {
			this.bgWidth = "1700";
		}
		if (this.screenWidth >= 1700) {
			this.bgWidth = "1800";
		}
		if (this.screenWidth >= 1800) {
			this.bgWidth = "1900";
		}
		if (this.screenWidth >= 1900) {
			this.bgWidth = "2000";
		}
		
		var bgId = this.mainNavigationItems[id];
		if (!bgId) {
			bgId = Math.ceil(Math.random() * 5);
			bgId = '0'+bgId;
		}

		// var bgId = id;
		// if (parseInt(id) >= 10) {
		// 	bgId = Math.ceil(Math.random() * 5);
		// 	bgId = '0'+bgId;
		// }

		jQuery("#oldBackgroundContainer").css('background-image', jQuery("#backgroundContainer").css('backgroundImage'));
		jQuery("#backgroundContainer").hide();

		this.backgroundImage = new Image();
		this.backgroundImage.src = "images/" + bgId + "/bg" + this.bgWidth + ".jpg";
		new PeriodicalExecuter(function (peObj) {
			if (this.backgroundImage.complete) { 
				
				// Avoid flickering by making sure the background container is hidden.
				jQuery("#backgroundContainer").hide();

				peObj.stop();
				this.backgroundContainer.setStyle({backgroundImage: "url(" + this.backgroundImage.src + ")"});
				//$("Loader").hide();
				
				// Fade in the new background image.
				if (initialLoad && jQuery.browser.msie && parseInt(jQuery.browser.version)==6) {
					jQuery('#backgroundContainer').show();
				}
				else {
					jQuery("#backgroundContainer").fadeIn(1000,'swing');
				}

			} else {
				//$("Loader").show();
			}
		}.bind(this), 0.5);				
	},
	OnLinkOver : function(evObj) {
		Event.element(evObj).src = Event.element(evObj).src.replace("_p", "_o");
	},
	OnLinkOut : function(evObj) {
		Event.element(evObj).src = Event.element(evObj).src.replace("_o", "_p");
	},
	OnWindowResize : function(evObj) {
		this.viewportProperties.Calculate();
		if (this.screenWidth != this.viewportProperties.WindowWidth)
			this.ChangeBackground(this.id);
		}
	}
	
/**
 * ViewportProperties.  
 */
 
var ViewportProperties = Class.create();
ViewportProperties.prototype = {
	initialize : function() {
		this.WindowWidth = 0;
		this.WindowHeight = 0;
		this.ScrollLeft = 0;
		this.ScrollTop = 0;
		this.DocWidth = 0;
		this.DocHeight = 0;
		this.Calculate();
	},
	Calculate : function() {
		if (window.innerWidth) {
			this.WindowWidth = window.innerWidth;
			this.WindowHeight = window.innerHeight;
		} else if (document.documentElement && document.documentElement.clientWidth) {
			this.WindowWidth = document.documentElement.clientWidth;
			this.WindowHeight = document.documentElement.clientHeight;
		} else if (document.body) {
			this.WindowWidth = document.body.clientWidth;
			this.WindowHeight = document.body.clientHeight;
		}
		if (window.pageYOffset) {
			this.ScrollLeft = window.pageXOffset;
			this.ScrollTop = window.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			this.ScrollLeft = document.documentElement.scrollLeft;
			this.ScrollTop = document.documentElement.scrollTop;
		} else if (document.body) {
		  this.ScrollLeft = document.body.scrollLeft;
		  this.ScrollTop = document.body.scrollTop;
		}
		if (document.body.scrollHeight > document.body.offsetHeight) {
			this.DocWidth = document.body.scrollWidth;
			this.DocHeight = document.body.scrollHeight;
		} else {
			this.DocWidth = document.body.offsetWidth;
			this.DocHeight = document.body.offsetHeight;
		}
	}
};






SR.PageContent = {	
	
	
	/**
	 * Cache as much as possible... 
	 */
	
	cache: {},	// html content
	news: [],	// news items
	
	
	/**
	 * Get the content of a page.
	 * This method is asynchronous (AJAX).
	 */
	
	get: function(name, onSuccessCallback) {
		if (!this.cache[name]) {
			var path = 'content/'+name+'/index.html';
			
			var that = this;
			jQuery.get(path, function(html) {
				that.cache[name] = html;
				onSuccessCallback(html);
			});			
		}
		else {
			onSuccessCallback(this.cache[name]);
		}
		
	},
	

	/**
	 * Get all news Items as JSON.
	 * This method is asynchronous (AJAX).
	 */
	
	getNews: function(callback) {
		
		if (this.news.length == 0) {		
			jQuery.getJSON('http://sascharuefer.a.customer.sylon.net/blog/?feed=json&callback=?', function(json) {
				SR.PageContent.news = json.items;
				
				callback(SR.PageContent.news);
			});
		}
		else {
			callback(this.news);
		}
	},
	

	loadId: function(id, displayObject, initialLoad) {
		
		var resultText = "";
		var animationHeight = 0;

		jQuery('#contentFadingBackgroundContainer').css({
			backgroundImage: jQuery('#backgroundContainer').css('background-image'),
			display: 'none'
		});
		
				
		jQuery('#contentFadingBackgroundContainer').fadeIn((initialLoad ? 0 : SR.conf.fadeTime), function() {
		
		//jQuery("#textContainer").fadeTo( (initialLoad ? 0 : SR.conf.fadeTime), 0.01, function() {
			
			

			if (id != displayObject.id) {
				// Check if id is still the active id.
				// (The user could have clicked another navigation element during the fade out...)
				return;
			}


			SR.PageContent.get(id, function(html) {
				
				if (id == 'news') {
					// We also need to load all the news items.
					
					SR.PageContent.getNews(function(newsItems) {
						
						var pageCount = Math.ceil(newsItems.length / 2);

						var style = '';
						for (var i = 0; i<newsItems.length; i++) {
							var item = newsItems[i];

							if (i >= 2) {
								style = 'style="display: none;"';
							}

							html += "<div " + style + " class=\"newsItem\">";
							html += "<h2>"+ item.title + "</h2>";
							html += "<p><span class=\"pubDate\">" + item.pubDate + "</span> - " + item.description + "<a class=\"more\" href=\"#\" rel=\""+i+"\">mehr&hellip;</a></p>";
							html += "</div>";


						}
						
						html = '<div id="newsFeed">' + html + '<\/div><div id="newsFeedItem"><\/div>';
						
						// Set the content html and change the background
						// after the content has finished fading/sliding in.
						SR.PageContent.setHtmlContent(html, function() {
							displayObject.ChangeBackground(id, initialLoad);

							new SR.PageContent.News(newsItems);

						});


						


					});
				}
				else {

					// Set the content html and change the background
					// after the content has finished fading/sliding in.
					SR.PageContent.setHtmlContent(html, function() {
						displayObject.ChangeBackground(id,initialLoad);
					});

					jQuery('#textContainer a').each(function() {
						
						var href = jQuery(this).attr('href').split('#');
						if (href.length < 2) return;						
						var page = href[1];
						
						jQuery(this).attr('rel',page).get(0).onclick = function(e) {
							
							// var elem = jQuery('#ReferenceNavigation img[alt='+page+']');
							// if (elem.length == 0) return;
							SR.navigationExtender.doClick(this);
							return false;
						}
					});

				}
				
			});
			
		});
	},
	
	
	hideBottomContainer: function() {

		if (jQuery("#contentBottom").hasClass("visible")) {
			
			jQuery("#contentBottom").stop().animate({height: 0}, {duration: 300, easing: 'easeInExpo'});	
			jQuery("#footer").stop().animate({bottom: 0}, {duration: 300, easing: 'easeInExpo'});	
			
			setTimeout(function() {
				jQuery("#contentBottom").attr("class","");
			},500)
		}
		
	},
	
	loadBottomId: function(id, displayObject) {


		var resultText = "";
		var animationHeight = '100px';
		
		var container = jQuery("#contentBottom");

		if (container.hasClass(id)) {
			// Avoid reloading the same content.
			return;
		}
		
		// Stop all animations on #contentBottom
		container.stop();
		
		
		if (!container.hasClass("visible")) {
			// The bottom container is already expanded.
			// Just update the content.
			
			container.attr("class","visible " + id);
			
			SR.PageContent.get(id, function(html) {
								
				container.find(".container").html(html);		
				
				container.animate({height: animationHeight}, 300);
				
				jQuery('#footer').animate({bottom: animationHeight}, 300);

				jQuery('#contentBottom a').each(function() {

					var href = jQuery(this).attr('href').split('#');
					if (href.length < 2) return;						
					var page = href[1];

					jQuery(this).attr('rel',page).get(0).onclick = function(e) {
						// var elem = jQuery('#ReferenceNavigation img[alt='+page+']');
						// if (elem.length == 0) return;
						SR.navigationExtender.doClick(this);
						return false;
					}
				});
				
				if (id == 'kontakt') {
					SR.Kontakt();
				}
				
			});
			
		}
		else {
			
			container = container.find(".container");

			container.fadeTo(200, 0.1, function() {

				container.parent().attr("class", "visible " + id);

			
				SR.PageContent.get(id, function(html) {
					
					container.html(html).fadeTo(500,1);

					jQuery('#contentBottom a').each(function() {

						var href = jQuery(this).attr('href').split('#');
						if (href.length < 2) return;						
						var page = href[1];

						jQuery(this).attr('rel',page).get(0).onclick = function(e) {
							// var elem = jQuery('#ReferenceNavigation img[alt='+page+']');
							// if (elem.length == 0) return;
							SR.navigationExtender.doClick(this);
							return false;
						}
					});
					
					if (id == 'kontakt') {
						SR.Kontakt();
					}
					
				});
				
			});
			
		}
		
	},
		
	setHtmlContent: function(html, callback) {

		var containerId = "textContentHolder";

		// Remember the current height.
		var h = jQuery('#textContainer').height() + 'px';


		// Now set the height to 'auto' and insert the new text.
		// With 'auto', we're able to measure the height of the new content.
		jQuery('#textContainer').css('height','auto');
		$(containerId).innerHTML = html;

		animationHeight = jQuery("#textContainer").height() + 'px';
	
		// Because we want to animate the change in height, we 
		// restore the height and animate to the new value.
		jQuery('#textContainer').css('height', h);
		
		jQuery("#textContainer").animate( { height:animationHeight }, { queue:false, duration:500 , easing: 'easeOutExpo' } );

		// jQuery("#textContainer").slideDown('slow', function() {
		// 	jQuery("#textContainer").fadeTo('slow',1, function() {
		// 		jQuery('#textContainer').css('opacity','');
		// 	});
		// 	// jQuery("#textContainer").fadeIn();
		// 
		// 	callback();
		// 
		// });
		// jQuery("#textContainer").slideDown('slow', function() {
			jQuery("#contentFadingBackgroundContainer").fadeOut('slow', function() {
				jQuery('#textContainer').css('opacity','');
			});
			// jQuery("#textContainer").fadeIn();

			callback();

		// });
	
		jQuery("#textContainer img").ifixpng();
		
	}
	
};

SR.PageContent.News = Class.create();
SR.PageContent.News.prototype = {
	
	currentIndex: 0,
	pageCount: 0,
	
	items: [],

	
	initialize: function(items) {



		/**
		 * News item overlay.
		 */
		
		var that = this;
		jQuery('#newsFeed .newsItem .more').click(function(e) {
			
			// The index of this item is stored in the href attribute.
			var idx = parseInt(jQuery(this).attr('rel'));
			var item = that.items[idx];


			// Create the HTML for the item.
			jQuery('#newsFeedItem').hide().html("<h1>" + item.title + "</h1><p><span class=\"pubDate\">" + item.pubDate + "</span> <br />" + item.content + "</p><div class=\"newsNavigationBack\"><a href=\"#\" class=\"back\">Zur&uuml;ck</a><br /><br /><br /></div>")

			
			jQuery('#contentFadingBackgroundContainer').css({
				display: 'none',
				backgroundImage: jQuery('#backgroundContainer').css('background-image')
			});
			
			jQuery('#contentFadingBackgroundContainer').fadeIn(200, function() {
				jQuery('#newsFeed').hide();
				jQuery('#newsFeedItem').show();
				jQuery('#contentFadingBackgroundContainer').fadeOut();
			});
			
			// jQuery('#newsFeed').fadeOut(200, function() {
			// 	jQuery('#newsFeedItem').fadeIn();
			// });
			
			
			
			// Close the item view => back to news items list.
			jQuery('#newsFeedItem a.back').click(function() {

				jQuery('#contentFadingBackgroundContainer').css({
					display: 'none',
					backgroundImage: jQuery('#backgroundContainer').css('background-image')
				});

				jQuery('#contentFadingBackgroundContainer').fadeIn(200, function() {
					jQuery('#newsFeedItem').hide();
					jQuery('#newsFeed').show();
					jQuery('#contentFadingBackgroundContainer').fadeOut();
				});
				
				
				// jQuery("#newsFeedItem").fadeOut(200, function() {
				// 	jQuery('#newsFeed').fadeIn();
				// });
				
				return false;
				
			});
			
			return false;
		});



		this.items = items;


		// Three preview items per page.
		this.pageCount	= Math.ceil(jQuery('.newsItem').length / 3.0);
		
		
		// List Navigation.
		jQuery('#newsFeed').append("\
				<div class=\"newsNavigation\">\
					<a class=\"next\" href=\"#\">&auml;ltere News</a>\
					<a class=\"prev\" href=\"#\">neuere News</a>\
					<br />\
					<a class=\"rss\" href=\"http://sascharuefer.a.customer.sylon.net/blog/?feed=rss2\">RSS Feed abonnieren</a>\
				</div>\
			");
		var that = this;
		jQuery('#textContentHolder .newsNavigation .prev').click(function() { that.prev(); return false; });
		jQuery('#textContentHolder .newsNavigation .next').click(function() { that.next(); return false; });
		
		this.updateNavigation();
	},
	
	/**
	 * Previous 3 items.
     */

	prev: function() {
		var idx = this.currentIndex * 3;
		
		
		jQuery(".newsItem").filter(":eq("+idx+"), :eq("+(idx+1)+"), :eq("+(idx+2)+")").fadeOut(0, function() {
			if (idx < 0) return;
			idx -= 3;
			jQuery(".newsItem").filter(":eq("+idx+"), :eq("+(idx+1)+"), :eq("+(idx+2)+")").fadeIn(0);
			idx = -1;
		});
		this.currentIndex--;
		this.updateNavigation();
	},
	
	
	/**
	 * Next 3 items.
	 */ 
	
	next: function() {
		var idx = this.currentIndex * 3;
		jQuery(".newsItem").filter(":eq("+idx+"), :eq("+(idx+1)+"), :eq("+(idx+2)+")").fadeOut(0, function() {
			if (idx < 0) return;
			idx += 3;
			jQuery(".newsItem").filter(":eq("+idx+"), :eq("+(idx+1)+"), :eq("+(idx+2)+")").fadeIn(0);
			idx = -1
		});
		this.currentIndex++;
		this.updateNavigation();
	},
	
	updateNavigation: function() {
		jQuery('#textContentHolder .newsNavigation .prev').css('visibility' , (this.currentIndex > 0 ? 'visible' : 'hidden'));
		jQuery('#textContentHolder .newsNavigation .next').css('visibility' , (this.currentIndex < this.pageCount-1 ? 'visible' : 'hidden'));
	}
		
	
};


SR.Kontakt = function() {
		
	jQuery('.contact-form a').click(function() {
		
		var email 		= jQuery('.contact-form [name=email]').val();
		var firma 		= jQuery('.contact-form [name=firma]').val();
		var telefon		= jQuery('.contact-form [name=telefon]').val();
		var name 		= jQuery('.contact-form [name=name]').val();
		var mitteilung	= jQuery('.contact-form [name=mitteilung]').val();
		
		var valid 		= true;
		
		
		if (jQuery.trim(email) != '' && /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
			jQuery('.contact-form [name=email]').removeClass('error');
		}
		else {
			valid = false;
			jQuery('.contact-form [name=email]').addClass('error');
		}
		
		if (jQuery.trim(name) != '') {
			jQuery('.contact-form [name=name]').removeClass('error');
		}
		else {
			valid = false;
			jQuery('.contact-form [name=name]').addClass('error');
		}
		
		if (jQuery.trim(telefon) != '') {
			jQuery('.contact-form [name=telefon]').removeClass('error');
		}
		else {
			valid = false;
			jQuery('.contact-form [name=telefon]').addClass('error');
		}
		
		if (jQuery.trim(mitteilung) != '') {
			jQuery('.contact-form [name=mitteilung]').removeClass('error');
		}
		else {
			valid = false;
			jQuery('.contact-form [name=mitteilung]').addClass('error');
		}
		
		if (!valid) return;
		
		jQuery(this.remove());
		
		jQuery.post('content/kontakt/index.php', {
			email: 		email,
			firma: 		firma,
			telefon: 	telefon,
			name:  		name,
			mitteilung: mitteilung
		},
		function(r) {
			jQuery('#contentBottom .container').html(r);
		});
	});
}