/**
 * JS Document.
 * @author Sandro Jordão.
 */
 /* ****** CRUD DASHBOARD ****** */
function novoDashboard()
{
	verificarLogado();

	$.post(basepath + "relatorio/modalClonar", {
		tipo : 'D'
	}, function(data){

		$('#listDashboards, #abaDashboards').animate({ left: '-=327' }, 100, function(){ $('#abaDashboards').fadeIn('fast'); });

		$("#janela_modal").html('');
		$("#overlay").html('');

		var overlay = '<div id="overlay"></div>';
		var overlayCSS = {'width' : pageWidth + 'px','height' : pageHeight + 'px', 'z-index' : '9999998'};

		var janela = '<div id="janela_modal"></div>';
		var janelaCSS = {'top' : '50%','left' : '50%','width' : '420px','height' : '200px','margin-left' : '-210px','margin-top' : '-150px', 'z-index' : '9999999'};

		var btnFechar = '<a onClick="fechar()"><img id="btnFechar" src="' + basepath + 'www/imagem/close.png" alt="Fechar" title="Fechar" /></a>';
		var btnFecharCSS = {'position' : 'absolute','top' : '50%','left' : '50%','cursor' : 'pointer','margin-left' : '185px','margin-top' : '-107px'}

		var btnCancelar = '<input type="image" id="btn_cancelar" name="btn_cancelar" src="' + basepath + 'www/imagem/btn_cancelar.png" onClick="fechar()" />';
		var btnCancelaCSS = {'position' : 'absolute','top' : '100%','left' : '100%','margin-left' : '-115px','margin-top' : '-45px','width' : '100px'}

		var btnOK = '<input type="image" id="btn_enviar" name="btn_enviar" src="' + basepath + 'www/imagem/btn_avancar.png" onClick="criarDashboard()" />';
		var btnOKCSS = {'position' : 'absolute','top' : '100%','left' : '0%','margin-left' : '215px','margin-top' : '-45px','width' : '100px'}

		$("body").append(overlay);
		$("body").append(janela);
		$("#overlay").css(overlayCSS).fadeIn('slow', function(){

			$("#janela_modal").append(data);

			$("#janela_modal").append(btnFechar);
			$("#btnFechar").css(btnFecharCSS).fadeIn("slow");

			$("#janela_modal").append(btnCancelar);
			$("#btn_cancelar").css(btnCancelaCSS);

			$("#janela_modal").append(btnOK);
			$("#btn_enviar").css(btnOKCSS);

			$("#janela_modal").css(janelaCSS).fadeIn("slow");
		});

		return false;
	});

	// window.location.href = basepath + 'cadastros/caddashboards';
}

function fechar()
{
    $("#janela_modal").fadeOut();
    $("#overlay").fadeOut();
}

function buscaDashboardsClonar()
{
	var opcao = $('input[name=rdoDashboardClonar]:radio:checked').val();

	if(opcao == 'E')
		$("#comboDashboards").removeAttr("disabled");
	else
		$("#comboDashboards").attr("disabled", true).val("");
}

function criarDashboard()
{
	var opcao = $("input[name='rdoDashboardClonar']:checked").val();

	if(opcao == 'E')
	{
		var dashboard = $("#comboDashboards").val();

		if(dashboard != '')
			window.location.href = basepath + 'cadastros/alterarDashboard/' + dashboard + '/true'; // window.location.href = basepath + 'cadastros/caddashboards/' + dashboard;
		else
			return false;
	}
	else
	{
		window.location.href = basepath + 'cadastros/caddashboards';
	}
}

function editarDashboard()
{
	var dashboard = $("input[name='rdoDashboard']:checked").val();

	if(dashboard)
		window.location.href = basepath + 'cadastros/alterarDashboard/' + dashboard;
	else
		jAlert('Selecionar um dashboard para alteração!', 'Alerta!', function() { return false; });
}

function deletarDashboard()
{
	var dashboard = $("input[name='rdoDashboard']:checked").val();

	var ativo = $("#dashboardid").val();

	if(dashboard)
	{
		$.post(basepath + 'principal/verificarLogado',
			function(logado) {
				if(logado == 0)
				{
					//
					jConfirm("Deseja realmente excluir o dashboard?", 'Confirmação!',
					function(r) {
						if (r == true)
						{
							$.post(basepath + "cadastros/excluirDashboard", {
								dashboard  : dashboard,
								ativo : ativo
							}, function(data){
								if(data == 1) {
									jAlert('Dashboard excluído com sucesso!', 'Alerta!', function(){ window.location.href = basepath + 'principal/dashboard'; });
								} else {
									jAlert('Ocorreu um erro:\n ' + data, 'Alerta de erro!');
								}
							});
						}
						else
						{
							return false;
						}
					});
					//
				}
				else
				{
					window.location.href = basepath + 'principal/' + logado;
				}
			});
	}
    else
	{
		jAlert('Selecionar um dashboard para exclusão!', 'Alerta!', function() { return false; });
	}
}
/**
 * Listas de Dashboard/Relatorios
 * Manipulação do campo de procura
**/
function valor(id)
{
	if($('#' + id).val() == '')
	{
		$('#' + id).val('Pesquisar...');
		$('#' + id).removeClass('inputProcurarOff').addClass('inputProcurarOn');
	}
}

/**
 * Listas de Dashboard/Relatorios
 * Manipulação do campo de procura
**/
function limpar(id)
{
	if($('#' + id).val() == 'Pesquisar...')
	{
		$('#' + id).val('');
		$('#' + id).removeClass('inputProcurarOn').addClass('inputProcurarOff');
	}
}

/**
 * Listas de Dashboard/Relatorios
 * Procurar
**/
function procurar(tipo)
{
	var valor = (tipo == 1) ? $.trim($("#procurarDashboard").val()) : $.trim($("#procurarRelatorio").val());

	var dashboard = $("#dashboardid").val();

	if(valor == 'Pesquisar...') valor = '';

	if(valor.length > 2 || valor == '')
	{
		$("#btnProcurar").hide();
		$("#loadingModal").show();

		$.post(basepath + "principal/procurar", {
			dashboard : dashboard,
			valor 	  : valor,
			tipo 	  : tipo
		}, function(data) {
			if(tipo == 1)
			{
				$("#abaDashboard").html(data);

				$(".trDashboard").click(selecionarDashboard);
			}
			else
			{
				$("#abaRelatorio").html(data);

				$("#listasDashboard").slideDown('fast');

				if(valor != '')
				{
					$(".grupoContent").show();

					$(".sinal").each(function(){
						$(this).html('-');
					});
				}

				$(".trRelatorio").click(selecionarRelatorio);
			}

			$("#loadingModal").hide();
			$("#btnProcurar").show();
		});
	}
}

/**
 * Efeito Toggle nos grupos de relatorios
**/
function toggleLista(indice)
{
	if( $("#group_" + indice).is(':visible') )
	{
		$("#group_" + indice).slideUp('fast', function() {
			$("#sinal_" + indice).html('+');
		});
	}
	else
	{
		$("#group_" + indice).slideDown('fast', function() {
			$("#sinal_" + indice).html('-');
		});
	}
}

/* ****** FIM CRUD DASHBOARD ****** */

function ismobile()
{
  var check = false;

  (function(a)
  {
    if(/(bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))
      check = true
  })(navigator.userAgent||navigator.vendor||window.opera);

  return check;
}

 /**
 * Trocar de Dashboard
**/
function trocarDashboard(dashboard, aba)
{
	if(ismobile()) 
	{
		// Abre na mesma aba
		window.location.href = "mostradashboard/" + dashboard;
	} 
	else 
	{
		// ABRE A ABA
		JanelasAbertas["aba_dashboard_" + dashboard] = window.open("", "aba_dashboard_" + dashboard);
		JanelasAbertas["aba_dashboard_" + dashboard].close();
		JanelasAbertas["aba_dashboard_" + dashboard] = window.open("mostradashboard/" + dashboard, "aba_dashboard_" + dashboard);

		// GRAVA
		setTimeout(function(){
			$.post(basepath + "principal/gravaescolha", {
				dashboard : dashboard
			}, function(data) {
				setTimeout(function(){
					location.reload();
				}, 6000);
			});
		}, 1000);
	}
}

/**
 *
**/
function selecionarRelatorio()
{
	$(this).children().children("input[name='rdoRelatorio']:first").attr('checked', true);

	$(".trSelected").removeClass('trSelected').addClass('trRelatorio');

	$(this).removeClass('trRelatorio').addClass('trSelected');

	return false;
}

/**
 * Mostra/Esconde a lista de relatorios
**/
function animateReports()
{
	emAnimacao = true;

	if($('#listReports').offset().left == 0)
	{
		$('#listReports, #abaReports').animate({ left: '-=327' }, 100, function(){ $('#abaReports').fadeIn('fast'); emAnimacao = false; });

		return false;
	}
	else
	{
		verificarLogado();

		var dashboard = $("#dashboardid").val();

		$.post(basepath + "principal/listaRelatorios", {
			dashboard : dashboard
		},function(data) {
			$('#listReports').html(data);

			$('#abaReports').fadeOut('fast');

			$('#listReports, #abaReports').animate({ left: '+=327' }, 1000, function() { emAnimacao = false; });

			$(".trRelatorio").click(selecionarRelatorio);
		});

		return false;
	}
}

/**
 *
**/
function selecionarDashboard()
{
	$(this).children().children("input[name='rdoDashboard']:first").attr('checked', true);

	$(".trSelected").removeClass('trSelected').addClass('trDashboard');

	$(this).removeClass('trDashboard').addClass('trSelected');

	return false;
}

/**
 * Mostra/Esconde a lista de dashboards
**/
function animateDashboards()
{
	emAnimacao = true;

	if($('#listDashboards').offset().left == 0)
	{
		$('#listDashboards, #abaDashboards').animate({ left: '-=327' }, 100, function(){ $('#abaDashboards').fadeIn('fast'); emAnimacao = false; });

		return false;
	}
	else
	{
		verificarLogado();

		var dashboard = $("#dashboardid").val();

		$.post(basepath + "principal/listaDashboards", {
			dashboard : dashboard
		},function(data) {
			$('#listDashboards').html(data);

			$('#abaDashboards').fadeOut('fast');

			$('#listDashboards, #abaDashboards').animate({ left: '+=327' }, 1000, function() { emAnimacao = false; });

			$(".trDashboard").click(selecionarDashboard);
		});

		return false;
	}
}

/**
 * Função Inicial
**/
function init()
{
	// Altura e Largura da Pagina
	pageWidth = $(document).width();
	pageHeight = $(document).height();

	// Abre/Fecha a lista de dashboards
	$('#abaDashboards').click(function(e) { e.stopPropagation(); if(!emAnimacao) { animateDashboards(); } });

	// Abre/Fecha a lista de relatorios
	$('#abaReports').click(function(e) { e.stopPropagation(); if(!emAnimacao) { animateReports(); } });
}
var emAnimacao = false;
$(document).ready(init);