var thousand_separator = ".";
var decimal_separator = ",";
var highlightColor = 'EA571E';
var subTotalEncomenda = 0;
var portesEncomenda = 0;
var totalEncomenda = 0;
var totalGeralEncomenda = 0;
var tranchesEncomenda = 0;
var highlightDuration = 1.5;
var constDateFormat = '%Y-%m-%d';
var id_user;
var id_grafico;
var id_periodo;
var id_pag;
var tipo_grafico;
var flashMovie;
var flashFile = "amcolumn.swf";
var dataFile = "data2.php";
var settingsFile = "teste-settings.php";
var img_ambiente_actual;
var img_ambiente_menor;
var img_ambiente_maior;
var somos_wikaboo_actual;
var somos_wikaboo_menor;
var somos_wikaboo_maior;
var calendario = null;
var listagem_calendario = null;
var campoauto;
var distanciaalt;
var tempoalt;
var minkmalt;
var changelock;
distanciaalt = false;
changelock = false;
tempoalt = false;
minkmalt = false;
function parse_str(str, array){
    // http://kevin.vanzonneveld.net
    // +   original by: Cagri Ekin
    // +   improved by: Michael White (http://crestidg.com)
    // *     example 1: parse_str('first=foo&second=bar');
    // *     returns 1: { first: 'foo', second: 'bar' }
    // *     example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.');
    // *     returns 2: { str_a: "Jack and Jill didn't see the well." }
 
    var glue1 = '=';
    var glue2 = '&';
 
    var array2 = str.split(glue2);
    var array3 = [];
    for(var x=0; x<array2.length; x++){
        var tmp = array2[x].split(glue1);
        array3[unescape(tmp[0])] = unescape(tmp[1]).replace(/[+]/g, ' ');
    }
 
    if(array){
        array = array3;
    } else{
        return array3;
    }
}

Ext.form.MyTimeField = Ext.extend(Ext.form.TextField,  {
    
    fieldClass: "x-form-field x-form-num-field",    
    separator : ":",
    baseChars : "0123456789",

    initEvents : function() {
        Ext.form.MyTimeField.superclass.initEvents.call(this);
        var allowed = this.baseChars+this.separator;
        this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
        var keyPress = function(e){
            var k = e.getKey();
            if(!Ext.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
                return;
            }
            var c = e.getCharCode();
            if(allowed.indexOf(String.fromCharCode(c)) === -1){
                e.stopEvent();
            }
        };
        this.el.on("keypress", keyPress, this);
    }
});
Ext.reg('mytimefield', Ext.form.MyTimeField);


Ext.form.MyDateField = Ext.extend(Ext.form.TextField,  {
    
    fieldClass: "x-form-field x-form-num-field",    
    separator : "-",
    baseChars : "0123456789",

    initEvents : function() {
        Ext.form.MyDateField.superclass.initEvents.call(this);
        var allowed = this.baseChars+this.separator;
        this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
        var keyPress = function(e){
            var k = e.getKey();
            if(!Ext.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
                return;
            }
            var c = e.getCharCode();
            if(allowed.indexOf(String.fromCharCode(c)) === -1){
                e.stopEvent();
            }
        };
        this.el.on("keypress", keyPress, this);
    }
});
Ext.reg('mydatefield', Ext.form.MyDateField);

function VO2Max(time, distance, unit) {
  time=0;
  if (unit == 2) {
    distance = distance / 1.609344;
  }
  v = (distance * 1000)/time;
  var percent_max = 0.8 + (0.1894393*Math.exp(-0.012778*time)) + (0.2989558*Math.exp(-0.1932605*time));
  var vo2 = -4.60 + (0.182258*v) + (0.000104*v*v);
  var vo2max = vo2 / percent_max;
  return vo2max;
}

function number_format(a, b, c, d) {
  a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
  e = a + '';
  f = e.split('.');
  if (!f[0]) {
    f[0] = '0';
  }
  if (!f[1]) {
    f[1] = '';
  }
  if (f[1].length < b) {
    g = f[1];
    for (i=f[1].length + 1; i <= b; i++) {
      g += '0';
    }
    f[1] = g;
  }
  if(d != '' && f[0].length > 3) {
    h = f[0];
    f[0] = '';
    for (j = 3; j < h.length; j+=3) {
      i = h.slice(h.length - j, h.length - j + 3);
      f[0] = d + i +  f[0] + '';
    }
    j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
    f[0] = j + f[0];
  }
  c = (b <= 0) ? '' : c;
  return f[0] + c + f[1];
}

//Ext.select('#dtotal2 span').update(number_format(totalCarrinho-totaldesconto, 2, decimal_separator, thousand_separator)).parent('td').highlight('01845d');

function initStuff() {
  Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab6 div.seccao-body div.totais .links ul li.ll1 a').on('click',
    function(e, el) {
      if (e) {
        e.preventDefault();
      }
      Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab6 div.seccao-body div.totais .tabela').addClass('hidden');
      Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab6 div.seccao-body div.totais .tabela.semanal').removeClass('hidden');
      return false;
    }
  );
  Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab6 div.seccao-body div.totais .links ul li.ll2 a').on('click',
    function(e, el) {
      if (e) {
        e.preventDefault();
      }
      Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab6 div.seccao-body div.totais .tabela').addClass('hidden');
      Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab6 div.seccao-body div.totais .tabela.mensal').removeClass('hidden');
      return false;
    }
  );
  Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab6 div.seccao-body div.totais .links ul li.ll3 a').on('click',
    function(e, el) {
      if (e) {
        e.preventDefault();
      }
      Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab6 div.seccao-body div.totais .tabela').addClass('hidden');
      Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab6 div.seccao-body div.totais .tabela.anual').removeClass('hidden');
      return false;
    }
  );
  Ext.select('.newbtnlimpar').on('click',
    function(e, el) {
      if (e) {
        e.preventDefault();
      }
      Ext.fly(this).parent('form').select("input:not([class*='donterase'])[type='text'], input:not([class*='donterase'])[type='password'], select:not([class*='donterase']), textarea:not([class*='donterase'])").each(
        function(el, els, index) {
          el.dom.value = '';
          if (Ext.fly(el).parent('.autohide'))
            Ext.fly(el).parent('.autohide').select('label').removeClass('hidden').show();
        }
      );
      return false;
    }
  );

  Ext.select('a.down').on('click',
    function(e, el) {
      if (e) {
        e.preventDefault();
      }
      if (Ext.fly(this).parent().select("ul li:not([class*='hidden'])").getCount() > 3)
        Ext.fly(this).parent().select("ul li:not([class*='hidden']):first").addClass('hidden');
      return false;
    }
  );
  
  Ext.select('a.up').on('click',
    function(e, el) {
      if (e) {
        e.preventDefault();
      }
      Ext.fly(this).parent().select("ul li.hidden:last").removeClass('hidden');
      return false;
    }
  );
    
  Ext.select('a.right').on('click',
    function(e, el) {
      if (e) {
        e.preventDefault();
      }
      if (Ext.fly(this).parent().select("ul li:not([class*='hidden'])").getCount() > 1)
        Ext.fly(this).parent().select("ul li:not([class*='hidden']):first").addClass('hidden');
      return false;
    }
  );
  
  Ext.select('a.left').on('click',
    function(e, el) {
      if (e) {
        e.preventDefault();
      }
      Ext.fly(this).parent().select("ul li.hidden:last").removeClass('hidden');
      return false;
    }
  );
    
    
  Ext.select('a.change_calendar').on('click',
    function(e, el) {
      var tmp = parseUri(this.href);
      var specialhref = tmp.path + "?" + tmp.query;
      var specialhref2 = '';
      var huz = specialhref.split("?");
      if (huz.length > 1)
        specialhref2 = specialhref + "&only_listagem=1";
      else
        specialhref2 = specialhref + "?only_listagem=1";
      if (huz.length > 1)
        specialhref = specialhref + "&only_render=1";
      else
        specialhref = specialhref + "?only_render=1";
      if (e) {
        e.preventDefault();
      }
      calendario.load({
        url: specialhref,
        text: "<img src='/adm/img/wait.gif' />",
        callback: function() {
          initStuff();
          initStuff2();
        },
        scripts: true
      });
      listagem_calendario.load({
        url: specialhref2,
        text: "",
        callback: function() {
          initStuff();
        },
        scripts: true
      });
      return false;
    }
  );
}

function initStuff2() {
  Ext.select('a.change_calendar2').on('click',
    function(e, el) {
      var tmp = parseUri(this.href);
      var specialhref = tmp.path + "?" + tmp.query;
      var specialhref2 = '';
      var huz = specialhref.split("?");
      if (huz.length > 1)
        specialhref2 = specialhref + "&only_listagem=1";
      else
        specialhref2 = specialhref + "?only_listagem=1";
      if (e) {
        e.preventDefault();
      }
      listagem_calendario.load({
        url: specialhref2,
        text: "",
        callback: function() {
          initStuff2();
        },
        scripts: true
      });
      return false;
    }
  );
}


function validaqtdecarrinho(frmval, msg) {
  if ( isNaN(frmval.qtd.value) || frmval.qtd.value<=0 ) {
    alert(msg);
    frmval.qtd.focus();
    return false;
  }
}

function alteraImagemAmbiente(i) {
  if (i != -1) {
    Ext.select('.imagem_ambiente#imagem_ambiente_' + i).fadeOut({duration: 3, callback: function(el){el.addClass('hidden').removeClass('nothidden')}});
    i = ((i+1) > img_ambiente_maior) ? img_ambiente_menor : i+1;
    Ext.select('.imagem_ambiente#imagem_ambiente_' + i).hide().addClass('nothidden').removeClass('hidden').fadeIn({duration: 3, callback: function(el){}});
    setTimeout("alteraImagemAmbiente(" + i + ")", 10000);
  }
  else {
    i = ((i+1) > img_ambiente_maior) ? img_ambiente_menor : i+1;
    setTimeout("alteraImagemAmbiente(" + i + ")", 7000);
  }
}

function alteraSomosWikaboo(i) {
  if (i != -1) {
    Ext.select('.texto_seccao#somos_wikaboo_' + i).fadeOut({duration: 3, useDisplay: true, callback: function() {
      i = ((i+1) > somos_wikaboo_maior) ? somos_wikaboo_menor : i+1;
      Ext.select('.texto_seccao#somos_wikaboo_' + i).fadeIn({duration: 3, useDisplay: true});
      setTimeout("alteraSomosWikaboo(" + i + ")", 10000);
    }});
  }
  else {
    i = ((i+1) > somos_wikaboo_maior) ? somos_wikaboo_menor : i+1;
    setTimeout("alteraSomosWikaboo(" + i + ")", 7000);
  }
}

function alteraPortes(novoPortes) {
  if (portesEncomenda != novoPortes) {
    portesEncomenda = novoPortes;
    var tmp = Ext.select('tr.fim.portes td.preco_total span').update('&euro;&nbsp;' + number_format(portesEncomenda, 2, decimal_separator, thousand_separator));
    if (novoPortes != 0) {
      Ext.select('tr.fim.portes').removeClass('hidden');
      tmp.parent('td').highlight(highlightColor, { duration: highlightDuration });
    }
    else {
      Ext.select('tr.fim.portes').addClass('hidden');
    }
  }
}

function alteraTranches(novoTranches) {
  if (tranchesEncomenda != novoTranches) {
    tranchesEncomenda = novoTranches;
    var tmp = Ext.select('tr.fim.total_tranches td.preco_total span').update('&euro;&nbsp;' + number_format(tranchesEncomenda, 2, decimal_separator, thousand_separator));
    if (novoTranches != 0) {
      Ext.select('tr.fim.total_tranches').removeClass('hidden');
      tmp.parent('td').highlight(highlightColor, { duration: highlightDuration });
    }
    else {
      Ext.select('tr.fim.total_tranches').addClass('hidden');
    }
  }
}

function alteraTotal(novoTotal) {
  if (totalEncomenda != novoTotal) {
    totalEncomenda = novoTotal;
    Ext.select('tr.fim.total td.preco_total span').update('&euro;&nbsp;' + number_format(totalEncomenda, 2, decimal_separator, thousand_separator)).parent('td').highlight(highlightColor, { duration: highlightDuration });
  }
}

function alteraTotalGeral(novoTotal) {
  if (totalGeralEncomenda != novoTotal) {
    totalGeralEncomenda = novoTotal;
    Ext.select('tr.fim.totalgeral td.preco_total span').update('&euro;&nbsp;' + number_format(totalGeralEncomenda, 2, decimal_separator, thousand_separator)).parent('td').highlight(highlightColor, { duration: highlightDuration });
  }
}

function calculaTranches() {
  var value2 = '';
  Ext.select('select.selecttranches').each(
    function(el, els, index) {
      value2 = value2 + ';'  + el.dom.id.replace(/selecttranches/, '') + ',' + el.dom.value;
    }
  );
  Ext.Ajax.request({
     url: '/loja/tranches.php',
     success: function(response) {
      brokenstring = response.responseText.split(";");
      novosTranches = brokenstring[0] / 100;
      valorlinha = brokenstring[1] / 100;
      alteraTranches(novosTranches);
      alteraTotal(subTotalEncomenda + portesEncomenda - (novosTranches < valorlinha ? valorlinha-novosTranches : valorlinha-valorlinha));
      alteraTotalGeral((novosTranches < valorlinha ? valorlinha-novosTranches : valorlinha-valorlinha) + totalEncomenda);
     },
     failure: function() {
      alteraTotal(subTotalEncomenda + portesEncomenda - tranchesEncomenda);
     },
     params: {
      value: value2
     }
  });
}

function calculaPortes(id_expedicao2, id_entrega2, id_pagamento2, subtotal2) {
  var whref = parseUri(window.location.href);
  var durl = whref["path"] == "/loja/confirmar.php" ? '/loja/portes.php' : '/loja/portes2.php';
  Ext.Ajax.request({
     url: durl,
     success: function(response) {
      novosPortes = response.responseText / 100;
      alteraPortes(novosPortes);
      calculaTranches();
     },
     failure: function() {
      calculaTranches();
     },
     params: {
      id_expedicao: id_expedicao2, 
      id_entrega: id_entrega2,
      id_pagamento: id_pagamento2,
      subtotal: subtotal2
     }
  });
}

function setupCalendar(idInput, idButton) {
  Calendar.setup(
    {
    inputField : idInput, 
    button : idButton, 
    ifFormat : constDateFormat, 
    showsTime : false, 
    singleClick : true, 
    step : 1, 
    weekNumbers : false
    }
  );
}


function recalculaEncomenda() {
  var id_expedicao = Ext.select('select#modoexpedicao').first().dom.value;
  var id_entrega = Ext.select('select#localentrega').first().dom.value;
  var id_pagamento = Ext.select('select#modopagamento').first().dom.value;
  calculaPortes(id_expedicao, id_entrega, id_pagamento, subTotalEncomenda);
  Ext.select("select#modopagamento").each(
    function(el, els, index) {      
      $('.informativo').addClass('hidden');
      $('#informativo_'+el.dom.value).removeClass('hidden');
    }
  );
}

function alteraModoExpedicao(id_entrega) {
  Ext.select('select#modoexpedicao option').addClass('hidden').filter('.entrega_' + id_entrega).removeClass('hidden');
  Ext.select('select#modoexpedicao').each(
    function(el, els, index) {
      if (el.select('option[value="' + el.dom.value + '"]').first().hasClass('hidden')) {
        el.dom.selectedIndex = el.select('option:not(.hidden)').first().dom.index;
        el.highlight(highlightColor, { duration: highlightDuration });
      }
    }
  );
  var id_expedicao = Ext.select('select#modoexpedicao').first().dom.value;
  alteraModoPagamento(id_entrega, id_expedicao);
}

function alteraModoPagamento(id_entrega, id_expedicao) {
  Ext.select('select#modopagamento option').addClass('hidden').filter('.expedicao_entrega_' + id_expedicao + "_" + id_entrega).removeClass('hidden');
  Ext.select('select#modopagamento').each(
    function(el, els, index) {
      if (el.select('option[value="' + el.dom.value + '"]').first().hasClass('hidden')) {
        el.dom.selectedIndex = el.select('option:not(.hidden)').first().dom.index;
        el.highlight(highlightColor, { duration: highlightDuration });
      }
    }
  );
  recalculaEncomenda();
}

function reloadGrafico() {
  if (!flashMovie) {
    flashMovie = document.getElementById("flashMovieId");
  }
  if (flashMovie) {
    flashMovie.reloadAll(escape("/diario-de-treino/" + dataFile + "?id=" + id_user + "&id_grafico=" + id_grafico + "&id_periodo=" + id_periodo + "&pag=" + id_pag), escape("/diario-de-treino/" + settingsFile + "?type=" + tipo_grafico + "&id_grafico=" + id_grafico + "&id_periodo=" + id_periodo + "&pag=" + id_pag));
  }
}

function setGrafico(id) {
  if (!flashMovie) {
    flashMovie = document.getElementById("flashMovieId");
  }
  if (flashMovie) {
    id_grafico = id;
    reloadGrafico();
    return false;
  }
}

function setTipoGrafico(id) {
  if (!flashMovie) {
    flashMovie = document.getElementById("flashMovieId");
  }
  if (flashMovie) {
    tipo_grafico = id;
    reloadGrafico();
    return false;
  }
}

function setPeriodo(id) {
  if (!flashMovie) {
    flashMovie = document.getElementById("flashMovieId");
  }
  if (flashMovie) {
    id_periodo = id;
    reloadGrafico();
    return false;
  }
}

function setPagina(id) {
  if (!flashMovie) {
    flashMovie = document.getElementById("flashMovieId");
  }
  if (flashMovie) {
    id_pag = id;
    reloadGrafico();
    return false;
  }
}

function setLine() {
  if (!flashMovie) {
    flashMovie = document.getElementById("flashMovieId");
  }
  if (flashMovie) {            
    flashMovie.reloadSettings(escape("/diario-de-treino/" + settingsFile + "?type=line&id_grafico=" + id_grafico + "&id_periodo=" + id_periodo + "&pag=" + id_pag));
    return false;
  }
}

function setColumn() {
  if (!flashMovie) {
    flashMovie = document.getElementById("flashMovieId");
  }
  if (flashMovie) {
    flashMovie.reloadSettings(escape("/diario-de-treino/" + settingsFile + "?type=column&id_grafico=" + id_grafico + "&id_periodo=" + id_periodo + "&pag=" + id_pag));
    return false;
  }
}

function amChartInited(chart_id){
  flashMovie = document.getElementById("flashMovieId");
}      

function amReturnData(chart_id, param){
}
 
function amReturnParam(chart_id, param){
}

function createGrafico() {
  var so = new SWFObject("/share/amcharts/lib/" + flashFile, "flashMovieId", "100%", "355", "8", "#FFFFFF");
  so.addParam("wmode", "transparent");
  so.addVariable("path", "/share/amcharts/lib/");
  so.addVariable("settings_file", escape("/diario-de-treino/" + settingsFile + "?type=" + tipo_grafico + "&id_grafico=" + id_grafico + "&id_periodo=" + id_periodo + "&pag=" + id_pag));
  so.addVariable("data_file", escape("/diario-de-treino/" + dataFile + "?id=" + id_user + "&id_grafico=" + id_grafico + "&id_periodo=" + id_periodo + "&pag=" + id_pag));
  so.addVariable("preloader_color", "#000000");
  so.write('grafico');
}

Ext.onReady(
  function() {
    Ext.select("a.new_window").on('click',
      function(e, el) {
        if (e) {
          e.preventDefault();
        }
        var win = new Ext.Window({
                closable: true,
                height: 530,
                width: 740,
                autoLoad: this.href + "&usar_tema=wikaboo/popup",
                modal: true,
                layout: 'fit',
                autoScroll: true
              });
        win.show();
        return false;
      }
    );
  
    Ext.select(".calendario_seccoes").each(
      function() {
        calendario = new Ext.Panel({
          applyTo: Ext.get("calendario_seccoes_"),
          baseCls: 'calendario_seccoes',
          autoHeight: true,
          border: false
        });
      }
    );
    Ext.select(".listagem_eventos").each(
      function() {
        listagem_calendario = new Ext.Panel({
          applyTo: Ext.get("listagem_eventos_"),
          baseCls: 'listagem_eventos',
          autoHeight: true,
          border: false
        });
      }
    );
    Ext.select('form.transformable').each (
      function(el, els, index) {
        var tmp = new Ext.BasicForm(el, {standardSubmit: true});
        el.select('input.algarismsonly').each (
          function(el, els, index) {
            this.add(new Ext.form.NumberField({applyTo: el, allowNegative: false, allowDecimals: false}));
          },
          tmp
        );
        el.select('input.timeonly').each (
          function(el, els, index) {
            this.add(new Ext.form.MyTimeField({applyTo: el}));
          },
          tmp
        );
        el.select('input.dateonly').each (
          function(el, els, index) {
            this.add(new Ext.form.MyDateField({applyTo: el}));
          },
          tmp
        );
        el.select('input.numeric').each (
          function(el, els, index) {
            this.add(new Ext.form.NumberField({applyTo: el, allowNegative: false, allowDecimals: true, decimalSeparator: decimal_separator}));
          },
          tmp
        );
        el.select('input[@type=reset]').on ('click',
          function(e, el) {
            if (e) {
              e.preventDefault();
            }
            Ext.fly(el).parent('form').select('input[@type=text], input[@type=password], textarea, select').each(
              function(el, els, index) {
                el.dom.value = '';
              }
            );
            Ext.fly(el).parent('form').select('.autohide label').show();
            return false;
          }
        );
        el.on('submit', 
          function(event, formid) {
            var tmp = Ext.fly(formid);
            tmp.select('.obrigatorio').each(
              function(el, els, index) {
                if (el.getValue() === '') {
                  if (this) {
                    this.preventDefault();
                  }
                  el.highlight(highlightColor, { duration: highlightDuration });
                  var s = Ext.fly(el).parent('.autohide');
                  if (s) {
                    alert("Campo '" + s.select('input[@type=text], input[@type=password], textarea, select').first().dom.title + "' obrigatório");
                  }
                  else {
                    alert("Campo obrigatório");
                  }
                  el.focus();
                  return false;
                }
              },
              event
            );
            tmp.select('.lesstoday').each(
              function(el, els, index) {
                event.preventDefault();
                var d=new Date();
                var day=d.getDate() + '';
                var month=(d.getMonth() + 1) + '';
                if (month < 10)
                  month = '0' + month;
                var year=d.getFullYear() + '';
                var today = year + month + day;
                var selected = el.getValue().replace(/-/g, '');
                if (selected > today) {
                  el.highlight(highlightColor, { duration: highlightDuration });
                  var s = Ext.fly(el).parent('.autohide');
                  var resultado = true;
                  if (s) {
                    resultado = confirm("'" + s.select('input[@type=text], input[@type=password], textarea, select').first().dom.title + "' é superior à actual. Deseja continuar?");
                  }
                  else {
                    resultado = confirm("Data superior à actual. Deseja continuar?");
                  }
                  if (resultado) {
                    Ext.get(formid).dom.submit();
                  }
                  el.focus();
                  return resultado;
                }
                else {
                  Ext.get(formid).dom.submit();
                  return true;
                }
              },
              event
            );
            tmp.select('.check_obrigatorio').each(
              function(el, els, index) {
                if (!el.dom.checked) {
                  if (this) {
                    this.preventDefault();
                  }
                  el.highlight(highlightColor, { duration: highlightDuration });
                  alert(el.dom.title);
                  el.focus();
                  return false;
                }
              },
              event
            );
          }
        );
      }
    );

    Ext.select('a.favoritos').on('click',
      function(e, el) {
        if (e) {
          e.preventDefault();
        }
        if (window.sidebar)
          window.sidebar.addPanel(document.title, window.location.href, '');
        else
          if (window.external)
            window.external.AddFavorite(window.location.href, document.title);
        return false;
      }
    );

    Ext.select('.link_tranches a').on('click',
      function(e, el) {
        if (e) {
          e.preventDefault();
        }
        var trtranches = Ext.get(el).parent('tr').next('tr.tranches');
        trtranches.toggleClass('hidden');
        var idtranche = trtranches.dom.id.replace(/tranches/, '');
        if (trtranches.is('.hidden')) {
          Ext.select('tr.id_linha'+idtranche).addClass('hidden');
        }
        else {
          var selecttranche = trtranches.select('select.selecttranches').first();
          var selectvalue = selecttranche.dom.value;
          Ext.select('tr.id_linha'+idtranche).addClass('hidden');
          Ext.select('tr.id_linha'+idtranche+'.tranche_'+selectvalue).removeClass('hidden');
        }
        return false;
      }
    );

    Ext.select('select.selecttranches').on('change',
      function(e, el) {
        var selectid = el.id.replace(/selecttranches/, '');
        var selectvalue = el.value;
        Ext.select('tr.id_linha'+selectid).addClass('hidden');
        Ext.select('tr.id_linha'+selectid+'.tranche_'+selectvalue).removeClass('hidden');
        recalculaEncomenda();
      }
    );
    
    Ext.select('select#localentrega').on('change',
      function(e, el) {
        var id_entrega = el.value;
        alteraModoExpedicao(id_entrega);
      }
    );
    
    Ext.select('select#modoexpedicao').on('change',
      function(e, el) {
        var id_entrega = Ext.select('select#localentrega').first().dom.value;
        var id_expedicao = el.value;
        alteraModoPagamento(id_entrega, id_expedicao);
      }
    );
    Ext.select("select#modopagamento").each(
      function(el, els, index) {
        $('.informativo').addClass('hidden');
        $('#informativo_'+el.dom.value).removeClass('hidden');
      }
    );
    Ext.select('select#modopagamento').on('change',
      function(e, el) {
        recalculaEncomenda();
      }
    );
    
    Ext.select('tr.fim.subtotal td.preco_total span').each(
      function(el, els, index) {
        if (el.dom.firstChild.textContent) {
          subTotalEncomenda = el.dom.firstChild.textContent.replace(/[^0-9]*/g, '') / 100;
        }
        else if (el.dom.innerText) {
          subTotalEncomenda = el.dom.innerText.replace(/[^0-9]*/g, '') / 100;
        }
      }
    );
    
    Ext.select('tr.fim.portes td.preco_total span').each(
      function(el, els, index) {
        if (el.dom.firstChild.textContent) {
          portesEncomenda = el.dom.firstChild.textContent.replace(/[^0-9]*/g, '') / 100;
        }
        else if (el.dom.innerText) {
          portesEncomenda = el.dom.innerText.replace(/[^0-9]*/g, '') / 100;
        }
      }
    );
    
    Ext.select('tr.fim.total td.preco_total span').each(
      function(el, els, index) {
        if (el.dom.firstChild.textContent) {
          totalEncomenda = el.dom.firstChild.textContent.replace(/[^0-9]*/g, '') / 100;
        }
        else if (el.dom.innerText) {
          totalEncomenda = el.dom.innerText.replace(/[^0-9]*/g, '') / 100;
        }
      }
    );

    Ext.select('.autohide input[@type=text], .autohide input[@type=password], .autohide textarea').on('blur',
      function(e, el) {
        if (el.value === '') {
          Ext.fly(el).parent().select('label').removeClass('hidden').show();
        }
      }
    );

    Ext.select('.autohide input[@type=text], .autohide input[@type=password], .autohide textarea').on('focus',
      function(e, el) {
        Ext.fly(el).parent().select('label').addClass('hidden').hide();
      }
    );
    
    Ext.select('.autohide input.calendario[@type=button]').each(
      function(el, els, index) {
        var idInput = Ext.fly(el).parent().select('input[@type=text], input[@type=password]').first().dom.id;
        var idButton = el.dom.id;
        setupCalendar(idInput, idButton);
      }
    );
    
    Ext.select('.autohide input[@type=text], .autohide input[@type=password], .autohide textarea').each(
      function(el, els, index) {
        if (el.dom.value !== '') {        
          el.parent().select('label').hide();
        }
        el.dom.onchange2 = function(e, el) {
          if (el.value !== '') {        
            Ext.fly(el).parent().select('label').hide();
          } else {
            Ext.fly(el).parent().select('label').show();
          }
        }
      }
    );
    
    Ext.select('form.entrada input#peso').on('change', 
      function(e, el) {
        if (el.value != '') {
          Ext.fly(el).parent('form').select('label#labelimc').hide();
          var peso = el.value.replace(decimal_separator, '.');
          var altura = Ext.fly(el).parent('form').select('input#altura').first().dom.value;
          var imc = number_format(peso/ ((altura / 100)*(altura / 100)), 2, decimal_separator, thousand_separator);
          Ext.fly(el).parent('form').select('input#imc').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = imc;
        }
        else {
          Ext.fly(el).parent('form').select('input#imc').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
          Ext.fly(el).parent('form').select('label#labelimc').show();
        }
      }
    );
    Ext.select('form.entrada input#distancia').on('change', 
      function(e, el) {
        if (!changelock) {
          var distancia = Ext.fly(el).parent('form').select('input#distancia').first().dom.value.replace(decimal_separator, '.');
          var tempo = Ext.fly(el).parent('form').select('input#tempo').first().dom.value;
          var minkm = Ext.fly(el).parent('form').select('input#minkm').first().dom.value;
          if (distancia != '') {
            if (!tempoalt || !minkmalt) {
              distanciaalt = true;
              if (minkmalt) {
                var minutoskm = 0;
                if ((minkm != '')) {
                  var minkm_array = minkm.split(":");
                  if (minkm_array.length == 1) {
                    minkm_array[1] = minkm_array[0];
                    minkm_array[0] = '00';
                  }
                  minutoskm = (0.0 + (minkm_array[0] ? minkm_array[0] * 1 : 0)) + (0.0 + (minkm_array[1] ? minkm_array[1] / 60 : 0));
                  tempo = distancia * minutoskm;
                  var tempoh = Math.floor(tempo / 60);
                  var tempom = Math.floor(tempo % 60);
                  var tempos = Math.round((tempo - (tempoh*60 + tempom))*60);
                  changelock = false;
                  Ext.fly(el).parent('form').select('label#labeltempo').hide();
                  Ext.fly(el).parent('form').select('input#tempo').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = sprintf('%02d:%02d:%02d', tempoh, tempom, tempos);
                  changelock = false;
                }
              }
              else if (tempoalt) {
                var minutos = 0;
                if ((tempo != '')) {
                  var tempo_array = tempo.split(":");
                  if (tempo_array.length == 1) {
                    tempo_array[2] = tempo_array[0];
                    tempo_array[0] = '00';
                    tempo_array[1] = '00';
                  }
                  else if (tempo_array.length == 2) {
                    tempo_array[2] = tempo_array[1];
                    tempo_array[1] = tempo_array[0];
                    tempo_array[0] = '00';
                  }
                  minutos = (0.0 + (tempo_array[0] ? tempo_array[0] * 60 : 0)) + (0.0 + (tempo_array[1] ? tempo_array[1] * 1 : 0)) + (0.0 + (tempo_array[2] ? tempo_array[2] / 60 : 0));
                  minkm = (distancia != 0) ? minutos / distancia : 0;
                  var minkmm = Math.floor(minkm);
                  var minkms = Math.round((minkm - minkmm)*60);
                  changelock = false;
                  Ext.fly(el).parent('form').select('label#labelminkm').hide();
                  Ext.fly(el).parent('form').select('input#minkm').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = sprintf('%d:%02d', minkmm, minkms);
                  changelock = false;
                }
              }
            }
            else {
              if (confirm("Cálculo automático do Diário de Treino. Deseja alterar os dados?")) {
                distanciaalt = true;
                tempoalt = false;
                minkmalt = false;
                Ext.fly(el).parent('form').select('input#tempo').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labeltempo').show().removeClass('hidden');
                Ext.fly(el).parent('form').select('input#minkm').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labelminkm').show().removeClass('hidden');
              }
              else {
                distanciaalt = false;
              }
            }
          }
          else {
            if (tempoalt && minkmalt) {
              if (confirm("Cálculo automático do Diário de Treino. Deseja alterar os dados?")) {
                distanciaalt = false;
                tempoalt = false;
                minkmalt = false;
                Ext.fly(el).parent('form').select('input#tempo').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labeltempo').show().removeClass('hidden');
                Ext.fly(el).parent('form').select('input#minkm').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labelminkm').show().removeClass('hidden');
              }
              else {
                distanciaalt = false;
              }
            }
            else {
              distanciaalt = false;
            }
          }
        }
      }
    );
    Ext.select('form.entrada input#tempo, form.entrada input#distancia, form.entrada input#minkm').set({autocomplete: "off"});
    Ext.select('form.entrada input#tempo').on('change', 
      function(e, el) {
        if (!changelock) {
          var distancia = Ext.fly(el).parent('form').select('input#distancia').first().dom.value.replace(decimal_separator, '.');
          var tempo = Ext.fly(el).parent('form').select('input#tempo').first().dom.value;
          var minkm = Ext.fly(el).parent('form').select('input#minkm').first().dom.value;
          if ((tempo != '')) {
            var tempo_array = tempo.split(":");
            if (tempo_array.length == 1) {
              tempo_array[2] = tempo_array[0];
              tempo_array[0] = '00';
              tempo_array[1] = '00';
            }
            else if (tempo_array.length == 2) {
              tempo_array[2] = tempo_array[1];
              tempo_array[1] = tempo_array[0];
              tempo_array[0] = '00';
            }
            minutos = (0.0 + (tempo_array[0] ? tempo_array[0] * 60 : 0)) + (0.0 + (tempo_array[1] ? tempo_array[1] * 1 : 0)) + (0.0 + (tempo_array[2] ? tempo_array[2] / 60 : 0));
            var tmpxyz = (0.0 + (tempo_array[0] ? tempo_array[0] * 60 * 60 : 0)) + (0.0 + (tempo_array[1] ? tempo_array[1] * 60 : 0)) + (0.0 + (tempo_array[2] ? tempo_array[2] * 1  : 0));
            var real_segundos = tmpxyz % 60;
            tmpxyz = (tmpxyz - real_segundos) / 60;
            var real_minutos = tmpxyz % 60;
            var real_horas = (tmpxyz - real_minutos) / 60;
            changelock = false;
            Ext.fly(el).parent('form').select('input#tempo').first().dom.value = sprintf('%02d:%02d:%02d', real_horas, real_minutos, real_segundos);
            changelock = false;
            if (!distanciaalt || !minkmalt) {
              tempoalt = true;
              if (minkmalt) {
                var minutoskm = 0;
                if ((minkm != '')) {
                  var minkm_array = minkm.split(":");
                  if (minkm_array.length == 1) {
                    minkm_array[1] = minkm_array[0];
                    minkm_array[0] = '00';
                  }
                  minutoskm = (0.0 + (minkm_array[0] ? minkm_array[0] * 1 : 0)) + (0.0 + (minkm_array[1] ? minkm_array[1] / 60 : 0));
                  distancia =  (minutoskm != 0) ? minutos / minutoskm : 0;
                  changelock = false;
                  Ext.fly(el).parent('form').select('label#labeldistancia').hide();
                  Ext.fly(el).parent('form').select('input#distancia').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = sprintf('%.2f', distancia).replace(".", ",");
                  changelock = false;
                }
              }
              else if (distanciaalt) {
                minkm = (distancia != 0) ? minutos / distancia : 0;
                var minkmm = Math.floor(minkm);
                var minkms = Math.round((minkm - minkmm)*60);
                changelock = false;
                Ext.fly(el).parent('form').select('label#labelminkm').hide();
                Ext.fly(el).parent('form').select('input#minkm').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = sprintf('%d:%02d', minkmm, minkms);
                changelock = false;
              }
            }
            else {
              if (confirm("Cálculo automático do Diário de Treino. Deseja alterar os dados?")) {
                tempoalt = true;
                distanciaalt = false;
                minkmalt = false;
                Ext.fly(el).parent('form').select('input#distancia').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labeldistancia').show().removeClass('hidden');
                Ext.fly(el).parent('form').select('input#minkm').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labelminkm').show().removeClass('hidden');
              }
              else {
                tempoalt = false;
              }
            }
          }
          else {
            if (distanciaalt && minkmalt) {
              if (confirm("Cálculo automático do Diário de Treino. Deseja alterar os dados?")) {
                tempoalt = false;
                distanciaalt = false;
                minkmalt = false;
                Ext.fly(el).parent('form').select('input#distancia').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labeldistancia').show().removeClass('hidden');
                Ext.fly(el).parent('form').select('input#minkm').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labelminkm').show().removeClass('hidden');
              }
              else {
                tempoalt = false;
              }
            }
            else {
              tempoalt = false;
            }
          }
        }
      }
    );
    Ext.select('form.entrada input#minkm').on('change', 
      function(e, el) {
        if (!changelock) {
          var distancia = Ext.fly(el).parent('form').select('input#distancia').first().dom.value.replace(decimal_separator, '.');
          var tempo = Ext.fly(el).parent('form').select('input#tempo').first().dom.value;
          var minkm = Ext.fly(el).parent('form').select('input#minkm').first().dom.value;
          if ((minkm != '')) {
            var minkm_array = minkm.split(":");
            if (minkm_array.length == 1) {
              minkm_array[1] = minkm_array[0];
              minkm_array[0] = '00';
            }
            minutoskm = (0.0 + (minkm_array[0] ? minkm_array[0] * 1 : 0)) + (0.0 + (minkm_array[1] ? minkm_array[1] / 60 : 0));
            changelock = false;
            Ext.fly(el).parent('form').select('input#minkm').first().dom.value = sprintf('%02d:%02d', minkm_array[0] ? minkm_array[0] : 0, minkm_array[1] ? minkm_array[1] : 0);
            changelock = false;
            if (!distanciaalt || !tempoalt) {
              minkmalt = true;
              if (tempoalt) {
                var minutos = 0;
                if ((tempo != '')) {
                  var tempo_array = tempo.split(":");
                  if (tempo_array.length == 1) {
                    tempo_array[2] = tempo_array[0];
                    tempo_array[0] = '00';
                    tempo_array[1] = '00';
                  }
                  else if (tempo_array.length == 2) {
                    tempo_array[2] = tempo_array[1];
                    tempo_array[1] = tempo_array[0];
                    tempo_array[0] = '00';
                  }
                  minutos = (0.0 + (tempo_array[0] ? tempo_array[0] * 60 : 0)) + (0.0 + (tempo_array[1] ? tempo_array[1] * 1 : 0)) + (0.0 + (tempo_array[2] ? tempo_array[2] / 60 : 0));
                  distancia =  (minutoskm != 0) ? minutos / minutoskm : 0;
                  changelock = false;
                  Ext.fly(el).parent('form').select('label#labeldistancia').hide();
                  Ext.fly(el).parent('form').select('input#distancia').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = sprintf('%.2f', distancia).replace(".", ",");
                  changelock = false;
                }
              }
              else if (distanciaalt) {
                tempo = distancia * minutoskm;
                var tempoh = Math.floor(tempo / 60);
                var tempom = Math.floor(tempo % 60);
                var tempos = Math.round((tempo - (tempoh*60 + tempom))*60);
                changelock = false;
                Ext.fly(el).parent('form').select('label#labeltempo').hide();
                Ext.fly(el).parent('form').select('input#tempo').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = sprintf('%02d:%02d:%02d', tempoh, tempom, tempos);
                changelock = false;
              }
            }
            else {
              if (confirm("Cálculo automático do Diário de Treino. Deseja alterar os dados?")) {
                minkmalt = true;
                distanciaalt = false;
                tempoalt = false;
                Ext.fly(el).parent('form').select('input#distancia').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labeldistancia').show().removeClass('hidden');
                Ext.fly(el).parent('form').select('input#tempo').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labeltempo').show().removeClass('hidden');
              }
              else {
                minkmalt = false;
              }
            }
          }
          else {
            if (distanciaalt && tempoalt) {
              if (confirm("Cálculo automático do Diário de Treino. Deseja alterar os dados?")) {
                minkmalt = false;
                distanciaalt = false;
                tempoalt = false;
                Ext.fly(el).parent('form').select('input#distancia').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labeldistancia').show().removeClass('hidden');
                Ext.fly(el).parent('form').select('input#tempo').first().highlight(highlightColor, { duration: highlightDuration }).dom.value = '';
                Ext.fly(el).parent('form').select('label#labeltempo').show().removeClass('hidden');
              }
              else {
                minkmalt = false;
              }
            }
            else {
              minkmalt = false;
            }
          }
        }
      }
    );
    Ext.select('.calculadora_vo2max input#tempo').on('change', 
      function(e, el) {
        if (el.value != '') {
          var tempo = Ext.fly(el).parent('form').select('input#tempo').first().dom.value;
          if (tempo != '') {
            var tempo_array = tempo.split(":");
            if (tempo_array.length == 1) {
              tempo_array[2] = tempo_array[0];
              tempo_array[0] = '00';
              tempo_array[1] = '00';
            }
            else if (tempo_array.length == 2) {
              tempo_array[2] = tempo_array[1];
              tempo_array[1] = tempo_array[0];
              tempo_array[0] = '00';
            }
            var tmpxyz = (0.0 + (tempo_array[0] ? tempo_array[0] * 60 * 60 : 0)) + (0.0 + (tempo_array[1] ? tempo_array[1] * 60 : 0)) + (0.0 + (tempo_array[2] ? tempo_array[2] * 1  : 0));
            var real_segundos = tmpxyz % 60;
            tmpxyz = (tmpxyz - real_segundos) / 60;
            var real_minutos = tmpxyz % 60;
            var real_horas = (tmpxyz - real_minutos) / 60;
            Ext.fly(el).parent('form').select('input#tempo').first().dom.value = sprintf('%02d:%02d:%02d', real_horas, real_minutos, real_segundos);
            var minutos = (0.0 + (tempo_array[0] ? tempo_array[0] * 60 : 0)) + (0.0 + (tempo_array[1] ? tempo_array[1] * 1 : 0)) + (0.0 + (tempo_array[2] ? tempo_array[2] / 60 : 0));
          }
        }
      }
    );
    /*Ext.select('form.entrada input#horassono').on('change', 
      function(e, el) {
        if (el.value != '') {
          var horassono = el.value;
          var horassono_array = horassono.split(":");
          if (horassono_array.length == 1) {
            horassono_array[2] = horassono_array[0];
            horassono_array[0] = '00';
            horassono_array[1] = '00';
          }
          else if (horassono_array.length == 2) {
            horassono_array[2] = horassono_array[1];
            horassono_array[1] = horassono_array[0];
            horassono_array[0] = '00';
          }
          el.value = sprintf('%d:%02d', horassono_array[0] ? horassono_array[0] : 0, horassono_array[1] ? horassono_array[1] : 0);
        }
      }
    );*/
    Ext.select('form.entrada input#data_entrada').on('change', 
      function(e, el) {
        if (el.value != '') {
          var data = el.value;
          var data_array = data.split("-");
          el.value = sprintf('%04d-%02d-%02d', data_array[0] ? data_array[0] : 0, data_array[1] && (data_array[1] >= 1) && (data_array[1] <= 12) ? data_array[1] : 1, data_array[2] && (data_array[2] >= 1) && (data_array[2] <= 31) ? data_array[2]  : 1);
        }
      }
    );
    Ext.select('.diario_tabs #grafico_diario_treino').each(
      function(el, els, index) {
        var whref = parseUri(window.location.href);
        var wquery = parse_str(whref.query);
        tipo_grafico = wquery["tipo_grafico"];
        if (!tipo_grafico) {
          tipo_grafico = "column";
        }
        id_grafico = wquery["id_grafico"] ? wquery["id_grafico"] : 1;
        id_periodo = wquery["periodo"] ? wquery["periodo"] : 1;
        id_pag = wquery["pag"] ? wquery["pag"] : 0;
        id_user = el.parent('.diario_tabs').id.replace(/diario_tabs_/, '');
        createGrafico();
      }
    );
    
    Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab7 div.seccao-body div.grafico_diario div.links ul li a').on('click',
      function(e, el) {
        var ehref = parseUri(this.href);
        var equery = parse_str(ehref.query);
        var id_g = equery["id_grafico"];
        var grafico = Ext.get("grafico_diario_treino");
        if (grafico) {
          if (e) {
            e.preventDefault();
          }
          setGrafico(id_g)
          return false;
        }
      }
    );
    
    
    Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab7 div.seccao-body div.grafico_diario div#grafico_diario_treino div.periodo_grafico ul li a').on('click',
      function(e, el) {
        var ehref = parseUri(this.href);
        var equery = parse_str(ehref.query);
        var id_p = equery["periodo"];
        var grafico = Ext.get("grafico_diario_treino");
        if (grafico) {
          if (e) {
            e.preventDefault();
          }
          Ext.fly(this).parent('ul').select('li').removeClass('activo');
          Ext.fly(this).parent('li').addClass('activo');
          setPeriodo(id_p);
          return false;
        }
      }
    );
    
    Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab7 div.seccao-body div.grafico_diario div#grafico_diario_treino div.nav_grafico ul li.ll1 a').on('click',
      function(e, el) {
        var grafico = Ext.get("grafico_diario_treino");
        if (grafico) {
          if (e) {
            e.preventDefault();
          }
          setPagina(parseInt(id_pag)-1);
          return false;
        }
      }
    );
    
    Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab7 div.seccao-body div.grafico_diario div#grafico_diario_treino div.nav_grafico ul li.ll2 a').on('click',
      function(e, el) {
        var grafico = Ext.get("grafico_diario_treino");
        if (grafico) {
          if (e) {
            e.preventDefault();
          }
          setPagina(parseInt(id_pag)+1);
          return false;
        }
      }
    );
    
    Ext.select('div.diario_tabs div.diario_treino div.diario_treino_tab#tab7 div.seccao-body div.grafico_diario div#grafico_diario_treino div.tipo_grafico ul li a').on('click',
      function(e, el) {
        var ehref = parseUri(this.href);
        var equery = parse_str(ehref.query);
        var id_t = equery["tipo_grafico"];
        var grafico = Ext.get("grafico_diario_treino");
        if (grafico) {
          if (e) {
            e.preventDefault();
          }
          Ext.fly(this).parent('ul').select('li').removeClass('hidden');
          Ext.fly(this).parent('li').addClass('hidden');
          setTipoGrafico(id_t);
          return false;
        }
      }
    );
    
    Ext.select('div.diario_tabs div.link_tabs ul li a').on('click',
      function(e, el) {
        var ehref = parseUri(this.href);
        var equery = parse_str(ehref.query);
        var id_tab = equery["tab"];
        var tab = Ext.get("tab" + id_tab);
        if ((tab) && (id_tab !=2)) {
          if (e) {
            e.preventDefault();
          }
          Ext.select('.diario_treino_tab').removeClass('activo').filter('#tab' + id_tab).addClass('activo');
          Ext.fly(this).parent('.diario_treino_tab').addClass('activo');
          return false;
        }
      }
    );
    
    Ext.select('div#header div.header-body div.header-content div.menu_topo#menu_topo_2 ul.menu li.menu_item').on('mouseover',
      function(e, el) {
        Ext.fly(this).select('ul.submenu').removeClass('hidden');
      }
    );
    
    Ext.select('div#header div.header-body div.header-content div.menu_topo#menu_topo_2 ul.menu li.menu_item').on(Ext.isIE ? 'mouseleave' : 'mouseout',
      function(e, el) {
        Ext.fly(this).select('ul.submenu').addClass('hidden');
      }
    );
    
    Ext.select('.imagem_ambiente.nothidden').each(
      function(el, els, index) {
        img_ambiente_actual = el.dom.id.replace(/imagem_ambiente_/, '');
        img_ambiente_maior = img_ambiente_actual;
        img_ambiente_menor = img_ambiente_actual;
      }
    );

    Ext.select('.somos_wikaboo > .texto_seccao.nothidden').each(
      function(el, els, index) {
        somos_wikaboo_actual = el.dom.id.replace(/somos_wikaboo_/, '');
        somos_wikaboo_maior = somos_wikaboo_actual;
        somos_wikaboo_menor = somos_wikaboo_actual;
      }
    );
    initStuff();
    initStuff2();
    
    Ext.select('.imagem_ambiente').each(
      function(el, els, index) {
        var i = el.dom.id.replace(/imagem_ambiente_/, '');
        if (i > img_ambiente_maior) {
          img_ambiente_maior = i;
        }
        if (i < img_ambiente_menor) {
          img_ambiente_menor = i;
        }
      }
    );
    if (img_ambiente_maior > img_ambiente_menor)
      alteraImagemAmbiente(-1);
    
    Ext.select('.somos_wikaboo > .texto_seccao').each(
      function(el, els, index) {
        var i = el.dom.id.replace(/somos_wikaboo_/, '');
        if (i > somos_wikaboo_maior) {
          somos_wikaboo_maior = i;
        }
        if (i < somos_wikaboo_menor) {
          somos_wikaboo_menor = i;
        }
      }
    );
    if (somos_wikaboo_maior > somos_wikaboo_menor)
      alteraSomosWikaboo(-1);
  }
);

