$(function() {
	var tide = getTide(50,65);
	var motion;
	var tideHeight;
	var wrapperHeight=$("#wrapper").height();
	$("#tide").css({top:tide+"px",height:wrapperHeight-340+"px"});
	$("#stuck").css({top:Math.ceil(tide-50)+"px",height:wrapperHeight-Math.ceil(tide-50)+"px"});
	
	function getTide(minVal,maxVal) {
		var randVal = minVal+(Math.random()*(maxVal-minVal));
		return Math.round(randVal)+"0";
	}

	function changeTide(tide){
		$("#stuck").animate({top:Math.ceil(tide-50)+"px",height:wrapperHeight-Math.ceil(tide-50)+"px"},2000,"jswing");
		$("#tide").animate({top:Math.ceil(tide-10)+"px"},2500,"jswing").animate({top:tide+"px"},2500,"jswing");
		motion = setInterval(function() {
			$("#tide").animate({top:Math.ceil(tide-10)+"px"},2500,"jswing").animate({top:tide+"px"},2500,"jswing");
		},1000);
		height = setInterval(function(){
			$("#tide").stop(true,false);
			clearInterval(motion);
			tide = newTide();
			$("#tide").animate({top:Math.ceil(tide-10)+"px"},2500,"jswing").animate({top:tide+"px"},2500,"jswing");
			$("#stuck").animate({top:Math.ceil(tide-50)+"px",height:wrapperHeight-Math.ceil(tide-50)+"px"},2000,"jswing");
			motion = setInterval(function() {
				$("#tide").animate({top:Math.ceil(tide-10)+"px"},2500,"jswing").animate({top:tide+"px"},2500,"jswing");
			},1000);
		},10000);
	}
	
	if ($.cookie("disableTide")!=1) {
		changeTide(tide);
	} else {
		$("#disable_tide").text("Start tide").attr("id","enable_tide");
	}
	
	function newTide(){
		if (tideHeight=="high") {
			tide = getTide(50,65);
			tideHeight="low";
		} else {
			tide = getTide(34,50);
			tideHeight="high";
		}
		return tide;
	}
	
	function disableTide(tide) {
		$("#tide").css({top:tide+"px",height:wrapperHeight-tide+"px"},2500,"jswing");
		$("#stuck").css({top:Math.ceil(tide-50)+"px",height:wrapperHeight-Math.ceil(tide-50)+"px"},2000,"jswing");
	}
	$("#disable_tide").live("click",function(){
		$.cookie("disableTide",1,{path:"/"});
		$(this).text("Start tide").attr("id","enable_tide");
		$("#tide").stop(true,false);
		clearInterval(motion);
		$("#stuck").stop(true,false);
		clearInterval(height);
	});
	$("#enable_tide").live("click",function(){
		$.cookie("disableTide",null,{path:"/"});
		$(this).text("Stop tide").attr("id","disable_tide");
		changeTide(tide);
	});
});
