addEvent(window, "load",  newDateBox);

//var tpEvent = ["mouseover","mousemove"];
var tpEvent = ["focus","click"];

function hasDtd() {
  return detectDoctype();
}

function resizeInput(input) {
  if (hasDtd()) {
    input.style.width = "100px";
  }
}

function newDateBox(){
  $$(".dateBox").invoke("observe",tpEvent[0], function(e){ 
    var data = (isNaN(this.value.slice(this.value.length-1,this.value.length))? false: dateToJson(this.value));
    getCalendar(this.id, data); //crio o div com o calendário
  }).each(
    function(s) {
      resizeInput(s);
    }
    );


 
  Event.observe(document, tpEvent[1], function(e) {
    if(!e.element().hasClassName('dateBox') && e.element().id != 'calendarBox'){
      var execute = true;
      e.element().ancestors().each(function(el) {
        if(el.id == 'calendarBox'){
          execute = false;
          return;
        }
      });
      if (execute){
        closeDateBox();
      }
    }
  });
}

function getCalendar(idEl, data){
  closeDateBox(); // removo só para garantir que não vai abrir um calendario com outro já aberto
  $(idEl).addClassName("active");
  var monthsNames = ["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"];
  var dt = new Date();
  var d = dHj = dt.getDate();
  var m = mHj = dt.getMonth();
  var y = yHj = dt.getFullYear();
  if(data){ 
    d=data.d; m=data.m; y=data.y;
  }
  dt = new Date(y,m,1);
  var s = dt.getDay();
  var mA = (m<=0? 11+m : m-1 );
  var yMA = (m<=0? y-1 : y );
  var mP = (m>=11? 0 : m+1 );
  var yMP = (m>=11? y+1 : y );
  var tr = new Template("<tr id='#{trId}'><td class='weekend' id='td_#{dDom}'>#{dDom}</td><td id='td_#{dSeg}'>#{dSeg}</td><td id='td_#{dTer}'>#{dTer}</td><td id='td_#{dQua}'>#{dQua}</td><td id='td_#{dQui}'>#{dQui}</td><td id='td_#{dSex}'>#{dSex}</td><td class='weekend' id='td_#{dSab}'>#{dSab}</td></tr>");
  var dSel = (dHj.toString().length>=2? dHj: "0" + dHj);
  var mSel = (mHj+1);
  mSel = (mSel.toString().length>=2? mSel: "0" + mSel);
  var html = "<table cellpadding='1' border='0' cellspacing='0'><thead>"+
  "<tr><th colspan='6' id='titCalendar'> "+ monthsNames[m] + " " + y +" </th><td onclick='closeDateBox();' id='closeDtBox'>&nbsp;</td></tr>" +
  "<tr><td class='prev2' onclick=\"getCalendar('"+idEl+"', {d:"+d+", m:"+m+", y:"+(y-1)+"})\">&nbsp;</td><td class='prev1' onclick=\"getCalendar('"+idEl+"', {d:"+d+", m:"+mA+", y:"+yMA+"})\">&nbsp;</td>"+
  "<td colspan='3' onclick=\"$('"+idEl+"').value=formatDate('"+dSel+"', '"+mSel+"', '"+yHj+"'); closeDateBox();\"> Hoje </td>"+
  "<td class='next1' onclick=\"getCalendar('"+idEl+"', {d:"+d+", m:"+mP+", y:"+yMP+"})\">&nbsp;</td><td class='next2' onclick=\"getCalendar('"+idEl+"', {d:"+d+", m:"+m+", y:"+(y+1)+"})\">&nbsp;</td></tr>" +
  "</thead><tbody><tr><th class='weekend'>Dom</th><th>Seg</th><th>Ter</th><th>Qua</th><th>Qui</th><th>Sex</th><th class='weekend'>Sáb</th></tr>";
  var dia = 1-s;
  for (var i = 0; i<= 6; i++){
    html += tr.evaluate({
      id:y+"."+m+"."+i,
      dDom:dia++,
      dSeg:dia++,
      dTer:dia++,
      dQua:dia++,
      dQui:dia++,
      dSex:dia++,
      dSab:dia++
    });
    if(dia > maxDays(m,y)){
      break;
    }
  }
  html += "</tbody></table>";
  var cDiv = new Element("div", { 
    'id': 'calendarBox'
  }).update(html);
  document.body.appendChild(cDiv);
  cDiv.style.left = $(idEl).cumulativeOffset().left + 'px';
  cDiv.style.top = ($(idEl).getHeight() + $(idEl).cumulativeOffset().top)  + 'px';
  for(var i=1-s; i<dia; i++){ 
    if( i<=0 ) { 
      dSel = maxDays(mA, yMA)+i; mSel=mA; ySel=yMA;
      $("td_"+i).update(dSel).addClassName("nonmonthday");
    }else if( i> maxDays(m,y) ) {
      dSel = i-maxDays(m, y); mSel=mP; ySel=yMP; 
      $("td_"+i).update(dSel).addClassName("nonmonthday");
    }else{
      dSel = i; mSel=m; ySel=y; 
      if( i==dHj && m==mHj && y==yHj) { 
        $("td_"+i).addClassName("today");
      }
    }
    mSel = (mSel+1);
    dSel = (dSel.toString().length>=2? dSel: "0" + dSel);
    mSel = (mSel.toString().length>=2? mSel: "0" + mSel);
    $("td_"+i).writeAttribute("value", formatDate(dSel, mSel, ySel));
    $("td_"+i).observe("click",function(e){
      $(idEl).value = this.readAttribute("value");
      closeDateBox();
    });
  }
}

function closeDateBox(){
  $$("#calendarBox").invoke("remove");
  $$(".dateBox.active").invoke("removeClassName","active");
}


//==== as funções abaixo podem ser reaproveitaveis em outros lugares e por isso poderiam ser movidas para algum shared.js ou algo do tipo...

function addEvent(obj, evType, fn){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, true)
  }else if (obj.attachEvent){
    obj.attachEvent("on" + evType, fn)
  }
}

function maxDays(mm, yyyy){
  var mDay = 30;
  if(!( (mm == 3) || (mm == 5) || (mm == 8) || (mm == 10) )){ 
    mDay = 31;
    if(mm == 1){
      mDay = 29;
      if (yyyy/4 - parseInt(yyyy/4) != 0){
        mDay = 28;
      } //calculo de ano bisexto valido somente entre os anos de 1901 a 2099, se passar deste ano favor corrigir para a formula correta.
    }
  }
  return mDay;
}

function formatDate(d,m,y,formato){//caso o formato não seja passado por parâmetro, passa a ser definido de acordo com um formato global 
  var data = (!formato? "dd/mm/yyyy": formato) //trocar "dd/mm/yyyy" por top.getLabel("bd.dateFormat");
  data = data.replace("yyyy", y).replace("yy", y.toString().slice(2,4));
  data = data.replace("mm", m).replace("m", Number(m));
  data = data.replace("dd", d).replace("d", Number(d));
  return data;
}

function dateToJson(dt, formato){//caso o formato não seja passado por parâmetro, passa a ser definido de acordo com um formato global 
  var json;
  var chr = (dt.indexOf("/")>0?"/":(dt.indexOf("-")>0?"-":" "));
  var aDt = dt.split(chr);
  switch((!formato? "dd/mm/yyyy": formato)) { //trocar "dd/mm/yyyy" por top.getLabel("bd.dateFormat");
    case "yyyy/mm/dd": case "yyyy-mm-dd": json = {
      d:Number(aDt[2]),
      m:(Number(aDt[1])-1),
      y:Number(aDt[0])
    }; break;
    case "mm/dd/yyyy": case "mm-dd-yyyy": json = {
      d:Number(aDt[1]),
      m:(Number(aDt[0])-1),
      y:Number(aDt[2])
    }; break;
    case "dd/mm/yyyy": case "d/m/yyyy": case "dd-mm-yyyy": case "d-m-yyyy": default: json = {
      d:Number(aDt[0]),
      m:(Number(aDt[1])-1),
      y:Number(aDt[2])
    }; break;
  //se precisar de outros formatos basta criar outros cases. caso venha a usar ano com 2 digitos, concatenar "20" ao lado. caso use nomes por extenso fazer processo inverso ao q for feito na função "formatDate"
  }
  return json;
}

/*a função abaixo já existe no shared.js do e-hunter*/

function posNaImagem(x,y,grade){
  return "background-position:-" + (x*grade) + "px -" + (y*grade) + "px;";
}

function docTypeInfo()
{
  this.xhtml="";
  this.version="";
  this.importance="";
  this.dtd="";
}

function detectDTD(){
  //Detect DTD
  var re=/\/+(\w+\-?\w+\.dtd)/gi;
  /*********************************************
  Just check for internet explorer.
  **********************************************/

  if(typeof document.namespaces != "undefined"){
    if(document.all[0].nodeType==8 && re.test(document.all[0].text))
      re.exec(document.all[0].text);
    else
      return null;
  }else{
    if(document.doctype != null && document.doctype.systemId != "")
      re.exec(document.doctype.systemId);
    else
      return null;
  }

  return RegExp.$1;
}

function detectDoctype(){
  var re=/\s+(X?HTML)\s+([\d\.]+)\s*([^\/]+)*\//gi;
  var iDocTypeInfo=new docTypeInfo();

  if(typeof document.namespaces != "undefined"){
    if(document.all[0].nodeType==8)
      re.exec(document.all[0].nodeValue);
    else
      return null;
  }else{
    if(document.doctype != null)
      re.exec(document.doctype.publicId);
    else
      return null;
  }
  iDocTypeInfo.xhtml=RegExp.$1;
  iDocTypeInfo.version=RegExp.$2;
  iDocTypeInfo.importance=RegExp.$3;
  iDocTypeInfo.dtd=detectDTD();
  return iDocTypeInfo;
}
