/*
* E-Catalog Book Index Tree Build script using YUI 2.7.0b
* Author: Kumar
* Date: Mar 13, 2009
*/

function stringSplitAndGetForIndex(inStr, splitStr, retIdx)
{ var retStr = "";
  if (!(isBlankStr(inStr) || isBlankStr(splitStr)))
  { xArr = inStr.split(splitStr);
    if ((xArr!=null) && (xArr.length >= retIdx))
    { retStr = xArr[retIdx];
    };
  };
  return (retStr);
}
function stringSplitAndGetAfterIndex(inStr, splitStr, retIdx)
{ var retStr = inStr;
  for (x=0; x<retIdx; x++)
  { retStr = retStr.substring(retStr.indexOf(splitStr)+(splitStr.length));
  }
  return (retStr);
}
function changeImage(imgObjId, imgLoc)
{ imgObj = getDocObj(imgObjId);
  if (imgObj!=null)
  { imgObj.src = imgLoc;
  };
}
function showBookLoad()
{ changeImage('bookRootIcon', '../img/loading.gif');
}
function stopBookLoad()
{ changeImage('bookRootIcon', '../img/AsplIsmPageZoomNormal.gif');
}
var buildBook = function()
{ showBookLoad();
  AjaxRequest.get(
                  {  'url':kBookOpenURL
                    ,'onSuccess':function(req){ buildBookResult(req); }
                    ,'onError':function(req){ buildBookFail(req); }
                    ,'timeout':(2*60*1000)
                    ,'onTimeout':function(req){ buildBookFail(req); }
                  }
                 );
}
function buildBookResult(xReq)
{ result = ""+escape(xReq.responseText);
  result = result.replace(/\%uFFFF/g, "");
  result = ""+unescape(result);
  result = result.replace(/[\n\r\t]/g, "");
  myBook.init(result);
  stopBookLoad();
}
function buildBookFail(xReq)
{ stopBookLoad();
  alert("Unable to load book index. Please try later.");
}

myBook = function() {
  var tree;

  function stringToNode(inStr, pPath)
  { xNodeType  = "";
    xNodeId    = "";
    xNodeLabel = "";
    isPage     = false;
    cPath      = pPath+(isBlankStr(pPath)? "" : "/")+inStr;
    pgNum      = "";
    if (!isBlankStr(inStr))
    { xNodeLabel = inStr;
      if (inStr.startsWith("-f"))
      { xNodeType  = "1";
        xNodeId    = stringSplitAndGetForIndex(inStr, "-", 1);
        xNodeLabel = "<b>"+stringSplitAndGetAfterIndex(inStr, "-", 2)+"</b>";
        isPage     = false;
      }
      else
      { xNodeType  = "0";
        xNodeId    = stringSplitAndGetForIndex(inStr, "-", 2);
        pgNum      = stringSplitAndGetForIndex(inStr, "-", 2);
        xNodeLabel = stringSplitAndGetAfterIndex(inStr, "-", 3);
        isPage     = true;
      };
    };
    var myBookNodeX = { bookNodeId:xNodeId, bookNodeType:xNodeType, label:xNodeLabel, xNodeData:inStr, xNodePath:cPath, xNodePgNum:pgNum, isLeaf:isPage};
    return (myBookNodeX);
  }

  function add2Node(node, children)
  { var bPath = (node.data.xNodePath)? node.data.xNodePath : "";

    var oResults = eval("(" + children + ")");
    if (!isBlankStr(children))
    { if((oResults.ResultSet.Result) && (oResults.ResultSet.Result.length)) {
        //Result is an array if more than one result, string otherwise
        if (YAHOO.lang.isArray(oResults.ResultSet.Result)) {
            for (var i=0, j=oResults.ResultSet.Result.length; i<j; i++) {
                var tempNode = new YAHOO.widget.TextNode(stringToNode(oResults.ResultSet.Result[i], bPath), node, expandBook);
            }
        } else {
            //there is only one result; comes as string:
            var tempNode = new YAHOO.widget.TextNode(stringToNode(oResults.ResultSet.Result, bPath), node, expandBook)
        }
      };
    };
  }

  function loadNodeData(node, fnLoadComplete)  {

      //alert("node.label: "+node.label+"\nnode.data.bookNodeType: "+node.data.bookNodeType+"\nnode.data.bookNodeId: "+node.data.bookNodeId);

      var bPath = (node.data.xNodePath)? node.data.xNodePath : "";
      //prepare URL for XHR request:
      var sUrl = kBookOpenURL+escape(bPath);

      //getDocObj("debugArea").value = sUrl;

      //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) {
              add2Node(node, oResponse.responseText);
              oResponse.argument.fnLoadComplete();
          },

          failure: function(oResponse) {
              //YAHOO.log("Failed to process XHR transaction.", "info", "example");
              oResponse.argument.fnLoadComplete();
          },

          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: 7000
      };

      //With our callback object ready, it's now time to
      //make our XHR call using Connection Manager's
      //asyncRequest method:
      YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
  } //End of loadNodeData

  function buildTree() {
      bookTopSections = arguments[0];

      //create a new tree:
      tree = new YAHOO.widget.TreeView("treeDiv1");

      //turn dynamic loading on for entire tree:
      tree.setDynamicLoad(loadNodeData, 1);

      //get root node for tree:
      var root = tree.getRoot();
      add2Node(root, bookTopSections);

      // Trees with TextNodes will fire an event for when the label is clicked:
      tree.subscribe("labelClick", pageClick);

      //render tree with these toplevel nodes; all descendants of these nodes
      //will be generated as needed by the dynamic loader.
      tree.draw();

  } //End of buildTree()

  return { init: function() { buildTree(arguments[0]); } }

} (); //End of MyBook

//////////////////////////////////////
