(function($){
	
	if (!window.console)
		window.console = {log:function(){},dir:function(){}};

	/**
	 * Tabs
	 */
	$.fn.tabs = function()
	{
		var m_this = $(this);
		
		m_this.find(">ul>li>a").each(function(i)
		{
			$(this).data("indx",i);
			$(this).click(function()
			{
				m_this.find(">ul>li").removeClass("active");
				$(this).parent().addClass("active");
				var idx = $(this).data("indx");
				m_this.find(">div").hide();
				m_this.find(">div:eq(" + idx + ")").show();
				return false;
			});
		})
		
		m_this.find(">ul>li>a:first").click();
	}
	
	/**
	 * Newsletter form
	 */
	$.fn.newsletter_form = function()
	{
		var m_this = $(this);
		var m_name = m_this.find("input[name='nn']");
		var m_email = m_this.find("input[name='ne']");
		
		function validate()
		{
			var retVal = true;
			
			if ($.trim(m_name.val()).length==0)
			{
				retVal = false;
				m_name.closest("p").addClass("error");
				m_name.closest("p").find("span").show();
			}
			else
			{
				m_name.closest("p").removeClass("error");
				m_name.closest("p").find("span").hide();
			}
			
			if ($.trim(m_email.val()).length==0 || !$.isEmail($.trim(m_email.val())))
			{
				retVal = false;
				m_email.closest("p").addClass("error");
				m_email.closest("p").find("span").show();
			}
			else
			{
				m_email.closest("p").removeClass("error");
				m_email.closest("p").find("span").hide();
			}
			return retVal;
		}
		
		m_this.submit(function()
		{
			if (validate())
			{
				$.showModalCover();
				return true;
			}
			else
				return false;
		})
	}	
	
	/**
	 * Twitter widget
	 */
	$.fn.twitter_feed = function()
	{
		var m_this = $(this);
		var u = "http://twitter.com/status/user_timeline/LINFOLIVE.json?count=6&callback=?";
		var TIMEOUT = 15000;
		
		function relative_time(time_value) {
			var values = time_value.split(" ");
			time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
			var parsed_date = Date.parse(time_value);
			var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
			var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
			delta = delta + (relative_to.getTimezoneOffset() * 60);
			
			if (delta < 60) {
				return 'meno di un minuto fa';
			} else if(delta < 120) {
				return 'un minuto fa';
			} else if(delta < (60*60)) {
				return (parseInt(delta / 60)).toString() + ' minuti fa';
			} else if(delta < (120*60)) {
				return 'un ora fa';
			} else if(delta < (24*60*60)) {
				return '' + (parseInt(delta / 3600)).toString() + ' ore fa';
			} else if(delta < (48*60*60)) {
				return 'ieri';
			} else {
				return (parseInt(delta / 86400)).toString() + ' giorni fa';
			}
		}
		
		function loadData()
		{
			$.ajax({
				url: u,
				dataType: 'json',
				success: function(data)
				{
					var h = [];
					h.push("<ul>");
					for (var i=0;i<data.length;i++)
					{
						var d = data[i].text.split("http://");
						h.push('<li>');
						if (d[1])
							h.push('<a href="http://' + d[1] + '">');
						h.push(d[0] + '<br/><span>' + relative_time(data[i].created_at)  + '</span>');
						if (d[1])
							h.push('</a>');
						h.push('</li>');
					}
					h.push("</ul>");
					
					m_this.find("ul").remove();
					m_this.find("h3").after(h.join(""));
					m_this.show();
					
					console.log("Twitter (re)loaded");
				}
			});
		}
		
		loadData();
		setInterval(loadData, TIMEOUT);
	}
	
	/**
	 * Twitter
	 */
	$.fn.twitterShare = function()
	{
		var m_this=$(this);
		
		var BTLY_LOGIN = "developoone";
		var BTLY_KEY = "R_1e62fbb71b91c860530a1092be8d79f2";
		var TWURL = "http://twitter.com/home?status=${title}++${url}";

		var url = m_this.attr("href");
		var title = m_this.attr("title");
		var endpoint = "http://api.bitly.com/v3/shorten?login=" + BTLY_LOGIN + "&apiKey=" + BTLY_KEY + "&longUrl=" + url + "&format=json";
		
		var m_twurl = "";
		
		$.ajax({
			type: "GET",
			async: true,
			url: endpoint,
			success: function(data)
			{
				m_twurl = TWURL.split("${title}").join(title).split("${url}").join(data.data.url);
			},
			error: function(a,b,c){ alert("Error"); $.hideModalCover(); console.log(a,b,c); },
			dataType: "jsonp"
		});	
		
		m_this.click(function()
		{
			if (m_twurl!="")
			{
				window.open(m_twurl);
				return false;
			}
			return false;
		});
	}
	
	/**
	 * Youtube etv widget
	 */
	$.fn.youtube_etv = function()
	{
		var m_this = $(this);
		
		var t1 = '' +
				'<h1></h1>' +
				'<iframe title="" width="410" height="260" src="#" frameborder="0"></iframe>' +
				'<div class="thumbs">${thumbs}</div>';

		var t2 = '<a href="${url}" title="${title}" class="${class}"><img src="${thumb}" alt="${title}" width="94" /></a>';
		
		// stop video when tab clicked
		m_this.find("a").click(function(i)
		{
			var src = m_this.find("div.cont:eq(" + i + ") iframe").attr("src");
			m_this.find("div.cont:eq(" + i + ") iframe").attr("src", src);
		})
		
		m_this.find("a").each(function(i)
		{
			var id = $(this).attr("href").split("/");
			id = id[id.length-1];
			var u = "http://gdata.youtube.com/feeds/users/" + id + "/uploads?alt=json-in-script&callback=?&max-results=5";
			var d = m_this.find("div.cont:eq(" + i + ")");
			
			$.ajax({
				url: u,
				dataType: 'json',
				success: function(data)
				{
					populate(data, d);
				}
			});
		});
		
		function populate(data, cont)
		{
    			var ht = [];

			$.each(data.feed.entry, function(i, item)
			{
				if (i<4)
				{
					var url = item['media$group']['media$content'][0]['url'];
	           			var thumb = item['media$group']['media$thumbnail'][0]['url'];
	           			var title = item['title']['$t'];
	           			ht.push(t2.split("${title}").join(title).split("${thumb}").join(thumb).split("${url}").join(url).split("${class}").join(i==0?"first":""));
				}
			})
			
			var c = t1.split("${thumbs}").join(ht.join(""));
			cont.html(c);
			cont.find("a").click(showVideo);
			cont.find("a:first").click();
		}
		
		function showVideo()
		{
			var src = $(this).attr("href");
			var title = $(this).attr("title");
			$(this).closest(".cont").find("h1").html(title);
			$(this).closest(".cont").find("iframe").attr("title",title);
			$(this).closest(".cont").find("iframe").attr("src",src);
			var embed = src.split("/");
			embed = embed[embed.length-1];
			$(this).closest(".cont").find("iframe").attr("src","http://www.youtube.com/embed/" + embed);
			return false;
		}
	}
	
	$.fn.etvMenu = function()
	{
		$("#etv").click(function(){
			$("#etvNav").fadeIn("slow");
			$("#etv").addClass("hover");
			return false;
		});
		$("#etvNav").mouseleave(function(){
			$("#etvNav").fadeOut("slow");
			$("#etv").removeClass("hover");
			return false;
		});
	}

	
	$.isEmail = function(val)
	{
		var reMail = RegExp("[a-zA-Z0-9._-]+@[a-zA-Z0-9]{1}[a-zA-Z0-9-]{2}[a-zA-Z0-9-.]*[a-zA-Z0-9]*[.]+[a-zA-Z]{2,4}");
		return reMail.test(val);
	}
	
	$.showModalCover = function()
	{
		if ($("#o1-modalCover").length==0)
		{
			$(document.body).append('<div id="o1-modalCover" style="background-color:#000;position:absolute;left:0;top:0">&nbsp;</div>');
			$("#o1-modalCover").css("opacity",0.3);
			$(window).resize(function()
			{
				$("#o1-modalCover").width($(window).width());
				$("#o1-modalCover").height($(window).height());
				$("#o1-modalCover").css("top", $("html,body").scrollTop());
			})
			$(window).scroll(function()
			{
				if ($("#o1-modalCover").is(":visible"))
				{
					$("#o1-modalCover").width($(window).width());
					$("#o1-modalCover").height($(window).height());
					$("#o1-modalCover").css("top", $("html,body").scrollTop());
				}
			})
		}
		$("#o1-modalCover").width($(window).width());
		$("#o1-modalCover").height($(window).height());
		$("#o1-modalCover").css("top", $("html,body").scrollTop());
		$("#o1-modalCover").show();
	}

	$.hideModalCover = function()
	{
		$("#cm-modalCover").hide();
	}
	
	/**
	 * Init
	 */
	$(document).ready(function(){
		$(".o1_tabs").each(function(){$(this).tabs()});
		$(".o1_twittershare").each(function(){$(this).twitterShare()});
		$(".o1_newsletter_form").each(function(){$(this).newsletter_form()});
		//$("body").etvMenu();
		$(".o1_twitter_feed").each(function(){$(this).twitter_feed()});
	});
	
	$(window).load(function(){
		$(".o1_youtube_etv").youtube_etv();
	});

})(jQuery);
