/**
 * This file defines a Filechooser object which displays a popup window containing a tree of the user's files.
 *
 * Suggested usage:
 *
    function okCallback()
    {
      this.panel.hide();
      alert_old(this.documentRecord.id);
    }

    function init()
    {
      var filechooser = new Filechooser("popup", okCallback);
      YAHOO.util.Event.addListener("choosefile", "click", filechooser.panel.show, filechooser.panel, true);
    }

    YAHOO.util.Event.addListener(window, "load", init);
 *
 * <div id="popup" class="filechooser"></div>
 * <button id="choosefile">Choose File</button>
 * 
 * The callback function runs in the scope of the filebrowser and has access to the panel, tree and documentRecord through this.panel etc.
 *
 * author: Simon
 * date: 29.07.2009
 * */

/**
 * Function to set the properties of the clicked on Node each time a user clicks a node.  Saved in filebrowser.documentrecord
 * */
function labelClick(event)
{
  var node = event.node;
  //store the currently selected node in the html form
  if (node.isLeaf)
  {
    //get the full path to the file and save it in the documentRecord
    var qualName = node.label;
    var tempNode = node;
    while (tempNode.parent != this.tree.getRoot())
    {
      qualName = tempNode.parent.label + "/" + qualName;
      tempNode = tempNode.parent;
    }
    this.documentRecord = new DocumentRecord(node.data.id, node.label, qualName.substring(1, qualName.length));
  }
}


/**
 * Function to load the data for each node in the tree.  Calls back to the FileAPI to load the data.
 * */
function loadData(node, fnLoadComplete)
{
  var baseURL = "../servlets/fileapi";

  //Get the node's label and urlencode it;  This is the directory we will load
  var nodeLabel = node.label;
  var tempNode = node;

  while (tempNode.parent.label !== undefined)
  {
    nodeLabel = tempNode.parent.label + "/" + nodeLabel;
    tempNode = tempNode.parent;
  }

  //remove the beginning slash that gets added
  if (nodeLabel !== "/MetaData" && nodeLabel.length > 1)
  {
    nodeLabel = nodeLabel.substring(1, nodeLabel.length);
  }
  nodeLabel = encodeURI(nodeLabel);


  //prepare URL for XHR request:
  var getDirURL = baseURL + "?method=getDir&path=" + nodeLabel + "&id=" + node.data.id;

  //prepare our callback object
  var callback = {

    //if our XHR call is successful, we want to make use
    //of the returned data and create child nodes.
    success: function(oResponse)
    {
      YAHOO.log("XHR transaction was successful.", "info", "example");
      YAHOO.log(oResponse.responseText);

      //get the results into a JS assoicative array
      var oResults = eval("(" + oResponse.responseText + ")");
      if (!oResults.error)
      {
        //deal with the directories
        if ((oResults.ResultSet.Directories) && (oResults.ResultSet.Directories.length))
        {
          //Result is an array if more than one result, string otherwise
          if (YAHOO.lang.isArray(oResults.ResultSet.Directories))
          {
            for (var i = 0, j = oResults.ResultSet.Directories.length; i < j; i++)
            {
              var label = { label: oResults.ResultSet.Directories[i].name, id: oResults.ResultSet.Directories[i].id, type: "folder" };
              var tempNode = new YAHOO.widget.TextNode(label, node, false);
            }
          }
          else
          {
            //there is only one result; comes as string:
            var label = { label: oResults.ResultSet.Directories.name, id: oResults.ResultSet.Directories.id, type: "folder" };
            var tempNode = new YAHOO.widget.TextNode(label, node, false)

          }
        }

        //deal with the files
        if ((oResults.ResultSet.Files) && (oResults.ResultSet.Files.length))
        {
          //Result is an array if more than one result, string otherwise
          if (YAHOO.lang.isArray(oResults.ResultSet.Files))
          {
            for (var i = 0, j = oResults.ResultSet.Files.length; i < j; i++)
            {
              var label = { label: oResults.ResultSet.Files[i].name, id: oResults.ResultSet.Files[i].id, type: "file" };
              var tempNode = new YAHOO.widget.TextNode(label, node, false);
              tempNode.isLeaf = true;
            }
          }
          else
          {
            //there is only one result; comes as string:
            var label = { label: oResults.ResultSet.Files.name, id: oResults.ResultSet.Files.id, type: "file" };
            var tempNode = new YAHOO.widget.TextNode(label, node, false)
            tempNode.isLeaf = true;
          }
        }
      }
      //When we're done creating child nodes, we execute the node's
      //loadComplete callback method which comes in via the argument
      //in the response object (we could also access it at node.loadComplete,
      //if necessary):
      oResponse.argument.fnLoadComplete();
    },

    //if our XHR call is not successful, we want to
    //fire the TreeView callback and let the Tree
    //proceed with its business.
    failure: function(oResponse)
    {
      alert("XHR Call to initialise filechooser failed");
      oResponse.argument.fnLoadComplete();
    },

    //our handlers for the XHR response will need the same
    //argument information we got to loadNodeData, so
    //we'll pass those along:
    argument: {
      "node": node,
      "fnLoadComplete": fnLoadComplete
    }

    //timeout -- if more than 7 seconds go by, we'll abort
    //the transaction and assume there are no children:
//    timeout: 10000
  };

  //call the server to get the contents of the directory
  YAHOO.util.Connect.asyncRequest('GET', getDirURL, callback);
}

/**
 * Constructor for Filebrowser.
 * Param1: id of the div that will display the popup
 * Param2: function to run when the user clicks the OK button
 * Param3: function to run when the user clicks the Cancel button.  Defaults to closing the panel.
 * The functions have access to this.documentRecord which holds the details of the selected node, this.tree and this.panel
 * */
function Filechooser(panelDivId, okFunction, cancelFunction, okFnParams)
{

  if(cancelFunction == undefined)
    cancelFunction = function(){this.filechooser.panel.hide();};

  var okfp;

  if(okFnParams === undefined || okFnParams === {})
    okfp = {filechooser:this};
  else
    okfp = {filechooser:this, params: okFnParams};


  // build the popup that will contain the link tree
  this.panel = new YAHOO.widget.Panel(panelDivId, { width:"320px", height:"400px", visible:false, fixedCenter:true, constraintoviewport: true,  draggable:true, close:true, zIndex:9999 });
  this.panel.setHeader("Choose File");
  this.panel.setBody("<div style='height:340px;overflow:auto;'><div id='" + panelDivId + "_filebrowser'></div></div><div id='" + panelDivId + "_chooseFileButtonContainer'></div>");
  this.panel.center();
  this.panel.render();

  //add button to the popup
  var okButton = new YAHOO.widget.Button({label:"OK", id: panelDivId + "_chooseFileButton", container: panelDivId + "_chooseFileButtonContainer"});
  YAHOO.util.Event.addListener(panelDivId + "_chooseFileButton", "click", okFunction, okfp, true);

  //add button to the popup
  var cancelButton = new YAHOO.widget.Button({label:"Cancel", id: panelDivId + "_cancelButton", container: panelDivId + "_chooseFileButtonContainer"});
  YAHOO.util.Event.addListener(panelDivId + "_cancelButton", "click", cancelFunction, okfp, true);

  //create the tree for the popup
  this.tree = new YAHOO.widget.TreeView( panelDivId + "_filebrowser");
  this.tree.setDynamicLoad(loadData, 0);

  //the labelClick function runs in the scope of *this* so that we can set the properties of the object
  this.tree.subscribe("clickEvent", labelClick, this, true);

  var tempNode = new YAHOO.widget.TextNode("/", this.tree.getRoot(), true);
  this.tree.getRoot().expand();
  this.tree.draw();
}

/** Create a file chooser tree inside an existing Div */
function FilechooserDiv(panelDivId, evHandler){
    this.tree = new YAHOO.widget.TreeView(panelDivId);
    this.tree.setDynamicLoad(loadData, 0);
    this.clickEventHandler = evHandler;
    this.tree.subscribe("clickEvent", evHandler);
    var tempNode = new YAHOO.widget.TextNode("/", this.tree.getRoot(), true);

    this.tree.getRoot().expand();
    this.tree.draw();
}

FilechooserDiv.prototype.unsubscribeEvents = function(){
    this.tree.unsubscribe("clickEvent", this.clickEventHandler);
};

FilechooserDiv.prototype.redraw = function(){
    this.tree.draw();
};

function DocumentRecord(id, label, path)
{
  this.id = id;
  this.label = label;
  this.path = path;
}




