$(function() {
	(function() {
		function Tooltip(el)
		{
			this.el = el;
			
			this.title = el.attr('title');
			
			var match = this.title.split('|');
			
			this.header = match[0] || '';
			this.text = match[1] || '';
			
			el.attr('title');
		}
		
		Tooltip.each = function() {
			var el = $(this);
			
			var tooltip = new Tooltip(el);
			
			el.mouseenter(Tooltip.bind(tooltip, tooltip.enter));
			el.mouseleave(Tooltip.bind(tooltip, tooltip.out));
			
			return this;
		};
		
		Tooltip.bind = function(scope, fn, args) {
			return function() {
				return fn.apply(scope, args || []);
			};
		};
		
		if($.browser.msie && $.browser.version < 8) {
			Tooltip.propertyEnter = {
				top: '+=25'
			};
			
			Tooltip.propertyOut = {
				top: '-=25'
			};
		} else {
			Tooltip.propertyEnter = {
				top: '+=25',
				opacity: 1
			};
			
			Tooltip.propertyOut = {
				top: '-=25',
				opacity: 0
			};
		}
		
		Tooltip.document = $(document);
		
		Tooltip.prototype = {
			title: null,
			container: null,
			height: null,
			list: null,
			build: function() {
				this.container = $(
					'<table class="tooltip" id="tooltip" cellspacing="0" cellpadding="0">' +
					'<tr class="top">' +
					'<td class="left"></td>' +
					'<td class="center" colspan="3"></td>' + 
					'<td class="right"></td>' +
					'</tr>' +
					'<tr class="middle">' +
					'<td class="left"></td>' +
					'<td class="center" colspan="3"></td>' + 
					'<td class="right"></td>' +
					'</tr>' +
					'<tr class="bottom">' +
					'<td class="left"></td>' +
					'<td class="center">&nbsp;</td>' +
					'<td class="arrow"></td>' +
					'<td class="center">&nbsp;</td>' +
					'<td class="right"></td>' +
					'</tr>' +
					'</table>'
				)
				.hide()
				.appendTo(document.body);
				
				var area = this.container.find('.middle .center');
				
				area.html('<strong>' + this.header + '</strong><p>' + this.text + '</p>');
				
				this.height = this.container.height();
				this.width = this.container.width();
				this.middle = this.el.width() / 2;
			},
			enter: function() {
				this.build();
				
				var
				offset = this.el.offset();
				
				offset.top += Tooltip.document.scrollTop() - this.height - 25;
				offset.left += Tooltip.document.scrollLeft() - this.width / 2 + this.middle;
				
				if (!$.browser.msie || $.browser.version > 8) {
					this.container.css('opacity', 0);
				} else {
					this.container.find('.bottom .center').css('width', Math.ceil((this.width - 44 - 30 * 2) / 2) + 'px');
				}
				
				this.container
				.offset(offset)
				.show()
				.animate(Tooltip.propertyEnter, 'fast');
			},
			out: function() {
				this.el.attr('title', this.title);
				
				this.container
				.animate(Tooltip.propertyOut, 'fast', 'swing', this.outComplete);
			},
			outComplete: function() {
				$(this).remove();
			}
		};
		
		
		
		$.fn.tooltip = function() {
			this.each(Tooltip.each);
			
			return this;
		};
		
		function paintBackground(index, el) {
			el = $(this);
			
			var height = el.height() + 'px';
			
			el.css('background', 'url(' + el.children('img').attr('src') + ') 0 -' + height);
		}
		
		function fadeOut() {
			$(this).children('img').fadeOut();
		}
		
		function fadeIn() {
			$(this).children('img').fadeIn();
		}
		
		$.fn.colorize = function() {
			this
			.each(paintBackground)
			.mouseenter(fadeOut)
			.mouseleave(fadeIn);
			
			return this;
		};
	})();
	
	(function() {
		function Slideshow(view, duration, viewWidth, moveWidth) {
			this.view = $(view);
			
			this.viewWidth = viewWidth;
			
			this.duration = duration || this.duration;
			
			this.current = parseFloat(this.view.css('left'));
			
			this.end = this.current;
			
			this.move = moveWidth;
			
			var scope = this;
			this.redraw = function() {
				scope.draw();
			};
		};
		
		Slideshow.prototype = {
			interval: null,
			duration: 1000,
			next: function() {
				this.end -= this.move;
				
				this.animate();
			},
			previous: function() {
				this.end += this.move;
				
				this.animate();
			},
			calc: function(value) {
				return value % this.viewWidth > 0 ? value % this.viewWidth - this.viewWidth : value % this.viewWidth;
			},
			draw: function() {
				var length = new Date().getTime() - this.timestamp;
				
				if(length < this.duration) {
					this.current = this.easing(length, this.start, this.end - this.start, this.duration);
					
					this.interval = setTimeout(this.redraw, 1);
				} else {
					this.current = this.easing(this.duration, this.start, this.end - this.start, this.duration);
					
					this.complete();
					
					this.interval = null;
				}
				
				this.view.css('left', this.calc(this.current) + 'px');
			},
			complete: function() {
				this.current = this.calc(this.current);
				this.start = this.calc(this.start);
				this.end = this.calc(this.end);
			},
			stop: function() {
				if(this.interval) {
					clearTimeout(this.interval);
				}
			},
			animate: function() {
				this.stop();
				
				this.timestamp = new Date().getTime();
				
				this.start = this.current;
				
				this.draw();
			},
			easing: function(t, b, c, d) {
				return -c * ((t=t/d-1)*t*t*t - 1) + b;
			}
		};
		
		function next(e) {
			e.data.next();
		}
		
		function previous(e) {
			e.data.previous();
		}
		
		function each(index, el) {
			el = $(el);
			
			var
			view = el.find('.view');
			
			view.fadeIn();
			
			var
			childrens = view.children(),
			viewWidth = view.width(),
			moveWidth = viewWidth / childrens.length,
			start = childrens.slice(0, 5),
			end = childrens.slice(-5);
			
			$(start.clone()).appendTo(view);
			$(end.clone()).prependTo(view);
			
			view.css('left', -moveWidth * 5 + 'px');
			
			var anim = new Slideshow(view, 1000, viewWidth, moveWidth);
			
			view.css('left', anim.calc(-moveWidth * 5) + 'px');
			
			el.find('.next').bind('click', anim, next);
			el.find('.previous').bind('click', anim, previous);
			
			view.find('a').colorize().tooltip();
		}
		
		$.fn.slideshow = function() {
			this.each(each);
		};
	})();
	
	var patternFBML = /^ *FBML *([\S\s]*?) *FBML *$/, textFBML;
	
	function fixFBML() {
		$(".fbml").each(function() {
			this.innerHTML = this.innerHTML.replace(/(<!-- *FBML *| *-->)/g, "");
			
			this.className += '-replaced';
		});
		
		if(typeof FB != "undefined") {
			FB.XFBML.parse(document.getElementById("body"));
		}
	}
	
	var hash = '', request, id;
	
	var pages = {
		href: window.location.pathname,
		onLoad: {
			'/': function() {
				$('.carousel').slideshow();
			},
			'/kontakta-oss': function() {
				var
				map = new GMap2(document.getElementById('google_map')),
				latlng = new GLatLng(57.689121,11.907136);
				map.setCenter(latlng, 15);
				map.addControl(new GSmallZoomControl3D());
				map.addOverlay(new GMarker(latlng));
			},
			'/tjanster/hemsidor': function() {
				$('.colorize a').colorize().tooltip();
			}
		},
		onUnload: {},
		unload: function() {
			if(this.onUnload[this.href]) {
				this.onUnload[this.href]();
			}
		},
		load: function() {
			fixFBML();
			try {
				var pageTracker = _gat._getTracker("UA-15751299-1");
				pageTracker._trackPageview(this.href);
			} catch(err) {}
			
			if(this.onLoad[this.href]) {
				this.onLoad[this.href]();
			}
		}
	};
	
	pages.load();
	
	function renderFonts() {
		Cufon.replace('h1', { fontFamily: 'Swis721 Th BT' });
		Cufon.replace('h2', { fontFamily: 'Swis721 Lt BT' });
		Cufon.replace('h3', { fontFamily: 'Scoder Hand' });
	}
	
	function beforeRequest() {
		$(document.body).addClass('autoAjax');
		
		if(request) {
			try {
				request.abort();
			} catch(e) {}
		}
	}
	
	function afterRequest() {
		if(!$.browser.msie || $.browser.msie > 6) {
			$('#body').hide();
		}
	}
	
	function successRequest(data) {
		window.location.hash = '#' + data.href;
		
		pages.href = data.href;
		
		hash = window.location.hash;
		
		for(id in data.contents) {
			$('#' + id).html(data.contents[id]);
		}
		
		document.title = data.title;
		
		renderFonts();
		$('#body').fadeIn(1000, finish);
	}
	
	function finish() {
		$(document.body).removeClass('autoAjax');
		
		pages.load();
	}
	
	function autoAjax(href) {
		beforeRequest();
		
		request = $.ajax({
			url: href + '?autoAjax=true',
			type: 'get',
			dataType: 'json',
			success: successRequest
		});
		
		afterRequest();
	}
	
	function replaceAjaxRequest(data) {
		var parent = this;
		
		setTimeout(function() {
			parent.html(data);
			
			parent.hide();
			parent.removeClass('loadingAjax');
			
			parent.fadeIn();
		}, 500);
	}
	
	function replaceAjax(href, parent) {
		if(request) {
			try {
				request.abort();
			} catch(e) {}
		}
		
		$(parent).addClass('loadingAjax');
		
		request = $.ajax({
			url: href + '/format/html',
			type: 'get',
			context: parent,
			success: replaceAjaxRequest
		});
	}
	
	function autoFormAjax(form) {
		beforeRequest();
		
		request = $.ajax({
			url: form.action + '?autoAjax=true',
			type: form.method.toLowerCase(),
			data: $(form).serialize(),
			success: successRequest
		});
		
		afterRequest();
	}
	
	function replaceFormAjax(form, parent) {
		if(request) {
			try {
				request.abort();
			} catch(e) {}
		}
		
		$(parent).addClass('loadingAjax');
		
		request = request = $.ajax({
			url: form.action + '/format/html',
			type: form.method.toLowerCase(),
			data: $(form).serialize(),
			context: parent,
			success: replaceAjaxRequest
		});
	}
	
	$('form[class!=noAjax]').live('submit', function(event) {
		var parent = $(this).parents('.replaceAjax');
		
		if(parent.size()) {
			replaceFormAjax(this, parent);
		} else {
			autoFormAjax(this);
		}
		
		return false;
	});
	
	$('a[class=must-confirm]').live('click', function() {
		return window.confirm(this.title);
	});
	
	$('a[class!=noAjax]').live('click', function(event) {
		if(this.href.indexOf(window.location.hostname) < 0) {
			if($(this).hasClass('new-window')) {
				window.open(this.href);
				
				return false;
			} else {
				return true;
			}
		}
		
		var parent = $(this).parents('.replaceAjax');
		
		if(parent.size()) {
			replaceAjax(this.href, parent);
		} else {
			autoAjax(this.href);
		}
		
		return false;
	});
	
	setInterval(function() {
		if(hash != window.location.hash) {
			hash = window.location.hash;
			
			autoAjax(window.location.hash.substring(1));
		}
	}, 100);
	
	renderFonts();
});

