(function($){
	var URL_ROOT = $('script[url-root]').attr('url-root');
	$.CMS = {
		URL_ROOT : URL_ROOT,
		URL_DATA : URL_ROOT+'cms-data/',
		FULL_URL_ROOT : location.href.replace(new RegExp(URL_ROOT+'.*$', 'i'), '')
	};
})(jQuery);

var rc = 0;
function renderNow(e) {
	rc++;
	if(!$.browser.msie || $.browser.version >= 9 || rc < 6) {}
	if($(e).data('initDone')) {
		return;
	}
	initClocks();
}

function initClocks() {
	$('#clocks .clock').each(function() {
		if($(this).data('initDone')) {
			return;
		}
		var clock = $(this),
			$canvas = clock.find('canvas'),
			canvas = $canvas[0],
			k = (!$.browser.msie || $.browser.version >= 9) ? 1 : 0.5;
		if(!canvas) {
			return;
		}
		if(!canvas.getContext) {
			canvas = clock.find('object')[0];
			if(!canvas || !canvas.getContext) {
				return;
			}
		}
		var c = canvas.getContext('2d'),
			date = new Date(),
			offset = clock.data('offset') + 0,
			over = 0,
			interval;
		if(!$.browser.msie || $.browser.version >= 9) {
			canvas.width = 98;
			canvas.height = 98;
			c.font = 'bold 20px Verlag';
		}
		c.lineWidth = 1.8 * k;
		c.strokeStyle = '#666';
		c.fillStyle = '#666';
		function drawLine(l, a) {
			a = Math.PI * 2 * a;
			c.beginPath();
			c.moveTo(49 * k, 49 * k);
			c.lineTo(49 * k + Math.sin(a) * l * k, 49 * k - Math.cos(a) * l * k);
			c.stroke();
			c.closePath();
		}
		function update() {
			if(!clock.closest('body').length) {
				clearInterval(interval);
				return;
			}
			var ms = (new Date()).getTime() + offset * 1000,
				h = ms % 86400000 / 3600000,
				m = ms % 3600000 / 60000,
				s = [12,1,2,3,4,5,6,7,8,9,10,11][(h<<0)%12]+':'+(m<10?'0':'')+(m<<0)+(h<12?' AM':' PM'),
				tw = (!$.browser.msie || $.browser.version >= 9) ? c.measureText(s).width : 80;	
			c.clearRect(0, 0, 98, 98);
			if(over && (!$.browser.msie || $.browser.version >= 9)) {
				c.fillText(s, 49 - tw / 2, 56);
			} else {
				c.strokeStyle = '#666';
				drawLine(30, h / 24);
				drawLine(39, m / 60);
				c.strokeStyle = '#bbb';
				drawLine(49, ms / 60000);
			}
			$canvas.attr('title', s);
		}
		$canvas.hover(function(){
			over = 1;
			update();
		}, function() {
			over = 0;
			update();
		});
	
		interval = setInterval(update, 100);
		update();
		clock.data('initDone', 1);
	});
}

jQuery(function($){
	var animK = navigator.userAgent.match(/iP(ad|hone|od)/i) || $.browser.msie && $.browser.version < 9 ? 0 : 1;
	
	initClocks();
	
	// Google Plus
	var timeout;
	$('body').delegate('.google-plus', 'mouseenter', function() {
		var that = $(this).closest('.google-plus'), timeout = that.data('timeout');
		if(timeout) {
			clearTimeout(timeout);
			that.data('timeout', 0);
		}
		$('.google-button', that).animate({
			top : 0
		});
	}).delegate('.google-plus', 'mouseleave', function() {
		var that = $(this).closest('.google-plus'), timeout = that.data('timeout');
		if(timeout) {
			clearTimeout(timeout);
		}
		that.data('timeout', setTimeout(function() {
			$('.google-button', that).animate({
				top : -40
			});
		}, 500));
	});
	
	/* Forms cleanup and validate */
	$('body').delegate('form', 'submit', function(event) {
		var ok = true;
		// Clear form placeholders on submit
		var placeholded = $('.placeholder', this).each(plhFocus);
		// Check required fields
		$(':input[required]', this).each(function() {
			ok = ok && $(this).val();
			$(this).toggleClass('error', !$(this).val());
		});
		// Check email fields
		$('.form-field-email input', this).each(function() {
			if(!$(this).val().match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
				ok = false;
				$(this).val('').addClass('error').blur();
			}
		});
		// Prevent submiting on error
		if(!ok) {
			event.stopImmediatePropagation();
			placeholded.each(plhBlur);
			return false;
		}
	});
	
	/* Subscribe form */
	$('body').delegate('#subscribe', 'submit', function() {
		var that = $(this);
		$.post(that.attr('action'), that.serialize(), function(result) {
			if(result) {
				that.find('.form').css({
					width : that.width(),
					position : 'absolute'
				}).fadeOut().end().find('.after-submit').fadeIn();
			}
		});
		return false;
	});
	
	/* Content forms */
	$('body').delegate('form.content-form', 'submit', function() {
		var that = $(this);
		ajaxFuncs.overlay(that.attr('action'), that.serialize());
		return false;
	});
	
	/* Input field placeholders */
	function plhFocus() {
		var that = $(this), placeholder = that.data('placeholder');
		if(that.is('.placeholder') && that.attr('type') != 'password') {
			if(that.attr('data-type') == 'password') {
				var replacement = $('<input>', {
					type : 'password',
					name : that.attr('name'),
					className : that.attr('class'),
					'data-placeholder' : that.attr('placeholder'),
					focus : plhFocus,
					blur : plhBlur
				});
				that.after(replacement).remove();
				replacement.data('placeholder', placeholder).removeClass('placeholder');
				replacement.focus();
			} else {
				that.val('').removeClass('placeholder');
			}
		}
	}
	function plhBlur() {
		var that = $(this), placeholder = that.data('placeholder');
		if(that.val() == '') {
			if(that.attr('type') == 'password') {
				var replacement = $('<input>', {
					type : 'text',
					name : that.attr('name'),
					className : that.attr('class'),
					'data-type' : 'password',
					focus : plhFocus,
					blur : plhBlur,
					val : placeholder
				}).addClass('placeholder');
				that.after(replacement).remove();
				replacement.data('placeholder', placeholder).addClass('placeholder');
			} else {
				that.val(placeholder).addClass('placeholder');
			}
		}
	}
	function initPlaceholders() {
		$('input[placeholder]:not(.phdone),textarea[placeholder]:not(.phdone)').each(function() {
			var that = $(this), val = that.attr('placeholder');
			that.data('placeholder', val).attr('placeholder', '').addClass('phdone');
			if(!that.attr('title')) {
				that.attr('title', val);
			}
		}).focus(plhFocus).blur(plhBlur).blur();
	}
	initPlaceholders();
	
	
	// Scrolling
	var wind = $(window);
	function initScroll() {
		$('.content.over').each(function() {
			var that = $(this), inner = that.find('.content-inner');
			if(!that.data('initDone')) {
				inner.addClass('fixed').wrapInner('<div class="content-pos"></div>');
				that.data('initDone', 1).height(that.find('.content-pos').height() + 150);
			}
		});
	}
	if($('#overlay').length) {
		$('body>.content:not(.over)').addClass('fixed').css({
			top : -wind.scrollTop()
		});
		$('body>.sidebar').addClass('fixed');
	}
	initScroll();
	wind.scroll(function(e) {
		var top = -wind.scrollTop();
		$('.content.over').each(function() {
			$(this).height($('.content-pos', this).height() + 150);
			$('.content-pos', this).css('top', top);
		});
	});
	
	function initMenuArrow() {
		$('<div class="arrow"></div>').appendTo($('.sidebar .menu').addClass('manual-arrow')).css('top', $('.sidebar .menu li.open').prevAll().length * 30);
	}
	initMenuArrow();
	
	
	// Ajax
	var ajaxFuncs = {
		overlay : function(url, data) {
			$.post(url+'.ajax', data || {}, function(data) {
				var data = $(data);
				try {
					document.title = $('#page-title', data).text();
					$('title').text(document.title);
				} catch(ex){}
				if(!$('#overlay').length) {
					$('body>.content:not(.over)').addClass('fixed').css({
						top : -wind.scrollTop()
					});
					$('body>.sidebar').addClass('fixed');
					$('<div id="overlay" class="closed"><div class="overlay-line"></div></div>').prependTo('body');
					setTimeout(function() {
						$('#overlay').removeClass('closed');
					}, 1);
					setTimeout(function() {
						$('#overlay').append($('.sidebar', data).hide().fadeIn(250 * animK));
						$('.content.over', data).appendTo('body').find('.content-inner').hide().fadeIn(250 * animK);
						initMenuArrow();
						initScroll();
						initPlaceholders();
						wind.scroll();
					}, 250 * animK);
				} else {
					$('.content.over').find('.content-inner').fadeOut(250 * animK, function() {
						$('.content.over').remove();
						$('.content.over', data).appendTo('body').find('.content-inner').hide().fadeIn(250 * animK);
						initScroll();
						initPlaceholders();
						wind.scroll();
					});
					if($('.sidebar .menu a[href="'+$('.sidebar .menu a.open', data).attr('href')+'"]').length) {
						$('.sidebar .menu .open').removeClass('open');
						$('.sidebar .menu a[href="'+$('.sidebar .menu a.open', data).attr('href')+'"]').addClass('open').parent('li').addClass('open');
						$('.sidebar .menu .arrow').stop().animate({
							top : $('.sidebar .menu li.open').prevAll().length * 30
						}, {
							duration : 350
						});
						wind.scroll();
					} else {
						$('.sidebar .menu', '#overlay').children().fadeTo(250 * animK, 0.1);
						setTimeout(function() {
							var menu = $('.sidebar .menu'), height = menu.height(), newHeight = $('.sidebar .menu', data), newMenu = $('.sidebar .menu', data).children();
							menu.height('').empty().append(newMenu.fadeTo(0, 0));
							newHeight = menu.height();
							menu.height(height).animate({
								height : newHeight
							}, {
								duration : 250 * animK
							}).children().fadeTo(250 * animK, 1);
							initMenuArrow();
							initPlaceholders();
							wind.scroll();
						}, 250 * animK);
					}
				}
			}, 'html');
		},
		main : function(url) {
			$('body>.content:not(.over)').removeClass('fixed').css({
				top : ''
			});
			$('body>.sidebar').removeClass('fixed')
			$('#overlay, .content.over').fadeOut(250 * animK, function() {
				$('#overlay, .content.over').remove();
			});
			$.post(url+'.ajax', function(data) {
				var data = $(data);
				try {
					document.title = lastMainTitle;
					lastMainTitle = $('#page-title', data).text();
					$('title').text(lastMainTitle);
				} catch(ex){}
				if($('.content[data-url]').data('url') != $('.content[data-url]', data).data('url')) {
					$('.content:not(.over)').fadeOut(250 * animK, function() {
						$('.content:not(.over)').remove();
						$('.content:not(.over)', data).appendTo('body').hide().fadeIn(250 * animK, function() {
							gapi.plusone.go();
						});
						initScroll();
						initPlaceholders();
					});
					$('body>.sidebar').fadeOut(250 * animK, function() {
						$('body>.sidebar').remove();
						$('#page-content>.sidebar', data).appendTo('body').hide().fadeIn(250 * animK);
						initClocks();
						wind.scroll();
					});
				}
			}, 'html');
		},
		undefined : function() {
		}
	};
	
	if($.browser.msie && $.browser.version < 9) { return; }
	
	var popped = ('state' in window.history), initialURL = location.href, lastMainUrl = $('.content[data-url]').data('url'), lastMainTitle = $('#overlay').length ? document.title.replace(/ - .*/, '') : document.title;
	function newState(url, func, noload) {
		if(history.pushState) {
			if(func == 'main') {
				lastMainUrl = url;
			}
			history.pushState(func, '', url);
		}
		if(!noload) {
			ajaxFuncs[func](url);
		}
		
		if(window._gaq) {
			window._gaq.push(['_trackPageview', url]);
		}
	}
	wind.bind('popstate', function(event) {
		var func = event.originalEvent.state, url = location.href.replace($.CMS.FULL_URL_ROOT, '');
		if(!func) {
			func = 'main';
			url = $.CMS.URL_ROOT;
		}
		if(func == 'main') {
			lastMainUrl = url;
		}
		// Ignore inital popstate that some browsers fire on page load
		var initialPop = !popped && location.href == initialURL;
		popped = true;
		if(initialPop) {
			return;
		}
		ajaxFuncs[func](url);
	});
	$('#menu a').click(function() {
		var url = $(this).attr('href');
		newState(url, 'overlay');
		return false;
	});
	$('body').delegate('#logo', 'click', function() {
		if($('#overlay').length) {
			$('.overlay-close').click();
			return false;
		}
	})
	$('body').delegate('.overlay-close', 'click', function() {
		var top = -parseInt($('body>.content:not(.over)').css('top'), 10);
		$('body>.content:not(.over)').removeClass('fixed').css({
			top : ''
		});
		$('body>.sidebar').removeClass('fixed')
		wind.scrollTop(top);
		$('#overlay, .content.over').fadeOut(250 * animK, function() {
			$('#overlay, .content.over').remove();
		});
		newState(lastMainUrl, 'main', true);
		if(lastMainTitle) {
			try {
				document.title = lastMainTitle;
				$('title').text(lastMainTitle);
			} catch(ex){}
		}
		return false;
	}).delegate('#overlay .sidebar .menu a, .news-nav a', 'click', function() {
		var url = $(this).attr('href');
		newState(url, 'overlay');
		return false;
	}).delegate('.project, body>.sidebar .nav a', 'click', function() {
		var url = $(this).attr('href');
		newState(url, 'main');
		return false;
	});
	
	if(navigator.userAgent.match(/iP(ad|hone|od)/i) || wind.width() <= 1024) {
		wind.scroll(function() {
			$('body>.sidebar').css('top', Math.max(0, wind.scrollTop() - 70) + 100);
		}).scroll();
	}
});

