/*
 *  Documento:  Javascript 
 *  Projeto:    TwitFlink
 *  Versão:     1.0
 *  Data:       dez/2010	 
 */

$(function() {
	
	// Hide loading gif
	$('#hidden').hide();
	
	// Adjust links on the top
	if ($('#auth-links').length)
		$('#twitter-auth').css('textAlign', 'center');
	else
		$('#twitter-auth').css('textIndent', '50px');
	
	// Add Delicious button
	$('a.delicious-button').deliciousButton({
  	url:'http://www.moretechtips.net/2010/02/google-buzz-widget-jquery-plugin.html',
    title:'Google Buzz Widget - A jQuery Plugin'      
  });
	
	// Add clouds
	$('body').prepend('<div id="left-cloud"></div><div id="right-cloud"></div>');
	
	// Add header background
	$('#body').prepend('<div id="header-bg"></div>');
	
	// Search field
	var initVal = 'Looking for a link? Just enter the @username here!';
	$('#user-field').val(initVal).clearInput(initVal, '@');
	// Show ajax loader in search fields
	$('#search-form, #keyword-form').submit(function() {
		var id = $(this).attr('id');
		var img = id == 'search-form' ?  'ajax-loader' : 'ajax-loader2';	
		if (id == 'search-form' && $(this).find('input').val() == initVal)
			return false;
		$('#'+id+' button')
			.css({'background': 'url(images/'+img+'.gif) no-repeat center center', 'cursor': 'default'})
			.blur()
		;
	});
 
	// Add title to nav items	
	$('#main-nav ul li').each(function() {
		$(this).prepend('<h3 class="ft-style2">'+$(this).find('a').html()+'</h3>')
	});
	
	// Add margin for each nav item
	$('#main-nav ul li:first').css('marginLeft', '12px');
	$('#main-nav ul li:eq(1)').css('marginLeft', '20px');
	$('#main-nav ul li:eq(2)').css('marginLeft', '30px');
	$('#main-nav ul li:eq(3)').css('marginLeft', '39px');
	$('#main-nav ul li:eq(4)').css('marginLeft', '35px');

	// "What is it?" box
	$('#nav-what').colorbox({
		width :'50%',
		height: '399px',
		inline: true,
		href: '#what-is-it'
	});
	
	// "Cool stuffs" box
	$('#nav-stuffs').colorbox({
		width: '50%',
		height: '447px',
		inline: true,
		href: '#cool-stuffs'
	});
	
	// "Nice tips" box
	$('#nav-tips').colorbox({
		width: '50%',
		height: '437px',
		inline: true,
		href: '#nice-tips'
	});
	
	// Alert box	
	$('#nav-api, #nav-strm').colorbox({
		width: '40%',
		height: '153px',
		inline: true,
		href: '#alert'
	});
	
	// Add "-" to the recent flinks	
	$('.scrollableArea p').append('<span class="ft-style3" style="margin-left: 5px;"> - </span>');
	
	// Add elements do scroll names in "Recent Flinks"
	$('#recent-flinks').prepend('<div class="scrollingHotSpotLeft"></div><div class="scrollingHotSpotRight"></div>');
	
	// Remove "-" into the last <p>
	if ($('.scrollableArea').width() <= 578)	
		$('.scrollableArea p:last span').remove();
	
	// Scroll recent flink
	$("div#recent-flinks")
		.smoothDivScroll({
			autoScroll: "always",
			autoScrollDirection: "endlessloopright",
			autoScrollStep: 1,
			autoScrollInterval: 25 
		})			
		.bind("mouseover", function(){
			$(this).smoothDivScroll("stopAutoScroll");
		})		
		.bind("mouseout", function(){
			$(this).smoothDivScroll("startAutoScroll");
		})
	;
	
	// Load tweets about TwitFlink
	$('#tf-tweets').twitterSearch({ 
  	bird:    false,
		pause:   true,
		animOut: { opacity: 1 },
		colorExterior: 'white', 
    colorInterior: 'white',
		term:  'twitflink', 
    timeout: 10000,
		birdLink:  'http://twitter.com/jquery'
	});
	
	// Append bird into footer
	$('footer').append('<div id="ft-bird"></div>');
	
	// Append div to style chat balloon
	$('#bird-msg').prepend('<div id="chat"></div>');
	
	// Add divs to give a fade effect on recent flinks	
	$('#recent-flinks').after('<div id="flinks-fade1"></div><div id="flinks-fade2"></div>');
	
	// Add a div to give a fade effect on tweets about TwitFlink 
	$('#tf-tweets').after('<div id="tf-tweets-fade1"></div><div id="tf-tweets-fade2"></div>');
	
  // Add rounded corners on chat balloon
	if ($.browser.name != 'msie')
		$('#bird-msg').addClass('rounded');
		
	// Add step bottom background
	$('#step-box').append('<div id="step-bottom"></div>'); 
	
	// Keyword field
	$('#keyword-form input').clearInput('Filter by keyword', '');
	
	// Tweet options
	$('.tweet-opt').hide();
	
	$('.tweet').live('mouseover mouseout', function(e) {
		if (e.type == 'mouseover')
    	$(this).find('.tweet-opt').show();
		else 
    	$(this).find('.tweet-opt').hide();
	});
	
	$('.tweet').each(function() {
		var info = $('.tweet-opt').attr('id').split('-');
		$(this).append('<div class="ask-tooltip">Hey, is this the link that you´re looking for? <span class="ft-style12"> > <a class="ft-style12 yes" href="http://twitter.com/share?url=http://twitter.com/'+info[0]+'/status/'+info[1]+'&text=Look at that! I´ve found this link from @'+info[0]+' on @TwitFlink">Yes</a></span><span class="ft-style12"> > <a href="#" class="ft-style12 no">No</a></span></div>');
	});
	
	// "Tweet found" Tooltip
	$('<div class="tooltip-bg"></div>').hide().appendTo('.tweet');
	$('.ask-tooltip').hide();
	
	// Open tooltip
	$('.tweet a.link-style').live('click', function() {
		$('.ask-tooltip, .tooltip-bg').fadeOut('slow');
		$(this)
			.parent()
				.parent()
					.find('.ask-tooltip, .tooltip-bg')
					.show('slow')
		;
	});
	
	// Link found
	$('.ask-tooltip .yes').live('click', function() {
		$(this).parent().parent()
		.html('That´s cool! <a href="'+$(this).attr('href')+'" class="ft-style12 tooltip-share">Let´s share it on Twitter?!</a>');
		return false;
	});
	
	$('.tooltip-share').live('click', function() {
		window.open($(this).attr('href'), 'Share link', "menubar=1,resizable=1,width=600,height=450");
		return false;	
	});
	
	// Close tooltip
	$('.ask-tooltip .no').live('click', function() {
		$('.ask-tooltip, .tooltip-bg').fadeOut('slow');
		return false;
	});
	
	// Retweet option
	$('.tweet-opt .rt').click(function() {
		window.open($(this).attr('href'), 'Retweet', "menubar=1,resizable=1,width=600,height=450");
		return false;
	});
	
	// Search next tweets button
	$('#next-bt').data({ n: 2 });
	$('#tweets').data({ 
		i: $('.tweet:last').length > 0 ? $('.tweet:last').attr('id') : 0,
		error: $('#tweets').find('#ajax-error').length > 0 ? true : false 
	});
	$('#next-bt').click(function() {
		var url = $('#next-bt').attr('href')+'/'+$('#next-bt').data('n');
		$.ajax({
			url: url,
			dataType: 'json',
			success: function(tweets) {
				var dhtml;
				if(tweets) {
					$.each(tweets, function(i, t) {
						dhtml += formatTweet(t);
					});
					if ($('#tweets').data('error')) $('#ajax-error').remove();
					$(dhtml).appendTo('#tweets');
					$('.ask-tooltip, .tweet-opt, .tooltip-bg').hide();
					var n = parseInt($('.tweet:last').attr('id'));
					var text = 'Look at that! I´ve got <strong class="ft-style12">'+n+' link';
					text += n > 1 ? 's' : '';
					text += '</strong> for you. I´m really smart, don´t you think?';
					$('#msg').html(text);
					$('#tweets').data({ i: n, error: false });
					text = $('#username').text()+' - '+n+' link';
					text += n > 1 ? 's ' : ' ';
					text += 'about '+$('#keyword').text()+' on TwitFlink';				 
					$('title').html(text);
				} else {
					dhtml = '<p class="ft-style12" id="ajax-error">Oops! We didn´t find any tweet containing this keyword, try to search older ones.</p>';
					if (!$('#tweets').data('error'))
						$('#tweets').append(dhtml).data('error', true);
				}
				$('#next-bt').data({ n: parseInt($('#next-bt').data('n')) + 1 });
			}
		});
		return false;
	});
		
  $("#ajax-loader").hide().ajaxStart(function(){
    $('#next-bt').hide();
	  $(this).fadeIn('slow');
  }).ajaxStop(function() {
  	$('#next-bt').show();
	  $(this).hide();
	});
 
		
});


/*
 * @function formatLinks
 * @abstract Insert URLs, usernames and hashtags into <a>.
 * @param text string - Text to be formated.   
 */
function formatLinks(text) {
	var attr = 'class="link-style" target="_blank"';
  text = text.replace(/([a-z]+:\/\/[^\s]+[a-z0-9]+\/?)/gi, "<a href=\"$1\" "+attr+">$1</a>");
	text = text.replace(/@(\w+)/gi, "<a href=\"http://twitter.com/$1\" "+attr+">$&</a>")
	return text.replace(/#(\w+)/gi, "<a href=\"http://twitter.com/search?q=%23$1\" "+attr+">$&</a>") 
}

/*
 * @function formatTweet
 * @abstract Create HTML to append tweets in the document.
 * @param t object - Object containing the informations from tweet.   
 */
function formatTweet(t) {
	var i = parseInt($('#tweets').data('i')) + 1;
	$('#tweets').data({ i: i });
	var dhtml = '<!-- Tweet -->';
	dhtml += '<div class="tweet new-twt" id="'+i+'">' ;
	dhtml += '  <p class="tweet-text">';
	dhtml += '    <span class="ft-style1">'+i+'.</span> ';
	dhtml += '    <span class="date">'+t.created_at+'</span> - '+formatLinks(t.text);
	dhtml += '  </p>';
	dhtml += '  <p class="tweet-opt opt-style" id="'+$('#username').text()+'-'+t.id+'">';
	dhtml += '    <a href="http://twitter.com/?status=RT '+t.text+'" class="rt">Retweet</a>';
	dhtml += '    <a href="http://twitter.com/#!/'+$('#username').text()+'/status/'+t.id+'" class="view" target="_blank">View tweet</a>';
	dhtml += '  </p>';
	dhtml += '  <div class="ask-tooltip">';
	dhtml += '    Hey, is this the link that you´re looking for? <span class="ft-style12"> > <a href="http://twitter.com/share?url=http://twitter.com/'+$('#username').text()+'/status/'+t.id+'&text=Look at that! I´ve found this link from @'+$('#username').text()+' on @TwitFlink" class="ft-style12 yes">Yes</a></span><span class="ft-style12"> > <a href="#" class="ft-style12 no">No</a></span>';
	dhtml += '  </div>';
	dhtml += '  <div class="tooltip-bg"></div>';
	dhtml += '</div>';
	dhtml += '<!-- [END] Tweet -->';
	return dhtml;
}

/*
 * @function clearInput
 * @abstract Clear the value of an input when it is focused.
 * @param initVal string - Initial input value.   
 */
(function($){
	$.fn.clearInput = function(initVal, val) {
    return this
      .focusin(function() {
        if ($.trim(this.value) == initVal) {
          this.value = val;
        }
      })
      .focusout(function() {
        if ($.trim(this.value) == '' || $.trim(this.value) == val) {
          this.value = initVal;
        }
      });
  };
})(jQuery);
