var fadeSpeed = 500;
var jones = {
	
	canvas: null,
	ctx: null,
	timer: null,
	fps: 10,
	
	offsetx: 0,
	offsety: 0,
	
	steps: 0,
	speed: 2.1,
	fadein: 5,
	fadeout: 30,
	
	historylength: 5,
	
	pauseone: 0,
	pauseboth: 6,
	step: 0,
	
	state: 0,
	city1: 0,
	city2: 1,
	
	cities: [
		[598, 203],
		[1050, 256],
		[284, 265],
		[608, 293],
		[358, 508],
		[670, 170],
		[175, 342],
		[555, 202],
		[171, 194],
		[1084, 608]
	],
	
	visited : [],
	
	drawCross: function(x, y) {
		jones.ctx.fillStyle = 'rgb(75, 134, 193)';
		jones.ctx.strokeStyle = 'rgb(75, 134, 193)';
		
		jones.ctx.moveTo(x, y);
		jones.ctx.fillRect (x-1, y-4, 2, 8);
		jones.ctx.fillRect (x-4, y-1, 8, 2);
	},
	
	drawCrossAlpha: function(x, y, t) {
		jones.ctx.fillStyle = 'rgba(75, 134, 193, '+(1-t)+')';
		jones.ctx.strokeStyle = 'rgba(75, 134, 193, '+(1-t)+')';
		
		jones.ctx.moveTo(x, y);
		jones.ctx.fillRect (x-1, y-4, 2, 8);
		jones.ctx.fillRect (x-4, y-1, 8, 2);
	},
	
	drawSmallCross: function(x, y) {
		jones.ctx.fillStyle = "#ff0000";
		jones.ctx.strokeStyle = "#ff0000";
		
		jones.ctx.moveTo(x, y);
		jones.ctx.fillRect (x-1, y-4, 2, 8);
		jones.ctx.fillRect (x-4, y-1, 8, 2);
	},
	
	drawCurve: function(x0, y0, x1, y1, x2, y2, x3, y3, t, first) {
		if (first) {
			var p0x = x1 - x0; var p0y = y1 - y0;
			var p1x = x2 - x1; var p1y = y2 - y1;
			var p2x = x3 - x2; var p2y = y3 - y2;
			var u0x = x0 + t * p0x; var u0y = y0 + t * p0y;
			var u1x = x1 + t * p1x; var u1y = y1 + t * p1y;
			var u2x = x2 + t * p2x; var u2y = y2 + t * p2y;
			var q0x = u1x - u0x; var q0y = u1y - u0y;
			var q1x = u2x - u1x; var q1y = u2y - u1y;
			var v0x = u0x + t * q0x; var v0y = u0y + t * q0y;
			var v1x = u1x + t * q1x; var v1y = u1y + t * q1y;
			var r0x = v1x - v0x; var r0y = v1y - v0y;
			var w0x = v0x + t * r0x; var w0y = v0y + t * r0y;
			
			jones.ctx.strokeStyle = 'rgb(75, 134, 193)';
			jones.ctx.beginPath();
			jones.ctx.moveTo(x0, y0);
			jones.ctx.bezierCurveTo(u0x, u0y, v0x, v0y, w0x, w0y);
		} else {
			jones.ctx.strokeStyle = 'rgba(75, 134, 193, ' + (1-t) + ')';
			jones.ctx.beginPath();
			jones.ctx.moveTo(x0, y0);
			jones.ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
		}
		
		jones.ctx.stroke();
	},
	
	drawPath: function(x0, y0, x1, y1, s, first) {
		var dx = x1 - x0; var dy = y1 - y0;
		var vx = dx; var vy = dy;
		
		if (dx > 0) {
			dx = x0 - x1;
			dy = y0 - y1;
		}
		
		var f = 0.1; var g = 0.2;
		var px = -dy * f + g * vx; var py = dx * f + g * vy;
		var qx = -dy * f - g * vx; var qy = dx * f - g * vy;
		
		jones.drawCurve(x0, y0, x0 + px, y0 + py, x1 + qx, y1 + qy, x1, y1, s, first);
	},
	
	randomInt: function(maximum) {
		return Math.floor(Math.random() * (maximum + 1));
	},
	
	redraw: function(d, c0, c1, l, first) {
		var s = (jones.step % d) / d;
		
		var x0 = jones.cities[jones.city1][0] + jones.offsetx;
		var y0 = jones.cities[jones.city1][1] + jones.offsety;
		var x1 = jones.cities[jones.city2][0] + jones.offsetx;
		var y1 = jones.cities[jones.city2][1] + jones.offsety;
		
		jones.ctx.clearRect(0, 0, jones.canvas.width, jones.canvas.height);
		
		if (c0 == 1) jones.drawCross(x0, y0);
		else if (c0 == 2) jones.drawCrossAlpha(x0, y0, s);
		
		if (c1 == 1) jones.drawCross(x1, y1);
		else if (c1 == 2) jones.drawCrossAlpha(x1, y1, s);
		else if (c1 == 3) jones.drawCrossAlpha(x1, y1, 1 - s);
		
		if (l == 1) jones.drawPath(x0, y0, x1, y1, s, first);
		else if (l == 2) jones.drawPath(x0, y0, x1, y1, 1.0, first);
		
		jones.step++;
		
		return jones.step >= d;
	},
	
	changeState: function(state) {
		jones.state = state;
		jones.step = 0;
	},
	
	animate: function() {
		// resizeJones();
		
		if (jones.state == 0) {
			/*
			jones.ctx.clearRect(0, 0, jones.canvas.width, jones.canvas.height);
			for (var i = 0; i < jones.cities.length; i++) {
				var x0 = jones.cities[i][0] + jones.offsetx;
				var y0 = jones.cities[i][1] + jones.offsety;
				jones.drawCross(x0, y0);
				
				for (var j = i; j < jones.cities.length; j++) {
					if (i != j) {
						var x1 = jones.cities[j][0] + jones.offsetx;
						var y1 = jones.cities[j][1] + jones.offsety;
						jones.drawPath(x0, y0, x1, y1, 1.0, true);
					}
				}
			}
			*/
			jones.city1 = jones.randomInt(jones.cities.length - 1);
			jones.state = 1;
			jones.step = 0;
		}
		
		if (jones.state == 1) {
			var valid = true;
			do {
				jones.city2 = jones.randomInt(jones.cities.length - 1);
				
				valid = jones.city2 != jones.city1;
				
				for (var i = 0; i < jones.visited.length; i++) {
					if (jones.visited[i] == jones.city2) valid = false;
				}
			} while (!valid);
			
			var x0 = jones.cities[jones.city1][0] + jones.offsetx;
			var y0 = jones.cities[jones.city1][1] + jones.offsety;
			var x1 = jones.cities[jones.city2][0] + jones.offsetx;
			var y1 = jones.cities[jones.city2][1] + jones.offsety;
			
			var dx = x1 - x0;
			var dy = y1 - y0;
			
			jones.steps = Math.round(Math.sqrt(dx * dx + dy * dy) / jones.speed);
			
			jones.state = 2;
			jones.step = 0;
		}
		
		if (jones.state == 2) {
			if (jones.redraw(jones.steps, 1, 0, 1, true)) jones.changeState(3);
		}
		
		if (jones.state == 3) {
			if (jones.redraw(jones.fadein, 1, 3, 2, true)) jones.changeState(4);
		}
		
		if (jones.state == 4) {
			if (jones.redraw(jones.pauseboth, 1, 1, 2, true)) jones.changeState(5);
		}
		
		if (jones.state == 5) {
			if (jones.redraw(jones.fadeout, 2, 1, 1, false)) jones.changeState(6);
		}
		
		if (jones.state == 6) {
			if (jones.redraw(jones.pauseone, 0, 1, 0, false)) {
				jones.changeState(1);
				
				jones.visited.push(jones.city1);
				while (jones.visited.length > jones.historylength) jones.visited.shift();
				
				jones.city1 = jones.city2;
			}
		}
	},
	
	init: function(elem) {
		jones.canvas = $('#'+elem).get(0);
		if (jones.canvas && jones.canvas.getContext) {
			jones.ctx = jones.canvas.getContext('2d');
			jones.timer = setInterval(jones.animate, 1000 / jones.fps);
		}
	}
}


function resizeJones() {
	var w = $(window).width();
	var h = $(window).height();
	$('#background').attr({ 'width': w, 'height': h });
	if ($.browser.msie) {
		$('#background > *').css({ 'width': w, 'height': h });
	}
	jones.offsetx = Math.round(w / 2) - 620;
}

$(window).resize(resizeJones);

(function($) {
	var initialized = false;
	
	$.smartload = function(options) {
		var opts = $.extend({}, $.smartload.defaults, options);
		
		$.smartload.initialize(loadPage);
	
		function loadPage(hash, options) {
			if ($.smartload.parameters.ignoreNext) return;
			$.smartload.parameters.ignoreNext = true;
			
			var p = $.extend({}, opts, options);
			
			if (hash) {
				$.ajax({
					url: p.urlPrefix + hash + '.html',
					type: p.requestType,
					data: opts.data,
					cache: p.cache,
					complete: function(xhr, status) {
						var html = jQuery.httpData(xhr);
						p.replace($(html), {
							htmlLang : html.match( /<html.*lang="(.+)".*>/ )[1],
							documentTitle: $.trim(html.replace( /([\s\S]+)<title>/, '' ).replace(/<\/title>([\s\S]+)/, '' ))
						});
					}
				});
			}
		};

		var hash = opts.hash ? opts.hash : $.smartload.urlToHash(opts.url, opts.absPrefix);
		if (hash === false) return true;
		
		$.smartload.parameters.ignoreNext = true;
		$.history.load(hash);
		$.smartload.parameters.ignoreNext = false;
		loadPage(hash, options);
		
		return false;
	};
	
	$.smartload.urlToHash = function(href, root) {
		if (root && (href.substring(0, root.length) == root)) href = href.substring(root.length);
		if (href.indexOf('://') !== -1) return false;
		
		var startPos = href.lastIndexOf('/') + 1;
		var filename = href.substring(startPos);
		
		if (filename == '') filename = 'index.html';
		if ((endPos = filename.lastIndexOf('.html')) == -1) return false;
		
		return filename.substring(0, endPos);
	};

	$.smartload.initialize = function(fn) {
		if (!initialized) {
			$.history.init(fn);
			initialized = true;
		}
	};
	
	$.smartload.parameters = {
		ignoreNext: false
	}
	
	$.smartload.defaults = {
		url: 'index.html',
		hash: false,
		data: '',
		urlPrefix: '/',
		absPrefix: false,
		cache: true,
		requestType: 'GET',
		replace: function(dom) {
			$('#logo').replaceWith(dom.find('#logo'));
		},
		success: function() { return; }
	};
	
})(jQuery);

function registerEventListeners() {
	$.smartload.parameters.ignoreNext = false;
	
	$('#navigation > li').mouseenter(function() {
		$(this).addClass('hover');
		$(this).siblings('.active').find('div.secnavcontainer').stop(true, true).compatFadeOut(fadeSpeed);
		$(this).siblings('.hover').find('div.secnavcontainer').stop(true, true).compatFadeOut(fadeSpeed);
		$(this).find('div.secnavcontainer').stop(true, true).compatFadeIn(fadeSpeed);
	});				
	$('#navigation > li').mouseleave(function() {
		if (!$(this).hasClass('active')) $(this).find('div.secnavcontainer').stop(true, true).compatFadeOut(fadeSpeed);
		$(this).removeClass('hover');
	});				
	$('#navigation').mouseleave(function() {
		$(this).find('.active').find('div.secnavcontainer').stop(true, true).compatFadeIn(fadeSpeed);
	});				
	$('#navigation > li').bind('toggle', function() {
		$(this).toggleClass('active');
	});
	
	$('form').each(function() {
		$(this).find('label').each(function() {
			var text = $(this).text();
			
			$('#'+$(this).attr('for')).each(function() {
				if ($(this).val() == '') $(this).val(text);
				$(this).attr('oldvalue', text);
				
				$(this).bind('focus', function() {
					if ($(this).val() == $(this).attr('oldvalue')) $(this).val('');
					return true;
				});
				
				$(this).bind('blur', function() {
					if ($(this).val() == '') $(this).val($(this).attr('oldvalue'));
					return true;
				});
			});
			
			$(this).css({display: 'none'});
		});
		
		$('form').bind('submit', function(ev) {
			$(this).find('label').each(function() {
				$('#'+$(this).attr('for')).each(function() {
					if ($(this).val() == $(this).attr('oldvalue')) $(this).val('');
				});
			});
			
			if ($.smartload({
				url: $(this).attr('action'),
				requestType: 'POST',
				data: $(this).serialize()+'&send=smartloader',
				urlPrefix: getWebRoot(),
				absPrefix: getWebRoot(true),
				cache: false,
				replace: replaceDomParts,
				success: registerEventListeners
			})) {
				return true;
			} else {
				ev.preventDefault();
				ev.stopPropagation();
				
				return false;
			}
		});
	});
}

function replaceDomParts(dom, opts) {
	$.smartload.parameters.ignoreNext = false;
	
	document.title = opts.documentTitle;
	$('#navigation').replaceWith(dom.find('#navigation'));
	$('#language').replaceWith(dom.find('#language'));
	$('#sitelinks').replaceWith(dom.find('#sitelinks'));
	
	var newcontent = dom.find('#layoutwrapper > *');
	$('#layoutwrapper').stop(true,true).compatFadeOut(fadeSpeed).children('*').remove();
	$('#layoutwrapper').append(newcontent).stop(true,true).compatFadeIn(fadeSpeed);
	
	if (opts.htmlLang && Hyphenator.languages[opts.htmlLang]) {
		$('.hyphenate').each(function() {
			Hyphenator.hyphenate(this, opts.htmlLang);
		});
	}
	
	registerEventListeners();
	
	// if (document.getElementById('googlemap')) google.setOnLoadCallback(googleMapsInitialize);
}

function googleMapsInitialize(latitude, longitude) {
	var map = new google.maps.Map2(document.getElementById('googlemap'));
	var latitude = 0.0;
	var longitude = 0.0;
	map.setCenter(new google.maps.LatLng(latitude, longitude - 0.02), 13);
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	var point = new GLatLng(latitude, longitude);
	var marker = new GMarker(point);
	var htmlPopup = '<span style="color: #036fb2">NP4 GmbH</span>';
	GEvent.addListener(marker, 'click', function() { 
		marker.openInfoWindowHtml(htmlPopup);
	});
	marker.openInfoWindowHtml(htmlPopup);
	map.addOverlay(marker);
}

$(document).ready(function () {
	$('body').removeClass('nojavascript');
	
	var isIPhone = (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i));
	
	if (!isIPhone && (!$.browser.msie || $.browser.version >= 7)) {
		var el = document.createElement('canvas');
		el.id = 'background';
		el.width = 1;
		el.height = 1;
		if ($.browser.msie) {
			G_vmlCanvasManager.initElement(el);
		}
		$('body').prepend(el);
	}
	
	if (!isIPhone) {
		jones.init('background');
		resizeJones();
		
		Hyphenator.config({ minwordlength: 10, remoteloading: false, intermediatestate: 'visible' });
		Hyphenator.run();
	}
	
/*
	google.load('maps', '2.x');
	google.setOnLoadCallback(googleMapsInitialize);
*/
	
	if (!isIPhone) {
		var webroot = getWebRoot();
		var absroot = getWebRoot(true);
		
		if (absroot != location.href && location.href.indexOf('#') == -1) {
			location.href = absroot + '#' + $.smartload.urlToHash(location.href.replace('http://', ''));
		}
		
		if (location.href.indexOf('#') != -1) {
			$.smartload({
				hash: location.href.substring(location.href.indexOf('#') + 1),
				urlPrefix: getWebRoot(),
				absPrefix: getWebRoot(true),
				cache: true,
				replace: replaceDomParts,
				success: registerEventListeners
			})
		}
		
		registerEventListeners();
		
		$('a').live('click', function(ev) {
			$('a').removeClass('active');
			
			if ($.smartload({
				url: $(this).attr('href'),
				urlPrefix: getWebRoot(),
				absPrefix: getWebRoot(true),
				cache: true,
				replace: replaceDomParts,
				success: registerEventListeners
			})) {
				$(this).addClass('active');
				return true;
			} else {
				ev.preventDefault();
				ev.stopPropagation();
				
				return false;
			}
		});
	}
});
