﻿Type.registerNamespace("Microsoft.Com.BrowseUsers");

Microsoft.Com.BrowseUsers.Base = function() {
    Microsoft.Com.BrowseUsers.Page.initializeBase(this);
}

Microsoft.Com.BrowseUsers.Page = {

    //gets things started.
    initialize: function(path, user, locale, bookmarkId, searchId) {
        if (locale) {
            this._currentLanguage = locale;
        } else {
            this._currentLanguage = "en-us";
        }

        this._userName = user;

        this._numResults = 0;
        this._numPages = 0;
        this._pageSize = 25;
        this._currentPage = 1;
        this._sortDesc = false;
        this._resultsSortMethod = null;

        this._serverPath = path;
        this._usersXSL = this.loadXMLDoc(this._serverPath + "XML/Users.xsl");
        this._bmXSL = this.loadXMLDoc(this._serverPath + "XML/BookmarkMini.xsl");

        this._spanResultsCount = $get("resultsCount");
        this._searchBox = $get(searchId);
        this._divLoading = $get("loading");
        this._divPager = $get("pagerLinks");
        this._divPager_bottom = $get("pagerLinks_bottom");
        this._divPagerContainer = $get("pager");
        this._divPagerContainer_bottom = $get("pager_bottom");
        this._divBM = $get("BookmarkMini");

        this._divNoResults = $get("noResults");
        this._divUsers = $get("userResults");
        this._divstatusContainerBrowse = $get("statusContainerBrowse");
        this._divstatusContainerBrowse_bottom = $get("statusContainerBrowse_bottom");

        this._userQuery = this._searchBox.value;
        this._bookmarkId = bookmarkId;

        this.loadContentFromServer(true);
    },

    // runs page method for retrieving new xml data from server
    loadContentFromServer: function(hidePager) {
        this._divUsers.innerHTML = "";
        this.activateLoader();

        if (hidePager) {
            this.hide(this._divstatusContainerBrowse);
            this.hide(this._divstatusContainerBrowse_bottom);
        }

        PageMethods.set_path(this._serverPath + "BrowseUsers.aspx");
        PageMethods.GetBrowseUsersData(this._currentPage, this._pageSize, this._sortDesc, this._userQuery, this._bookmarkId, this._currentLanguage, this.OnSucceeded, this.OnFailed);
    },

    // This is the callback function that
    // processes the Web Service return value.
    OnSucceeded: function(result) {
        Microsoft.Com.BrowseUsers.Page.updatePage(result);

        Microsoft.Com.BrowseUsers.Page.show(Microsoft.Com.BrowseUsers.Page._divstatusContainerBrowse)
        Microsoft.Com.BrowseUsers.Page.show(Microsoft.Com.BrowseUsers.Page._divstatusContainerBrowse_bottom)
        Microsoft.Com.BrowseUsers.Page.hide(Microsoft.Com.BrowseUsers.Page._divLoading);
    },

    // action taken in instance of page method fail
    OnFailed: function(error) {
        var stackTrace = error.get_stackTrace();
        var message = error.get_message();
        var statusCode = error.get_statusCode();
        var exceptionType = error.get_exceptionType();
        var timedout = error.get_timedOut();

        // Display the error.    
        var RsltElem =
            document.getElementById("error");
        Microsoft.Com.BrowseUsers.Page.show(RsltElem);


        this.hide(this._divLoading);
        this.hide(this._divPagerContainer);
        this.hide(this._divPagerContainer_bottom);
    },

    // refreshes the content on the page using xml data
    updatePage: function(result) {
        // convert result string into xml object, if present
        if (result != null) {
            this._usersXML = this.loadXMLString(result);
            this.generatePager();
        }

        if (this._numResults == 0) {
            this.hide(this._divstatusContainerBrowse);
            this.hide(this._divstatusContainerBrowse_bottom);
            this.show(this._divNoResults);
        }
        else {
            this.hide(this._divNoResults);
        }

        this.loadContent(null, this._usersXSL, "userResults");
        this.loadContent(null, this._bmXSL, "BookmarkMini");

        //todo: this.getCurrentView();
        //todo: this.createStateHash();
    },

    // converts an XML document from a file location to an XML object
    loadXMLDoc: function(fname) {
        var xmlDoc;

        // new object for IE
        if (window.ActiveXObject) {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        }

        // new object for Moz, Firefox
        if (document.implementation && document.implementation.createDocument) {
            xmlDoc = document.implementation.createDocument("", "", null);
        }

        xmlDoc.async = false;
        xmlDoc.load(fname);
        return (xmlDoc);
    },

    // converts a string of XML data into an XML document object
    loadXMLString: function(stringInput) {
        var xmlDoc;

        // new object for IE
        if (window.ActiveXObject) {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
            xmlDoc.loadXML(stringInput);
        }

        // new object for Moz, Firefox
        if (document.implementation && document.implementation.createDocument) {
            xmlDoc = document.implementation.createDocument("", "", null);
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(stringInput, "text/xml");
        }

        return (xmlDoc);
    },

    // takes data from xml source, xsl translates, and fills the destination page element
    loadContent: function(xmlInput, xslSource, destination, language) {
        // for loading an xml source other than the default
        if (xmlInput == null)
            xmlSource = this._usersXML;
        else
            xmlSource = this.loadXMLString(xmlInput);

        // new object for IE
        if (window.ActiveXObject) {
            ex = xmlSource.transformNode(xslSource);
            if (destination != null) {
                $get(destination).innerHTML = ex;
            } else {
                return ex;
            }
        }

        // new object for Moz, Firefox
        if (document.implementation && document.implementation.createDocument) {
            xsltProcessor = new XSLTProcessor();

            xsltProcessor.importStylesheet(xslSource);
            resultDocument = xsltProcessor.transformToFragment(xmlSource, document);

            // remove existing child nodes if they're present

            if (document.getElementById(destination).childNodes.length > 0) {
                while (document.getElementById(destination).childNodes.length >= 1) {
                    $get(destination).removeChild($get(destination).firstChild);
                }
            }

            $get(destination).appendChild(resultDocument);
        }

    },

    // turn on 'loading bookmarks...' status view
    activateLoader: function() {
        this.show(this._divLoading);
    },

    // sets an elements display properties to hide from view
    hide: function(object) {
        if (object != null) {
            if (object.style == null)
                object = $get(object);

            object.style.display = "none";
        }
    },

    // sets an elements display properties to visible
    show: function(object) {
        if (object.style == null)
            object = $get(object);

        object.style.display = "block";
    },

    // builds pager, fills pager div
    generatePager: function() {
        this._numResults = this._usersXML.getElementsByTagName("users")[0].getAttribute("ct");

        this._spanResultsCount.innerHTML = this._numResults;

        this._numPages = Math.ceil(this._numResults.replace(/[^0-9]+/g, '') / this._pageSize);

        this.renderPageButtons(this._divPager, false);
        this.renderPageButtons(this._divPager_bottom, true);

        if (this._numResults > this._pageSize) {
            this._divPagerContainer.style.display = "inline";
            this._divPagerContainer_bottom.style.display = "inline";
        }

        if (this._numResults > this._pageSize) {
            this._divPagerContainer.style.display = "inline";
            this._divPagerContainer_bottom.style.display = "inline";
        }

    },

    // generates the html for the pager buttons within a provided object
    renderPageButtons: function(target, shiftUp) {
        target.innerHTML = "";

        var shiftCode = "";

        if (shiftUp) {
            shiftCode = ";window.scrollTo(0,270);";
        }

        var windowSize = 6;
        var showNextPrev = true;
        var currentPageNavigable = false;

        var bookLeft = 3;
        //var bookRight = (this._numPages - bookLeft) + 1;
        var windowStart = this._currentPage - Math.round((windowSize / 2));
        if (windowStart < 1)
            windowStart = 1;

        var windowEnd = windowStart + windowSize - 1;
        if (windowEnd > this._numPages)
            windowEnd = this._numPages;

        if (this._currentPage > 1 && showNextPrev == true) {
            var pageItem = document.createElement("a");
            pageItem.appendChild(document.createTextNode('<<'));
            pageItem['onclick'] = new Function('Microsoft.Com.BrowseUsers.Page.changePage(' + (this._currentPage - 1) + ')' + shiftCode);
            target.appendChild(pageItem);
        }

        var collapseRendered = false;

        for (var i = 1; i <= windowEnd; i++) {
            if (i > bookLeft) {
                if (i < windowStart) {
                    if (collapseRendered == false) {
                        target.appendChild(document.createTextNode("..."));
                        collapseRendered = true;
                    }
                    continue;
                } else {
                    collapseRendered = false;
                }
            }

            var pageItem = document.createElement("a");
            pageItem.appendChild(document.createTextNode(i));
            if (i == this._currentPage && !currentPageNavigable) {
                pageItem.className = "currentPage";
            }
            else {
                pageItem['onclick'] = new Function('Microsoft.Com.BrowseUsers.Page.changePage(' + i + ')' + shiftCode);
            }

            target.appendChild(pageItem);
        }

        if (this._currentPage < this._numPages && showNextPrev == true) {
            var pageItem = document.createElement("a");
            pageItem.appendChild(document.createTextNode('>>'));
            pageItem['onclick'] = new Function('Microsoft.Com.BrowseUsers.Page.changePage(' + (this._currentPage + 1) + ')' + shiftCode);
            target.appendChild(pageItem);
        }

    },

    // changePage
    // action to change the page and get new content from the server
    changePage: function(pageNum) {
        this._currentPage = pageNum;
        this.loadContentFromServer(false);
    },

    // search
    search: function() {
        this._userQuery = this._searchBox.value;
        this._currentPage = 1;
        this.loadContentFromServer(false);
    },

    // searchEnter
    searchEnter: function(event) {
        var keyCode = null;

        if (event.which) {
            keyCode = event.which;
        }
        else if (event.keyCode) {
            keyCode = event.keyCode;
        }

        if (13 == keyCode) {
            Microsoft.Com.BrowseUsers.Page.search();
            return false;
        }

        return true;

    },

    // gets node value depending on browser
    getNodeValue: function(xmlNode) {
        if (window.ActiveXObject && xmlNode != null) {
            return xmlNode.text; // return text for IE
        } else if (xmlNode != null) {
            return xmlNode.textContent; //return textContent for Moz
        } else {
            return "";
        }
    }
};