/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);

var confirmFallback = false;
var ajaxTimeout = 20;
var contentDiv = 'maincontent';
	var fallbackMsg = 'Dein Avatar muss von Vorne beginnen, wenn du diesen Link aufrufen willst. Willst du den Link aufrufen?';
	var ajaxRequestStarted = 0;
	
		$('body').prepend('<div id="ajaxloader"></div>');
		$('a').live('click', function(){
			if(! $('#' + contentDiv).length ) {	
				//alert(2);
				return true;
			}
			var href = $(this).attr('href');
			var rel = $(this).attr('rel');
                        var target = $(this).attr('target');
                        if (href.match(/^javascript/)) {
                            return true;
                        }

			if ('_blank' != target && !href.match(/^http/) && !href.match(/^javascript/) && !href.match(/^mailto/) && !href.match(/(jpg|jpeg|png|gif|pdf)$/) && !href.match(/^#/)) {
				window.location = '#' + href;
				return false;
			}
			else if (href.match(/^http/) && -1 != href.indexOf(window.location.host)) {
				var pos = href.indexOf(window.location.host) + window.location.host.length;
				window.location = '#' + href.substr(pos, href.length - pos);
				return false;
			}

                        if ('ssl' == rel && 'http:' == location.protocol) {
                          //  alert('ssl' + href);
                        }
                        else if ('ssl' != rel && 'https:' == location.protocol) {
                           // alert('no-ssl' + href);
                        }

		});
		$('#searchform,#searchformTop').live('submit', function(){
			window.location = '#/meta/suche/' + encodeURIComponent($('#searchword').val());
			//ajaxGoTo('/index.php?id=307&search=' + $('#searchword').val());
			return false;
		});
    
	
	
	$(window).load(function(){
		var hash = location.hash.replace(/#/, '');
		
		if ('' != hash) {
			if (window.location.toString().replace(/^(.+?)(#.+?)$/, '$1') != window.location.protocol + '//' + window.location.hostname  + hash) {
				ajaxGoTo(hash);
			}
		}
		else if ('' == hash && window.location.pathname != '/' && window.location.toString().match(/#$/)) {
			ajaxGoTo('/');
		}
		
		
		$(window).hashchange( function(){
			var hash = location.hash.replace(/#/, '');
			ajaxGoTo(hash);
		});
	});
	
	function ajaxGoTo(href) {
		var offset = $('#' + contentDiv).offset();
		var height = $('#' + contentDiv).height();
		var width = $('#' + contentDiv).width();
		var data = ''; 
		
		if ('' == href) {
			data = window.location.search.toString().replace(/^\?/, '');
			href = window.location.href.toString().replace(/^([^\?]+?)\?.+?$/g, '$1');
		}
		
		var start = new Date();
		ajaxRequestStarted = Math.round(start.getTime() / 1000);
		ajaxFallback();
		$('#ajaxloader').css({
			display: 'none',
			position: 'absolute',
			top: offset.top + 'px',
			left: offset.left + 'px',
			height: height + 'px',
			width: width + 'px',
			backgroundImage: 'url(/fileadmin/templates/img/ajax-loader.gif)',
			backgroundPosition: 'center',
			backgroundRepeat: 'no-repeat',
			zIndex: 100
		});
		$('#ajaxloader').fadeIn(500);
		
		if (-1 == navigator.userAgent.indexOf('MSIE')) {
			$('#' + contentDiv).fadeTo(500, .3);
		}
		
		$('.textTeaserPaperclip,.singlepicPaperclip').remove();
		$.ajax({
			url: href,
			data: data,
			dataType: 'json',
			success: function(data){
                            if (null == data) {
				var hash = location.hash.replace(/#/, '');
				window.location = hash;
                                return;
                            }
				//$('head').append('<link rel="stylesheet" type="text/css" href="/fileadmin/templates/youngPanda/css/style_default.css" />');
				if ('object' != typeof(data) || 'undefined' == typeof(data['html']) || ('undefined' != typeof(data['error']) && 1 == data['error'])) {
					if (!confirmFallback || confirm(fallbackMsg)) {
						var hash = location.hash.replace(/#/, '');
						window.location = hash;
						return;
					}
					
					return;
				}
				
				if (typeof(data['css']) == "object") {
					for (i in data['css']) {
						$('head').append('<link rel="stylesheet" type="text/css" href="' + data['css'][i] + '" />');
					}
				}
				
				ajaxRequestStarted = 0;
				$('#' + contentDiv).html(data['html']);
				if ('undefined' != typeof(data['subnavi']) && '' != data['subnavi']) {
					$('#sub_menu_wrap').html(data['subnavi']);
					$('#sub_menu_top,.teaser_spacer:first').show();
				}
				else {
					$('#sub_menu_top,.teaser_spacer:first').hide();
					$('#sub_menu_wrap').html('');
				}
				
                                if ('undefined' != typeof(data['webtrekk']) && '' != data['webtrekk'] && 'undefined' != typeof(wt_sendinfo)) {
                                    wt_sendinfo(data['webtrekk']);
                                }
				
				if ('undefined' != typeof(data['topics']) && '' != data['topics']) {
					$('#drop_down_wrap').html(data['topics']);
					$('#sub_menu_top .drop_down').show();
				}
				else {
					$('#drop_down_wrap').html('');
					$('#sub_menu_top .drop_down').hide();
				}
				
				if ('undefined' != typeof(data['sidebar']) && '' != data['sidebar']) {
					$('#col_2').html(data['sidebar']);
					$('#col_2').show();
				}
				else {
					$('#col_2').hide();
				}
				
				$('#ajaxloader').fadeOut(500);
				if (-1 == navigator.userAgent.indexOf('MSIE')) {
					$('#' + contentDiv).fadeTo(500, 1);
					if ('undefined' != typeof(data['title']) && '' != data['title']) {
						$('title').html(data['title']);
					}
				}
				
				var headerHeight = parseInt($('#head').css('height').replace(/\D/g, ''));
				if ('undefined' != typeof(data['headersize']) && '' != data['headersize'] && data['headersize'] > 0 && data['headersize'] != headerHeight) {
					//$('#head').css('height', data['headersize'] + 'px');
					$('#head').animate({ height: data['headersize'] + 'px'}, 500);
				}
				else if (headerHeight != 550) {
					//$('#head').css('height', '550px');
					$('#head').animate({ height: '550px'}, 500);
				}
				
				initPage();

                                var currentScrollPos = 0;
                                if ('undefined' == typeof(window.pageYOffset)) {
                                    currentScrollPos = document.documentElement.scrollTop;
                                }
                                else {
                                    currentScrollPos = window.pageYOffset;
                                }
                                // nur scrollen, wenn fenster nicht an oberster position sitzt
                                if (0 < currentScrollPos) {
                                    var contentOffset = $('#main').offset(); // position subnavileiste

                                    // scrollen, falls subnavileiste nicht im sichtbaren bereich
                                    if (contentOffset.top < currentScrollPos || contentOffset.top > currentScrollPos + $(window).height()) {
                                        var scrollTo = contentOffset.top - 50;
                                            scrollTo = scrollTo < 0 ? 0 : scrollTo;
                                        $('html,body').animate({scrollTop: scrollTo},500);
                                    }
                                }
				
				return false;
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if ('object' == typeof(console)) {
					console.log(textStatus);
					console.log(errorThrown);
				}
				var hash = location.hash.replace(/#/, '');
				window.location = hash;
			}
		});
	}
	
	function ajaxFallback() {
		if (ajaxRequestStarted > 0) {
			var now = new Date();
			if (Math.round(now.getTime() / 1000) - ajaxRequestStarted > ajaxTimeout && ajaxTimeout > 0) {
				if ('object' == typeof(console)) {
					console.log("Timeout: " + (Math.round(now.getTime() / 1000) - ajaxRequestStarted));
				}
				var hash = location.hash.replace(/#/, '');
				if (!confirmFallback || confirm(fallbackMsg)) {
					window.location = hash;
				}
				else {
					ajaxRequestStarted = 0;
				}
			}
			window.setTimeout("ajaxFallback()", 1000);
		}
	}
