/* ===-----------=== Komanche 2.0 ===-----------===

           Copyright:     © 2004, CBA Consult ltda.
            Coded by:  Luiz Antonio B. Silva [Labs]
                      Todos os direitos reservados.

                http:         www.cbaconsult.com.br
                mail:   comercial@cbaconsult.com.br

   Funções genéricas.

-------------=== Vs. 1.0 - Jan/2004 | By Labs --=== */



// ======== Funções de help por campo:

function HelpOn(label){
  document.getElementById(label).className = 'help_on';
}

function HelpOff(label){
  document.getElementById(label).className = 'help_off';
}


// =================================================================== //
// ======== Timers:
var banners_timer  = new Array();
var chamadas_timer = new Array();


// =================================================================== //
// ======== Preload de imagens:

function preLoadImgs(url, imgs){

    var len = imgs.length; 
    for (x=0; x<len; x++){
       var img = new Image();
       img.src = url + imgs[x];
    }
}


// =================================================================== //
// ======== Funções de fade de áreas:


function fadeContents(area, delay, timer_name){

    // Acerta indices:
    eval('var len = ' + area + '_arr.length;');
    eval('var ndx = ' + area + '_ndx;');
    ndx++;
    ndx = (ndx < len ? ndx : 0);
    eval(area + '_ndx = ' + ndx + ';');

    // Pega conteudo:
    eval('var content = escape(' + area + '_arr[' + ndx + ']);');

    // Dá fade-out na área:
    setTimeout('fadeAreaOut(\"' + area + '_fade\")', 1 * 100);

    // Dá fade-in na área:
    setTimeout('fadeAreaIn(\"' + area + '_fade\", \"' + content + '\")', 1.5 * 1000);

    // Restarta o processo:
    delay = (delay < 2 ? 2 : delay);
    var res  = setTimeout('fadeContents(\"' + area + '\", ' + delay + ', \"' + timer_name + '\")', (delay + 2) * 1000);

    // Armazena timers:
    eval(timer_name + '["' + area + '"]  = ' + res  + ';');
}

function fadeAreaOut(area) {

    // Recupera a área:
    obj = document.getElementById(area);
    if (!obj) return false;

    // Fade out:
    if (navigator.appName == 'Microsoft Internet Explorer'){
        obj.style.filter="blendTrans(duration=1)";
        if (obj.filters.blendTrans.status != 2) {
            obj.filters.blendTrans.apply();
            obj.style.visibility="hidden";
            obj.filters.blendTrans.play();
        }
    } else {
        obj.style.visibility="hidden";
    }

    // Apaga o conteudo:
    //obj.innerHTML = "";
}

function fadeAreaIn(area, content, timerId) {

    // Recupera a área:
    obj = document.getElementById(area);
    if (!obj) return false;

    // Altera o conteudo:
    if (content){
        obj.innerHTML = unescape(content);
    }

    // Fade in:
    if (navigator.appName == 'Microsoft Internet Explorer'){
        obj.style.filter="blendTrans(duration=2)";
        if (obj.filters.blendTrans.status != 2) {
            obj.filters.blendTrans.apply();
            obj.style.visibility="visible";
            obj.filters.blendTrans.play();
        }
    } else {
        obj.style.visibility="visible";
    }
}

// =================================================================== //
// ======== Funções de banners:

function putBanner(area, keys, ndx, delay){

    eval("var _banners = new Array(" + keys + ")");
    var len = _banners.length;
    var key = _banners[ndx];

    ndx++;
    ndx = (ndx >= len ? 0 : ndx);

    // Dá fade-out na área:
    setTimeout('fadeAreaOut(\"' + area + '\")', 1 * 100);


    call({pack: 'banners', modulo: 'banners', object: 'banBanners',
          action: 'getItem', box: area, banner: key, KMScript: 0}, 'putHTML');

    // Dá fade-in na área:
    setTimeout('fadeAreaIn(\"' + area + '\")', 1.5 * 1000);

    banners_timer[area] = setTimeout('putBanner(\"' + area  + '\", \"' + keys  + '\", '
                                                    + ndx   + ',' + delay + ')', delay * 1000);

}

function processClick(banner_key, url){

    call({pack: 'banners', modulo: 'banners', object: 'banBanners',
          action: 'setClick', key: banner_key});

    if (url){
        window.open(url);//, 'floats', 'scrollbars=no,toolbar=no,location=no,directories=no,status=yes,menubar=no,resizable=no,width=' + largura + ',height=' + altura + ',left=50,top=50');
    }
}


// =================================================================== //
// ======== 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;
}


// =================================================================== //
// ======== Funções de menu:

var _LAST_MENU_ = "";

// Alterna o ítem aberto:
function swapMenu(id){
    if (_LAST_MENU_ != id){
        swapOff(_LAST_MENU_);
        _LAST_MENU_ = id;
    }               
    swapOn(id);
}

function closeMenu(){
    swapOff(_LAST_MENU_);
}


// =================================================================== //
// ======== Swaps:

function Swap(id){
    obj = document.getElementById(id);
    if (obj){
        if (obj.style.display == 'none'){
            obj.style.display = 'block';
            return true;
        } else {
            obj.style.display = 'none';
            return false;
        }   
    }
    return false;
}


// =================================================================== //
// ======== Swaps:

function swapOn(id){
    obj = document.getElementById(id);
    if (obj){
        obj.style.display = 'block';
        return true;
    }
    return false;
}


// =================================================================== //
// ======== Swaps:

function swapOff(id){
    obj = document.getElementById(id);
    if (obj){
        obj.style.display = 'none';
        return false;
    }
    return false;
}


// =================================================================== //
// ======== Swaps Tabs:
// var old_tab = 'tab1';
function SwapTab(id){
  if (old_tab == id) return;

  // 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   = "tabOff";
  }

	// Ativa a nova tab
	if (old_tab != id){
      obj = document.getElementById("tab_" + id);
      btn = document.getElementById("btn_" + id);
      obj.style.display = 'block';
      btn.className   = "tabOn";
      old_tab = id;

      edt = document.getElementById("old_tab");
      if (edt) edt.value = id;

  } else {
      old_tab = "";
  }
}


// =================================================================== //
// ======== Swaps Buttons:

var old_btn = "";
function SwapButton(id){
  // Tab ativa fica inativa:
  if (old_btn != ""){
      obj = document.getElementById("tab_" + old_btn);
      btn = document.getElementById("btn_" + old_btn);
      obj.style.display = 'none';
  }

	// Ativa a nova tab
	if (old_btn != id){
      obj = document.getElementById("tab_" + id);
      btn = document.getElementById("btn_" + id);
      obj.style.display = 'block';
      old_btn = id;
  } else {
      old_btn = "";
  }
}


// =================================================================== //
// ======== 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_on, value_off){
  to_obj = document.getElementById(to_id);
  to_obj.value = (from_obj.checked ? value_on : value_off);
}


// =================================================================== //
// ======== 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;

*/
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ção para preview de Imagens ====================== //
                                                       //-- By Labs 12/2003 --//

/* */
function swapKImg(box_id, path, src){

  var img_div = document.getElementById(box_id);
  var arr = src.split(".");

  if (arr[1] == 'swf'){
      img_div.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0">' +
                           '<param name="movie" value="' + path + '/' + src + '">' +
                           '<param name="quality" value="high">' +
                           '<embed src="' + path + '/' + src + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>' +
                          '</object>';
  } else {
      img_div.innerHTML = '<img src="' + path + '/' + src + '" border="0"><br>';
  }

  if (document.getElementById("div_temp")){
      document.getElementById("div_temp").innerHTML = img_div.innerHTML;
  }
}

/* */
function showKImg(img_div){

    return false;

    if (document.getElementById("div_temp")) return false;

    var l = img_div.style.left;
    var t = img_div.style.top; alert(t);

    var tmp_div = document.createElement('<div id="div_temp" style="position: absolute; top: 40%; left: 25%"></div>');
    tmp_div.innerHTML = img_div.innerHTML;
    tmp_div.left = l;
    tmp_div.top = t;


    img_div.parentElement.insertAdjacentElement('beforeEnd', tmp_div); alert('ok');
}

/* */
function hideKImg(img_div){

}



// =================================================================== //
// ======== Funções de wizzard:

function getStep(btn, compId, max){
    var steps = document.getElementById('steps_' + compId);
    var step  = steps.options[btn.step].value; 
    var btnBack = document.getElementById('btnBack_' + compId);
    var btnEnd  = document.getElementById('btnEnd_'  + compId);
    var btnNext = document.getElementById('btnNext_' + compId);
    
    if (btn == btnBack){
        btnNext.step = btnBack.step+1;
        btnBack.step--;
        
    } else {
        btnBack.step = btnNext.step-1;
        btnNext.step++;
    }
    
    btnBack.disabled = (btnBack.step < 0);
    btnNext.disabled = (btnNext.step == max);
        
    eval('call({' + step + ', area: \'' + compId + '_wizarea\', box: \'' + compId + '_wizarea\'}, \'putHTML\', \'getAreaValues\')');
}

function resetWizzButtons(compId){
    
    var btnBack = document.getElementById('btnBack_' + compId);
    var btnNext = document.getElementById('btnNext_' + compId);
    btnBack.step = 0;
    btnBack.disabled = true;
    
    btnNext.step = 1;
    btnNext.disabled = (btnNext.step == btnNext.max);
        
}



// ==================== Funções para pop-up ====================== //
// retirado de page_editor

// Global counter to always bring the clicked window to the top.
var zCounter = 1;
function startDrag() {
    if (window._dragObject) {
        window._dragging = true;
        //window._dragObject = window.document.all.popup_editor;
        window._dragObject._mouseLeft = event.offsetX;
        window._dragObject._mouseTop = event.offsetY;
        window._dragObject.style.zIndex = zCounter++;
    }
    return false;
}

function moveMe() {
    // If dragging, move to follow mouse
    if (window._dragging) {
        window._dragObject.style.pixelTop =  document.body.scrollTop  + event.clientY - window._dragObject._mouseTop;
        window._dragObject.style.pixelLeft = document.body.scrollLeft + event.clientX - window._dragObject._mouseLeft;
    }
}

function clearDrag() {
    // Mouse goes up, clear drag objects
    window._dragging = false;
    window._dragObject = null;
}

function doLoad() {
  // setup()
    // Check if DHTML support
    if (document.all!=null) {
        document.onmousedown = startDrag;
        document.onmousemove = moveMe;
        document.onmouseup   = clearDrag;
        document.ondragstart = new Function("return false");
    }
}
doLoad();




// ==================== Funções para pop-up ====================== //
// retirado de page_edit

      //var _top  = 50;
      //var _left = 50;

      function getTop(obj){
          var res = obj.offsetTop;
          while (obj.offsetParent){
              obj = obj.offsetParent;
              res += obj.offsetTop;
          }
          return res;
      }
      function getLeft(obj){
          var res = obj.offsetLeft;
          while (obj.offsetParent){
              obj = obj.offsetParent;
              res += obj.offsetLeft;
          }
          return res;
      }

      function popEditor(popId, width, title, callParams){
          // Pega posicionamento:
          /*if (_top == 0){
              _top  = getTop(obj)  + 10;
              _left = getLeft(obj) + 30;
              _left = (_left + 300 > 750 ? 600 : _left);
          }*/

          // Chama a tela:
          call(callParams, 'putHTML'); 
          
          // Titulo:
          document.getElementById('pop_' + popId + '_title').innerHTML = title;
              
          // Deixa visível:
          var container = document.getElementById('pop_' + popId + '_container');
          var w = (isNaN(width) ? width : width+'%');
          container.style.width   = w;
          container.style.display = 'block';
      }
