/*                                                                                                                                                      
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 0.11.0
*/ 
/*                                                                                                                                                      
Copyright (c) 2006, e-Corvina Kft. Minden jog fenntartva.
Copyright (c) 2006, e-Corvina limited company. All rights reserved.
*/ 

YAHOO.widget.TreeView = function(id,url,cellpadding) {
    if (id) { this.init(id,url,cellpadding); }
};

YAHOO.widget.TreeView.prototype = {

    /**
     * The id of tree container element
     *
     * @type String
     */
    id: null,

    /**
     * The url to be downloaded on expand
     *
     * @type String
     */
    url: null,
    
    /** 730: a children-eket ilyen szeles mezobe kell majd belepakolni, amibol x16 lesz a fuggoleges pontozott vonal (|), es balra illetve jobbra jon cellpadding pixelnyi padding */
    cellpadding: null,

    /**
     * The host element for this tree
     * @private
     */
    /* A tablazatban 2 <tr></tr> van fenntartva: "a" a parent node-nak, "b" a child node-oknak (id+'a',id+'b') */
    _el_a: null,  _el_b: null, _el_c: null,

    /**
     * We lock the tree control while waiting for the dynamic loader to return
     *
     * @type boolean
     */
    locked: false,

    /** allapot: 0 1 vagy 2 (nem kibontott, kibontas alatt allo, kibontott) (a csomopont megjelenesere utal */
    state: 0,
    
    /** Betöltés alatt áll-e */
    isLoading: false,
    
    /** Következo sor tartalma (id+'c'). Ha null, akkor még sosem volt letöltve. */
    content: null,

    /**
     * Initializes the tree
     *
     * @parm {string|HTMLElement} id the id of the element that will hold the tree
     * @private
     */
    init: function(id,url,cellpadding) {

        this.id = id;
        this.url = url;
	this.cellpadding = cellpadding;

        if ("string" !== typeof id) {
            this._el = id;
            this.id = this.generateId(id);
        }

        // store a global reference
        YAHOO.widget.TreeView.trees[this.id] = this;

//        // Set up the root node
//        this.root = new YAHOO.widget.RootNode(this);
    },

    /**
     * Returns the tree's host element
     * @return {HTMLElement} the host element
     */
    getEla: function() {
        if (! this._el_a) {
            this._el_a = document.getElementById(this.id+'a');
        }
        return this._el_a;
    },
    getElb: function() {
        if (! this._el_b) {
            this._el_b = document.getElementById(this.id+'b');
        }
        return this._el_b;
    },
    getElc: function() {
        if (! this._el_c) {
            this._el_c = document.getElementById(this.id+'c');
        }
        return this._el_c;
    },


    /**
     * toString
     * @return {string} string representation of the tree
     */
    toString: function() {
        return "TreeView " + this.id;
    },

    /**
     * private
     */
    generateId: function(el) {
        var id = el.id;

        if (!id) {
            id = "yui-tv-auto-id-" + YAHOO.widget.TreeView.counter;
            YAHOO.widget.TreeView.counter++;
        }

        return id;
    },

    /** Ki kell nyitni, vagy be kell csukni */
    onClick: function() {
      var oldstate = this.state;
      if(this.state==1) { this.collapse(); }
      else if(this.state==2) { this.collapse(); }
      else if(this.state==0) { this.expand(); }
      return;
    },
    
    /** Becsukjuk a csomópontot */
    collapse: function() {
      if(this.isLoading) {
        this.state=0;
      } else {
//      this.content=this.getElb().innerHTML;
        this.state=0;
      }
      this.getEla().className="ygtvap";
      this.getElb().style.display="none"; // FIXME: lock
    },
    
    /** Kibontjuk a csomópontot */
    expand: function() {
      if(this.isLoading) {
        this.getEla().className="ygtvloading";
        this.state=1;
      } else {
        if(this.content==null) { // elinditjuk a requestet.
          this.state=1;
          this.getEla().className="ygtvloading";
          this.loadChildren(this);
        } else {
          this.state=2;
          this.getEla().className="ygtvbm";
//        this.getElb().innerHTML=this.content;
          this.getElb().style.display=""; // "table-row";  table-row: szabványos, firefox/opera szereti, ie nem szereti. "": nem szabványos, de firefox/opera/ie szereti.
        }
      }
    },
    
    expanded: function() {
      return this.state>=1;
    },
    /**
     * Returns the css style name for the toggle
     *
     * @return {string} the css class for this node's toggle
     */
    getStyle: function() {
        if (this.isLoading && this.expanded()) {
            return "ygtvloading";
        } else {
            // location top or bottom, middle nodes also get the top style
            var loc = "b"; // (this.nextSibling) ? "t" : "l";

            // type p=plus(expand), m=minus(collapase), n=none(no children)
            var type = "n";
            if (this.hasChildren(true)) {
            // if (this.hasChildren(true)) {
                type = (this.expanded()) ? "m" : "p";
                if(!this.expanded()) { loc="a"; }
            } else {
              loc="a";
            }
            return "ygtv" + loc + type;
        }
    },
    getStyle2: function(nextSibling) {
      // location top or bottom, middle nodes also get the top style
      var loc = (nextSibling) ? "t" : "l";

      // type p=plus(expand), m=minus(collapase), n=none(no children)
      var type = "n";

      return "ygtv" + loc + type;
    },
    getStyle2b: function(nextSibling) {
      return (nextSibling) ? "ygtvvline" : "ygtvnoline";
    },
    /**
     * Returns the hover style for the icon
     * @return {string} the css class hover state
     */
    getHoverStyle: function() { 
        var s = this.getStyle();
        if (this.hasChildren(true) && !this.isLoading) { 
            s += "h"; 
        }
        return s;
    },
    hasChildren: function(checkForLazyLoad) { 
      return true;
    },

    /** Betölti a cuccot XMLHttpRequest-tel
      * @param {TreeView} parentNode this node's parent node.
      * Kell neki az id, hogy az alapján tudja majd, mennyire mehet ki jobbra a táblázat.
      */
    loadChildren: function(parentNode) {
      if(this.isLoading) { return; }
      this.isLoading=true;
      this.doTheXMLHTTPRequest(parentNode);
      return;
    },

    doTheXMLHTTPRequest: function(parentNode) {
      var tthis=this;
      var handleSuccess = function(o) {
        if(o.responseText !== undefined && o.status==200) {
          var children = [];
          var root = document.createElement("div");
          root.innerHTML = o.responseText;
//        children[children.length] = root.firstChild.nodeName;
//        children[children.length] = root.innerHTML;
          var nodeList1 = root.childNodes;
          var node1;
          // Az elso nem text node-ot keressük.
          for(var i=0;i<nodeList1.length;i++) {
            var node=nodeList1.item(i);
            if(node.nodeName.toLowerCase() !== "table") { continue; }
            node1=node;
            break;
          }
//        children[children.length] = node1.nodeName;
          var nodeList2=node1.firstChild.childNodes; // firstChild: <thead>?
          // Az elso nem text node-ban az osszes child-ot keressuk.
          for(var i=0;i<nodeList2.length;i++) {
            var node=nodeList2.item(i);
            children[children.length]=node.innerHTML; // <td>...</td><td>...</td>
          }
/*        
*/        

          var sb=[];
          var last_i=children.length-1;
          for (var i in children) {
            var child = children[i];
            var nextSibling = i<last_i ? 1 : 0;
            sb[sb.length] = '<tr>'
            sb[sb.length] = '<td class="'+tthis.getStyle2b(nextSibling)+'"><div class="'+tthis.getStyle2(nextSibling)+'" style="background-color: rgb(255, 255, 255);">&nbsp;</div></td>';
//            sb[sb.length] = '<td width="'+(tthis.x730-tthis.x16)+'"><table border="0" cellspacing="0" cellpadding="0" style="width:100%"><tr>'+child+'</tr></table></td>'; // child: <td>...</td><td>...</td> formatumu
            sb[sb.length] = '<td><table border="0" cellspacing="0" cellpadding="0"><tr>'+child+'</tr></table></td>'; // child: <td>...</td><td>...</td> formatumu
            sb[sb.length] = '</tr>';
          }
	  var padding_str='padding: 0px, '+tthis.cellpadding+'px, 0px, '+tthis.cellpadding+'px';
//          tthis.content = '<table border="0" cellspacing="0" cellpadding="0" style="width:'+tthis.x730+'px;">'+sb.join("")+'</table>';
          tthis.content = '<table border="0" cellspacing="0" cellpadding="0" style="width:100%">'+sb.join("")+'</table>';
          tthis.onLoadCompleted();
          return;
        }
      }

      var handleFailure = function(o){
        if(o.responseText !== undefined){
          var s = "<li>Transaction id: " + o.tId + "</li>";
          s += "<li>HTTP status: " + o.status + "</li>";
          s += "<li>Status code message: " + o.statusText + "</li>";
          tthis.content = s;
          tthis.onLoadCompleted();
          return;
        }
      }

      var callback =
      {
        success:handleSuccess,
        failure:handleFailure,
        argument: { foo:"foo", bar:"bar" }
      };
      var sUrl = this.url; // "?action=onelong&showtype=long&recnum=21761";
//      var sUrl = "?action=onelong&showtype=longlong&recnum=21761";
//      var sUrl = "?action=onelong&showtype=longlong&recnum=21323";
//      var sUrl = "?pagesize=10&sort=0&showonetype=longlong&basket21323=on&basket21322=on&basketset=21323,21322&action=showbasket&d";
      sUrl +='&cid='+this.id;
      var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback);
    },

    onLoadCompleted: function() {
      this.isLoading=false;
      this.getElb().style.display="none";
      this.getElc().innerHTML=this.content;
      this.content="a"; // ne null legyen, és ne foglaljon sok helyet.
      if(this.state==1) {
        this.state=0;
        this.expand();
      }
    }
};

/**
 * Global cache of tree instances
 *
 * @type Array
 * @private
 */
YAHOO.widget.TreeView.trees = [];

/**
 * @private
 */
YAHOO.widget.TreeView.counter = 0;

/**
 * Global method for getting a tree by its id.  Used in the generated
 * tree html.
 *
 * @param treeId {String} the id of the tree instance
 * @return {TreeView} the tree instance requested, null if not found.
 * FIXME: nem használt
 */
YAHOO.widget.TreeView.getTree = function(treeId) {
    var t = YAHOO.widget.TreeView.trees[treeId];
    return (t) ? t : null;
};

/**
 * Ha még nem létezne ilyen id-vel, akkor létrehozza. Ha létezik, akkor visszaadja, és
 * beállítja az url-t.
 *
 * A paraméterek ugyanazok, mint az init-nél.
 * @return {TreeView} the tree instance requested
 */
YAHOO.widget.TreeView.getInstance = function(id,url,cellpadding) {
    var t = YAHOO.widget.TreeView.trees[id];
    if(t) { t.url=url; }
    else {
      t=new YAHOO.widget.TreeView(id,url,cellpadding);
    }
    return t;
};


/**
 * Adds an event.  Replace with event manager when available
 *
 * @param el the elment to bind the handler to
 * @param {string} sType the type of event handler
 * @param {function} fn the callback to invoke
 * @param {boolean} capture if true event is capture phase, bubble otherwise
 */
YAHOO.widget.TreeView.addHandler = function (el, sType, fn, capture) {
    capture = (capture) ? true : false;
    if (el.addEventListener) {
        el.addEventListener(sType, fn, capture);
    } else if (el.attachEvent) {
        el.attachEvent("on" + sType, fn);
    } else {
        el["on" + sType] = fn;
    }
};

/**
 * Attempts to preload the images defined in the styles used to draw the tree by
 * rendering off-screen elements that use the styles.
 */
YAHOO.widget.TreeView.preload = function(prefix) {
    prefix = prefix || "ygtv";
//    var styles = ["tn","tm","tmh","tp","tph","ln","lm","lmh","lp","lph","loading"];
    var styles = ["an","am","amh","ap","aph","bn","bm","bmh","bp","bph","tn","ln","loading","vline","noline"];
    var sb = [];
    
    for (var i = 0; i < styles.length; ++i) { 
        sb[sb.length] = '<span class="' + prefix + styles[i] + '">&nbsp;</span>';
    }

    var f = document.createElement("DIV");
    var s = f.style;
    s.position = "absolute";
    s.top = "-1000px";
    s.left = "-1000px";
    f.innerHTML = sb.join("");

    document.body.appendChild(f);
};

YAHOO.widget.TreeView.addHandler(window, 
                "load", YAHOO.widget.TreeView.preload);


