
// funcao que exibe a ajuda.
function exibe_help(msg){
	document.getElementById("ajuda").innerHTML = msg;
}
function AbrirPopup(url,name,features)
{
    var janela = window.open(url,name,features);
    
    if(janela==null)
    {
        alert('Prezado(a) usuário(a),o seu navegador da internet está utilizando um tipo de bloqueador de pop-up. Por favor desbloquei-o para continuar a navegação.');
    }
}

//Funcao responsavel por abrir um nova janela com caracteristicas.
function MM_openBrWindow(theURL,winName,features) 
{
    window.open(theURL,winName,features).moveTo(300,300);
}

// funcao Oculta a div que aparece ao carregar uma pagina.
function fecha_div() {
	document.getElementById('carregando').style.visibility = "hidden";
}


//Função responsavel por ocultar a mensagem de sucesso em alguma operação
function OcultaMessagem()
{
    document.getElementById('include_messagem').style.display = 'none';
}



// GET PAGE/Funções responsaveis por mudar o foco das abas no modulo Configurações.
// ..................................................................................
function getPage()
{
	return pg_referencia;
}

function setClass(obj, classe)
{
	obj.className = classe;
}

function verPag()
{
	pag = getPage();
	if(pag=='')
		pag = 'default';	
	obj = document.getElementById(pag);
	setClass(obj,'selected');
}

// ................................................................................................
// ................................................................................................

// ................................................................................................
//Responsavel por marcar ou desmarcar uma fileira(Horizontal) de checkbox.
function CheckAllBoxesH(source)
{
	var children = document.getElementById(source).getElementsByTagName("INPUT");
	//Verifica se deve marcar ou desmarcar as imagens
	
	var estado = document.getElementById("estadoCheckbox");
	
	var flag = false;
	for (var i = 0; i < children.length; i++)
	{
		var input = children[i];
		if (input.type == "checkbox")
		{
			if(input.checked == false)
			{
                if(estado.value == "1")
                {
			        input.checked = true;
			        flag = true;   
			    }
			}
			if(estado.value!="1")
			{
		        input.checked = false;
		        flag = false;
		     }
		}
		
	}
	if(flag){
	    estado.value = "0";
	    }
	 else{
	    estado.value = "1";
	    }
}


//Desabilita...
function DisableAll(source) {
	var children = document.getElementById(source).getElementsByTagName("INPUT");
	
	for (var i = 0; i < children.length; i++)
	{
		var input = children[i];
		if (input.type == "checkbox")
			input.disabled = true;
	}
}

function keyDown(event)
{
	var ieKey = 0;
	if (!event)
		event = window.event;
	if (ns4)
		ieKey = event.which;
	else
  	ieKey = event.keyCode;

  if (ieKey == 27) { //Esc
  	var janela = window;
		while(janela.parent!=janela)
			janela = janela.parent;
		janela.close();
  }
	if (ns4)	
		document.captureEvents(Event.KEYDOWN)
  document.onkeydown = keyDown;
}
// ................................................................................................


//.......................Metodos para marcar e desmarcar um checkbox dentro do RadGrid..............
//Cria a linha com o checkbox do grid.
function RowCreated(gridRow)
{
    //Ao se criar uma linha dentro do grid, verifica aonde a linha é do tipo Item ou AlternatingItem.
    if ((gridRow.ItemType == "Item") ||
        (gridRow.ItemType == "AlternatingItem"))
    {
       //Pega-se as tabela  onde contém-se as linhas.
        var gridRowTable = gridRow.Owner;
       
        //Variavel que contém a linha que tem o nome TemplateColumn.
        var cell = gridRowTable.GetCellByColumnUniqueName(gridRow, "TemplateColumn");

        if (!cell)
            return;
        //Chama a função GetCheckBox passando a linha.
        var checkBox = GetCheckBox(cell);
            
        if (!checkBox)
        {
            return false;
          }
        
        //Verifica se a linha está selecionada ou não. Em caso afirmativo, o checkbox também fica marcado
        //Caso contrário fica desmarcado.
        gridRow.Selected ? checkBox.checked = true : checkBox.checked = false;

        
        var gridTable = this;
        checkBox.onclick = function()
        {
           gridTable.SelectRow(gridRow.Control, false);
        };
    }
}

//Pega a linha selecionada
function RowSelected(gridRow)
{
    var gridRowTable = gridRow.Owner;
    var cell = gridRowTable.GetCellByColumnUniqueName(gridRow, "TemplateColumn");
    
    if (!cell)
        return;

    var checkBox = GetCheckBox(cell);
    
    if (!checkBox){
        return false;
     }
    
   gridRow.Selected ? checkBox.checked = true : checkBox.checked = false;
   
}
function RowSelecting(gridRow)
{
    var gridRowTable = gridRow.Owner;
    var cell = gridRowTable.GetCellByColumnUniqueName(gridRow, "TemplateColumn");
    
    if (!cell)
        return;

    var checkBox = GetCheckBox(cell);

    if (!checkBox)
    {
       return false;
    }
}

function RowDeselected(gridRow)
{
    var gridRowTable = gridRow.Owner;
    var cell = gridRowTable.GetCellByColumnUniqueName(gridRow, "TemplateColumn");

    if (!cell)
        return;

    var checkBox = GetCheckBox(cell);

    if (!checkBox)
    {
       return false;
    }
    gridRow.Selected ? checkBox.checked = true : checkBox.checked = false;
}
//Passa-se um linha e retorna o controle.
function GetCheckBox(control)
{
    
    if (!control)
        return;
    //Percorre-se todos os controles ...   
    for (var i = 0; i < control.childNodes.length; i++)
    {
        if (!control.childNodes[i].tagName)
            continue;
         //Se o controle for o checkox, retorna ele.
        if ((control.childNodes[i].tagName.toLowerCase() == "input") &&
            (control.childNodes[i].type.toLowerCase() == "checkbox"))
        {
            
            return control.childNodes[i];
        }
    }
}

//Variavel que conterá o grid.
var WRGrid;


//Função chamada quando o grid é criado...aqui seta-se a variavel WRGrid com o grid da pagina.
function GridCreated()
{ 
    WRGrid = this;
    setFooter();
}

//Função chamada para marcar todos os checkbox de uma pagina.            
function CheckAll(checkGrid)
{
  
  for (var i = 0; i < WRGrid.MasterTableView.Rows.length; i++)
  {
    var gridRow = WRGrid.MasterTableView.Rows[i];
    if ((gridRow.ItemType == "Item") ||
          (gridRow.ItemType == "AlternatingItem"))
    {
          var cell = WRGrid.MasterTableView.GetCellByColumnUniqueName(gridRow, "TemplateColumn");

          if (!cell)
                return;

          var checkBox = GetCheckBox(cell);
          
          if(checkBox)
          {
            if(checkGrid.checked)
            {
                if(!gridRow.Selected)
                    checkBox.click();
             }
             else{
                if(gridRow.Selected)
                    checkBox.click();
             }
            
            
          }
          
    }
  }
}

//.....................................................................................................

//......................................................................................................
//Função responsável pela barra do exportar(Word e Excel) presente nas paginas de "ver".
//Passa-se o id da div que irá sumir e aparecer, e as imagens que serão exibidas quando a div
//estiver aparecendo e quando não estiver.
function toggle(id,img1,img2)
{
    el = document.getElementById(id);
    
    var display = el.style.display ? '' : 'none';
    if(display==''){
        document.getElementById('imagemSeta').src = img1;
    }
    else{
        document.getElementById('imagemSeta').src = img2;
    }
    
    el.style.display = display;
}
//..........................................................................................................

/*Bloc de funções responsaveis pelo componente Telerik Window*/

//Funcao responsavel por abrir uma nova janela
function criaJanela(url,largura,altura)
{
    // Invoca o window
    var oWindow = window.radopen(url, null);

    oWindow.SetSize(largura, altura);
    oWindow.SetModal(true);
    oWindow.MoveTo(80,80);
}

function GetRadWindow()
{
	var oWindow = null;
	if (window.radWindow) oWindow = window.radWindow;
	else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
	return oWindow;
}

function fecharWindow() {
    var oWindow = GetRadWindow();
    oWindow.Close();
}


//Para sumir com as barras quando se está no modo modal
function OnClientShow(radWindow)
{ 
    if (document.all)
    {               
        document.body.scroll = "no";
    }
    else
    {
        var oTop = document.body.scrollTop;
        document.body.style.overflow = "hidden";
        document.body.scrollTop = oTop;
    }
}    
    
function OnClientClose(radWindow)
{
    document.body.scroll = "";
    document.body.style.overflow = "";
}   


//.................................................................................................
//Função responsável por fazer a tabela que contém o id FormCadastro aparecer..
function tabelaCadastro(modulo,tipo){
   
    //Metodo ajax para verifica se o usuário tem permissão para inserir ou não.
    var aux = Permissao.PermissoesInserirPagina(modulo,tipo).value;
    if(aux == false)
    {
        window.open(Permissao.RetornaCaminho().value,"_self");
    }
      //Fim Ajax.
    else{
      
        
        el = document.getElementById('FormCadastro');     
        el.style.display = '';
        //Sumindo com a barra principal ao tentar inserir...
        barra = document.getElementById('barraPrincipal');
        barra.style.display='none';    
    }
    
}


//Função responsável por cancelar uma ação do usuário.Somente usado quando o formulário está 
//na mesma pagina do ver.
function Cancelar(redireciona){
      
    el = document.getElementById('FormCadastro');     
    if(confirm('Você tem certeza que deseja cancelar a ação?')){
        el.style.display = 'none';
        window.location = redireciona;
    }
    else{
        el.style.display = '';
    }
}

function Cancelar2(redireciona)
{
    if(confirm('Você tem certeza que deseja cancelar a ação?')){
        window.location = redireciona;
    }
    else
    {
        return false;
    }
}


//-----------------Busca--------------------------------------
//Função responsavel por aparecer e desaparecer com o texto no campo Busca
function switchText(object, baseText, eventName)
{
    if (eventName == "blur")
    {
	    if (object.value == "")
	    {
		    object.value = baseText;
	    }
    }
    else
    {
	    if (object.value == baseText)
	    {
		    object.value = "";
	    }
    }
}
//---------------------------------------------------------------------------------------------------------------

//Função para ao se dá um Enter cair sobre o evento de submit da pagina...
//Está função só é valida para os formulário que são exibidos na mesma pagina que o VER.
//Por padrão foi definido que a tabela que contém o formulário deverá ter o ID:FormCadastro
//E o botão de submit do formulario deverá ter o ID:cadastra
function Enter()
{
    if(event.keyCode==13)
    {
        if(document.getElementById('FormCadastro').style.display==''){
            document.getElementById('cadastra').click();		
            return false;
        }
    }
    return true;
}

//---------------------------------------------------------------------------------------------------------------

//Função utilizada para verificar o Maxlenth em campos tipo TextArea ou TextBox do tipo Multiline.
function verificaTamanho(controle,tam, tipo)
{
    var n_car = controle.value.length;
    if(n_car > tam){
        if(tipo == "cortar")
        {
            controle.value = controle.value.slice(0,tam);
        }
        return false;
     }
    return true;
}


//---------------------------------------------------------------------------------------------------------------

//Function responsavel por exibir as mensagens que aparecem quando se vai excluir algum item que está sendo exibido dentro
//de um grid.
function MessagemExcluir(mensagem)
{
    if(confirm(mensagem))
    {
        return true;
    }
    return false;
}
//-------------------------------------------------------------------------------------------------------------------

//Adcionando Evento no onLoad da pagina..
function addLoadEvent(func){
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}else{
		window.onload = function(){
			oldonload();
			func();
		}
	}
}