// GLOBALS
var DEBUG = 0;
var winWidth = 0; 
var winHeight  = 0;


var imgNr = 1
var globalDynamicID=1
var globalZIndex=1 


function updateGlobals(){
	winWidth = $(window).width(); 
	winHeight  = $(window).height(); 
	$(".draggable").draggable();
	$(".draggable").hover(bringDraggableToTop);
}

$(function () {
	if (DEBUG){ 
		showContent();
	} else {
		setTimeout('showSplash()', 1000);
	}
	setInterval('toggleDots()', 20000);
	initTimeInfoLayer();
	
	// loadImage( imgNr );
	if(!$.browser.msie){ initGalleryTools(); }
}); 
 
function initGalleryTools(){
	$("#gallerySize").slider({
		orientation: "vertical",
		range: "min",
		min: 100,
		max: 500,
		value: 300,
		step: 10,
		slide: function(event, ui) {
			$("#amount").show();
			$("#amount").val(ui.value);
		},
		stop: function(event, ui) { 
			$("#amount").hide();
		}
	});
	$("#amount").val($("#gallerySize").slider("value"));
	
	
	$('#closeAllImages').click(function(){  
		$('#gallery canvas').hide('scale', 1000, function(){ $(this).remove() })
	})
	$('#likeImage').click(function(){ loadImage( imgNr ); })
	$('#nextImage').click(function(){ loadImage( ++imgNr % 8 ); })
}
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----


function loadImage( imgNr ){
	drawImageInBubble( 'gallery/'+imgNr+'.jpg' ); 
}
function toFront(element){
	globalZIndex++
	element.css("z-Index", 1000 + globalZIndex);
}
function showBubbleImage(element){ 
	element.show('scale', Math.random() * 500 + 500, function(){
		element.draggable({  
			cursor: 'move', 
			start: function(event, ui) {
				toFront( $(this) );
			}
		})	 
		element.click(function(){
			$(this).hide('scale', Math.random() * 500 + 500, function(){ $(this).remove() });
		})
	})
} 

function drawImageInBubble(imageSrc){
	var w = $("#gallerySize").slider('value');
	var h = w

	var id = "dynamicElement" + (globalDynamicID++); 
	
	$('#gallery').append("<canvas id='"+id+"' style='position: absolute; display: none'></canvas>"); 
	var element = $('#'+id)	
	element.css('left', Math.random() * ($(document).width() - w - 200) + 100 )
	element.css('top', Math.random() * ($(document).height() - h - 200) + 100 )
	element.css('width', w+20 )
	element.css('height', h+20 )
	  
	var canvas = document.getElementById(id);  
	canvas.setAttribute('width', w+20);  
	canvas.setAttribute('height', h+20); 
	
	var img = new Image();  

	img.onload = function(){ 
		var ctx = canvas.getContext('2d');
		ctx.translate(10, 10);
		
		var canvasHalfWidth = w/2;
		var canvasHalfHeight = h/2;
		
		var border = w < 300 ? 10 : 20;
		
		ctx.fillStyle = "#FF7800";
		ctx.beginPath();
		ctx.arc(canvasHalfWidth, canvasHalfHeight, canvasHalfWidth, canvasHalfHeight, Math.PI*2, true); 
		ctx.closePath(); 
		ctx.shadowOffsetX = 0;
		ctx.shadowOffsetY = 0;
		ctx.shadowBlur    = 20;
		ctx.shadowColor   = 'rgba(0, 0, 0, 0.5)';  
		ctx.fill();  

		ctx.shadowBlur    = 0; 
		ctx.beginPath();  
		ctx.arc(canvasHalfWidth, canvasHalfHeight, canvasHalfWidth - border, canvasHalfHeight - border, Math.PI*2, true); 
		ctx.clip();
		
		ctx.translate(canvasHalfWidth, canvasHalfHeight);
        ctx.rotate( ( ( Math.random() * 40 ) - border ) * Math.PI / 180);
		ctx.translate(-canvasHalfWidth, -canvasHalfHeight);
		
		var scaleX = w / img.width;
		var scaleY = h / img.height;
		
		var scale  = scaleX < scaleY ? scaleX : scaleY 
		ctx.drawImage(img,  
			canvasHalfWidth - (img.width * scale / 2), 
			canvasHalfHeight - (img.height * scale / 2), 
			img.width * scale, 
			img.height * scale
		); 
	}  
	img.src = imageSrc;   
	element.data("originalImage", img); 
	
	toFront(element)
	showBubbleImage(element);
}


// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

function loadContactForm(){
	$("#contact .content").load("contact.jsp");
}

function showInformations(){
	function add(){ time+=1000; }
	var time = DEBUG ? 0 : 1000;
	add(); $("#gallery_small").saveFadeIn(time);
	add(); $("#contact_small").saveFadeIn(time);
	add(); $("#impressum_small").saveFadeIn(time);
	if(!$.browser.msie){ 
		add(); $("#gallery").saveFadeIn(time);
	}
}

function showContent(){
	updateGlobals();
	if (DEBUG < 2){
		splashDots();
		
		$("#logo").animate({ left: "-87px", top: "-211px" }, 700) 
		$('#splash').remove();

		setTimeout("showInformations()", 3000);
	}
	showContentButtons();
    loadContactForm();
    
    $('body').dblclick( addBookmark )
}
function addBookmark(){  
	$("#addBookmark").load("addBookmark.jsp");
}

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
function showContentButtons(){
	registerBubble("impressum", 87, 352, toggleImpressum);
	registerBubble("contact", 307, 172, toggleContact);
	registerBubble("gallery", 147, 32, toggleGallery);
}

function registerBubble(id, correctX, correctY, toggleFunction){
	$("#"+id+" .close").click( toggleFunction )
	$("#"+id+"_small").click( toggleFunction )
	$("#"+id+"").css({top: winHeight/2 - correctX, left: winWidth/2 - correctY});  
	$("#"+id+"_small").hover(
			function(){ $("#"+id+"_small img").saveFadeIn();  },
			function(){ $("#"+id+"_small img").saveFadeOut(); }
	)
	$("#"+id+" .close").hover(
		function (){ $(this).moveBy(0,2,100);	},
		function (){ $(this).moveBack(100); }
	);
}

function blurAllFormFields(){
	$("input").blur();
	$("textarea").blur();
	$("select").blur();
} 
function toggleContact(){ 	toggleBubbles($("#contact_small"), 		$("#contact"));		blurAllFormFields();	$("#contactSender").focus();} 
function toggleGallery(){   	toggleBubbles($("#gallery_small"), 		$("#gallery"));     	}
function toggleImpressum(){ toggleBubbles($("#impressum_small"), 	$("#impressum")); 	}

function toggleBubbles(small, big){
	if (small.data("disabled")){
		small.enableButton(500);
		big.saveFadeOut(500);
		small.removeData("disabled");
	} else {
		small.disableButton(500);
		bringToTop(big, ".bubble");
		big.saveFadeIn(500); 
		small.data("disabled", true);
	}
} 

function bringDraggableToTop(){
	bringToTop($(this), ".draggable");
}
function bringToTop(element, selector){
	var max = 0;
	$(".draggable").each( function(){ max = MathMax(max, $(this).css("z-index")) } );
	element.css("z-index", ++max);
} 

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
function splashDots(){
	//createDot("#dot1", "454px", "400px", "40");
	createDot("#dot1", "554px", "64px", "40");
	createDot("#dot1", "370px", "313px", "40");
	createDot("#dot1", "395px", "180px", "40");
	createDot("#dot1", "49px", "537px", "40");
	createDot("#dot1", "228px", "227px", "40");
	createDot("#dot1", "231px", "466px", "40");
	createDot("#dot1", "197px", "445px", "40");
	createDot("#dot2", "201px", "367px", "90");
	createDot("#dot2", "418px", "69px", "90");
	createDot("#dot2", "372px", "235px", "90");
	createDot("#dot2", "31px", "409px", "90");
	createDot("#dot2", "272px", "132px", "90");
	createDot("#dot2", "-97px", "389px", "90");
	createDot("#dot3", "-101px", "372px", "140");
	createDot("#dot3", "250px", "197px", "140");
	createDot("#dot3", "354px", "-86px", "140");
	createDot("#dot3", "275px", "-13px", "140");
	createDot("#dot4", "35px", "202px", "240");
	createDot("#dot5", "-41px", "-65px", "340");
	createDot("#dot5", "-124px", "75px", "340");

	moveDotsToTarget();
	$("#logo").click(function(){ 
		toggleDots(); 
	})
}

var dynID=1
var arrayDynDots=new Array()
function createDot(draft, top, left, diameter){
	var o = $(draft).clone();
	o.hide();
	o.insertAfter("#logo");
	o.attr("id","dyn" + (dynID++));
	o.css("position","absolute");
	o.targetPointTop  = top;
	o.targetPointLeft = left;
	o.originPointTop  = 170/2-diameter/2;
	o.originPointLeft = 340/2-diameter/2;
	o.css("top", o.originPointTop);
	o.css("left", o.originPointLeft);
	o.saveFadeIn(2000);
	arrayDynDots[ arrayDynDots.length ] = o;
}

function moveDotsToTarget(){
	for(var i=0; i < arrayDynDots.length; i++){
		var o = arrayDynDots[i]
		o.animate({ top: o.targetPointTop, left: o.targetPointLeft }, 700)
	}
}
var dotsMovementTime = true;
function moveDotsToOrigin(){
	for(var i=0; i < arrayDynDots.length; i++){
		var o = arrayDynDots[i]
		var randomnumber=Math.floor(Math.random()*1000)+500
		if (dotsMovementTime){
			dotsMovementTime = 700;
		}
		o.animate({ top: o.originPointTop, left: o.originPointLeft }, randomnumber)
	}
	dotsMovementTime = !dotsMovementTime
}
var dotsHeadingToTarget = false
function toggleDots(){
	if (dotsHeadingToTarget)
		moveDotsToTarget();
	else
		moveDotsToOrigin();
	dotsHeadingToTarget = !dotsHeadingToTarget;
}

//---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
var serverTimeDifference = 0;
function initTimeInfoLayer(){
	$("#siteInfo").hover(
			function(){ 
				$(this).children(".hoverInfo").show(); 
				$(this).children(".hoverHidden").hide(); 
			},
			function(){ 
				$(this).children(".hoverInfo").hide(); 
				$(this).children(".hoverHidden").show(); 
			}
	)  
}
function setCurrentTime( serverTime ){
	serverTimeDifference = new Date().getTime() - serverTime;
	setInterval("updateCurrentTime()", 900);
}
function prettyTime(value){
	return (value<=9?"0":"") + value;
}
function updateCurrentTime(){
	var currentTime = new Date()
	currentTime.setTime( currentTime.getTime() + serverTimeDifference )
	$('.currentDate').html( 
		prettyTime(currentTime.getDate()) 
		+ "." + prettyTime(currentTime.getMonth()+1) 
		+ "." + (""+currentTime.getFullYear()).substring(2,4) 
	);
	$('.currentTime').html( 
		prettyTime(currentTime.getHours())
		+ ":" + prettyTime(currentTime.getMinutes())
		+ ":" + prettyTime(currentTime.getSeconds())
	);
	var diff = Math.round(serverTimeDifference/1000);
	if (diff == 0){
		$('#timeDifference').html("Deine Uhr geht genau. ");
	} else if (diff = 1){
		$('#timeDifference').html("Deine Uhr geht nur um eine Sekunde "+((diff>0)?"vor":"nach")+". ");
	} else if (diff < 1){
		$('#timeDifference').html("Deine Uhr geht nur um "+diff+" Sekunden "+((diff>0)?"vor":"nach")+". ");
	} else {
		$('#timeDifference').html("Deine Uhr geht um "+diff+" Sekunden "+((diff>0)?"vor":"nach")+". ");
	} 
}

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
function showSplashText(){
	if (!$('#splash')) return;
	$('#splash span').saveFadeIn(1000);  
	setTimeout('hideSplashText()', 1000);
}
function hideSplashText(){
	if (!$('#splash')) return;
	$('#splash span').saveFadeOut(1000);  
	setTimeout('showSplashText()', 1000);
}
function showSplash(){
	$('#splash').saveFadeIn('slow');  
	$('#splash').click(function(){
		$(this).saveFadeOut('slow', showContent);
	}) 
	setTimeout('showSplashText()', 5000);
}

//---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
function MathMax(a,b){ return a>b?a:b; }

jQuery.fn.extend({  
	saveFadeIn: function(speed, callback){
		if($.browser.msie){
			this.show();
			if (callback) callback();
		} else {
			this.fadeIn(speed, callback);
		}
	},
	saveFadeOut: function(speed, callback){
		if($.browser.msie){
			this.hide();
			if (callback) callback();
		} else {
			this.fadeOut(speed, callback);
		}
	},
	moveBy: function(moveByX, moveByY, speed, callback){  
		var top=this.position().top;
		var left=this.position().left;
		this.data("orgLeft", left);
		this.data("orgTop", top);
		left += moveByX;
		top += moveByY;
		return this.animate({left: left+"px", top: top+"px"}, speed, callback); 
	},
	moveBack: function(speed, callback){    
		return this.animate({left: this.data("orgLeft")+"px", top: this.data("orgTop")+"px"}, speed, callback);
	},
	disableButton: function(speed, callback){    
		return this.animate({opacity: 0.3}, speed, callback);  
	},
	enableButton: function(speed, callback){  
		return this.animate({opacity: 1}, speed, callback);   
	}  
});
jQuery.fn.log = function (msg) {
	  console.log("%s: %o", msg, this);
	  return this;
};
