//verifica o navegador
var IE = (navigator.userAgent.indexOf('MSIE') > -1);
var strCarregando = '<div class="block center"><img src="/images/carregando.gif" alt="Carregando..." title="Carregando..." /></div>';

window.onbeforeunload = loading;

function loading(action) {
	$('#dialog').dialog('option', 'title', 'Aguarde!');
	$("#dialog").html(strCarregando);
    if(action == 'show') {
        $("#dialog").dialog("open");
        $(".ui-dialog-titlebar-close").hide();
    } else if(action == 'hide') {
        $("#dialog").dialog("close");
    }
}

$(document).ready(function() {
	//Exibe carregando ao trocar de pagina
	$(window).unload(function() {
        loading('show');
    });
	
//	$("h1").corner("top");
	
	//Faz o over nas img
	$(".over").mouseover(function(){
		$(this).attr("src", $(this).attr("src").replace('.gif', '_over.gif'));
	});
	$(".over").mouseout(function(){
		$(this).attr("src", $(this).attr("src").replace('_over.gif', '.gif'));
	});
	
	$(".overJpg").mouseover(function(){
		$(this).attr("src", $(this).attr("src").replace('.jpg', '_over.jpg'));
	});
	$(".overJpg").mouseout(function(){
		$(this).attr("src", $(this).attr("src").replace('_over.jpg', '.jpg'));
	});
	
	//Marca o menu
	$("#menuLateral a").each(function(index) {
		if($(this).attr('href') == location.pathname) {
			$(this).parents('ul').removeClass('none');
			
			//Verifica se está no relacionamento com a comunidade
			if($(this).attr('href').split('/')[1] == 'relacionamento_comunidade')
				$(this).addClass('suMenuMarcadoVerde');
			else
				$(this).addClass('suMenuMarcado');
		}
	});
	
	//Define as validaçoes para o form de newsletter
	var validator = $('#frmRecebaNovidades').validate({
		rules: {
			DSC_NOME: {required: true},
			DSC_EMPRESA: {required: true},
			DSC_EMAIL: {required: true, email: true}
		},
		messages: {
			DSC_NOME: '<br />Digite o nome',
			DSC_EMPRESA: '<br />Digite o nome da empresa',
			DSC_EMAIL: '<br />E-mail invalido'
		},
		errorPlacement: function(error, element) {
			error.appendTo(element.next('span'));
		},
//		success: function(label) {
//			label.html('&nbsp;').addClass('checked');
//		},
		errorElement: 'span'
	});
	//Adiciona o evento no submit
	$('#frmNews').submit(function() {
		addNews();
		return false;
	});
	//Seta os valores default para o dialog
	$("#dialog").dialog({
		bgiframe: true,
		autoOpen: false,
		resizable: false,
		modal: true,
		position: ['center',100]
	});
	
	//Atribui as funcoes do menu
	$("#menuLateral ul li a").click(function(index) {
		//Verifica se tem a classe de primeiro nivel
		if($(this).hasClass('cat_menu_filho_0')) {
			$("#cat_" + $(this).attr('id')).slideToggle();
			return false;
		}
	 });
	
});

/**
 * Exibe uma foto ampliada
 * @param strNomeFoto - Nome da foto
 * @return
 */
function fotoAmpliada(strNomeFoto) {
	strPath = '/modulos/upload/originais/' + strNomeFoto;
	strLegenda = '';
	var objFoto;
	objFoto = new Image();			
	objFoto.src = strPath;

	if(objFoto.complete) {
		$('#dialog').html('<img src="'+objFoto.src+'" alt="" /><br />'+strLegenda)
	}else {
		$("#dialog").html('<div class="center"><img src="'+strPath+'" alt="" title="" /></div>');
		objFoto.onload = function(){
			$('#dialog').html('<img src="'+objFoto.src+'" alt="" /><br />'+strLegenda)
			$( "#dialog" ).dialog( "option", "position", 'center' );
		}
	}
	$( "#dialog" ).dialog( "option", "position", 'center' );
	//Janela do form
	$('#dialog').dialog('option', 'title', 'Detalhe');
	$('#dialog').dialog('option', 'width', 'auto');
	$('#dialog').dialog('option', 'buttons', { "Ok": function() { $(this).dialog('close');} });
	$('#dialog').dialog('open');
}

function validaCPF() {
	var strCPF = $("#NUM_CPF").val().replace(/[^0-9]/g, '');
	if(strCPF.length != 11) 
		return false;
	if(strCPF == '00000000000' || strCPF == '11111111111' || strCPF == '22222222222' || strCPF == '33333333333' || strCPF == '44444444444' || strCPF == '55555555555' || 
			strCPF == '66666666666' || strCPF == '77777777777' || strCPF == '88888888888' || strCPF == '99999999999')
		return false;
	else {
		var arrCPF = strCPF.split('');
		var soma1 = (arrCPF[0]*10) + (arrCPF[1]*9) + (arrCPF[2]*8) + (arrCPF[3]*7) + (arrCPF[4]*6)
				 		+ (arrCPF[5]*5) + (arrCPF[6]*4) + (arrCPF[7]*3) + (arrCPF[8]*2);
		var resto = soma1 % 11;
		var digito1 = resto < 2 ? 0 : 11 - resto;
		var soma2 = (arrCPF[0]*11) + (arrCPF[1]*10) + (arrCPF[2]*9) + (arrCPF[3]*8) + (arrCPF[4]*7)
				 		+ (arrCPF[5]*6) + (arrCPF[6]*5) + (arrCPF[7]*4) + (arrCPF[8]*3) + (arrCPF[9]*2);
		var resto = soma2 % 11;
		var digito2 = resto < 2 ? 0 : 11 - resto;
		if(arrCPF[9] != digito1 || arrCPF[10] != digito2)
			return false;
	}
	
	return true;
}

function recuperaSenha() {
	$("#dialog").html('Carregando..');
	$('#dialog').dialog('option', 'title', 'Carregando..');
	$('#dialog').dialog('option', 'width', 330);
	$('#dialog').dialog('option', 'buttons', {});
	$('#dialog').dialog('open');
	
	if($("#DSC_LOGIN").val() == '') {
		$('#dialog').html('Digite seu login');
		$('#dialog').dialog('option', 'buttons', { "Ok": function() {$(this).dialog('close');} });
	}else {
		$.ajax({
		   type: "POST",
		   url: "/ajax/clientes_ajax/recuperaSenha/",
		   data: "DSC_LOGIN=" + $("#DSC_LOGIN").val(),
		   success: function(strRetorno) {
				$('#dialog').html(strRetorno);
				$('#dialog').dialog('option', 'buttons', { "Ok": function() {$(this).dialog('close');} });
		   }
		 });
	}
}

function addNews() {
	if(!$('#frmNews').valid())
		return false;
	$("#dialog").html('Carregando..');
	$('#dialog').dialog('option', 'title', 'Newsletter');
	$('#dialog').dialog('option', 'width', 430);
	$('#dialog').dialog('option', 'buttons', {});
	$('#dialog').dialog('open');
	$.ajax({
	   type: "POST",
	   url: "/ajax/clientes_ajax/addNews/",
	   data: $('#frmNews').serialize(),
	   success: function(strRetorno) {
			$("#dialog").html(strRetorno);
	   }
	 });
}

//adicionarFavoritos(): abre a janela de adicionar aos favoritos
function adicionarFavoritos(){
	if (document.all)
		window.external.AddFavorite(location.href, document.title);
	else if (window.sidebar)
		window.sidebar.addPanel(document.title, location.href, '')
}

function enviarAmigo() {
	if (document.title.indexOf('#') > - 1)
		var linkNome = document.title.substring(document.title.lastIndexOf("- ") + 1, document.title.indexOf('#'));
	else
		var linkNome = document.title.substring(document.title.lastIndexOf("- ") + 1);
	
	var url = location.href.substr(location.href.indexOf('.br') + 3);
		
	$.ajax({
	   type: "POST",
	   url: "/ajax/envie_amigo_ajax/index/",
	   data: "strLinkNome=" + linkNome + "&URL=" + url, 
	   success: function(strRetorno) {
			$("#dialog").html(strRetorno);
			$('#frmIndiqueAmigo').ajaxForm({
			    success: function(strRetorno) {
					enviarAmigo();
			    }
			});
			
			$('#dialog').dialog('option', 'title', 'Indique para um amigo');
			$('#dialog').dialog('option', 'width', 450);
			$('#dialog').dialog('option', 'buttons', { "Ok": function() {$(this).dialog('close');} });
			$('#dialog').dialog('open');
	   }
	 });
}

//esconderCombos(): esconde todos os combos que existem na p�gina, para o combo n�o ficar por cima do menu
function esconderCombos(){
	var selects = document.getElementsByTagName('select');
	for (var i = 0; i < selects.length; i++)
		selects[i].style.visibility = 'hidden';
	var videos = document.getElementsByTagName('iframe');
	for (var i = 0; i < videos.length; i++)
		videos[i].style.visibility = 'hidden';
}
//mostrarCombos(): mostra todos os combos escondidos da p�gina
function mostrarCombos(){
	var selects = document.getElementsByTagName('select');
	for (var i = 0; i < selects.length; i++)
		selects[i].style.visibility = '';
	var videos = document.getElementsByTagName('iframe');
	for (var i = 0; i < videos.length; i++)
		videos[i].style.visibility = '';
}

//mostrarConteudo(): torna um conteudo vis�vel
//	- id: id do conteudo a monstrar
function mostrarConteudo(id){
	$("#"+id).slideDown(600);
}

//esconderConteudo(): esconde um conteudo
//	- id: id do conteudo a esconder
function esconderConteudo(id){
	$("#"+id).slideUp(600);
}


//trocarConteudo(): troca um conteudo vis�vel por outro
//	-id: id do conteudo a trocar
var visivel = '';
function trocarConteudo(id){
	if(id != visivel){
		if(visivel.length > 0) 
			esconderConteudo(visivel);
	}
	mostrarConteudo(id);
	visivel = id;
}

//trocarConteudoClique(): troca um conteudo vis�vel por outro. caso clique no conteudo que ja esteje visivel, esconde ele
//	-id: id do conteudo a trocar
function trocarConteudoClique(id){	
	if(visivel.length > 0) 		
		esconderConteudo(visivel);
	if(visivel != id){
		mostrarConteudo(id);
		visivel = id;
	}else{
		visivel = '';
	}
}

//	- idCombo: id do combo a marcar
//	- valor: parametro a ser comparado para marcar
function marcarComboValor(idCombo, valor){
	var opts = document.form[idCombo].options;	
	for(var i = 0; i < opts.length; i ++){		
		if(valor == opts[i].value){
			opts[i].selected = true;
			break;
		}
	}
}

//marcarCombo(): marca um combo, caso algum dos seus options contenham a url no seu value
//	- idCombo: id do combo a marcar
function marcarCombo(idCombo){	
	var opts = document.form[idCombo].options;	
	for(var i = 0; i < opts.length; i ++){		
		if(location.href.indexOf(opts[i].value) > -1){
			opts[i].selected = true;
			break;
		}
	}
}

/* Retira a borda dos flashes
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 = GetArguments(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);
}

//GetArguments(): fun��o auxiliar para retirar a borda dos flashes
//	- retorna os argumentos da tag object e os parametros
function GetArguments(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;
}
