////////////////////////////////////////////////
///  Declares
////////////////////////////////////////////////
var ajax = false;
var m_nSessionID = 0;

// Column Types
var CT_NAME = 1;
var CT_DESC = 2;
var CT_PROFILE1 = 3;
var CT_PROFILE2 = 4;
var CT_PROFILE3 = 5;
var CT_PROFILE4 = 6;
var CT_PROFILE5 = 7;
var CT_PROFILE6 = 8;
var CT_PROFILE7 = 9;
var CT_PROFILE8 = 10;
var CT_PROFILE9 = 11;
var CT_PROFILE10 = 12;
var CT_PROFILE11 = 13;
var CT_PROFILE12 = 14;
var CT_PROFILE13 = 15;
var CT_PROFILE14 = 16;
var CT_PROFILE15 = 17;
var CT_PROFILE16 = 18;
var CT_CREATED_BY = 19;
var CT_CREATED_DATE = 20;
var CT_MODIFIED_BY = 21;
var CT_MODIFIED_DATE = 22;

// Sort Directions
var SD_ASCENDING = 1;
var SD_DESCENDING = 2;

function loadTree(sessionID, cabID, displayName) {
    // Store Session ID
    m_nSessionID = sessionID;
    
    // Initialize Ajax                  
    initAjax(sessionID);

    // Load Root Cabinet
    var eCab = new DefaultCabinet(cabID, displayName);
    var tr = insertCabinet(eCab, true);
       
    // Auto-Expand
    toggleExpansion(tr);
}

function unloadTree(sessionID) {
    ajax.open("POST", getAjaxUrl(), true);    	
	ajax.send("SessionID=" + sessionID + "&Action=LogOut");
}

////////////////////////////////////////////////
///  initAjax()
////////////////////////////////////////////////
function initAjax() {    
    if(window.XMLHttpRequest) {
		// Create IE XMLHttpRequest		
		ajax = new XMLHttpRequest();			
	}	
	else if(window.ActiveXObject) {
		// Create Mozilla XMLHttpRequest			
		ajax = new ActiveXObject("Microsoft.XMLHTTP");
	}
}

////////////////////////////////////////////////
///  getAjaxUrl()
////////////////////////////////////////////////
function getAjaxUrl() {
    return "http://www.acics.org/publications/ACICS_ajax.aspx";    
}

////////////////////////////////////////////////
///  getStorageItem(PathExpression)
////////////////////////////////////////////////
function getStorageItem(PathExpression, insert) {    
    setWaitCursor();
    ajax.open("POST", getAjaxUrl(), true);
    
    // Remove brackets to get ID
    var sID = PathExpression.replace("[","");
    sID = sID.replace("]","");
        
    ajax.onreadystatechange = function() {						
		if(ajax.readyState == 4 && ajax.status == 200) {	
		    // Create the XML Document from response text 
		    var xDoc = new ActiveXObject("Microsoft.XMLDOM");
		    		    		    
		    xDoc.async = "false";		    		    
		    xDoc.loadXML(ajax.responseText);
		    
			getStorageItemCallback(sID, xDoc, insert);			
		}
	}
	
	ajax.send("SessionID=" + m_nSessionID + "&Action=GetStorageItem&PathExpression=" + PathExpression);
}

////////////////////////////////////////////////
///  getStorageItemCallback(ID, xDoc) 
////////////////////////////////////////////////
function getStorageItemCallback(ID, xDoc, insert) {
    try {
        if(checkError(xDoc)) { 
            clearWaitCursor();            
            return;
        }
    
        // Get Root Element 
        var e = xDoc.childNodes[0];
        if(!e) return;
    
        var trNew = null;
                 
        switch(e.nodeName) {
            case "cabinet":
                if(insert) {
                    // Perform Insert
                    trNew = insertCabinet(e, true);
                    
                    // Perform Post Insert Actions
                    doPostInsertAction(trNew, omsTree);
                }
                else {
                    var cab = new Cabinet(e);
                    //updateStorageRow(cab);
                }
                    
                break;
                
            case "drawer":         
                if(insert) {
                    // Get Parent Cabinet            
                    var parentID = "C" + getNodeValue(e, "@parentID", "0");
                    var trCab = document.getElementById(parentID);
                    
                    // If Not expanded, perform getChildItems and return
                    if(!trCab.getAttribute("isExpanded").toString() == "true") {
                        incrementChildCount(trCab);
                        var newID = "D" + getNodeValue(e, "@id", "0");
                        getChildItems("[" + parentID + "]", newID);
                        return;
                    }                    
                    
                    // Get Insert Location
                    var nInsertLoc = getChildInsertLoc(trCab);
                    
                    // Perform Insert                                         
                    trNew = insertDrawer(e, nInsertLoc, true);
                    
                    // Perform Post Insert Actions
                    doPostInsertAction(trNew, trCab);
                }
                else {
                    var drw = new Drawer(e);
                    //updateStorageRow(drw);
                }
                
                break;
                
            case "folder":               
                if(insert) {
                    // Get Parent Drawer
                    var parentID = "D" + getNodeValue(e, "@parentID", "0");
                    var trDrw = document.getElementById(parentID);
                                        
                    // If Not expanded, perform getChildItems and return
                    if(!trDrw.getAttribute("isExpanded").toString() == "true") {
                        incrementChildCount(trDrw);
                        var newID = "F" + getNodeValue(e, "@id", "0");
                        getChildItems("[" + parentID + "]", newID);
                        return;
                    }
                    
                    // Get Insert Location
                    var nInsertLoc = getChildInsertLoc(trDrw);
                    
                    // Perform Insert
                    trNew = insertFolder(e, nInsertLoc, true); 
                    
                    // Perform Post Insert Actions
                    doPostInsertAction(trNew, trDrw);
                }
                else {
                    var fld = new Folder(e);
                    //updateStorageRow(fld);
                }    
                    
                break;
                
            case "document":
                if(insert) {                    
                    // Get Parent Folder
                    var parentID = "F" + getNodeValue(e, "@parentID", "0");
                    var trFld = document.getElementById(parentID);
                    
                    // If Not expanded, perform getChildItems and return
                    if(!trFld.getAttribute("isExpanded").toString() == "true") {
                        incrementChildCount(trFld);
                        var newID = "O" + getNodeValue(e, "@id", "0");
                        getChildItems("[" + parentID + "]", newID);
                        return;
                    }
                    
                    // Get Insert Location
                    var nInsertLoc = getChildInsertLoc(trFld);
                    
                    // Perform Insert
                    trNew = insertDocument(e, nInsertLoc, true); 
                    
                    // Perform Post Insert Actions
                    doPostInsertAction(trNew, trFld);
                }
                else {
                    var doc = new Document(e);
                    //updateDocumentRow(doc);
                }
                    
                break;
        } 
        
        hideRetry(); 
   }
   catch(e) {
        alert(e.message);
   }    
    
    //repaint(trNew.rowIndex, null);
    clearWaitCursor();
}

////////////////////////////////////////////////
///  getChildItems(ParentPathExpression)
////////////////////////////////////////////////
function getChildItems(ParentPathExpression, autoSelectID) {
    setWaitCursor();
        
    ajax.open("POST", getAjaxUrl(), true);
            
    // Remove brackets to get ID
    var sParentID = ParentPathExpression.replace("[","");
    sParentID = sParentID.replace("]","");
        
    if(sParentID.length > 0) 
        params = getFetchParams(document.getElementById(sParentID));            
    else
        params = getFetchParams(null);
    
    ajax.onreadystatechange = function() {						
		if(ajax.readyState == 4 && ajax.status == 200) {
		    // Create the XML Document from response text 
		    var xDoc = new ActiveXObject("Microsoft.XMLDOM");
		    		    
		    xDoc.async = "false";		    		    
		    xDoc.loadXML(ajax.responseText);
            
		    getChildItemsCallback(sParentID, xDoc, autoSelectID);	    
		}			
	}
	
	ajax.send("SessionID=" + m_nSessionID + "&Action=GetChildItems&ParentPathExpression=" + ParentPathExpression);	
}

////////////////////////////////////////////////
///  getChildItemsCallback(ParentID, xDoc) 
////////////////////////////////////////////////
function getChildItemsCallback(parentID, xDoc, autoSelectID) {  
    try {                   
        if(checkError(xDoc)) { 
            clearWaitCursor();            
            return;
        }
                        
        var dStart = new Date();
            
        // Get Storage List Type    
        var sType = getNodeValue(xDoc, "//storageList/@type", "").toLowerCase();
        var lst = xDoc.getElementsByTagName(sType);  
        var trNew = null;
        var trFirst = null;
        var parentElement = null;
                
        // Reference Parent
        if(parentID) 
            parentElement = document.getElementById(parentID);  // Parent is Storage TR        
        else
            parentElement = document.getElementById("omsTree"); // Parent is Table                       

        // Load All Child Elements                    
        for(var i = 0; i < lst.length; i++) {
            window.status = "Loading item " + i.toString() + " of "  + lst.length.toString();
            
            var isLast = (i >= (lst.length -1));                        
            if(parentElement.rowIndex) nInsertAfter = parentElement.rowIndex + i + 1;
                        
            switch(sType) {
                case "cabinet":
                    trNew = insertCabinet(lst[i], isLast, trNew);                                        
                    if(i == 0) trFirst = trNew;
                    
                    break;
                    
                case "drawer":                             
                    trNew = insertDrawer(lst[i], nInsertAfter, isLast, trNew);                    
                    if(i == 0) trFirst = trNew;
                    
                    break;
                    
                case "folder":               
                    trNew = insertFolder(lst[i], nInsertAfter, isLast, trNew); 
                    if(i == 0) trFirst = trNew;
                    
                    break;
                    
                case "document":
                    trNew = insertDocument(lst[i], nInsertAfter, isLast, trNew); 
                    if(i == 0) trFirst = trNew;
                    
                    break;
            }          
        }
        
        // Update Parent Information
        parentElement.setAttribute("firstChildID", trFirst.id);
        parentElement.setAttribute("lastChildID", trNew.id);        
        parentElement.setAttribute("isExpanded", true);
        
        if(sType == "cabinet")  {
            // Need to set childCount on table parent
            parentElement.setAttribute("childCount", lst.length);                            
        }
        else {
            // Need to handle row expansion for storage tr parents
            setRowExpansion(parentElement, true);    
        }
        
        if(autoSelectID) {
            var trSelect = document.getElementById(autoSelectID);
            selectRow(trSelect, true);
            ensureVisible(trSelect);
        }
        
        hideRetry();
        
        var dEnd = new Date();
        window.status = "Load Time: " + ((dEnd.getTime() - dStart.getTime()) / 1000).toString() + " seconds.";
   }
   catch(e) {
        alert(e.message);
   }    
    
    //repaint();    
        
    clearWaitCursor();
    hideProgress();
}

////////////////////////////////////////////////
///  Cabinet Class
////////////////////////////////////////////////
function Cabinet(eCab) {
    this.ID = "C" + getNodeValue(eCab, "@id", "0");
    this.Rights = getNodeValue(eCab,"@rights","0");
    this.ChildCount = getNodeValue(eCab, "@childCount", "0");
    this.Name = getNodeValue(eCab, "name", "");
    this.Description = getNodeValue(eCab, "description", "");
    this.Profile = getNodeValue(eCab, "profile", "");
    this.ProfileField1 = getNodeValue(eCab, "profileField1", "");    
    this.ProfileField2 = getNodeValue(eCab, "profileField2", "");
    this.ProfileField3 = getNodeValue(eCab, "profileField3", "");
    this.ProfileField4 = getNodeValue(eCab, "profileField4", "");
    this.ProfileField5 = getNodeValue(eCab, "profileField5", "");
    this.ProfileField6 = getNodeValue(eCab, "profileField6", "");
    this.CreatedBy = getNodeValue(eCab, "createdBy", ""); 
    this.CreatedDate = getNodeValue(eCab, "createdDate", ""); 
    this.ModifiedBy = getNodeValue(eCab, "modifiedBy", "");
    this.ModifiedDate = getNodeValue(eCab, "modifiedDate", "");
}

////////////////////////////////////////////////
///  DefaultCabinet Class
////////////////////////////////////////////////
function DefaultCabinet(id, name) {
    this.ID = "C" + id;
    this.Rights = 2;
    this.ChildCount = 10;
    this.Name = name;
    this.Description = "";
    this.Profile = "";
    this.ProfileField1  = "";
    this.ProfileField2  = "";
    this.ProfileField3  = "";
    this.ProfileField4  = "";
    this.ProfileField5  = "";
    this.ProfileField6  = "";
    this.CreatedBy = "";
    this.CreatedDate = new Date();
    this.ModifiedBy = ""
    this.ModifiedDate = new Date();
}

////////////////////////////////////////////////
///  Drawer Class
////////////////////////////////////////////////
function Drawer(eDrw) {
    this.ID = "D" + getNodeValue(eDrw, "@id", "0");
    this.ParentID = getNodeValue(eDrw, "@parentID", "0");
    this.Rights = getNodeValue(eDrw,"@rights","0");
    this.ChildCount = getNodeValue(eDrw, "@childCount", "0")
    this.Name = getNodeValue(eDrw, "name", "");
    this.Description = getNodeValue(eDrw, "description", "");
    this.Profile = getNodeValue(eDrw, "profile", "");    
    this.ProfileField1 = getNodeValue(eDrw, "profileField1", "");    
    this.ProfileField2 = getNodeValue(eDrw, "profileField2", "");
    this.ProfileField3 = getNodeValue(eDrw, "profileField3", "");
    this.ProfileField4 = getNodeValue(eDrw, "profileField4", "");
    this.ProfileField5 = getNodeValue(eDrw, "profileField5", "");
    this.ProfileField6 = getNodeValue(eDrw, "profileField6", "");
    this.CreatedBy = getNodeValue(eDrw, "createdBy", ""); 
    this.CreatedDate = getNodeValue(eDrw, "createdDate", ""); 
    this.ModifiedBy = getNodeValue(eDrw, "modifiedBy", "");
    this.ModifiedDate = getNodeValue(eDrw, "modifiedDate", "");
}

////////////////////////////////////////////////
///  Folder Class
////////////////////////////////////////////////
function Folder(eFld) {
    this.ID = "F" + getNodeValue(eFld, "@id", "0");
    this.ParentID = getNodeValue(eFld, "@parentID", "0");
    this.Rights = getNodeValue(eFld,"@rights","0");
    this.ChildCount = getNodeValue(eFld, "@childCount", "0")
    this.Name = getNodeValue(eFld, "name", "");
    this.Description = getNodeValue(eFld, "description", "");
    this.Profile = getNodeValue(eFld, "profile", "");
    this.ProfileField1 = getNodeValue(eFld, "profileField1", "");    
    this.ProfileField2 = getNodeValue(eFld, "profileField2", "");
    this.ProfileField3 = getNodeValue(eFld, "profileField3", "");
    this.ProfileField4 = getNodeValue(eFld, "profileField4", "");
    this.ProfileField5 = getNodeValue(eFld, "profileField5", "");
    this.ProfileField6 = getNodeValue(eFld, "profileField6", "");
    this.CreatedBy = getNodeValue(eFld, "createdBy", ""); 
    this.CreatedDate = getNodeValue(eFld, "createdDate", ""); 
    this.ModifiedBy = getNodeValue(eFld, "modifiedBy", "");
    this.ModifiedDate = getNodeValue(eFld, "modifiedDate", "");
}

////////////////////////////////////////////////
///  Document Class
////////////////////////////////////////////////
function Document(eDoc) {    
    this.ID = "O" + getNodeValue(eDoc, "@id", "0");
    this.ParentID = getNodeValue(eDoc, "@parentID", "0");
    this.Rights = getNodeValue(eDoc,"@rights","0");   
    this.Status = getNodeValue(eDoc, "@status", "0");
    this.DocType = getNodeValue(eDoc, "@docType", "C"); 
    this.Name = getNodeValue(eDoc, "name", "");
    this.Description = getNodeValue(eDoc, "description", "");
    this.Template = getNodeValue(eDoc, "template/name", "");
    this.DocIcon = getNodeValue(eDoc, "docIcon", "")
    this.Profile = getNodeValue(eDoc, "profile/name", "");
    this.ProfileField1 = getNodeValue(eDoc, "profileField1", "");    
    this.ProfileField2 = getNodeValue(eDoc, "profileField2", "");
    this.ProfileField3 = getNodeValue(eDoc, "profileField3", "");
    this.ProfileField4 = getNodeValue(eDoc, "profileField4", "");
    this.ProfileField5 = getNodeValue(eDoc, "profileField5", "");
    this.ProfileField6 = getNodeValue(eDoc, "profileField6", "");
    this.ProfileField7 = getNodeValue(eDoc, "profileField7", "");    
    this.ProfileField8 = getNodeValue(eDoc, "profileField8", "");
    this.ProfileField9 = getNodeValue(eDoc, "profileField9", "");
    this.ProfileField10 = getNodeValue(eDoc, "profileField10", "");
    this.ProfileField11 = getNodeValue(eDoc, "profileField11", "");
    this.ProfileField12 = getNodeValue(eDoc, "profileField12", "");
    this.ProfileField13 = getNodeValue(eDoc, "profileField13", "");    
    this.ProfileField14 = getNodeValue(eDoc, "profileField14", "");
    this.ProfileField15 = getNodeValue(eDoc, "profileField15", "");
    this.ProfileField16 = getNodeValue(eDoc, "profileField16", "");    
    this.CreatedBy = getNodeValue(eDoc, "createdBy", ""); 
    this.CreatedDate = getNodeValue(eDoc, "createdDate", ""); 
    this.ModifiedBy = getNodeValue(eDoc, "modifiedBy", "");
    this.ModifiedDate = getNodeValue(eDoc, "modifiedDate", "");
}

////////////////////////////////////////////////
/////   showProgress()
////////////////////////////////////////////////
function showProgress() {
    /*try {
        var w = window.parent.Header;
        if(!w) return;
        
        w.ShowProgressBar();
    }
    catch(e) {
        // Ignore
    }*/
}
	
////////////////////////////////////////////////
/////   hideProgress()
////////////////////////////////////////////////
function hideProgress() {
    /*try {
        var w = window.parent.Header;
        if(!w) return;
        
        w.HideProgressBar();
    }
    catch(e) {
        // Ignore
    }*/
}

////////////////////////////////////////////////
///  doPostInsertAction(trNew, trParent)
////////////////////////////////////////////////
function doPostInsertAction(trNew, parentElement) {
    // if childCount was 0, need to set first child
    if(parentElement.getAttribute("childCount") == 0) 
        parentElement.setAttribute("firstChildID", trNew.id);
    
    // Increment Parent's Child Count
    incrementChildCount(parentElement);
    
    // Reference the Parent's Current Last Child
    var trLastChild = getLastChild(parentElement);
    
    // Update parent with this, the new "last child"
    parentElement.setAttribute("lastChildID", trNew.id);
    
    if(trLastChild) {
        // the last child is no longer "last"
        trLastChild.setAttribute("isLast", false);
        
        // set my previous sibling id to the last child
        trNew.setAttribute("prevSiblingID", trLastChild.id);
        
        // set last child's next sibling id to me
        trLastChild.setAttribute("nextSiblingID", trNew.id);
        
        // refresh the previous last Child's state
        refreshStateClass(trLastChild);
    }
    
    // refresh parent element's state (if tr)
    if(parentElement.nodeName == "TR") {
        parentElement.setAttribute("isExpanded", "true");
        refreshStateClass(parentElement);
    }
    
    // if not first child and prev sibling is expanded, paint sibling lines to previous sibling
    if(!isFirstChild(trNew)) {    
        var trPrevSib = getPrevSibling(trNew);
        if(trPrevSib) {
            if(trPrevSib.getAttribute("isExpanded").toString() == "true")
                paintSiblingLines(trPrevSib, trNew, true); 
        }
    }
    
    // Auto Select
    selectRow(trNew, true);
    ensureVisible(trNew);
}

////////////////////////////////////////////////
///  openDocument(docID)
////////////////////////////////////////////////
function openDocument(docID) {
    hideMenus();
    
    var id = 0;
    
    if(docID)
        id = docID;
    else {    
        // Get Mode
        var cmd = document.getElementById("btnView");
        var sMode = cmd.getAttribute("mode");
        
        if(sMode == "Table") 
            var tr = pubsSelectedRow;        
        else
            var tr = getSelectedItem();
        
        id = tr.id.replace("O","");  
    }
    
    extractDocument(id);
}

////////////////////////////////////////////////
///  hideMenus()
////////////////////////////////////////////////
function hideMenus() {
    var mnu = document.getElementById("mnuDocumentContext");
    if(mnu) mnu.style.display = "none";
}

////////////////////////////////////////////////
///  extractDocument(docID)
////////////////////////////////////////////////
function extractDocument(docID) {
    setWaitCursor();
    ajax.open("POST", getAjaxUrl(), true);
        
    ajax.onreadystatechange = function() {						
		if(ajax.readyState == 4 && ajax.status == 200) {	
		    // Create the XML Document from response text
		    var xDoc = new ActiveXObject("Microsoft.XMLDOM");
		    		    		    
		    xDoc.async = "false";		    		    
		    xDoc.loadXML(ajax.responseText);
		    
			extractDocumentCallback(xDoc);			
		}
	}

    ajax.send("SessionID=" + m_nSessionID + "&Action=GetDocument&DocumentID=" + docID);		
}

///////////////////////////////////////////////
///  extractDocumentCallback(xDoc)
////////////////////////////////////////////////
function extractDocumentCallback(xDoc) {
    if(checkError(xDoc)) { 
        clearWaitCursor();            
        return;
    }

    try {
        var url = xDoc.childNodes[0].text;
        window.open(url);
    }
    catch(e) {
        alert(e.message);
    }
    
    hideRetry();
    clearWaitCursor();   
}

///////////////////////////////////////////////
///  gotoCEDM()
////////////////////////////////////////////////
function gotoCEDM() {
    window.open("http://convergentedm.com");
}
