/**
 * @author Manfred.Egger
 */

var lastOffset = 0;
var old = '';
var veryold = '';
var veryoldTime = '';
var tooltipVisible = false;

function resetOld() { old=''; } 

function animateHeadFoot(){
	marginleft = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
	lastOffset = marginleft;
	$("#header").stopTime();
	$("#footer").stopTime();
	$("#header").oneTime("100ms", function(){
		$(this).animate({marginLeft: marginleft}, { duration: 800, easing: "easeInOutQuint"});
	});
	$("#footer").oneTime("800ms", function(){
		$(this).animate({marginLeft: marginleft}, { duration: 1600, easing: "easeInOutQuint"} );
	});
}

function myScrollTo(id) {
	$("body").stopTime();
	old = '';
	$.scrollTo(id,1000);
	$("body").everyTime("500ms",  function(){
		marginleft = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
		if( lastOffset != marginleft ) {
			animateHeadFoot();
			lastOffset = marginleft;
		}
	});
}

jQuery( function($) {
	var $hinweis = $('<div id="hinweis" style="cursor: pointer; background: url(fileadmin/images/back_hinweis.png) no-repeat left top; z-index: 2; width:388px;height:190px;position:absolute;left: -388px;top:113px;"></div>');
	$hinweis.prependTo($('#outermargin'));
	$hinweis.oneTime("400ms", function(){
		$hinweis.animate({
			left: -315
		},'slow', function(){
			$hinweis.animate({
				left: -332
			},'slow');
		})
	});
	$hinweis.click(function(){
		if(!$hinweis.hasClass('clicked')) {
			$hinweis.stop(true,true).animate({
				left: -44
			}).addClass('clicked');
		} else {
			$hinweis.stop(true,true).animate({
				left: -332
			}).removeClass('clicked');
		}
	});
	var version = deconcept.SWFObjectUtil.getPlayerVersion();
	$("#tooltip").hide().oneTime("4000ms", function(){	
		tooltipVisible = true;
		
	});
	$("body").css("overflow","hidden");
	if(!jQuery.support.style) {
		$("html").css("overflow","hidden");
	}
	
	function viewportWidth() {
		return self.innerWidth || jQuery.boxModel
				&& document.documentElement.clientWidth
				|| document.body.clientWidth;
	}

	function urlencode( str ) {
	    var histogram = {}, tmp_arr = [];
	    var ret = str.toString();
	    
	    var replacer = function(search, replace, str) {
	        var tmp_arr = [];
	        tmp_arr = str.split(search);
	        return tmp_arr.join(replace);
	    };
	    
	    // The histogram is identical to the one in urldecode.
	    histogram["'"]   = '%27';
	    histogram['(']   = '%28';
	    histogram[')']   = '%29';
	    histogram['*']   = '%2A';
	    histogram['~']   = '%7E';
	    histogram['!']   = '%21';
	    histogram['%20'] = '+';
	    
	    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
	    ret = encodeURIComponent(ret);
	    
	    for (search in histogram) {
	        replace = histogram[search];
	        ret = replacer(search, replace, ret) // Custom replace. No regexing
	    }
	    
	    // Uppercase for full PHP compatibility
	    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
	        return "%"+m2.toUpperCase();
	    });
	    
	    return ret;
	}
	
	String.prototype.startsWith = function(str){var toMatch = "^"+str.replace(/\?/g,'\\?'); return (this.match(toMatch)==str)}
	String.prototype.endsWith = function(str){var toMatch = str.replace(/\?/g,'\\?')+"$"; return (this.match(toMatch)==str)}

	$.localScroll.defaults.axis = 'x';
	$.scrollTo.defaults.axis = 'x'; 	
	$.localScroll.hash({
		queue:true,
		duration:1500
	});
	
	$("body").mousemove(function(e) {
		if(tooltipVisible && (window.innerWidth+lastOffset <= 1600 || lastOffset==0 )) {
			$("#tooltip").css("left",e.clientX+lastOffset-69).css("top",e.clientY-100).fadeIn(1500);
		}
	});
	$("#tooltip").mousemove(function(e) {
		if(tooltipVisible && (window.innerWidth+lastOffset <= 1600 || lastOffset==0 )) {
			$("#tooltip").css("left",e.clientX+lastOffset-69).css("top",e.clientY-100).fadeIn(1500);
		}
	});
	
	var maxWidth = Math.max(1600,$('#scriptreplace a').size()*1600);
	$("#innermargin").width(maxWidth).mousedown( function(e) {
		$(this).stopTime();
		$("body").stopTime();
		$("#header").stopTime();
		$("#footer").stopTime();
		$("#tooltip").stopTime().fadeOut(500);
		tooltipVisible = false;
		old = e.clientX;
		veryold = old;
		return false;
	}).mousemove(
			function(e) {
				if (old) {
					var newX = old - e.clientX;
					if(newX > 0) $.scrollTo( "+="+newX );
					else if(newX < 0) $.scrollTo( "-="+(-1*newX) );
					old = e.clientX;
				}
			}).bind("selectstart", function(e) { return false; });
	
	$("html").mouseup( function(e) {
		old = '';
		$(this).oneTime("1500ms",  function(){
			marginleft = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
			if( lastOffset != marginleft ) {
				animateHeadFoot();
				lastOffset = marginleft;
			}
			veryoldTime = new Date();
			$("#tooltip").oneTime("4000ms", function(){
				tooltipVisible = true;
			});
		});
	})
	/*.everyTime("2000ms",  function(){
			marginleft = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
			if( lastOffset != marginleft ) {
				animateHeadFoot();
				lastOffset = marginleft;
			}
		});*/
	
	var links = new Object();
	var checkCount = 0;
	var linkCount = $('#scriptreplace a').size();
	var tagcloudText = '';
	var tagcloudIndex = 0;
	
	$('#scriptreplace').show();
	$('#scriptreplace a').each(function(i){
		$(this).after('<div class="section" id="section' + i + '" name="section' + i + '"><img src="fileadmin/images/preloader.gif" style="margin: 100px 300px;"/><\/div>');
		// Request the remote document
		$.ajax({
			url: this.href,
			type: "GET",
			dataType: "html",
			cache: false,
			complete: function(res, status){
				// If successful, inject the HTML into all the matched elements
				if ( status == "success" || status == "notmodified" ) {
					// See if a selector was specified
					var tempText = jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g, "")).find('.section');
					if(tempText.find('.tx-t3mcumulustagcloud-pi1').size()>0) {
						tagcloudText = tempText.html();
						tagcloudIndex = i;
					} else {
						var text = tempText.html();
						$('#section' + i).html(text);
					}
				} else {
					$('#section' + i).html("");
				}
				if( version["major"] > 8 ) {
					$('#section' + i).find("#tags").hide();
					$("#wpcumuluswidgetcontent").css("margin-top","-20px");
				}
				linkCount--;
			}
		});
		links[this.href.replace(/&no(script|_cache)(=\d)?/g,"")] = '#section' + i;
		$(this).remove();
	});
	
	$('#scriptreplace').everyTime("100ms",  function(){
		if( linkCount == 0 ) {
			$(this).stopTime();
			$('#section' + tagcloudIndex).html(tagcloudText);
			if( version["major"] > 8 ) {
				$('#section' + tagcloudIndex).find("#tags").hide();
				$("#wpcumuluswidgetcontent").css("margin-top","-20px");
			}
			$('#scriptreplace a').each(function(i){
				var href = this.href.toString()+'@';
				if($(this).attr('href') != '#') {
					for (var link in links) {
						if(href.startsWith(link+'@')) {
							$(this).attr('href',links[link]);
							break;
						}
					}
				} else { if( version["major"] > 8 ) $(this).attr('href',''); }
			});
			
			var findlinks = "#tags"
			if(!jQuery.support.style) {
				findlinks = "#innermargin";
			}
			$(findlinks+" a[href^=#]").each(function(){
				if($(this).attr('href') != '#' && $(this).attr('href') != ''){
					this.href='javascript:myScrollTo(\''+$(this).attr('href')+'\');';
				} else {
					if(!$(this).parents("#tags")) {
						$(this).attr('href','javascript:myScrollTo(\''+$(this).attr('href')+'\');');
					} else { if( version["major"] > 8 ) $(this).attr('href',''); }
				}
			});
			
			if( version["major"] < 9 ) {
				$("#tags").html($("#tags").html().replace(/href="(#|)"/,''));
			}

			$("#tags a[href$=#]").attr('href','');
			
			$.getScript("typo3temp/tagcloud.js", function(){
				var html = '<div id="tags">'+$("#tags").html()+'</div>';
				html = html.replace(/\s(rel|title|class|id)=([^"'\s>]+)/g,' $1="$2"').replace(/FONT-SIZE/g,"font-size").replace(/<([^\s>]+)/g, function(s1){return s1.toLowerCase();});
				if(typeof(SWFObject) == 'function'){
					makeTagCloud(urlencode(html));
				} else { $("#tags").show(); }
			});
			
			var myLocation = window.location.toString()+'@';
			for (var link in links) {
				if(myLocation.startsWith(link+'@')) {
					myScrollTo(links[link]);
					break;
				}
			}
			
			$.localScroll({
				queue:true,
				duration:1000,
				hash:true,
				onAfter:function( anchor, settings ){
					animateHeadFoot();
				}
			});
			
			$("img").bind("dragstart", function(){return false;});
			$("body").oneTime("1000ms",  function(){
				marginleft = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
				if( lastOffset != marginleft ) {
					animateHeadFoot();
					lastOffset = marginleft;
				}
			});
		}
	});
	
	$('#header a').attr('href','#section0');	
	$('#footer a').each(function(i){
		var href = this.href.toString()+'@';
		if($(this).attr('href') != '#') {
			for (var link in links) {
				if(href.startsWith(link+'@')) {
					$(this).attr('href',links[link]);
					break;
				}
			}
		} else { if( version["major"] > 8 ) $(this).attr('href',''); }
	});
	
		
	$.localScroll({
		//target: '#content', // could be a selector or a jQuery object too.
		queue:true,
		duration:1000,
		hash:true,
		onAfter:function( anchor, settings ){
			animateHeadFoot();
		}
	});
});

