$(document).ready(function() {
	if(typeof productShow10119main2 == 'undefined')
		return;
		
	var base = $('base').attr('href');	
	var subPath = window.location.href.replace(base, '').replace('tekijat', '');
	
	if(!subPath) {
		$('.productResults .productItem').eq(0).find('a').eq(0).click();
	} else {
		$('.productInfoCenter').css('right', 0);
		var twitterAccount = $('.productInfo .productFieldTwitterAccountContent a').attr('href');
		if(twitterAccount)
			twitterAccount = twitterAccount.replace('http://twitter.com/#!/', '');
		if(twitterAccount)
			latestTwitterTweet(twitterAccount);
		
		var blogAccount = $('.productInfo .productFieldBlogAccountContent').text().trim();
		if(blogAccount)
			latestBlogPosts(blogAccount);
		
		createTabs();
	}
	
	$(productShow10119main2).bind("beforeProductShowEvent", function() {
		var $infoCenter = $('.productInfoCenter');
		if($infoCenter.length) {
			$infoCenter.stop().animate({
				right: -($('.productInfo').width())
			}, 300);
		}
	});
	$(productShow10119main2).bind("afterProductShowEvent", function(evt, data) {
		$('.productInfoCenter').stop().animate({
			right: 0
		}, 500);
		
		// Enable caching
		$.ajaxSetup({ cache: true });
		if(data.itemValues.twitterAccount) {
			latestTwitterTweet(data.itemValues.twitterAccount);
		}
		if(data.itemValues.blogAccount) {
			latestBlogPosts(data.itemValues.blogAccount);
		}
		createTabs();
	});
	$('.productResults .productItem A').live('click', function() {
		var node = $("html,body");
		if(node.scrollTop < $('#main').offset().top)
			return;
		$("html,body").animate({scrollTop: $('#main').offset().top}, 100);
	});
});

function createTabs() {
	// Create tabs
	$('.productFieldText4').addClass('teamPane');
	$('.productFieldText5').css('display', 'none').addClass('teamPane');
	var $tabs = $('.productFieldText3 li');
	$tabs.click(function() {
		$tabs.removeClass('teamTabOpen');
		$(this).addClass('teamTabOpen');
		$('.teamPane').hide();
		$('.teamPane').eq($('.productFieldText3 li').index($(this))).show();
	});
	$($tabs[0]).click();
}

function latestBlogPosts(blogAccount) {
	var $blogTab = $('.blogPostsTitle');
	$blogTab.css('display', 'block');
	$.ajax({
		type : 'GET',
		url : 'blogi-nosto/author/'+blogAccount+'/?target=10196&method=renderView',
		success : function(feed) {
			var $container = $('<div class="blogFeeds teamPane"/>');
			$container.css('display', 'none');
			$(feed).find('#postIndex-1').appendTo($container);
			$(feed).find('#postIndex-2').appendTo($container);
			$('.productInfo .productItemContent').append($container);
			$blogTab.css('background', 'none');
			$blogTab.find('span').fadeIn();
		}
	});	
}

function latestTwitterTweet(twitterAccount) {
	$.ajax({
		type : 'GET',
		dataType : 'jsonp',
		data: {
			screen_name: twitterAccount
		},
		url : 'http://api.twitter.com/1/users/show.json',
		success : function(user) {
			var result = user.status;
			if(!result) {
				return;
			}
			var $container = $('<div class="twitterContainer"/>');
			var $div = $('<div class="twitterTweet"/>');
			var $user = $('<div class="twitterUser"/>');
			var $created = $('<div class="twitterCreated"/>');
			var $text = $('<div class="twitterText"/>');
			$user.html("<a href='http://twitter.com/#!/" + user.screen_name 
						+ "' target='_blank'>" + user.screen_name + "</a>: ");
			$created.text(prettyDate(result.created_at));
			$text.html(parseLinks(result.text));
			$div
				.append($user)
				.append($text)
				.append($created)
				.css({ opacity: 0 })
			;
			$container
				.append($div)
				.css({ marginLeft: -100 })
			;
			$('.productDescLong').prepend($container);
			$container.animate({ marginLeft: 0 }, function() { 
				$div.animate({ opacity: 1 }); 
			});
		}
	});	
}

function parseLinks(string) {
	var regexp = /(http|https|ftp):\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/;
	return string.replace(regexp, function(url) {
		return "<a href='" + url + "' target='_blank'>" + url + "</a>";
	});
}


/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	var date = new Date(time),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
	
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};
