/* Classe FileManager développée par Elforia Design */
/* http://www.elforia-design.fr */

function FileManager(tableName, filesPath) {
  this._tableName = tableName;
  this._tableNode = document.getElementById(tableName);
  this._filesPath = filesPath;
  this._files = new Array();
  this._fieldOrdered = 'none';
  this._sensOrdered  = 'none';

  var tmp = this;
  this.returnXmlRequest = function() {

    var messg, xmldoc;

    if (http_request.readyState == 4) {
       if (http_request.status == 200) {
         xmldoc = http_request.responseXML;

         var root_node = xmldoc.getElementsByTagName('root').item(0);
         tmp.drawFileManager(root_node);

       } else {
         messg = 'Probleme avec la requete';
       }
    }
  }

  this.init = function() {
    makeRequest(this._filesPath+'returnfiles.php', '', this.returnXmlRequest);
  }

  this.drawFileManager = function(root_node) {
    this.clearFileManager();
    var dirname = root_node.getElementsByTagName('dir').item(0).firstChild.data;
    var filesNode = root_node.getElementsByTagName('file');
    var numFiles = filesNode.length;

    document.getElementById(this._tableName+'Path').innerHTML = dirname;
  
    this._files = new Array();
    for (var i=0;i<numFiles;i++) {
      var file = new File(dirname, filesNode[i]);
      if (file.name()=='..') {
        this.createRow(file);
        this._files.unshift(file);
      } else this._files.push(file);
    }

    for (var i=0;i<numFiles;i++) if (this._files[i].name()!='..') this.createRow(this._files[i]);

    this.sort();
  }

  this.clearFileManager = function() {
    var tbody = this._tableNode.getElementsByTagName('tbody')[0];
    var trs = tbody.getElementsByTagName('tr');
    var num = trs.length;

    for (var i=2;i<num;i++) tbody.removeChild(trs[2]);
  }

  this.createRow = function(file) {
    var tbody = this._tableNode.getElementsByTagName('tbody')[0];
    var tr = document.createElement('tr');  
    file.setTR(tr);

    tbody.appendChild(tr);

    var td;
    td = document.createElement('td');
    var a = document.createElement('a');
    var attr = document.createAttribute("class");
    attr.nodeValue = "icon";
    a.setAttributeNode(attr);
    a.style.display = 'block';
    var img = document.createElement('img');
    var text = document.createTextNode(file.name());
    a.appendChild(img);
    a.appendChild(text);
    img.src = this._filesPath+'icons/'+file.icon();
    if (file.type()=='dir') {
      var parameters = 'dirname=' + file.dirname() + '&clickon=' + file.name();
      a.href = "javascript: makeRequest('"+this._filesPath+"returnfiles.php', '" + parameters + "', "+this._tableName+".returnXmlRequest);";
    } 
    td.appendChild(a);
    tr.appendChild(td);

    var td;
    td = document.createElement('td');
    attr = document.createAttribute("class");
    attr.nodeValue = "right";
    td.setAttributeNode(attr);

    var size = file.size();  
    if (size<1024)  size = size + " octets";
    else if (size<1024*1024) size = Math.round(size/1024*10)/10 + " Kos";
    else size = Math.round(size/1024/1024*10)/10 + " Mos";

    td.appendChild( document.createTextNode(size) );
    tr.appendChild(td);

    var td;
    td = document.createElement('td');
    attr = document.createAttribute("class");
    attr.nodeValue = "right";
    td.setAttributeNode(attr);
    td.appendChild( document.createTextNode(file.modifiedStr()) );
    tr.appendChild(td);

    var td;
    td = document.createElement('td');
    td.appendChild( document.createTextNode(file.permissions()) );
    tr.appendChild(td);

    var td;
    td = document.createElement('td');
    td.appendChild( document.createTextNode(file.owner()) );
    tr.appendChild(td);
  }

  this.lessThan = function(a, b) {
    if (this._fieldOrdered=='name') {
      if (a.name().toLowerCase()<b.name().toLowerCase()) return 1;
      else if (a.name().toLowerCase()>b.name().toLowerCase()) return 2;
    }

    if (this._fieldOrdered=='size') {
      if (a.size()<b.size()) return 1;
      if (a.size()>b.size()) return 2;
    }

    if (this._fieldOrdered=='modified') {
      if (a.timestamp()<b.timestamp()) return 1;
      if (a.timestamp()>b.timestamp()) return 2;

    }

    return 0;
  }

  this.sortBy = function(field) {
    if (this._fieldOrdered!='none') document.getElementById('imgSortBy'+this._fieldOrdered).src = this._filesPath+'icons/blank.gif';

    this._fieldOrdered = field;

    if (this._sensOrdered=='none' || this._sensOrdered=='desc') this._sensOrdered = 'asc';
    else this._sensOrdered = 'desc';

    if (this._sensOrdered=='asc') document.getElementById('imgSortBy'+this._fieldOrdered).src = this._filesPath+'icons/down.gif';
    else document.getElementById('imgSortBy'+this._fieldOrdered).src = this._filesPath+'icons/up.gif';

    this.sort();
  }

  this.sort = function() {
    if (this._files.length==1) return;
    if (this._fieldOrdered=='none') return;

    var tbody = this._tableNode.getElementsByTagName('tbody')[0];

    var firstIndice = 0;
    if (this._files[0].name()=='..') firstIndice = 1;

    var stop = false;
    while (!stop) {
      stop = true;
      for (var i=firstIndice;i<this._files.length-1;i++) {

        var res = this.lessThan(this._files[i], this._files[i+1]);
 
        var swap = true;
        if (this._sensOrdered=='asc') {
          if (res==1||res==0) swap = false;
        } else {
          if (res==2||res==0) swap = false;
        }

        if (swap) {

          stop = false;

          var clone = this._files[i].tr().cloneNode(true);
          tbody.replaceChild(this._files[i+1].tr(), this._files[i].tr());
          this._files[i].setTR(clone);

          if (i+2<=this._files.length-1) tbody.insertBefore(clone, this._files[i+2].tr());

          else tbody.appendChild(clone);

          copie = this._files[i];
          this._files[i]   = this._files[i+1];
          this._files[i+1] = copie;
        }
      }
 
    }
  }

}

function File(dirname, fileNode) {
  this._dirname = dirname;
  this._type = fileNode.getElementsByTagName('type').item(0).firstChild.data;
  this._name = fileNode.getElementsByTagName('name').item(0).firstChild.data;
  this._size = parseInt(fileNode.getElementsByTagName('size').item(0).firstChild.data, 10);

  this._permissions = fileNode.getElementsByTagName('permissions').item(0).firstChild.data;
  this._owner = fileNode.getElementsByTagName('owner').item(0).firstChild.data;
  this._tr = null;

  var fields = fileNode.getElementsByTagName('modified').item(0).firstChild.data.split(' ');  
  this._modified = new Date(fields[0],fields[1],fields[2],fields[3],fields[4],fields[5]);

  this.dirname = function() { return this._dirname; }
  this.type = function() { return this._type; }
  this.name = function() { return this._name; }
  this.size = function() { return this._size; }
  this.modified = function() { return this._modified; }
  this.permissions = function() { return this._permissions; }
  this.owner = function() { return this._owner; }
  this.tr = function() { return this._tr; }
  this.modifiedStr = function() { 
    var d = this._modified.getDate(); 
    var m = this._modified.getMonth() + 1;
    var y = this._modified.getFullYear();
    var h = this._modified.getHours();
    var i = this._modified.getMinutes();
    var s = this._modified.getSeconds();

    d = (d<10) ? "0"+d : d;
    m = (m<10) ? "0"+m : m;
    h = (h<10) ? "0"+h : h;
    i = (i<10) ? "0"+i : i;
    s = (s<10) ? "0"+s : s;

    return  d + "/" + m + "/" + y + " " + h + ":" + i + ":" + s;
  }

  this.timestamp = function() {
    var d = this._modified.getDate(); 
    var m = this._modified.getMonth();
    var y = this._modified.getFullYear();
    var h = this._modified.getHours();
    var i = this._modified.getMinutes();
    var s = this._modified.getSeconds();

    return Date.UTC(y,m,d,h,i,s);
  }

  this.icon = function() {
    if (this._type=='dir') return 'folder.gif';

    var array = this._name.split('.');
    if (array.length==1) return 'icon-unknown.gif';
    var ext = array[ array.length - 1 ];

    if (ext=='html') return 'icon-html.gif';
    else if (ext=='php') return 'icon-php.gif';
    else if (ext=='tpl') return 'icon-tpl.gif';
    else if (ext=='css') return 'icon-tpl.gif';
    else if (ext=='js') return 'icon-tpl.gif';
    else if (ext=='pdf') return 'icon-pdf.gif';

    return 'icon-unknown.gif';
  }
  this.setTR = function(tr) {
    this._tr = tr;
  }
}

