/*
 *Created by Foster Web Solutions 
 *Web sites, Webdesign, E-commerce, E-Business, Internet Marketing
 *http://www.foster.com.br
*/

//verifico qual navegador
var IE = (navigator.userAgent.indexOf("MSIE") > -1);

$(function(){
	//faço a transparência pro IE 5 IE 6.
	$(document).ready(function(){
		$('#controlaLinks li a').pngFix();
	});
	
	//corrige bug no chrome
	$(document).ready(function(){
		$('body').css('height','100%');
	});
		
	//FAZ O OVER DO MENU SUPERIOR
	$('.menuAbas .primeiroNivel').hover(
		function(){
			var indice = $('.menuAbas li').index(this);
			
			if('0' == indice & this.className != 'SuperiorMarcado'){
				$(this).css('background-position','left 0px');
				$(this).find('a:first').css('background-position','left 0px');
				$(this).find('.subMenu').css('visibility','visible');
				zIndex();
			}
			if('5' == indice & this.className != 'SuperiorMarcado') {
				$(this).css('background-position','right 0px');
				$(this).find('a:first').css('background-position','left 0px');	
				$(this).find('.subMenu').css('visibility','visible');
				zIndex();
			}
			if(indice != '5' & indice != '0' & this.className != 'SuperiorMarcado'){
				$(this).css('background-position','right 0px');
				$(this).find('a:first').css('background-position','right 0px');	
				$(this).find('.subMenu').css('visibility','visible');
				zIndex();
			}
		},
		function(){
			
			var indice = $('.menuAbas li').index(this);
			
			if('0' == indice & this.className != 'SuperiorMarcado'){
				$(this).css('background-position','right -30px');
				$(this).find('a:first').css('background-position','left -30px');
				$(this).find('.subMenu').css('visibility','hidden');
				tiraZIndex();
			}
			if('5' == indice & this.className != 'SuperiorMarcado') {
				$(this).css('background-position','right -30px');
				$(this).find('a:first').css('background-position','left -30px');	
				$(this).find('.subMenu').css('visibility','hidden');
				tiraZIndex();
			}
			if(indice != '5' & indice != '0' & this.className != 'SuperiorMarcado2'){
				$(this).css('background-position','right -30px');
				$(this).find('a:first').css('background-position','right -30px');
				$(this).find('.subMenu').css('visibility','hidden');
				tiraZIndex();
			}
		}
	)
	function zIndex(){
		$('#container').css('z-index','-1');
		$('#containerHome').css('z-index','-1');
	}
	function tiraZIndex(){
		$('#container').css('z-index','0');
		$('#containerHome').css('z-index','0');
	}
	
	
	//retiro o value dos inputs
	$('#campoBusca').resetDefaultValue(); // for all input elements
	//$('input').resetDefaultValue(); // for some elements
	//$('textarea').resetDefaultValue(); // work with textarea too
	
	$('#controlaLinks li').hover(
		function(){
			var img = $(this).find('img').attr('src').split('.').join('-over.');
			$(this).find('img').attr('src',img);
		},
		function(){
			var img = $(this).find('img').attr('src').split('-over.').join('.');
			$(this).find('img').attr('src',img);
		}
	);
	
	
	var opcoes = $('#listaLinks ul li a');
	for(var i = 0; i < niveis.length; i++)
	{
		for(var a = 0; a < opcoes.length; a++)
		{
			if(opcoes[a].id == niveis[i])
			{
				$(opcoes[a]).css('font-weight','bold');
			}
		}
	}
	
	var endereco1 = "produtos.asp,revenda.asp,residenciais.asp,canais.asp,downloads.asp,assistencia-tecnica.asp";
	endereco1 = endereco1.toLowerCase().split(',');
	var url = location.pathname;
	url = url.toLowerCase().split('/');
	
	for(var i=0; i< endereco1.length; i++){
		for(var k=0; k< url.length; k++){
			if(url[k] == endereco1[i]){
				$('#menuLateral #premiosLateral').addClass('teste');
				$('#menuLateral #premiosLateral').css('display','none');
			}	
		}
	}
	
	var endereco2 = "revenda.asp,canais.asp";
	endereco2 = endereco2.toLowerCase().split(',');
	
	for(var i=0; i< endereco2.length; i++){
		for(var k=0; k< url.length; k++){
			if(url[k] == endereco2[i]){
				$('#menuLateral #certificadosLateral').css('display','none');
			}	
		}
	}
});

/*plugin faço o reset do pesquisar*/
jQuery.fn.resetDefaultValue = function() {
	function _clearDefaultValue() {
		var _$ = $(this);
		if ( _$.val() == this.defaultValue ) { _$.val(''); }
	};
	function _resetDefaultValue() {
		var _$ = $(this);
		if ( _$.val() == '' ) { _$.val(this.defaultValue); }
	};
	return this.click(_clearDefaultValue).focus(_clearDefaultValue).blur(_resetDefaultValue);
}

//FUNCÃO DO MENU 
var niveis = location.pathname.split("/");
$(function(){
	try{
		
		var lisSuperior = $('.menuAbas li');
		var linksSuperior = $('.menuAbas li a');
		
		var divContainer = $('#lateral');
		var divs = $('#lateral div');
		var ulsLateral = $('#lateral div ul');
		var linksLateral = $('#lateral div ul li a');
		
		
		for(var i=0; i<niveis.length; i++){
			
			for(var a = 0; a < linksSuperior.length; a++)
			{
				if(linksSuperior[a].id == niveis[i] && (niveis[i] != ''))
				{
					//meu background é diferente dos demais do topo
					if(niveis[i] == 'imprensa'){
						$(lisSuperior[a]).addClass('SuperiorMarcado2');
						$(linksSuperior[a]).addClass('SuperiorMarcado2');	
					}
					else{
						$(lisSuperior[a]).addClass('SuperiorMarcado');
						$(linksSuperior[a]).addClass('SuperiorMarcado');
					}
				}
			}
			for(var c=0; c<divs.length; c++){
				
				if((niveis[i] == divs[c].className) && (niveis[i] != '')){
					$(divs[c]).css('display','block');
					$(divContainer).css('display','block');
				}
			}
			
			for(var c = 0; c < ulsLateral.length; c++){
				if(ulsLateral[c].className == niveis[i])
				{
					$(ulsLateral[c]).css('display','block');
				}
			}
			
			for(var b = 0; b < linksLateral.length; b++){
				if(linksLateral[b].id == niveis[i])
				{
					$(linksLateral[b]).addClass('lateralMarcada');
				}
			}	
		}	
	}
	catch(e){};
});

/* TIRA A BORDA DOS FLASHS
Copyright 2006 Adobe Systems, Inc. All rights reserved.
Versão compacta, alterada por Renato Herculano
	- src, width e height são obrigatórios
	- os demais parametros são opcionais
*/
function flash(src, width, height, id, flashVars, wmode, menu, scale){
	var ret = GetArgumentos(src, width, height, id, flashVars, wmode, menu, scale);
	var str = '<object ';
	for (var i in ret.objAttrs)
		str += i + '="' + ret.objAttrs[i] + '" ';
		str += '>';
	for (var i in ret.params)
		str += '<param name="' + i + '" value="' + ret.params[i] + '" /> ';
		str += '</object>';
	document.write(str);
}

function GetArgumentos(src, w, h, id, flashVars, wmode, menu, scale){
	var ret = new Object();
	ret.params = new Object();
	ret.objAttrs = new Object();

	ret.objAttrs['data'] = ret.params["movie"] = src;
	ret.objAttrs['width'] = w;
	ret.objAttrs['height'] = h;
	ret.params['quality'] = 'high';
	ret.objAttrs['type'] = 'application/x-shockwave-flash';
	ret.params['menu'] = 'false';
	
	if(id) ret.objAttrs['id'] = id;
	
	if(flashVars) ret.params['flashVars'] = flashVars;
	
	ret.params['wmode'] = (wmode)? wmode : 'transparent';
	ret.params['scale'] = (scale)? scale : 'exactfit';
	ret.params['menu'] = (menu)? menu : 'false';
	
	return ret;
}
//SCRIPT POPUP - PARAMETROS: URL, NOME, LARGURA, ALTURA, TOP, LEFT, SCROLL 
function abrePag(url,nome,w,h,t,l,s){
	var win,config

	config='width='+w+',height='+h+',top='+t+',left='+l+',scrollbars='+s+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
	win = window.open(url, nome, config);
	win.focus();
}

var tam = 11;

function mudaFonte(tipo,elemento){
	if (tipo=="mais") {
		if(tam<16) tam+=1;createCookie('fonte',tam,365);
		if(tam>=16){
			alert('Atenção! Este é o tamanho máximo da Letra.');
		}
	}
	else {
		if(tam>10) tam-=1;createCookie('fonte',tam,365);
		if(tam<=10){
			alert('Atenção! Este é o tamanho mínimo da Letra.')
		}
	}
	$('#conteudoPagina, #conteudoPagina >*').find('a, ul li, p, h2, h3, h4, h5, h6, div, span, font, i, table tr td, em, strong, label').css('font-size',tam+'px');

}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

//função que volta pro topo
function voltaTop(){
	$.scrollTo('body',2000);
}

/*carousel da lateral*/
var mycarousel_itemList = [
		{url: "/produtos/images/premio-nobreak.gif", title: "Campeões do Canal - 2009. Categoria Nobreak."},
		{url: "/produtos/images/premio-estabilizador.gif", title: "Campeões do Canal - 2009. Categoria Estabilizador"},
		{url: "/produtos/images/premio-sms-informatica-hoje-1.jpg", title: "200 Maiores de Informática - 2009."},
        {url: "/produtos/images/premio-sms-topfive.gif", title: "Os 5 fornecedores preferidos pelos leitores do NEI em 405 categorias de produtos."},
		{url: "/produtos/images/premio-sms-setor-hoteleiro.gif", title: "Marca preferida do Setor Hoteleiro na Categoria Nobreaks"},
		{url: "/produtos/images/premio-sms-setor-hospitalar.gif", title: "Os 5 fornecedores preferidos pelos leitores do NEI em 405 categorias de produtos"},
		{url: "/produtos/images/premio-sms-100maiores.gif", title: "100 maiores de TI & Telecom"},
        {url: "/produtos/images/premio-sms-qualidade2008.gif", title: "Pelo 13º ano consecutivo: Prêmio Qualidade 2008"},
		{url: "/produtos/images/premio-sms-infoexame.gif", title:"200 maiores de tecnologia 2008"},
		{url: "/produtos/images/premio-sms-infoexame-marcas.gif", title: "7º Pesquisa Info de Marcas 2008"},
		{url: "/produtos/images/premios-sms-maiores-de-ti-02.jpg", title:"100 maiores de TI & Telecom 2008"},
		{url: "/produtos/images/premio-sms-anuario-informatica.gif", title: "200 maiores de informática 2008"},
		{url: "/produtos/images/premio-sms-100-maiores-1.jpg", title: "100 maiores de TI & Telecom."},
		{url: "/produtos/images/premio-sms-informatica-hoje-2.jpg", title: "Destaque do ano 2008."}
    ];

function mycarousel_itemLoadCallback(carousel, state)
{
    for (var i = carousel.first; i <= carousel.last; i++) {
        if (carousel.has(i)) {
            continue;
        }
		if (i > mycarousel_itemList.length) {
            break;
        }
		carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[i-1]));
    }
};
function mycarousel_getItemHTML(item)
{
    return '<a href="/conheca-sms/certificado-sms/certificados.asp"><img src="' + item.url + '" alt="' + item.title + '" title="'+ item.title +'" /></a>';
};

jQuery(document).ready(function() {
	var indice = $('#menuLateral #premiosLateral').hasClass('teste');
	
	if(!indice){
    	jQuery('#premios').jcarousel({
			scroll: 1,
    	    size: mycarousel_itemList.length,
    	    itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback}
    	});
	}
});

$(function(){
	$('.controlaBordaDestaque .jcarousel-prev-horizontal,').hover(
		function(){
			$(this).css('background','transparent url(/produtos/images/seta-premios-01-over.gif) no-repeat 0px 0px')
		},
		function(){
			$(this).css('background','transparent url(/produtos/images/seta-premios-01.gif) no-repeat 0px 0px')
		}
	)
	$('.controlaBordaDestaque .jcarousel-next-horizontal').hover(
		function(){
			$(this).css('background','transparent url(/produtos/images/seta-premios-02-over.gif) no-repeat 0px 0px')
		},
		function(){
			$(this).css('background','transparent url(/produtos/images/seta-premios-02.gif) no-repeat 0px 0px')
		}
	)
});

//SCRIPT POPUP - PARAMETROS: URL, NOME, LARGURA, ALTURA, TOP, LEFT, SCROLL 
function abrePag(url,nome,w,h,t,l,s){
	var win,config

	config='width='+w+',height='+h+',top='+t+',left='+l+',scrollbars='+s+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
	win = window.open(url, nome, config);
	win.focus();
}
//VALIDA DATA
function validaData(obj){
	try{
		if (!(((event.keyCode >= 48) && (event.keyCode <= 57)) || (event.keyCode == 47)))
			event.returnValue = false;
	} catch(e){  return false;  }	
}

//funções para o compartilhes
function exibeCompartilhe(){
	var posicaoIndiqueTop = $('#boxUtilidades ul li:first').offset();
	$('#controlaWidgets').css({left: posicaoIndiqueTop.left - 47 +'px',top: posicaoIndiqueTop.top + 20 +'px'});
	document.getElementById("controlaWidgets").style.display = (document.getElementById("controlaWidgets").style.display == "block") ? "none" : "block";
}

function MontaEmail(div, nome)
{
	var email = "<form method='post' id='form_compartilhe_email' name='formCompartilhe_email'>";
	email+= 	"<div id='email_compartilhe'>";
	email+= 	"   <div style='float:right;'><a href='javascript: void(0);' onClick='exibeCompartilhe()' title='fechar'>Fechar</a></div><br>";
	email+= 		"<fieldset>";
	email+=				"<label for='compartilhe_nome'><span class='laranja'>*</span> Seu Nome: </label><input type='text' size=30 id='compartilhe_nome' maxlength=255 >";
	email+= 		"</fieldset>";
	email+= 		"<fieldset>";
	email+=				"<label for='compartilhe_email'>Seu E-mail: </label><input type='text' id='compartilhe_email' size=30 maxlength=255>";
	email+= 		"</fieldset>";
	email+= 		"<fieldset>";
	email+=				"<label for='compartilhe_nome_destino'><span class='laranja'>*</span> Nome Amigo: </label><input type='text' id='compartilhe_nome_destino' size=30 maxlength=255>";
	email+= 		"</fieldset>";
	email+= 		"<fieldset>";
	email+=				"<label for='compartilhe_email_destino'><span class='laranja'>*</span> E-mail Amigo: </label><input type='text' id='compartilhe_email_destino' size=30 maxlength=255>";
	email+= 		"</fieldset>";
	email+= 		"<fieldset>";
	email+=				"<label for='compartilhe_mensagem'>Mensagem: </label><textarea id='compartilhe_mensagem' onkeyup='validarNumeroCaracteres(this, 500, \"quantidade\");' ></textarea>";
	email+=             "<div id='caracteres' style='float:right;'><span id='quantidade'>500</span> caracteres </div>";
	email+= 		"</fieldset>";	
	email+=				"<div id='botoes_compartilhe'>";
	email+=					"<a href='javascript:' onclick='verificaEmail()' >Enviar</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:' onclick='limparEmail()' >Limpar</a><br />";
	email+=					"<span class='laranja'>*</span> campos obrigatórios";
	email+=				"</div>";
	email+= 	"</div>";	
	email+= "</form>";
	div.innerHTML = email;
}

//Limita o maximo de caracteres em um campo
function validarNumeroCaracteres(campo, maximo, spanId) {
	if (campo.value.length <= maximo)
		
		document.getElementById(spanId).innerHTML = maximo - campo.value.length;
	else
		campo.value = campo.value.substring(0, maximo);
}

function limparEmail()
{
	if(confirm("Deseja limpar os campos do formulário?"))
	{
		var form = document.getElementById("form_compartilhe_email")	
		form.compartilhe_nome.value = '';
		form.compartilhe_email.value = '';
		form.compartilhe_nome_destino.value = '';
		form.compartilhe_email_destino.value = '';
		form.compartilhe_mensagem.value = '';
	}
}

function verificaEmail()
{
	var form = document.getElementById("form_compartilhe_email")	
	nome = form.compartilhe_nome;
	email = form.compartilhe_email;
	nome_destino = form.compartilhe_nome_destino;
	email_destino = form.compartilhe_email_destino;
	mensagem = form.compartilhe_mensagem;
		
	if(!nome.value || nome.value.length < 4){
		alert("Preencha seu Nome!");
		nome.focus();
		return;
	}
	if(!nome_destino.value || nome_destino.value.length < 4){
		alert("Preencha o Nome do Destinatário!");
		nome_destino.focus();
		return;
	}
	if(!email_destino.value || email_destino.value.length < 4){
		alert("Preencha o E-mail Destino!");
		email_destino.focus();
		return;
	}
	else{
		if(email_destino.value.indexOf(',') > 0 || email_destino.value.indexOf(' ') > 0 || email_destino.value.indexOf('(') > 0 || email_destino.value.indexOf(')') > 0)
		{
			alert("Preencha o E-mail Destino Corretamente");
			email_destino.focus();
			return;		
		}
		email_destino_p1 = email_destino.value.split("@")
		if(email_destino_p1.length > 1)	{
			email_destino_p2 = email_destino_p1[1].split(".");
			if(!email_destino_p2[1])
			{
				alert("Preencha o E-mail Destino Corretamente");
				email_destino.focus();
				return;
			}	
		}
		else{
			alert("Preencha o E-mail Destino Corretamente");
			email_destino.focus();
			return;
		}
	}
	if(mensagem.value == "")
	{
		if(!confirm("Deseja indicar sem mensagem?"))
		{
			return;
		}
	}
	enviaEmail(nome, email, nome_destino, email_destino, mensagem);
}

function enviaEmail(nome, email, nome_destino, email_destino, mensagem)
{
	$.ajax({
		type: "GET",
		url: "/includes/envia_email_compartilhe.asp",
		data: 'endereco=' + location.href + '&titulo=' + document.title + '&nome=' + nome.value + '&email=' + email.value + '&nome_destino=' + nome_destino.value + '&email_destino=' + email_destino.value + '&mensagem_visitante=' + mensagem.value,
		success: function(){
				alert('Mensagem enviada!');
				nome.value = '';
				email.value = '';
				nome_destino.value = '';
				email_destino.value = '';
				mensagem.value = '';
		},
		error: function(){
			alert("Erro ao enviar Mensagem!");
			alert(nome.value);
			alert(email_destino.value);
		}
	});
}


//FUNÇÃO QUE MARCA O ÍNDICE DE OPÇÕES DA PÁGINA DE EQUIPAMENTOS CONDICIONADORES DE ENERGIA 


//Função responsavel por tirar espaços a direita e a esquerda da string
//str:      Uma string qualquer 
function Trim(str){return str.replace(/^\s+|\s+$/g,"");}


/*Guardo a função do topo para os produtos*/
function EnviaValorPotencia(potencia, categoria, action){
    document.passaValorPotencia.potencia.value = potencia;
    document.passaValorPotencia.categoria.value = categoria;
    document.passaValorPotencia.action = action;
    document.passaValorPotencia.submit();
}
