jQuery(function(){
	jQuery('a[rel=external]').attr('target','_blank');

	/* Background */
	$('#wrap').scroll(function(){
		var x = $(this).scrollTop();		
		$(this).css({'background-position' : 'center '+ parseInt(84 + (-x / 5)) + 'px'});
		$('#background').css({'background-position' : 'center '+ parseInt(-x / 2) + 'px'});
	});
	
	/* Escolher loja */
	$('#header .choose-store').click(function(){
		$(this).fadeOut('fast', function(){
			$(this).remove();
		});
	});
	
	/* Slider */
	$('#slider').cycle({
		fx: 'scrollVert',
		prev: '#slider-next',
		next: '#slider-prev',
		timeout: 3000
	});
	
	$('.it-pictures ul').cycle({
		fx: 'scrollVert',
		prev: '.it-pictures .next',
		next: '.it-pictures .prev',
		timeout: 3000
	});
	
	/* Twitter feed */
	$('.twitter-feed .next').click(function(){
		$('.twitter-feed li:first').fadeOut(300, function(){
			$(this).next().hide().fadeIn(300);
			$(this).appendTo('.twitter-feed ul').show();
		});
		return false;
	});
	$('.twitter-feed .prev').click(function(){
		$('.twitter-feed li:first').fadeOut(300, function(){
			$('.twitter-feed li:last').prependTo('.twitter-feed ul').hide().fadeIn(300);
			$(this).show();
		});
		return false;
	});
	
	/* Blog feed */
	$('.feat .dsh-blog').hover(function(){
		$(this).find('p').slideUp();
	},function(){
		$(this).find('p').slideDown('fast');
	});
	
	/* Menu */
	$('#nav a').hover(function(){
		$(this).stop().animate({backgroundColor : '#F1F1F1'});
	},function(){
		$(this).stop().animate({backgroundColor : '#FFF'}, 'fast');
	});
	$('#nav .active a').hover(function(){
		$(this).stop().animate({backgroundColor : '#F1F1F1'});
	},function(){
		$(this).stop().animate({backgroundColor : '#F1F1F1'}, 'fast');
	});
	
	/* Menu blog */
	$('#blog #nav a').hover(function(){
		$(this).stop().animate({backgroundColor : '#F1F1F1'});
	},function(){
		$(this).stop().animate({backgroundColor : '#FFF'}, 'fast');
	});
	$('#blog #nav .active a').hover(function(){
		$(this).stop().animate({backgroundColor : '#F1F1F1'});
	},function(){
		$(this).stop().animate({backgroundColor : '#F1F1F1'}, 'fast');
	});
	
	/* Ju Santos */
	$('.feat .ju-santos').hover(function(){
		$(this).find('h3').fadeIn();
	}, function(){
		$(this).find('h3').fadeOut();
	});
	
	/* Contato */
	$('body').not('#contato .setor, .choose-event').click(function(){
		$('#contato .setor ul, .choose-event ul').slideUp('fast');
	});
	
	/* Selects */
	$('#contato .setor a, .choose-event a').click(function(e){
		if( $(this).next().is(':hidden') == true ) {
			$(this).next().slideDown();
		} else {
			$(this).next().slideUp();
		};
		e.stopPropagation();
	});
	
	$('#contato .setor li, .choose-event li').click(function(){
		var setor = $(this).text();
		$(this).parent().parent().find('a').text(setor);
		$(this).parent().slideUp('fast');
	});
	
	/* Banner das Marcas */
	function rotate(){
		$('.feat .banner .ad-wrap:first').fadeOut(500, function(){
			$(this).next().hide().fadeIn(300);
			$(this).appendTo('.feat .banner').show();
		});
	};
	
	setInterval(rotate, 3000);
	
	/* IT Pictures */
	var itImg =  $('.it-pictures li').length;
	
	if(itImg > 1 ){
		$('.it-pictures a').addClass('active');
		
		$('.it-pictures .next').click(function(){
			$('.it-pictures li:first').appendTo('.it-pictures ul');
			return false;
		});
		$('.it-pictures .prev').click(function(){
			$('.it-pictures li:last').prependTo('.it-pictures ul');			
			return false;
		});
	} else {
		$('.it-pictures a').click(function(){
			return false;
		});
	};
	
	/* About IT Pictures */
	var itImg =  $('.about-slider li').length;
	
	if(itImg > 1 ){
		$('.about-slider a').addClass('active');
		
		$('.about-slider .next').click(function(){
			$('.about-slider li:first').fadeOut(300, function(){
				$(this).next().hide().fadeIn(300);
				$(this).appendTo('.about-slider ul').show();
			});
			return false;
		});
		$('.about-slider .prev').click(function(){
			$('.about-slider li:first').fadeOut(300, function(){
				$('.about-slider li:last').prependTo('.about-slider ul').hide().fadeIn(300);
				$(this).show();
			});
			return false;
		});
	} else {
		$('.about-slider a').click(function(){
			return false;
		});
	};
	
	/* Clear forms */
	(function($){
		$.fn.clearDefault = function(){
			return this.each(function(){
				var default_value = $(this).val();
				$(this).focus(function(){
					if ($(this).val() == default_value) $(this).val("");
				});
				$(this).blur(function(){
					if ($(this).val() == "") $(this).val(default_value);
				});
			});
		};
	})(jQuery);
	
	$('.clear-text').clearDefault();
});

function remove(str, strToRemove) {
   i = str.indexOf(strToRemove);
   r = "";
   if (i == -1) return str;
   r += str.substring(0,i) + remove(str.substring(i + strToRemove.length), strToRemove);
   return r;
}

function validateEmail(email) {
	var ret = false;
	var em = new String();
	em = String(email);
	var RegExPattern = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{ 1,3}){3}\])$/; 
	if ( em.match(RegExPattern) ) {
		ret = true;
	}
	return ret;
}

function trim(str){
	if (typeof(str) == "string") {
		return str.replace(/^\s+|\s+$/g,"");
	} else {
		return str;
	}	
}

function maskFormat(mask,obj){
	if(obj.value != ""){
		sObj = obj.value.toString();
		nString = "";
		for(i=0;i<(sObj.length);i++){
			if(!isNaN(sObj.charAt(i)) && (sObj.charAt(i) != " ")) {
				nString = nString + sObj.charAt(i);
			}
		}
		j = 0;
		k = 0;
		mString = "";
		while(j < nString.length && k < mask.length){
			if(mask.charAt(k).toUpperCase() == "N"){
				mString = mString + nString.charAt(j);
				j = j+1;
			} else {
				mString = mString + mask.charAt(k);
			}
			k = k+1;
		}
		obj.value = mString;
	}
}

function validarCPF(cpf){
	var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
	if(!filtro.test(cpf)){
		return false;
	}
	cpf = remove(cpf, ".");
	cpf = remove(cpf, "-");
	if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
		cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
		cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
		cpf == "88888888888" || cpf == "99999999999"){
			return false;
	}
	soma = 0;
	for(i = 0; i < 9; i++)
		soma += parseInt(cpf.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if(resto == 10 || resto == 11)
		resto = 0;
	if(resto != parseInt(cpf.charAt(9))){
		return false;
	}
	soma = 0;
	for(i = 0; i < 10; i ++)
		soma += parseInt(cpf.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if(resto == 10 || resto == 11)
		resto = 0;
	if(resto != parseInt(cpf.charAt(10))){
		return false;
	}
	return true;
}

function entraNoEdit(obj, txt) {
	if ($.trim(obj.value) == txt) {
		obj.value =	"";
	}
}
function saiDoEdit(obj,	txt) {
	if ($.trim(obj.value) == "") {
		obj.value =	txt;
	}
}

function getEndereco(cep) {
	var arrCep = new Array();
	var cepLimpo = $.trim(cep);
	cepLimpo = cepLimpo.replace("-","");
	if(cepLimpo != ""){
		$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep=" + cepLimpo, function(){
			if(resultadoCEP["resultado"]){
				var txtLogradouro = ($.trim(unescape(resultadoCEP["tipo_logradouro"]) + " " + unescape(resultadoCEP["logradouro"])));
				var txtBairro = (unescape(resultadoCEP["bairro"]));
				var txtCidade = (unescape(resultadoCEP["cidade"]));
				var slEstado = (unescape(resultadoCEP["uf"]));
				arrCep.push(txtLogradouro);
				arrCep.push(txtBairro);
				arrCep.push(txtCidade);
				arrCep.push(slEstado);
			}
		});				
	}
	return arrCep;
}

function validateUrl(txt) {
	var urlRegxp = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([\w]+)(.[\w]+){1,2}$/;
	if ((txt.match(urlRegxp)) && (trim(txt!=''))) {
		return true;
	} else {
		return false;
	}
}

function setGoogleAnalitics(tag) {
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
	try {
		var pageTracker = _gat._getTracker(tag);
		pageTracker._trackPageview();
	} catch(err) {}
}

_send_contact = function() {
	var name = $("#name");
	var email = $("#email");
	var sector = $(".setor a");
	var message = $("#message");
	var err_found = false;
	var err_str = "<strong>Verifique os seguintes erros abaixo:</strong><br /><br />";
	
	$('div.msg').html('enviando...');
	
	if (name.val() == "") {
		err_str += '- Por favor preencha o nome<br />';
		err_found = true;
	}
	
	if (!validateEmail(email.val())) {
		err_str += '- Por favor preencha o e-mail corretamente<br />';
		err_found = true;
	}
	
	if (sector.text() == "Selecione") {
		err_str += '- Por favor escolha o setor<br />';
		err_found = true;
	}
	
	if (message.val() == "") {
		err_str += ' - Por favor preencha a mensagem<br />';
		err_found = true;
	}
	
	if (err_found) {
		$('div.msg').html(err_str);
		
		return false;
	}
	
	$.ajax({
		type: "POST",
		url: "send_contact.php",
		data: $('form').serialize() + '&sector=' + sector.text(),
		success: function(msg){
			if (trim(msg) == "1") {
				$('form').get(0).reset();
				$('div.msg').html('Sua mensagem foi enviada com sucesso.');
			} else {
				$('div.msg').html('Ocorreu um erro inesperado. Tente novamente mais tarde.');
			}
		}
	});
	
	return false;
};

_sign_newsletter = function() {
	var name = $("#newsletter-name");
	var email = $("#newsletter-email");

	var err_found = false;
	var err_str = "Preencha os campos corretamente.";
	var suc_str = "E-mail cadastrado com sucesso.";
	
	$('div.msg').html('enviando...');

	if (name.val() == "" || name.val() == "Digite seu nome") {
		err_found = true;
	}
	
	if (!validateEmail(email.val()) || email.val() == "Digite seu e-mail") {
		err_found = true;
	}

	if (err_found) {
		$('#newsletter span').html(err_str);
		return false;
	}
	
	$.ajax({
		type: "POST",
		url: "sign_newsletter.php",
		data: $('#newsletter').serialize(),
		success: function(msg){
			if (trim(msg) == "1") {
				$('form').get(0).reset();
				$('#newsletter span').html(suc_str);
			} else {
				$('#newsletter span').html(err_str + ".");
			}
		}
	});
	
	return false;
};


_send_comment = function(){
	var name = $("#txtNome");
	var email = $("#txtMail");
	var comment = $("#txtComment");
	var err = false;
	var str = '<p>Verifique novamente o preenchimento do(s) seguinte(s) campo(s):<em>';
	
	$('#comment-err').html('enviando...');
	
	if (name.val() == "Nome" || name.val() == "") {
		str += 'Nome';
		err = true;
	};
	
	if (!validateEmail(email.val())) {
		if (err) {
			str += ', ';
		};
		str += 'E-mail';
		err = true;
	};
	
	if (comment.val() == "Deixe suas impressões" || comment.val() == "") {
		if (err) {
			str += ', ';
		};
		str += 'Deixe suas impressões';
		err = true;
	};
	
	str += '</em></p>';
	
	if (err) {
		$('#comment-err').html(str);
	} else {
		$.ajax({
			type: "POST",
			url: "comment.php",
			data: $('form').serialize(),
			success: function(msg){
				if (trim(msg) == "1") {
					$('#leave-comment').get(0).reset();
					$('#comment-err').html('<p>O comentário foi incluído, aguarde a moderação.</p>');
				} else {
					$('#comment-err').html('Ocorreu um erro inesperado. Tente novamente mais tarde.');
				}
			}
		});
	};
	
	return false;
};

/* twitter*/

/*
1 - From a user
2 - Mentioning a user
3 - Replying to a user
4 - Containing a word
5 - Containing a hashtag
*/
var _key; 
var _atualize; 
var _timeout;
var _tammax;
var _nohRetorno;
var _option;

function Twitter(key, atualize, timeout, tammax, nohRetorno, option) {
	_key = key;
	_atualize = atualize;
	_timeout = timeout;
	_tammax = tammax;
	_nohRetorno = nohRetorno;
	_option = option;
	execute();
}

function execute() {
	if (this._atualize) {
		setInterval('_updateTwitts();', _timeout * 1000);
	}
	_updateTwitts();
}

function _updateTwitts() {
	var s = "<scr"+"ipt src=\"http://search.twitter.com/search.json?callback=_up"+_option+"&";
	switch(_option)
	{
		case 1:
			s += "q=from:"+ _key;
			break;
		case 2:
			s += "q=%40"+ _key;
			break;
		case 3:
			s += "q=to:"+ _key;
			break;
		case 4:
			s += "q="+ _key;
			break;
		case 5:
			s += "q=%23"+ _key;
			break;
		default:
	} 
	s += "&c="+Math.random()+"\"></scr"+"ipt>";
	$("head").append(s);
}

function _up1(d){
	var t = "";
	if (d.results) {
		var tamlst = d.results.length;
		var max = _tammax;
		if (tamlst < max) {
			max = tamlst;
		}
		for (var ix=0;ix<max;ix++) {
			t += '<li>';
			t += _getLink(d.results[ix]['text']);
			t += '</li>';
		}
	}
	$("#"+_nohRetorno).html(t);
	$('a[rel=external]').attr('target','_blank');
}

function _up2(d){
	var t = "";
	if (d.results) {
		var tamlst = d.results.length;
		var max = _tammax;
		if (tamlst < max) {
			max = tamlst;
		}
		for (var ix=0;ix<max;ix++) {
			t += "<li>";
			t += "<div>";
			t += "<a href=\"http://twitter.com/"+d.results[ix]['from_user']+"\" rel=\"external\"><img src=\""+d.results[ix]['profile_image_url']+"\" /></a> ";
			t += "<strong><a href=\"http://twitter.com/"+d.results[ix]['from_user']+"\" rel=\"external\">@"+d.results[ix]['from_user']+"</a></strong> ";
			t += _getLink(d.results[ix]['text']);
			t += "<span>"+_formatDateTw(d.results[ix]['created_at'])+"</span>";
			t += "</div>";
			t += "</li>";
		}
	}
	$("#"+_nohRetorno).html(t);
	/*$('a[rel=external]').attr('target','_blank');*/
}

function _up3(d){
	var t = "";
	if (d.results) {
		var tamlst = d.results.length;
		var max = _tammax;
		if (tamlst < max) {
			max = tamlst;
		}
		for (var ix=0;ix<max;ix++) {
			t += "<li>";
			t += "<div>";
			t += "<a href=\"http://twitter.com/"+d.results[ix]['from_user']+"\" rel=\"external\"><img src=\""+d.results[ix]['profile_image_url']+"\" /></a> ";
			t += "<strong><a href=\"http://twitter.com/"+d.results[ix]['from_user']+"\" rel=\"external\">@"+d.results[ix]['from_user']+"</a></strong> ";
			t += _getLink(d.results[ix]['text']);
			t += "<span>"+_formatDateTw(d.results[ix]['created_at'])+"</span>";
			t += "</div>";
			t += "</li>";
		}
	}
	$("#"+_nohRetorno).html(t);
	/*$('a[rel=external]').attr('target','_blank');*/
}

function _up4(d){
	var t = "";
	if (d.results) {
		var tamlst = d.results.length;
		var max = _tammax;
		if (tamlst < max) {
			max = tamlst;
		}
		for (var ix=0;ix<max;ix++) {
			t += "<li>";
			t += "<div>";
			t += "<a href=\"http://twitter.com/"+d.results[ix]['from_user']+"\" rel=\"external\"><img src=\""+d.results[ix]['profile_image_url']+"\" /></a> ";
			t += "<strong><a href=\"http://twitter.com/"+d.results[ix]['from_user']+"\" rel=\"external\">@"+d.results[ix]['from_user']+"</a></strong> ";
			t += _getLink(d.results[ix]['text']);
			t += "<span>"+_formatDateTw(d.results[ix]['created_at'])+"</span>";
			t += "</div>";
			t += "</li>";
		}
	}
	$("#"+_nohRetorno).html(t);
	/*$('a[rel=external]').attr('target','_blank');*/
}

function _up5(d){
	var t = "";
	if (d.results) {
		var tamlst = d.results.length;
		var max = _tammax;
		if (tamlst < max) {
			max = tamlst;
		}
		for (var ix=0;ix<max;ix++) {
			t += "<li>";
			t += "<div>";
			t += "<a href=\"http://twitter.com/"+d.results[ix]['from_user']+"\" rel=\"external\"><img src=\""+d.results[ix]['profile_image_url']+"\" /></a> ";
			t += "<strong><a href=\"http://twitter.com/"+d.results[ix]['from_user']+"\" rel=\"external\">@"+d.results[ix]['from_user']+"</a></strong> ";
			t += _getLink(d.results[ix]['text']);
			t += "<span>"+_formatDateTw(d.results[ix]['created_at'])+"</span>";
			t += "</div>";
			t += "</li>";
		}
	}
	$("#"+_nohRetorno).html(t);
	/*$('a[rel=external]').attr('target','_blank');*/
}

function _formatDateTw(time){
	var timeAtual = (new Date()).getTime();
	var date = new Date(time);
	var timeTw = date.getTime();
	var diff = ((timeAtual - timeTw) / 1000);
	var 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";
}

function _getLink(str) {
	var strFinal = "";
    var regExpUrl = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
    var regExpTwt = /[\@]+([A-Za-z0-9-_]+)/gi;
    var regExpTag = /(?:^| )[\#]+([A-Za-z0-9-_]+)/gi;
	var regExpEmail = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{ 1,3}){3}\])$/;
	var arrStr = str.split(' ');
	for (var i=0;i<arrStr.length;i++) {
		var parte = arrStr[i];
		parte = parte.replace(regExpUrl,"<a href=\"$1\" rel=\"external\">$1</a>");
		if (regExpEmail.test(parte))
		{
			parte = parte.replace(parte,"<a href=\"mailTo:"+parte+"\" rel=\"external\">"+parte+"</a>");
		}
		else
		{
			parte = parte.replace(regExpTwt,"<a href=\"http://twitter.com/$1\" rel=\"external\">@$1</a>");
		}
		parte = parte.replace(regExpTag,"<a href=\"http://search.twitter.com/search?q=&tag=$1\" rel=\"external\">#$1</a>");
		
		
		strFinal += parte + " ";
    }
	return strFinal;
}
/**/
