/**
 *
 */


function showEspera(){
	$('#divEspera').css('display','block');

	var caixa = $('<div class="caixaEspera">' +
				  '	<div class="conteudoEspera">' +
				  '		<img class="imgEspera" src="./imagens/ajaxLoader.gif" />' +
				  '	<p>Aguarde...</p>' +
				  '	</div>' +
				  '</div>');
	$('#caixaEspera').append(caixa);
}

/*
 * Esconde a tela de espera
 */
function hideEspera(){
	$('#divEspera').css('display','none');
	$('#caixaEspera').find('.caixaEspera').remove();
}




String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}


$.fn.ClearTypeFadeTo = function(options) {
    if (options)
            $(this)
                    .show()
                    .each(function() {
                            if (jQuery.browser.msie) {
                                    // Save the original background color
                                    $(this).attr('oBgColor', $(this).css('background-color'));
                                    // Set the bgColor so that bold text renders correctly (bug with IE/ClearType/bold text)
                                    $(this).css({ 'background-color': (options.bgColor ? options.bgColor : '#fff') })
                            }
                    })
                    .fadeTo(options.speed, options.opacity, function() {
                            if (jQuery.browser.msie) {
                                    // ClearType can only be turned back on if this is a full fade in or
                                    // fade out. Partial opacity will still have the problem because the
                                    // filter style must remain. So, in the latter case, we will leave the
                                    // background color and 'filter' style in place.
                                    if (options.opacity == 0 || options.opacity == 1) {
                                            // Reset the background color if we saved it previously
                                            $(this).css({ 'background-color': $(this).attr('oBgColor') }).removeAttr('oBgColor');
                                            // Remove the 'filter' style to restore ClearType functionality.
                                            $(this).css('filter','');

											if( options.opacity == 0 )
                                            	$(this).get(0).style.removeAttribute('filter');
                                    }
                            }
                            if (options.callback != undefined) options.callback();
                    });
};

$.fn.ClearTypeFadeIn = function(options) {
    if (options)
            $(this)
                    .css({ opacity: 0 })
                    .ClearTypeFadeTo({ speed: options.speed, opacity: 1, callback: options.callback });
};

$.fn.ClearTypeFadeOut = function(options) {
    if (options)
            $(this)
                    .css({ opacity: 1 })
                    .ClearTypeFadeTo({ speed: options.speed, opacity: 0, callback: options.callback });
};




function inputFocus(input){
	$(input).not('.inputReadonly').addClass('focus');
	//$(input).removeClass('blur');
}

function inputBlur(input){
	$(input).not('.inputReadonly').removeClass('focus');
	//$(input).addClass('blur');

}

function topoClick(topo){
	var meio = $(topo).next('.meio');

	if( ( $.browser.msie ) )
		var display = 'block';
	else
		var display = 'table';

	if ($(meio).css('display') == 'none') {
		$(meio).slideDown(200,function(){
			$(meio).css('display',display);
			$(meio).ClearTypeFadeIn({ speed: 400, callback: function(){ $(meio).css('display',display); } });
		})
	} else {
		$(meio).ClearTypeFadeOut( { speed: 400, callback: function(){ $(meio).slideUp(200); } } );
	}
}

function radioClick(radio){
	var td = $(radio).parent();
	var tr = $(td).parent();
	var soma = $(tr).find('.trSoma');
	var classe = $(radio).attr("class");

	$(tr).find(':radio[class="'+classe+'"]').each(function(){
		$(this).parent().removeClass('corSelecionado');
		$(this).css('background-color','transparent');
		$(this).css('border','none');
	})

	$(td).addClass('corSelecionado');
	$(radio).css('background-color','transparent');

	// Faz o somatório
	var somatorio = 0;

	$(tr).find('input[checked="true"]:radio').each(function(){
		somatorio = somatorio + parseInt($(this).val());
	})

	if(soma)
		$(soma).text(somatorio);
}

function abreConcorrencia(){
	var meio = $('#caixaResumoConcorrentes').find('#meioResumoConcorrentes');

	if ($(meio).css('display') == 'none') {

		$.ajax({
			type: "GET",
			url: "./ajax/ajaxGetResumoConcorrentes.php",
			cache: false,
			error: function(){
				alert("Erro ao obter a tabela de resumo da concorr�ncia!");
				hideEspera();
			},
			success: function(msg){
				$(meio).slideDown(200,function(){
					$(meio).html(msg);
					$(meio).fadeTo(200,1);
					$('#caixaResumoConcorrentes #topoResumoConcorrentes p').html('Clique para ocultar o quadro de resumo dos concorrentes');
				})

				hideEspera();
			}
		});

	} else {
		$(meio).fadeTo(400,0,function(){
			$(meio).slideUp(200);
			$('#caixaResumoConcorrentes #topoResumoConcorrentes p').html('Clique para visualizar o quadro de resumo dos concorrentes');
		})
	}
}


$(document).ready(function(){
	var ordemSlides = Array("1","2","3","externa","4","5","6","interna");

	$('html').animate(
		{scrollTop: $('#imgSlide').offset().top},
		500);


//	$('.menu li').click( function(){
//		showEspera();
//	});

	$('button[name="entrar"]').click( function(){
		showEspera();
	});

	$('.linkMenu').click( function(){
		showEspera();
	});


	$('#conteudo #caixaQuestoes #topoCaixaQuestoes').click(function(){
		var meio = $('#caixaQuestoes').find('#meioCaixaQuestoes');

		if ($(meio).css('display') == 'none') {
			$(meio).slideDown(200,function(){
				$(meio).fadeTo(200,1);

				if( !$.browser.msie )
					$(meio).css('display','table');

				$('#caixaQuestoes #topoCaixaQuestoes p').html('Clique para ocultar as questões complementares');
			})
		} else {
			$(meio).fadeTo(400,0,function(){
				$(meio).slideUp(200);
				$('#caixaQuestoes #topoCaixaQuestoes p').html('Clique para visualizar as questões complementares');
			})
		}
	})

	$('#conteudo #caixaSWOT #topoCaixaSWOT').click(function(){
		var meio = $('#caixaSWOT').find('#meioCaixaSWOT');

		if ($(meio).css('display') == 'none') {
			$(meio).slideDown(200,function(){
				$(meio).fadeTo(200,1);

				if( !$.browser.msie )
					$(meio).css('display','table');

				$('#caixaSWOT #topoCaixaSWOT p').html('Clique para ocultar a matriz <abbr title="For&ccedil;as, Oportunidades, Fraquezas e Amea&ccedil;as">FOFA</abbr>');
			})
		} else {
			$(meio).fadeTo(400,0,function(){
				$(meio).slideUp(200);
				$('#caixaSWOT #topoCaixaSWOT p').html('Clique para visualizar a matriz <abbr title="For&ccedil;as, Oportunidades, Fraquezas e Amea&ccedil;as">FOFA</abbr>');
			})
		}
	})

	$('#conteudo #caixaPostura #topoCaixaPostura').click(function(){
		var meio = $('#caixaPostura').find('#meioCaixaPostura');

		if ($(meio).css('display') == 'none') {
			$(meio).slideDown(200,function(){
				$(meio).fadeTo(200,1);
				$('#caixaPostura #topoCaixaPostura p').html('Clique para ocultar a postura estrat&eacute;gica');
			})
		} else {
			$(meio).fadeTo(400,0,function(){
				$(meio).slideUp(200);
				$('#caixaPostura #topoCaixaPostura p').html('Clique para visualizar a postura estrat&eacute;gica');
			})
		}
	})


	$('#objetivos .topo').click(function(){
		topoClick($(this));
	})

	$('textarea, :text').focus(function(){
		inputFocus(this);
	});

	$('textarea, :text').blur(function(){
		inputBlur(this);
	});

	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}

	$('.submenu a').click(function(){

		$('.menu').not($(this).next('ul')).css('display','none');

		$(this).next('ul').each(function(){
			if ($(this).css('display') == 'none') {
				$(this).css('display', 'block');
			} else {
				$(this).css('display', 'none');
				$('.submenu2').css('display','none');
			}
		});

	})

	$('.menu a').mouseover(function(){

		$(this).parent().find('ul').each(function(){
			if ($(this).parent().find('ul').css('display') == 'none') {
				$('.submenu2').css('display','none');
				$(this).parent().find('ul').css('display', 'block');
			}
		});
	});

	$('.submenu2').mouseover(function(){
		$(this).css('display', 'block');
	})

	$('.menu a').mouseout(function(){

		$(this).parent().find('ul').each(function(){
			$(this).parent().find('ul').css('display', 'none');
		});
	});

	$('input:radio').blur(function(){
		var td = $(this).parent();
		var tr = $(td).parent();

		$(tr).find('input[type="radio"]').each(function(){
			$(this).css('background-color','transparent');
			$(this).css('border','none');
		})

		$(this).css('background-color','transparent');

	});

	$('input:radio').click(function(){
		radioClick($(this));
	});

	$("div.boxPlano > div.topo").click(function(){
		topoClick($(this));
	});


	$('#formFCS').submit(function(){
		var completo = true;
		$(this).find('textarea').each(function(){
			if ($(this).val() == '') {
				completo = false;
			}
		})

		if(!completo)
			alert("Os fatores cr�ticos de sucesso não podem ser vazios!")
		return completo;
	});


	$('#relatorioTodos').click(function(){
		var estado = $(this).attr('checked');
		$('#formRelatorio').find(':checkbox').each(function(){
			$(this).attr('checked',estado);
		});
	});

	$('#formRelatorio :checkbox').click(function(){
		if ($(this).attr('checked') == false) {
			$('#relatorioTodos').attr('checked','');
		}
	})
});

/*
function showEspera(){
	$('#divEspera').css('width','100%');
	$('#divEspera').css('height','100%');
}
*/
/**
 * Fun��o para esconder a tela de espera
 *
 * @return void
 */
/*
function hideEspera(){
	$('#divEspera').css('width','0');
	$('#divEspera').css('height','0');
}
*/

function urlDecode(string, overwrite){
    if(!string || !string.length){
        return {};
    }
    var obj = {};
    var pairs = string.split('&');
    var pair, name, value;
    var lsRegExp = /\+/g;
    for(var i = 0, len = pairs.length; i < len; i++){
        pair = pairs[i].split('=');
        name = unescape(pair[0]);
        value = unescape(pair[1]).replace(lsRegExp, " ");
        //value = decodeURIComponent(pair[1]).replace(lsRegExp, " ");
        if(overwrite !== true){
            if(typeof obj[name] == "undefined"){
                obj[name] = value;
            }else if(typeof obj[name] == "string"){
                obj[name] = [obj[name]];
                obj[name].push(value);
            }else{
                obj[name].push(value);
            }
        }else{
            obj[name] = value;
        }
    }
    return obj;
}


function jsGet(param)
{
	var wl = window.location.href;
	var params = urlDecode(wl.substring(wl.indexOf("?")+1));
	return(params[param]);
}

function gravarFator(id,bt){
	showEspera();

	var data = "";

	var formulario = $(bt).parent().parent().parent().parent();

	var arrayIdIndicador = '';
	var arrayNomeIndicador = '';
	var arrayExplicacaoIndicador = '';
	var arrayOpo = '';
	var arrayAme = '';
	var arrayFra = '';
	var arrayFor = '';

	var arrayNomeIndicadorNovo = '';
	var arrayExplicacaoIndicadorNovo = '';
	var arrayTipo1Novo = '';
	var arrayTipo2Novo = '';

	var descFator = '';
	var idFator = id;
	var fator;

	var indicadores = '';
	var novosIndicadores = '';

	$('#fator'+id+' :input').each(function (){

		/* *************************** */
		if(($(this).attr('name') == 'idIndicador'))
			arrayIdIndicador = arrayIdIndicador + "&idIndicador[]=" + $(this).val();

		if (($(this).attr('name') == 'nomeIndicador')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			arrayNomeIndicador = arrayNomeIndicador + "&nameIndicador[]=" + tmp;
		}

		if (($(this).attr('name') == 'explicacaoIndicador')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			arrayExplicacaoIndicador = arrayExplicacaoIndicador + "&explicacaoIndicador[]=" + tmp;
		}

		if (($(this).attr('name') == 'opo')) {
			if($(this).attr('checked') == true)
				arrayOpo = arrayOpo +  "&opo[]=on";
			else
				arrayOpo = arrayOpo +  "&opo[]=";
		}

		if (($(this).attr('name') == 'ame')) {
			if($(this).attr('checked') == true)
				arrayAme = arrayAme +  "&ame[]=on";
			else
				arrayAme = arrayAme +  "&ame[]=";
		}

		if (($(this).attr('name') == 'for')) {
			if($(this).attr('checked') == true){
				arrayFor = arrayFor +  "&for[]=on";
			}else{
				arrayFor = arrayFor +  "&for[]=";
			}

		}

		if (($(this).attr('name') == 'fra')) {
			if($(this).attr('checked') == true)
				arrayFra = arrayFra +  "&fra[]=on";
			else
				arrayFra = arrayFra +  "&fra[]=";
		}

		/* *************************** */

		if (($(this).attr('name') == 'descFator'))
			descFator = escape( $(this).val().trim() );


		/* *************************** */
		if (($(this).attr('name') == 'nomeIndicadorNovo')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			arrayNomeIndicadorNovo = arrayNomeIndicadorNovo + "&nameIndicadorNovo[]=" + tmp;
		}

		if (($(this).attr('name') == 'explicacaoIndicadorNovo')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			arrayExplicacaoIndicadorNovo = arrayExplicacaoIndicadorNovo + "&explicacaoIndicadorNovo[]=" + tmp;
		}

		if (($(this).attr('name') == 'tipo1')) {
			if($(this).attr('checked') == true)
				arrayTipo1Novo = arrayTipo1Novo +  "&tipo1Novo[]=on";
			else
				arrayTipo1Novo = arrayTipo1Novo +  "&tipo1Novo[]=";
		}

		if (($(this).attr('name') == 'tipo2')) {
			if($(this).attr('checked') == true)
				arrayTipo2Novo = arrayTipo2Novo +  "&tipo2Novo[]=on";
			else
				arrayTipo2Novo = arrayTipo2Novo +  "&tipo2Novo[]=";
		}

	});

	if(arrayIdIndicador.length > 0){
		indicadores = arrayIdIndicador+
					  arrayNomeIndicador+
					  arrayExplicacaoIndicador+
					  arrayOpo+
					  arrayAme+
					  arrayFor+
					  arrayFra;
	}

	if(arrayNomeIndicadorNovo.length > 0){
		novosIndicadores = arrayNomeIndicadorNovo+
						   arrayExplicacaoIndicadorNovo+
						   arrayTipo1Novo+
						   arrayTipo2Novo;
	}

	if(idFator){
		fator = "descFator="+descFator+
				"&idFator="+idFator;
	}

	if (descFator != '') {

		$.ajax({
			type: "POST",
			url: "./ajax/ajaxGravaFator.php",
			cache: false,
			data: fator +
			indicadores +
			novosIndicadores,
			error: function(){
				alert("Erro ao gravar os dados!");
				hideEspera();
			},
			success: function(msg){
				$(formulario).html(msg);

				alert("Dados gravados com sucesso!");
				hideEspera();
			}
		});
	}else{
		alert("O nome do fator não pode ser vazio!");
		hideEspera();
	}

}

/*
 * Grava um fator novo
 */
function gravarNovo(bt){

	var formulario = $(bt).parent().parent().parent().parent();

	var arrayNomeIndicadorNovo = '';
	var arrayExplicacaoIndicadorNovo = '';
	var arrayTipo1Novo = '';
	var arrayTipo2Novo = '';

	var descFator = '';

	var novosIndicadores = '';

	$(formulario).find(':input').each(function (){
		if (($(this).attr('name') == 'descFatorNovo'))
			descFator = $(this).val().trim();


		/* *************************** */
		if (($(this).attr('name') == 'nomeIndicadorNovo')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			arrayNomeIndicadorNovo = arrayNomeIndicadorNovo + "&nameIndicadorNovo[]=" + tmp;
		}

		if (($(this).attr('name') == 'explicacaoIndicadorNovo')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			arrayExplicacaoIndicadorNovo = arrayExplicacaoIndicadorNovo + "&explicacaoIndicadorNovo[]=" + tmp;
		}

		if (($(this).attr('name') == 'tipo1')) {
			if($(this).attr('checked') == true)
				arrayTipo1Novo = arrayTipo1Novo +  "&tipo1Novo[]=on";
			else
				arrayTipo1Novo = arrayTipo1Novo +  "&tipo1Novo[]=";
		}

		if (($(this).attr('name') == 'tipo2')) {
			if($(this).attr('checked') == true)
				arrayTipo2Novo = arrayTipo2Novo +  "&tipo2Novo[]=on";
			else
				arrayTipo2Novo = arrayTipo2Novo +  "&tipo2Novo[]=";
		}
	});

	if(arrayNomeIndicadorNovo.length > 0){
		novosIndicadores = arrayNomeIndicadorNovo +
						   arrayExplicacaoIndicadorNovo +
						   arrayTipo1Novo +
						   arrayTipo2Novo;
	}

	if(jsGet('modulo').replace('#','') == 'externa')
		var analise = 'AE';
	else if(jsGet('modulo').replace('#','') == 'interna')
		var analise = 'AI';
	else if(jsGet('modulo').replace('#','') == 'fcs')
		var analise = 'FC';

	showEspera();

	if (descFator != '') {
		$.ajax({
			type: "POST",
			url: "./ajax/ajaxGravaFatorNovo.php",
			cache: false,
			data: "analise=" + analise +
			"&descFator=" +
			escape( descFator ) +
			novosIndicadores +
			"&random=" +
			Math.random(),
			error: function(){
				alert("Erro ao gravar os dados!");
				hideEspera();
			},
			success: function(msg){
				$(formulario).html(msg);
				alert("Dados gravados com sucesso!");
				hideEspera();
			}
		});
	}else{
		alert("O nome do fator não pode ser vazio!");
		hideEspera();
	}
}


/*
 * Exclui fator
 */
function excluirFator(bt,id){
	showEspera();
	if (confirm("Deseja excluir esse fator?")) {
		$.ajax({
			type: "GET",
			url: "./ajax/ajaxExcluiFator.php",
			cache: false,
			data: "idFator=" + id+"&random=" + Math.random(),
			error: function(){
				alert("Erro ao excluir o fator!");
				hideEspera();
			},
			success: function(msg){
				if (!msg) {
					$(bt).parent().parent().parent().parent().parent().remove();
				} else {
					alert(msg);
				}
				hideEspera();
			}
		});
	}else
		hideEspera();
}

/*
 * Exclui fator novo
 */
function excluirFatorNovo(bt){
	showEspera();
	if (confirm("Deseja excluir esse fator e seus indicadores?")) {
		$(bt).parent().parent().parent().parent().parent().remove();
		hideEspera();
	}else
		hideEspera();
}

/*
 * Exclui indicador
 */
function excluirIndicador(bt,idIndicador){
	showEspera();
	if (confirm("Deseja excluir esse indicador?")) {
		$.ajax({
			type: "GET",
			url: "./ajax/ajaxExcluiIndicador.php",
			cache: false,
			data: "idIndicador=" + idIndicador+"&random=" + Math.random(),
			error: function(){
				alert("Erro ao excluir o indicador!");
				hideEspera();
			},
			success: function(msg){

				if(msg == "true")
					$(bt).parent().parent().remove();
				else
					alert(msg);

				hideEspera();
			}
		});
	}else
		hideEspera();
}

/*
 * Exclui indicador novo
 */
function excluirIndicadorNovo(bt){
	showEspera();
	if (confirm("Deseja excluir esse indicador?")) {
		$(bt).parent().parent().remove();
		hideEspera();
	}else
		hideEspera();
}

/*
 * Adicionar um indicador ao fator
 */
function adicionarIndicador(idFator){
	showEspera();
	var contador = '';

	$('#fator'+idFator).find('#contadorIndicadores').each(function(){
		contador = parseInt($(this).val());
		contador = contador+1;
		$(this).val(contador);
	});

	var linha = '<tr class="trIndicador"><input type="hidden" name="tipo" value="novo" /><td><textarea onblur="inputBlur(this);" onfocus="inputFocus(this);"  name="nomeIndicadorNovo" id="nomeIndicadorNovo'+contador+'" class="nomeFator"></textarea></td><td><textarea  onblur="inputBlur(this);" onfocus="inputFocus(this);" name="explicacaoIndicadorNovo" id="explicacaoIndicador'+contador+'" class="explicacaoFator" ></textarea></td><td class="tdClassifica"><input type="checkbox" name="tipo1" id="tipo1'+contador+'" /></td><td class="tdClassifica"><input type="checkbox" name="tipo2" id="tipo2'+contador+'" /></td><td class="tdClassifica"><img src="imagens/excluir.png" class="imgBt btExcluir" title="Excluir indicador" onclick="excluirIndicadorNovo(this,'+idFator+')" /></td></tr>';

	$('#fator'+idFator).find('table tbody').each(function(){
		$(linha).appendTo(this);
	});
	hideEspera();
}

/*
 * Adicionar um indicador a um novo fator
 */
function adicionarIndicadorNovoFator(bt){
	showEspera();
	var contador = '';
	var formulario = $(bt).parent().parent().parent().parent();

	contador = $(formulario).find("#contadorIndicadores").val();

	contador = parseInt(contador);
	contador = contador+1;
	$(formulario).find("#contadorIndicadores").val(contador);

	var linha = '<tr class="trIndicador"><input type="hidden" name="tipo" value="novo" /><td><textarea onblur="inputBlur(this);" onfocus="inputFocus(this);"  name="nomeIndicadorNovo" id="nomeIndicadorNovo'+contador+'" class="nomeFator"></textarea></td><td><textarea  onblur="inputBlur(this);" onfocus="inputFocus(this);" name="explicacaoIndicadorNovo" id="explicacaoIndicador'+contador+'" class="explicacaoFator" ></textarea></td><td class="tdClassifica"><input type="checkbox" name="tipo1" id="tipo1'+contador+'" /></td><td class="tdClassifica"><input type="checkbox" name="tipo2" id="tipo2'+contador+'" /></td><td class="tdClassifica"><img src="imagens/excluir.png" class="imgBt btExcluir" title="Excluir indicador" onclick="excluirIndicadorNovo(this)" /></td></tr>';

	$(formulario).find('table tbody').each(function(){
		$(linha).appendTo(this);
	});
	hideEspera();
}

/*
 * Adicionar um fator
 */
function adicionarFator(){
	showEspera();
	var contador = $(document).find("#contadorFatorNovo").val();
	contador = parseInt(contador)+1;
	$(document).find("#contadorFatorNovo").val(contador);


	if(jsGet('modulo').replace('#','') == 'externa'){
		var tipo1 = '<abbr title="Op. = Oportunidade, Am. = Amea&ccedil;a">Op.</abbr>';
		var tipo2 = '<abbr title="Op. = Oportunidade, Am. = Amea&ccedil;a">Am.</abbr>';
	}else if(jsGet('modulo').replace('#','') == 'interna'){
		var tipo1 = '<abbr title="Fo. = For&ccedil;a, Fr. = Fraqueza">Fo.</abbr>';
		var tipo2 = '<abbr title="Fo. = For&ccedil;a, Fr. = Fraqueza">Fr.</abbr>';
	}else if(jsGet('modulo').replace('#','') == 'fcs'){
		var tipo1 = '<abbr title="Fo. = For&ccedil;a, Fr. = Fraqueza">Fo.</abbr>';
		var tipo2 = '<abbr title="Fo. = For&ccedil;a, Fr. = Fraqueza">Fr.</abbr>';
	}

	var linha = '<span  id="caixaFatorNovo'+contador+'"><div class="fator"><form class="formFator" id="fatorNovo'+contador+'"><input type="hidden" name="contadorIndicadores" id="contadorIndicadores" value="0" /><table><tr><th class="coluna1">Fatores:</th><th class="coluna2" rowspan="2">Explica&ccedil;&atilde;o</th><th class="coluna3" colspan="2">Classifica&ccedil;&atilde;o</th><th class="coluna4" rowspan="2"><img src="imagens/excluir.png" class="imgBt btExcluir" title="Excluir fator" onclick="excluirFatorNovo(this)" /></th></tr><tr><th><input  onblur="inputBlur(this);" onfocus="inputFocus(this);" type="text" name="descFatorNovo" id="descFatorNovo['+contador+']" value="" class="descFator" /></th><th>'+tipo1+'</th><th>'+tipo2+'</th></tr></table><div class="controles"><button type="button" onblur="inputBlur(this);" onfocus="inputFocus(this);"  title="Adicionar um indicador ao fator" onclick="adicionarIndicadorNovoFator(this)">Adicionar indicador</button><button type="button" class="btEsp" title="Gravar as altera&ccedil;&otilde;es do fator"  onblur="inputBlur(this);" onfocus="inputFocus(this);" onclick="gravarNovo(this)">Gravar</button></div></form></div></span>';

	$('#analise').each(function(){
		$(linha).appendTo(this);
	});
	hideEspera();
}











function gravarAnaliseConcorrentes(bt){
	var form = $(bt).parent().parent();
	var div = $(bt).parent().parent().parent();

	var idFCS = '';
	var notaInst = '';
	var idConcorrente = '';
	var codigoConcorrente = '';
	var notaConcorrente = ''

	$(form).find(':input').each(function(){
		if (($(this).attr('name') == 'idFCS'))
			idFCS = 'idFCS=' + $(this).val();

		if (($(this).attr('name') == 'notaInst[]'))
			if($(this).attr('checked'))
				notaInst = '&notaInst=' + $(this).val();

		if(($(this).attr('name') == 'idConcorrente[]')){
			idConcorrente = idConcorrente + '&idConcorrente[]=' + $(this).val();
			codigoConcorrente = $(this).val();
		}

		if(($(this).attr('name') == 'nota1['+codigoConcorrente+'][]'))
			if($(this).attr('checked'))
				notaConcorrente = notaConcorrente + '&notaConcorrente['+codigoConcorrente+']=' + $(this).val();
	})

	if (idFCS != '') {
		showEspera();
		$.ajax({
			type: "GET",
			url: "./ajax/ajaxGravaAnaliseConcorrentes.php",
			cache: false,
			data: idFCS +
				  notaInst +
				  idConcorrente +
				  notaConcorrente,
			error: function(){
				alert("Erro ao gravar os dados!");
				hideEspera();
			},
			success: function(msg){
				if (msg == 'false') {
					alert("Erro ao gravar os dados!");
				} else {
					var boxConcorrente = $(form).parent().parent();
					var topo = $(boxConcorrente).find('.topo');
					var meio = $(boxConcorrente).find('.meio');

					$(topo).removeClass('nao_preenchido');
					$(topo).removeClass('completo');
					$(topo).removeClass('incompleto');

					$(meio).removeClass('nao_preenchido');
					$(meio).removeClass('completo');
					$(meio).removeClass('incompleto');

					$(topo).addClass(msg);
					$(meio).addClass(msg);

					alert("Dados gravados com sucesso!");

					$('#meioResumoConcorrentes').fadeTo(400,0,function(){
						$('#caixaResumoConcorrentes #meioResumoConcorrentes').slideUp(200);
						$('#caixaResumoConcorrentes #topoResumoConcorrentes p').html('Clique para visualizar o quadro de resumo dos concorrentes');
					})
				}
				hideEspera();
			}
		});
	}
}


function excluirObjetivo( bt ){
	showEspera();
	if (confirm("Deseja excluir esse objetivo?")) {
		var tr = $(bt).parent().parent();
		var pagina = $(tr).parent().parent().parent().parent().parent();

		var apagar = false;

		// Veririfica se � um objetivo novo (n�o salva no bd)
		// ou seja, n�o tem um id atribu�do a ele
		if ($(tr).find('input[name="idObjetivo"]').val() == null) {
			if ($(tr).find(':input[name="objetivoNovo"]').val() != null) {
				try {
					$(tr).remove();
				} catch(e){
					alert("Erro ao excluir o objetivo!");
				}
			} else {
				alert("Erro ao excluir o objetivo!");
			}
			hideEspera();
		} else {
			var idObjetivo = $(tr).find('input[name="idObjetivo"]').val();
			$.ajax({
				type: "GET",
				url: "./ajax/ajaxExcluiObjetivo.php",
				cache: false,
				data: "idObjetivo=" + idObjetivo,
				error: function(){
					alert("Erro ao excluir o objetivo!");
					hideEspera();
				},
				success: function(msg){
					if(msg == 'false')
						alert("Erro ao excluir o objetivo!");
					else
						$(tr).remove();

					hideEspera();

					var contador = 1;

					$('.tdNumeracao').each(function(){
						$(this).text(contador);
						contador = contador + 1;
					});

				}
			});
		}

	}else
		hideEspera();
}

function adicionarObjetivo(){
	showEspera();
	var meio = $('#objetivosEstrategicos');

	var table = $(meio).find('table');
	var contador = parseInt($(meio).find('#contador').val());
	contador += 1;
	$(meio).find('#contador').val(contador)

	var linha = '<tr>' +
				'	<td class="coluna4 tdNumeracao"></td>' +
				'	<td>' +
				'		<label for="objetivoNovo['+contador+']">Defini&ccedil;&atilde;o</label>' +
				'		<textarea onfocus="inputFocus(this)" onblur="inputBlur(this)" type="text" name="objetivoNovo" id="objetivoNovo['+contador+']"></textarea>' +
				'		<label for="detalhamentoNovo['+contador+']">Detalhamento</label>' +
				'		<textarea onfocus="inputFocus(this)" onblur="inputBlur(this)" type="text" name="detalhamentoNovo" id="detalhamentoNovo['+contador+']"></textarea>' +
				'		<label for="indicadorNovo['+contador+']">Indicador</label>' +
				'		<textarea onfocus="inputFocus(this)" onblur="inputBlur(this)" type="text" name="indicadorNovo" id="indicadorNovo['+contador+']"></textarea>' +
				'	</td>' +
				'	<td class="coluna4 tdExcluir">' +
				'		<img src="imagens/excluir.png" class="btExcluir imgBt" title="Excluir objetivo" onclick="excluirObjetivo(this)" />' +
				'	</td>' +
				'</tr>';

	$(linha).appendTo(table);
	hideEspera();
}

function gravarObjetivo(){
	var form = $('#formObjetivos');

	var objetivosNovos = '';
	var detalhamentosNovos = '';
	var indicadoresNovos = '';
	var objetivos = '';
	var detalhamentos = '';
	var indicadores = '';
	var idObjetivos = '';

	$(form).find(':input').each(function(){
		if (($(this).attr('name') == 'objetivoNovo')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			objetivosNovos = objetivosNovos + "&objetivosNovos[]=" + tmp;
		}

		if (($(this).attr('name') == 'detalhamentoNovo')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			detalhamentosNovos = detalhamentosNovos + "&detalhamentosNovos[]=" + tmp;
		}

		if (($(this).attr('name') == 'indicadorNovo')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			indicadoresNovos = indicadoresNovos + "&indicadoresNovos[]=" + tmp;
		}


		if (($(this).attr('name') == 'idObjetivo'))
			idObjetivos = idObjetivos + "&idObjetivos[]=" + $(this).val();

		if (($(this).attr('name') == 'objetivo')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			objetivos = objetivos + "&objetivos[]=" + tmp;
		}

		if (($(this).attr('name') == 'detalhamento')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			detalhamentos = detalhamentos + "&detalhamentos[]=" + tmp;
		}

		if (($(this).attr('name') == 'indicador')) {
			var tmp = escape( $(this).val().replace(/\n/g,'<br>') );
			indicadores = indicadores + "&indicadores[]=" + tmp;
		}

	})

	// Se tem algum dado para ser salvo...

	if ((objetivosNovos != '') || (idObjetivos != '')) {
		showEspera();
		$.ajax({
			type: "POST",
			url: "./ajax/ajaxGravaObjetivos.php",
			cache: false,
			data: objetivosNovos +
				  detalhamentosNovos +
				  indicadoresNovos +
				  idObjetivos +
				  objetivos +
				  detalhamentos +
				  indicadores,
			error: function(){
				alert("Erro ao gravar os dados!");
				hideEspera();
			},
			success: function(msg){
				$('#objetivosEstrategicos').html(msg);
				alert("Dados gravados com sucesso!");
				hideEspera();
			}
		});
	}else
		hideEspera();
}


function adicionarFCS(){
	showEspera();
	var meio = $('#analise');

	var table = $(meio).find('table');
	var contador = parseInt($(meio).find('#contador').val());

	$(meio).find('#contador').val(contador + 1)
	contador += 1;

	var linha = '<tr><td><textarea name="fcsNovo['+contador+']" id="fcsNovo['+contador+']" onfocus="inputFocus(this)" onblur="inputBlur(this)" ></textarea></td><td class="tdNotas"><input type="radio" name="notaNovo['+contador+'][]" class="nota" value="1" id="notaNovo1['+contador+']" onclick="radioClick(this)" /></td><td class="tdNotas"><input type="radio" name="notaNovo['+contador+'][]" class="nota" value="3" id="notaNovo3['+contador+']" onclick="radioClick(this)" /></td><td class="tdNotas"><input type="radio" name="notaNovo['+contador+'][]" class="nota" value="5" id="notaNovo5['+contador+']" onclick="radioClick(this)" /></td><td class="tdNotas"><input type="radio" name="notaNovo['+contador+'][]" class="nota" value="7" id="notaNovo7['+contador+']" onclick="radioClick(this)" /></td><td class="tdNotas"><input type="radio" name="notaNovo['+contador+'][]" class="nota" value="9" id="notaNovo9['+contador+']" onclick="radioClick(this)" /></td><td class="tdPOAC"><input type="checkbox" name="checkPOACNovo['+contador+'][]" id="checkPOACNovo['+contador+']" /></td><td class="tdClassifica"><img src="imagens/excluir.png" class="btExcluir imgBt" title="Excluir fator" onclick="excluirFCS(this,false)" /></td></tr>';

	$(linha).appendTo(table);
	hideEspera();
}

function excluirFCS(bt,id){
	showEspera();
	if (confirm("Deseja excluir este fator crítico de sucesso?")) {
		if (id != false) {
			$.ajax({
				type: "GET",
				url: "./ajax/ajaxExcluiFCS.php",
				cache: false,
				data: "idFCS=" + id,
				error: function(){
					alert("Erro ao excluir o FCS!");
					hideEspera();
				},
				success: function(msg){
					if (msg != "false") {
						$(bt).parent().parent().parent().html(msg);
					}
					else
						alert(msg);
					hideEspera();
				}
			});
		}else{
			$(bt).parent().parent().remove();
			hideEspera();
		}
	}else{
		hideEspera();
	}
}



