/**
  @author Diogo "Mr. Fogg" Goes <fileasfogg@gmail.com>
  @copyright Creative Commons Share-Alike
  @license http://creativecommons.org/licenses/by-sa/2.5/br/
  @classDescription Rotinas diversas
  @since 2008-03-03
  @version 1.0
*/

/**
 * Seleciona um Objeto pelo id
 * @return {Object}
 * @param {String} e Id do objeto a ser procurado
 */ 
function $$(e) {
 return document.getElementById(e);
}


/**
 * Seleciona um ou vários Objeto(s) pela tagname
 * @return {Array}
 * @param {String} e Tag do objeto a ser procurado
 */ 
function $$T(e) {
 return document.getElementsByTagName(e);
}


/**
 * Seleciona um ou vários Objeto(s) pelo name
 * @return {Array}
 * @param {String} e Nome do objeto a ser procurado
 */ 
function $$N(e) {
 return document.getElementsByName(e);
}


/**
 * Retorna uma porcentagem de um número
 * @return {number} Valor numérico da porcentagem
 * @param {number} p Valor em porcentagem
 * @param {number} n Valor total
 */
function Perc(p,n) {
 return (p*n)/100;
}


/**
 * Centraliza um objeto
 * @return {void}
 * @param {Object} e Objeto a ser centralizado
 * @param {String} p Tipo do posicionamento
 */
function everCenter(e,p) {
 e.style.top = 50+"%";
 e.style.left = 50+"%";
 e.style.position = p;
 e.style.marginLeft = -1*parseInt(e.offsetWidth/2) + "px";
 e.style.marginTop = -1*parseInt(e.offsetHeight/2) + "px";
}


/**
 * Agrega um evento a um objeto
 * @return {void}
 * @param {Object} e Objeto
 * @param {String} evt Evento a ser agregado
 * @param {String} f Funcao que deve ser executada
 */
function addEvent(e, evt, f) {
 // FF
 if (e.addEventListener)
  e.addEventListener(evt, f, true);
 // IE
 if (e.attachEvent)
  e.attachEvent("on" + evt, f);
}


/**
 * Cria uma popup
 * @return {void} 
 * @param {String} url Url que deve ser aberta
 * @param {String} titulo Titulo da janela (opcional)
 * @param {Integer} width Largura da janela
 * @param {Integer} height Altura da janela
 * @param {yes|no} tootlbar [Padrao no] Barra de ferramentas
 * @param {yes|no} directories [Padrao no] Pasta Links dos Favoritos
 * @param {yes|no} status [Padrao no] Barra de status
 * @param {yes|no} location [Padrao no] Barra de enderecos
 * @param {yes|no} menubar [Padrao no] Menu padrao
 * @param {yes|no} resizable [Padrao no] Redimensionamento 
 * @param {yes|no} scrollbars [Padrao no] Barra de rolagem
 */
function PopupWindow() {
 this.url = "";
 this.titulo = "";
 this.width = "";
 this.height = "";
 this.toolbar = "no";
 this.directories = "no";
 this.status = "no";
 this.location = "no";
 this.menubar = "no";
 this.resizable = "no";
 this.scrollbars = "no";
 this.move = "";
 this.openWindow = function() {
  var popup = window.open(this.url, this.titulo, "width=" + this.width +
                                                 ",height=" + this.height +
                                                 ",innerWidth=" + this.width +
                                                 ",innerHeight=" + this.height +
                                                 ",toolbar=" + this.toolbar + 
                                                 ",directories=" + this.directories + 
                                                 ",status=" + this.status + 
                                                 ",location=" + this.location + 
                                                 ",menubar=" + this.menubar + 
                                                 ",resizable=" + this.resizable + 
                                                 ",scrollbars=" + this.scrollbars);
 
  if (popup == false) {
   window.alert("Este site utiliza popups!\nPor favor desabilite seu bloqueador de popups e tente novamente!");
  }

  if (this.move != "") {
   var p = explode(",", this.move);
   popup.moveTo(p[0], p[1]);
  }
 
 };
}


/**
 * Dá ou retira foco de um objeto
 * @return {void}
 * @param {Object} e Dá ou retira foco a objeto selecionado
 */
function Focus(e) {
 e.className = e.className == "selecionado" ? "nao_selecionado" : "selecionado";
}


/**
 * Limpa complemetamente um formulário
 * @return {void}
 * @param {Object} e Apaga o formulário, inclusive os valores default
 */
function FormClean(e) {
 for (i = 0, t = $$(e).length; i < t; i++) { 
  switch ($$(e).elements[i].type) {
   case "select-one":
    $$(e).elements[i].options[0].selected = true;
   break;
   
   case "select-multiple":
    for(j = 0, g = $$(e).elements[i].length; j < g; j++) {
     $$(e).elements[i].options[j].selected = false;
    }
   break;
     
   case "radio":
   case "checkbox":
    $$(e).elements[i].checked = false;
   break; 
   
   case "text":
   case "hidden":
   case "textarea":
    $$(e).elements[i].value = "";
   break; 
  }
 }
}


/**
 * Emula a função ereg do PHP
 * @return {Boolean}
 * @param {String} patern Expressão Regular
 * @param {String} value Valor a ser testado
 */
function ereg(pattern, value) {
 var patt1 = new RegExp(pattern);
 return patt1.test(value);
}


/**
 * Formata números/valores financeiros para notações brasileira/inglesa
 * @return {Number} n
 * @param {Number} n
 */
var to = {
  decimalIN: function(n){
   var n1 = n.toString();
    if (ereg("^[+-]?([0-9]{1,3}(\.[0-9]{3})*|[0-9]+)\,[0-9]+$", n)) {
     n1 = n1.indexOf(".") > -1 ? n1.replace(".", "").replace(",", ".") : n1.replace(",", ".");
    }
   return parseFloat(n1);
  },
  decimalBR: function(n){
   var n1 = n.toString();
   if (ereg("^[+-]?([0-9]{1,3}(\,[0-9]{3})*|[0-9]+)\.[0-9]+$", n1)) {
     n1 = n1.indexOf(",") > -1 ? n1.replace(",", "").replace(".", ",") : n1.replace(".", ",");
    }
   return n1;
  },
  currencyIN: function(n){ 
    if (ereg("^[+-]?[0-9]{1,3}(\.[0-9]{3})*\,[0-9]{2}$",n)) {
      var f = explode(",", n);
      f[0] = f[0].replace(".",",");
      n = f.join(".");
    }
    return n;
   },
  currencyBR: function(n){
    if (ereg("^[+-]?[0-9]{1,3}(\,[0-9]{3})*\.[0-9]{2}$",n)) {
      var f = explode(".", n);
      f[0] = f[0].replace(",",".");
      n = f.join(",");
    }
    return n;
   }
}


/**
 * Emula a função explode do PHP
 * @return {Array}
 * @param {String} glue Separador de texto
 * @param {String} text Texto
 */
function explode(glue, text) {
 var i = 0;
 var s = 0;
 var r = new Array();
 var c = text.indexOf(glue);

 while (c > 0) {
  r[i++] = text.slice(s, c);
  s = c+1;
  c = text.indexOf(glue, s);
 }

 if (text.slice(s) != "") r[i++] = text.slice(s);
 
 return r;
}


/**
 * Verifica se alguma opção foi selecionada
 * @return {Boolean}
 * @param {Array} e Array de elementos a ser testado
 */
function is_checked(e) {
 for(i = 0, t = e.length; i < t; i++) {
  if(e[i].checked == true) {
   return true;
  }
 }
 return false;
}


/**
 * Simula a função empty do PHP
 * @return {Boolean}
 * @param {String} v string a ser testada
 */
function empty(v) {
 v = v.replace(/^[\s\t\r\n]+$/g, "");
 return v == "" ? true : false;
}


/**
 * Simula a funçõa trim do PHP
 * @return {String}
 * @param {String} v
 */
function trim(v) {
 return v.replace(/^\s+|\s+$/g,"");
}


/**
 * Simula a função ltrim do php
 * @return {String}
 * @param {String} v
 */
function ltrim(v) {
 return v.replace(/^\s+/, "");
}


/**
 * Simula a função rtrim do PHP
 * @param {String} v
 * @return {String}
 */
function rtrim(v){
 return v.replace(/\s+$/, "");
}


/**
 * Verifica se o CPF é válido
 * @param {String} v
 * @return {Boolean}
 */
function CheckCPF(v) {
 var s1 = 0;
 var s2 = v.charAt(9)*2;
 for (i = 0; i < 9;i++) { 
  s1 = s1 + (v.charAt(i)*(10-i)); 
  s2 = s2 + (v.charAt(i)*(11-i)); 
 }
 var d1 =  (11-(s1%11) > 10 ? 0 : (11-(s1%11)) );
 var d2 =  (11-(s2%11) > 10 ? 0 : (11-(s2%11)) );
 
 return d1 != v.charAt(9) || d2 != v.charAt(10) || ereg("^[0-9]{11}$",v) == false ? false : true;
}


/**
 * Insere o flash na página
 * @return void
 * @param {String} c caminho do flash
 * @param {Integer} l largura
 * @param {Integer} a altura
 */
function flash(c, l, a) {
 document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="'+l+'" height="'+a+'">');
  document.write('<param name="movie" value="'+c+'">');
  document.write('<param name="quality" value="high">');
  document.write('<param name="wmode" value="transparent">');
  document.write('<param name="menu" value="false">');
  document.write('<embed src="'+c+'" wmode="transparent" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="'+l+'" height="'+a+'"></embed>');
 document.write('</object>');
}


/* Rastrar pedidos */
 var popRastrear = new PopupWindow();
     popRastrear.width = "550";
     popRastrear.height = "400";
     popRastrear.resizable = "yes";
     popRastrear.url = "http://websro.correios.com.br/sro_bin/txect01$.startup?P_LINGUA=001&P_TIPO=001";
/* FIM Rastrar pedidos */


