/**
 * @author Bruno Germano
 */
String.prototype.link = function(str,opt){
	aux = "";
	if(!opt)
		return "<a href='"+ str +"'>" + this + "</a>"
	else{
		if(opt.nofollow)
			aux += " rel='nofollow' "
		if(opt.newWindow)
			aux += " target='_blank' "
		if(opt.className)
			aux += " class='" + opt.className + "' "
			
		return "<a href='"+ str +"'" + aux + ">" + this + "</a>"
	}	
}

// Prototipação para criar links do twitter
String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) {
		var options = {nofollow:true, newWindow: true};
		return url.link(url, options);
	});
};
String.prototype.parseUsername = function() {
	return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
		var username = u.replace("@","")
		var options = {nofollow:true, newWindow: true};
		return u.link("http://twitter.com/"+username, options);
	});
};

String.prototype.parseHashtag = function() {
	return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
		var tag = t.replace("#","%23")
		var options = {nofollow:true, newWindow: true};
		return t.link("http://search.twitter.com/search?q="+tag, options );
	});
};
 
 
jQuery(document).ready(function($) {
	var hoverAnim = {
		 init: function() {
			 var project = $('#items li.campanha, li.produto');
			 var projectTxt = project.children('.hover');
			
			 project.children('.hover').css({left: '0px'})
			 project.children().children('.hover-bg').fadeTo(1, 0.0)
			 project.children().children('.hover-content').css({left: '237px'})
			
			 project.hover(
				 function () {
					 $(this).children().children('.hover-content').css({left: '237px'});
					 $(this).children('.hover-bg').stop().fadeTo(600, 0.9);
					 $(this).children().children('.hover-content').stop().animate({left: '0px'} , { queue: false, duration: 450, easing: 'easeOutQuint' });
				 },
				 function () {
					 $(this).children('.hover-bg').stop().fadeTo(800 , 0.0);
					 $(this).children().children('.hover-content').stop().animate({left: '-237px'} , { queue: false, duration: 300, easing: 'easeOutQuint' });
				 }
		 	 );
		
		 }
	};
	hoverAnim.init(); 

});

//Carrossel de Produtos
function mycarousel_initCallback(carousel) {
	$('.sorvetes a.nav.proximo').bind('click', function() {
        carousel.next();
        return false;
    });
 
    $('.sorvetes a.nav.anterior').bind('click', function() {
        carousel.prev();
        return false;
    });
};


//Carrossel de tweets
function tweetCarousel_initCallback(carousel) {
	$('.twitter a.nav.proximo').bind('click', function() {
        carousel.next();
        return false;
    });
 
    $('.twitter a.nav.anterior').bind('click', function() {
        carousel.prev();
        return false;
    });
};


$(document).ready(function($) {
    $("#tweets").jcarousel({
        scroll: 1,
        wrap: 'circular',//torna o carrossel infinito..
        easing: 'easeOutQuint',
        initCallback: tweetCarousel_initCallback,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
    
    $("#carrossel-sorvetes").jcarousel({
        scroll: 1,
        wrap: 'circular',//torna o carrossel infinito..
        easing: 'easeOutQuint',
        initCallback: mycarousel_initCallback,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
    
    $('.hover-content').each(function(){
    	var p_height = $(this).parent().innerHeight() - $(this).outerHeight();
    	$(this).css('margin-top', (p_height/2) + 'px');
    });
});

// Build tweets para contruir a lista
function buildTweet (tweet){
	var from = document.createElement('div');
	var msg = document.createElement('div');
	var date = document.createElement('div');
	
	//from user
	from.className = 'from';
	from.innerHTML ="TWITTER — @" + tweet.user.screen_name;
	
	//message
	msg.className = 'mensagem';
	msg.innerHTML =  tweet.text;
	
	//date from menssage
	var data = new Date(Date.parse(tweet.created_at)).toLocaleDateString();
    var hora = new Date(Date.parse(tweet.created_at)).toLocaleTimeString();
    var tweetDate = new Date(data + ' ' + hora);
    var today = new Date();
    
    var diff = (today.getTime()-tweetDate.getTime());
    var dataText = '';
    
    if(diff<(1000*60*60*24)){
    	if(diff<(1000*60*60)){
    		var minutos = Math.floor(diff/(1000*60))
    		if(minutos <= 1)
    			dataText = 'agora';
    		else{
    			dataText = minutos.toString() + ' minutos atrás'
    		}
    	}else{
    		var horas = Math.floor(diff/(1000*60*60))
    		dataText = horas.toString() + (horas==1?' hora atrás':' horas atrás');	
    	}
    }else{
    	var dias = Math.floor(diff/(1000*60*60*24))
    	if(dias==1){
    		dataText = 'ontem';
    	}else{
    		dataText = dias.toString() + ' dias atrás';	
    	}
    }
    date.className = 'data';
    date.innerHTML = dataText;
	
	var div = document.createElement('div');
	
	div.appendChild(from);
	div.appendChild(msg);
	div.appendChild(date);
	
	return div.innerHTML;
}

var old_class = '';

$(document).bind("estruturaLoaded", function(){
	//trackers twitter
	$('#tweets .tweet .from a').click(function(){estrutura.trackEvents('home', 'twitter-kibonbr');});
	
	//tracker campanha
	$($('#items .item.campanha')[0]).find('.botao a').click(function(){ var titulo = $($('#items .item.campanha')[0]).find('.titulo a p').html(); estrutura.trackEvents('home', 'destaque-box1-['+titulo+']' );});
	$($('#items .item.campanha')[1]).find('.botao a').click(function(){ var titulo = $($('#items .item.campanha')[1]).find('.titulo a p').html(); estrutura.trackEvents('home', 'destaque-box2-['+titulo+']' );});
	
	//tracker produtos
	$($('#items .item.produto')[0]).find('.botao a').click(function(){ var titulo = $($('#items .item.produto')[0]).find('.titulo a p').html(); estrutura.trackEvents('home', 'destaque-box3-['+titulo+']' );});
	$($('#items .item.produto')[1]).find('.botao a').click(function(){ var titulo = $($('#items .item.produto')[1]).find('.titulo a p').html(); estrutura.trackEvents('home', 'destaque-box4-['+titulo+']' );});
	
	//trackers adcast
	$('#adcast ul li a span').click(function(){ estrutura.trackEvents('home', 'destaque['+$.trim($(this).parent().parent().find('.titulo').html().replace(/&[^;]+;/g, ''))+']');});
	
	
	
	//tracker carrossel de sorvetes
	$('#carrossel-sorvetes li a').click(function(){estrutura.trackEvents('home', 'imagem_produto');});
	
	$('#adcast li').each(function(){
		$(this).attr('bg', $(this).css('background-image'));
		$(this).css('background','transparent');
		$(this).css('background-color','transparent'); 
	});
	
	_adcast.onBefore = function(){
		var _this = this;
		
		var classBody = $(_this).attr('rel');
				
		$('body').attr('class','');
				
		if($(_this).hasClass('cor-menu-vermelho')){
			$('body').addClass('menu-vermelho');
		}else{
			$('body').addClass('menu-branco');
		}
		
		if(classBody) {
			$('body').addClass(classBody);
			$('body').removeClass(old_class);
			old_class = classBody;
		}
		
		$(this).css('background','transparent');
		$(this).css('background-color','transparent'); 
		
		$('#bg .mask').fadeIn({duration:400,  easing: 'easeOutQuint', complete: function(){
			if(!$(_this).attr('bg'))
			{
				$('#bg').css({
					'background-image': $(_this).css('background-image')
				});
				
				$(_this).attr('bg', $(_this).css('background-image')); 
				$(_this).css('background','none'); 
			}
			else
			{
				$('#bg').css({
					'background-image': $(_this).attr('bg')
				});
			}
		}});
	}
	
	_adcast.onAfter = function(){
		$('#bg .mask').fadeOut({duration:400, easing: 'easeOutQuint'});
	}
});

