// ======== Funções de help por campo:

function HelpOn(label){
  document.getElementById(label).className = 'help_on';
}

function HelpOff(label){
  document.getElementById(label).className = 'help_off';
}


// =================================================================== //
// ======== Funções de menu:

// Alterna o ítem aberto:
function SwapMenu0(id){
  var item = document.getElementById(GetCookie('menu_item'));

  if (item) item.style.display = 'none';
	document.getElementById(id).style.display = 'block';
  SetCookie('menu_item', id);
}

// Abre / fecha um ítem:
function SwapMenu(id){
  var item = document.getElementById(id);

  if (item.style.display == 'block'){
	    item.style.display = 'none';
	} else {
	  item.style.display = 'block';
	}
    SetCookie('menu_item', id);
}

// Mantem o menu aberto durante a navegação:
function OpenLastItem(){
    var id = GetCookie('menu_item');
    if (id != null) SwapMenu(id) ;
}


// =================================================================== //
// ======== Funções de coockies:

function SetCookie(name, value){
    document.cookie = name + "=" + value + ";";
}

function getCookieVal (offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return getCookieVal (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}


// =================================================================== //
// ======== Swaps:

function Swap(id){
    obj = document.getElementById(id);
    if (obj){
        obj.style.display = (obj.style.display == 'none') ? 'block' : 'none';
    }
}


// =================================================================== //
// ======== Swaps Tabs:

var old_tab = "";
function SwapTab(id){
  // Tab ativa fica inativa:
  if (old_tab != ""){
      obj = document.getElementById("tab_" + old_tab);
      btn = document.getElementById("btn_" + old_tab);
      obj.style.display = 'none';
      btn.className   = "tab_off";
  }

	// Ativa a nova tab
	if (old_tab != id){
      obj = document.getElementById("tab_" + id);
      btn = document.getElementById("btn_" + id);
      obj.style.display = 'block';
      btn.className   = "tab_on";
      old_tab = id;
  } else {
      old_tab = "";
  }
}


// =================================================================== //
// ======== goTo:

function goTo(url){
  document.location = url;
}


// =================================================================== //
// ======== doSubmit:

function doSubmit(actn){
  var frm = document.getElementById('frm');
  if (frm == 'undefined'){
      alert('Formulário "frm" não encontrado.');
      return false;
  }

  frm.action = actn;
  frm.submit();
}

// =================================================================== //
// ======== setChecked:

function setChecked(from_obj, to_id, value){
  to_obj = document.getElementById(to_id);
  to_obj.value = (from_obj.checked ? value : '');
}


// =================================================================== //
// ======== Editor DHTML

// Aplica comandos:
function apply(nome, what, interf, value){
  var div_html = document.getElementById("html_" + nome);
  var txt_area = document.getElementById("area_" + nome);

  if (div_html.style.display == 'block'){
      applyDHTML(what, interf, value);
      txt_area.innerText = div_html.innerHTML;
  } else {
     applyText(what, value);
    // div_html.innerHTML = txt_area.innerText;
  }

}

// Aplica comandos DHTML:
function applyDHTML(what, interf, value){
  var selType   = document.selection.type;
	var textRange = document.selection.createRange();
	var msgSel    = "Você deve selecionar algo na página para executar esta operação."

	// ==== Seleção inválida:
	if (textRange == null || textRange == "undefined"){
	    alert(msgSel);
		return false;
	}

	// ==== Imagem:
	if (what == "Image"){

		// Nada selecionado
		if (selType == "None"){
		    alert(msgSel);
		    return false;

		// Inserção de imagem:
		} else if (selType == "Text"){
		       imgName = prompt("Informe o nome da imagem.", "img.gif");
		       textRange.parentElement().insertAdjacentHTML("beforeEnd", "<img src=\"publish/imgprod/fotos_clipping/" + imgName + "\" hspace=\"0\" vspace=\"0\" align=\"left\">");
			     return true;

		// Alteração de imagem:
		} else if (textRange.item(0).tagName == "IMG"){
		       imgName = prompt("Informe o nome da imagem.", "img.gif");
		       textRange.item(0).src = "publish/imgprod/fotos_clipping/" + imgName;
		       return true;
		}
	}

	// ==== Cores:
	if (what == "Cor"){
	    if (textRange.text != ""){
          textRange.execCommand("ForeColor", false, value);
          textRange.select();
			    return true;
      }
		return false;
	}

  // ==== Estilos / Hiperlinks / Alinhamentos:
  if (textRange.text != "")
      textRange.execCommand(what, interf, value);
}

// Aplica comandos Text:
function applyText(what, value){
  var selType   = document.selection.type;
	var txtRange  = document.selection.createRange();
	var msgSel    = "Você deve selecionar algo na página para executar esta operação."

	// ==== Seleção inválida:
	if (txtRange == null || txtRange == "undefined"){
	    alert(msgSel);
		return false;
	}

  switch (what){
      case 'JustifyRight'  : txtRange.text = '<p align=right>'  + txtRange.text + '</p>';
                             break;

      case 'JustifyCenter' : txtRange.text = '<p align=center>' + txtRange.text + '</p>';
                             break;

      case 'JustifyLeft'   : txtRange.text = '<p align=left>'   + txtRange.text + '</p>';
                             break;

      case 'Underline'     : txtRange.text = '<u>' + txtRange.text + '</u>';
                             break;

      case 'Italic'        : txtRange.text = '<i>' + txtRange.text + '</i>';
                             break;

      case 'Bold'          : txtRange.text = '<b>' + txtRange.text + '</b>';
                             break;

      case 'CreateLink'    : txtRange.text = '<a href="">' + txtRange.text + '</a>';
                             break;
  }
  document.selection.empty()
  return true;
}

// Move o conteudo do div p/ o textarea:
function moveSource(nome){
  var div_html = document.getElementById("html_" + nome);
  var txt_area = document.getElementById("area_" + nome);

  if (div_html && txt_area)
      txt_area.innerText = div_html.innerHTML;
}


// Alterna modo HTML/Texto puro:
function swapHTML(nome, img, base_href){
  var div_html = document.getElementById("html_" + nome);
  var txt_area = document.getElementById("area_" + nome);

  if (div_html.style.display == 'block'){
      txt_area.innerText = div_html.innerHTML;
      div_html.style.display = 'none';
      txt_area.style.display = 'block';
      img.src = base_href + "/botao_html_on.gif";
  } else {
      div_html.innerHTML = txt_area.innerText;
      div_html.style.display = 'block';
      txt_area.style.display = 'none';
      img.src = base_href + "/botao_html_off.gif";
  }
}




// =================================================================== //
// ======== Altera valor em estilos:

// Deve haver na pág. onde for usado a seguinte estrutura:
// <script>
// var passo = 5;                 <== Valor de incremento de fonte;
// var styleArr = new Array();    <== Lista de estilos que serão alterados;
// styleArr[0] = ".exemplo H1";
// styleArr[1] = ".exemplo p";
// styleArr[2] = ".exemplo td";
// </script>

var storeArr = new Array();

// Pega estilo por selector - nome do estilo
function getStyleBySelector(selector){
    var sheetList = document.styleSheets;
    var ruleList;
    var i, j;
    var msg = "";

    for (i=sheetList.length-1; i >= 0; i--){
         ruleList = sheetList[i].rules;

         for (j=0; j<ruleList.length; j++){
            if (ruleList[j].selectorText.toUpperCase() == selector.toUpperCase())
                return ruleList[j].style;
        }
    }
    return null;
}

// Altera tamanho de fonte por estilo:
function changeFontSize(to){

  // Pega os estilos:
  if (storeArr.length == 0){
      for (x = 0; x < styleArr.length; x++)
           storeArr[x] = getStyleBySelector(styleArr[x]);
  }

  // Altera tamanho da fonte:
  for (x = 0; x < styleArr.length; x++){

       if (storeArr[x] != null){
           n = parseInt(storeArr[x].fontSize);

           if (n == 0)   n = 8;
           if (isNaN(n)) n = 8;

           if (to == 'up') n += passo;
           else n -= passo;
           storeArr[x].fontSize = n + "pt";
       }
  }

}



// =================================================================== //
// ======== Multiselect em listagens:

/* function rowColor(row, color)

   Função (shameless) adaptada do MySQLAdmin
   para setar cores em uma listagem.

*/

// Cores padrão:
var hover_on  = "#e4e4e4";
var hover_off = "#eeeeee";
var hover_sel = "#FDEE9C";
var hover_del = "#F1C17D";
var img_hover_off = "#808080";

//
var old_row = '';
var old_row_status = '';



function onOverColor(row){
    if (row.status == 'sel_off' && row.to_del == 'false') rowColor(row, hover_on);
}

function onOutColor(row){
    if (row.status == 'sel_off' && row.to_del == 'false') rowColor(row, hover_off);
}


function rowColor(row, color){
  // Se não vier a cor:
  if (!color){
      switch (row.status){
          case 'sel_on'  : color = hover_sel; break;
          case 'sel_off' : color = hover_off; break;
      }
      if (row.to_del == 'true'){
          color = hover_del;
      }
  }

  // Seta a nova cor:
  var rcount = row.cells.length;
  for (var c = 0; c < rcount; c++)
       row.cells[c].style.backgroundColor = color;

  return true;
}

function selRow(from_td, value){
  document.getElementById('_list_sel_').value = value;
  var row = from_td.parentElement;
  var color = '';

  // Deseleciona:
  if (old_row != ''){
      old_row.status = old_row_status;
      rowColor(old_row);
  }
  old_row_status = row.status;
  old_row = row;

  row.status = 'sel_on';
  if (row.to_del == 'true') color = hover_sel;

  rowColor(row, color);

  return true;
}

function selRowToDel(from_td){
  var row = from_td.parentElement.parentElement;

  // Deseleciona:
  row.to_del = (row.to_del == 'true' ? 'false' : 'true');

  // Seta a nova cor:
  rowColor(row);
}


function cellColor(cell, color){
  if (cell.status == 'sel_on' && color != hover_sel)
      return false;

  // Seta a nova cor:
  cell.style.backgroundColor = color;

  return true;
}


function swapSelCell(cell, chkid){
  chk = document.getElementById(chkid);

  // Deseleciona:
  if (cell.status == 'sel_on' || cell.status == 'sel_del'){
      cell.status = 'sel_off';
      cor = hover_on;
      if (chk != 'undefined'){
          chk.checked = false;
      }

  //Seleciona:
  } else {
      cell.status = 'sel_on';
      cor = hover_sel;
      if (chk != 'undefined'){
          chk.checked = true;
      }
  }

  // Seta a nova cor:
  cellColor(cell, cor);

  return true;
}


function swapCheck(cell, id){
  chk = document.getElementById(id);
  chk.checked = (cell.status == 'sel_on');
}


function getInputOn(owner, type){
  var inputs = owner.getElementsByTagName('INPUT');
  var count  = inputs.length;
  var result = new Array();

  for (var x = 0; x < count; x++){
       if (inputs[x].type == type)
           result[result.length] = inputs[x];
  }
  return result;
}


//========================== Verifica Selecionados ===========================//
                                                       //-- By Labs 05/2003 --//

/* chkSel():
       Verifica se existem registros selecionados, se não, reclama.
*/
function chkSel(tipo){
  var frm = document.getElementById('frm');
  if (frm == 'undefined'){
      alert('Formulário "frm" não encontrado.');
  }

  // Verificação por checkbox:
  if (tipo == "chk"){
      chkArr = getInputOn(document, 'checkbox');
      tmpArr = new Array();
      var count = chkArr.length;
      for (var x = 0; x < count; x++){
           if (chkArr[x].checked) tmpArr[x] = chkArr[x];
      }
      count = tmpArr.length;

  // Verificação por input hidden:
  } else {
    count = document.getElementById('_list_sel_').value;
  }

  if (count == 0){
      alert('Nenhum registro selecionado.');
      return false;
  }

  return true;
}


// ============================ Confirma Deleção ============================ //
                                                       //-- By Labs 05/2003 --//
/* function verifyDel()
   Função para confirmar deleção.
*/
function verifyDel(msg, actn){
  var frm = document.getElementById('frm');
  if (frm == 'undefined'){
      alert('Formulário "frm" não encontrado.');
  }

  if (confirm(msg)){
      frm.action = actn;
      frm.submit();
  }
}


/* function scrollBox(dir, id_box)

   Função para scroll lateral em um box.
   Devem ser setadas as seguintes variáveis na página:

*/
   var sRepeat = null;
   var amount  = 20;


function scrollBox(dir, id_box) {
   var box = document.getElementById(id_box);
   if (dir=="right") box.scrollLeft -= amount;
   else box.scrollLeft += amount;

   if (sRepeat == null)
       sRepeat = setInterval("scrollBox('" + dir + "', '" + id_box + "')", 100);

   return false;
}


// =================================================================== //
// ======== Funções de filtros em listagens:


/* function rowColor(row, color)

   Função (shameless) adaptada do MySQLAdmin
   para setar cores em uma listagem.

*/
function setFiltro(sel, sel_val, params){
    tbl_area = document.getElementById('_filtro_area_');
    if (!tbl_area) return false;

    var areaRow   = tbl_area.rows[0];
    var areaCells = areaRow.cells;

    // Remove antiga:
    var c = areaCells.length;
    for (x = 0; x < c; x++){
        areaRow.deleteCell();
    }

    if (sel_val != '' && sel_val != undefined){
        sel.value = sel_val;
    }

    // Cria a nova area:
    val = sel.value;
    document.getElementById('_tipo_filtro_').value = filtArr[val][0];
    switch (filtArr[val][0]){

      // Filtro por valor parcial:
      case 'texto' : if (params != '' && params != undefined) parm1 = params[0];
                     else parm1 = "";

                     var cell_1 = areaRow.insertCell(areaCells.length);
                     cell_1.width = '80%';
                     cell_1.style.border = "2px solid silver";
                     cell_1.innerHTML = "<label>" + filtArr[val][1] + ":</label><br>";
                     cell_1.innerHTML += "<input type='text' name='_PARAM1_' style='width:100%' value='" + parm1 + "'>";

                     var cell_2 = areaRow.insertCell(areaCells.length);
                     cell_2.style.border = "2px solid silver";
                     cell_2.innerHTML = "<input type='checkbox' name='_pre_percent_' id='_pre_percent_' value='%' checked>";
                     cell_2.innerHTML += "<label for='_pre_percent_'>% antes<label>&nbsp;&nbsp;";
                     cell_2.innerHTML += "<input type='checkbox' name='_pos_percent_' id='_pos_percent_' value='%' checked>";
                     cell_2.innerHTML += "<label for='_pos_percent_'>% depois<label>&nbsp;&nbsp;";
                     break;

    // Filtro booleano:
    case 'boolean' : if (params != '' && params != undefined) parm1 = params[0];
                     else parm1 = "";
                     var chkd1 = (parm1 == 1 ? 'checked' : '');
                     var chkd2 = (parm1 == 0 ? 'checked' : '');

                     var cell_1 = areaRow.insertCell(areaCells.length);
                     cell_1.width = '100%';
                     cell_1.style.border = "2px solid silver";
                     cell_1.innerHTML = "Selecione o valor: <input type='radio' name='_PARAM1_' id='_PARAM1a_' value='1' " + chkd1 + ">";
                     cell_1.innerHTML += "<label for='_PARAM1a_'>" + filtArr[val][1] + "<label>&nbsp;&nbsp;";
                     cell_1.innerHTML += "<input type='radio' name='_PARAM1_' id='_PARAM1b_' value='0' " + chkd2 + ">";
                     cell_1.innerHTML += "<label for='_PARAM1a_'>" + filtArr[val][2] + "<label>&nbsp;&nbsp;";
                     break;

  // Filtro por faixas de valores:
  case 'faixa_num' : if (params != '' && params != undefined){
                         parm1 = params[0];
                         parm2 = params[1];
                     } else{
                         parm1 = "";
                         parm2 = "";
                     }

                     var cell_1 = areaRow.insertCell(areaCells.length);
                     cell_1.width = '50%';
                     cell_1.style.border = "2px solid silver";
                     cell_1.innerHTML  = "<label>" + filtArr[val][1] + ":</label><br>";
                     cell_1.innerHTML += "<input type='text' name='_PARAM1_' style='width:100%' value='" + parm1 + "'>";

                     var cell_2 = areaRow.insertCell(areaCells.length);
                     cell_2.width = '50%';
                     cell_2.style.border = "2px solid silver";
                     cell_2.innerHTML += "<label>" + filtArr[val][2] + ":</label><br>";
                     cell_2.innerHTML += "<input type='text' name='_PARAM2_' style='width:100%' value='" + parm2 + "'>";
                     break;

 // Filtro por faixas de data:
 case 'faixa_data' : if (params != '' && params != undefined){
                         parm1 = params[0];
                         parm2 = params[1];
                     } else{
                         parm1 = "";
                         parm2 = "";
                     }

                     var cell_1 = areaRow.insertCell(areaCells.length);
                     cell_1.width = '50%';
                     cell_1.style.border = "2px solid silver";
                     cell_1.innerHTML  = "<label>" + filtArr[val][1] + ":</label><br>";
                     cell_1.innerHTML += "<input type='text' name='_PARAM1_' style='width:100%' value='" + parm1 + "'>";

                     var cell_2 = areaRow.insertCell(areaCells.length);
                     cell_2.width = '50%';
                     cell_2.style.border = "2px solid silver";
                     cell_2.innerHTML += "<label>" + filtArr[val][2] + ":</label><br>";
                     cell_2.innerHTML += "<input type='text' name='_PARAM2_' style='width:100%' value='" + parm2 + "'>";
                     break;

    }

    tbl_area.style.display = 'block';
}
