You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@rave.apache.org by er...@apache.org on 2013/03/25 18:00:19 UTC

svn commit: r1460762 [2/4] - in /rave/trunk/rave-portal-resources/src: main/webapp/static/script/ main/webapp/static/script/core/ main/webapp/static/script/portal/ test/dependencies/ test/javascript/

Added: rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_layout.js
URL: http://svn.apache.org/viewvc/rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_layout.js?rev=1460762&view=auto
==============================================================================
--- rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_layout.js (added)
+++ rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_layout.js Mon Mar 25 17:00:18 2013
@@ -0,0 +1,613 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+var rave = rave || {};
+rave.layout = rave.layout || (function () {
+    var MOVE_PAGE_DEFAULT_POSITION_IDX = -1;
+    var $moveWidgetDialog;
+    var showImportExportUI = false;
+    var $movePageDialog = $("#movePageDialog");
+    var $pageFormTabbed = $("#pageFormTabbed");
+    var $pageFormImport = $("#pageFormImport");
+    var $omdlFile = $("#omdlFile");
+    var $pageForm = $("#pageForm");
+    var $tab_title_input = $("#tab_title"),
+        $tab_id = $("#tab_id"),
+        $page_layout_input = $("#pageLayout");
+
+    // page menu related functions
+    var pageMenu = (function () {
+        var $addPageButton = $("#addPageButton");
+        var $menuItemEdit = $("#pageMenuEdit");
+        var $menuItemDelete = $("#pageMenuDelete");
+        var $menuItemMove = $("#pageMenuMove");
+        var $menuItemShare = $("#pageMenuShare");
+        var $menuItemRevokeShare = $("#pageMenuRevokeShare");
+        var $MenuItemExport = $("#pageMenuExport");
+
+        /**
+         * Initializes the private pageMenu closure
+         * - binds click event handler to menu button
+         * - binds menu item click event handlers
+         * - binds body click event handler to close the menu
+         */
+        function init(showImportExport) {
+            showImportExportUI = showImportExport;
+            // initialize the page form validator overriding the
+            // styles to wire in bootstrap styles
+            $pageForm.validate({
+                errorElement: 'span',
+                errorClass: 'help-inline',
+                highlight: function (element, errorClass) {
+                    $(element).parent().parent().addClass('error');
+                },
+                unhighlight: function (element, errorClass) {
+                    $(element).parent().parent().removeClass('error');
+                }
+            });
+            $pageFormTabbed.validate({
+                errorElement: 'span',
+                errorClass: 'help-inline',
+                highlight: function (element, errorClass) {
+                    $(element).parent().parent().addClass('error');
+                },
+                unhighlight: function (element, errorClass) {
+                    $(element).parent().parent().removeClass('error');
+                }
+            });
+            $pageFormImport.validate({
+                errorElement: 'span',
+                errorClass: 'help-inline',
+                highlight: function (element, errorClass) {
+                    $(element).parent().parent().addClass('error');
+                },
+                unhighlight: function (element, errorClass) {
+                    $(element).parent().parent().removeClass('error');
+                }
+            });
+
+
+            // initialize the close button in the page menu dialog
+            $("#pageMenuCloseButton").click(rave.layout.closePageDialog);
+            $("#pageMenuCloseButtonTab").click(rave.layout.closePageDialogTabbed);
+            if (showImportExport) {
+                $("#pageMenuExport").removeClass('hidden');
+            }
+
+            // setup the edit page menu item
+            $addPageButton.bind('click', function (event) {
+                if (showImportExport) {
+                    var $pageMenuUpdateButtonTabbed = $("#pageMenuUpdateButtonTab");
+                    $pageMenuUpdateButtonTabbed.html(rave.getClientMessage("common.add"));
+                    $("#page-tabs").tabs();
+                    $pageMenuUpdateButtonTabbed.click(rave.layout.addOrImportPage);
+                    $('#pageMenuDialogTabbed').on('shown', function () {
+                        $("#tab_title").first().focus();
+                    });
+                    $("#pageMenuDialogTabbed").modal('show');
+                } else {
+                    $("#pageMenuDialogHeader").html(rave.getClientMessage("page.add"));
+                    var $pageMenuUpdateButton = $("#pageMenuUpdateButton");
+                    $("#pageLayoutGroup").show();
+                    $pageMenuUpdateButton.html(rave.getClientMessage("common.add"));
+                    // unbind the previous click event since we are sharing the
+                    // dialog between separate add/edit page actions
+                    $pageMenuUpdateButton.unbind('click');
+                    $pageMenuUpdateButton.click(rave.layout.addPage);
+                    $('#pageMenuDialog').on('shown', function () {
+                        $("#tab_title").first().focus();
+                    });
+                    $("#pageMenuDialog").modal('show');
+                }
+            });
+
+            // setup the edit page menu item
+            $menuItemEdit.bind('click', function (event) {
+                rave.api.rpc.getPagePrefs({pageId: getCurrentPageId(),
+                    successCallback: function (result) {
+                        $tab_title_input.val(result.result.name);
+                        $tab_id.val(result.result.id);
+                        $page_layout_input.val(result.result.pageLayout.code);
+                        $("#pageMenuDialogHeader").html(rave.getClientMessage("page.update"));
+                        var $pageMenuUpdateButton = $("#pageMenuUpdateButton");
+                        $("#pageLayoutGroup").show();
+                        $pageMenuUpdateButton.html(rave.getClientMessage("common.save"));
+                        // unbind the previous click event since we are sharing the
+                        // dialog between separate add/edit page actions
+                        $pageMenuUpdateButton.unbind('click');
+                        $pageMenuUpdateButton.click(rave.layout.updatePage);
+                        $('#pageMenuDialog').on('shown', function () {
+                            $("#tab_title").first().focus();
+                        });
+                        $("#pageMenuDialog").modal('show');
+                    }
+                });
+            });
+
+            // setup the delete page menu item if it is not disabled
+            if (!$menuItemDelete.hasClass("menu-item-disabled")) {
+                $menuItemDelete.bind('click', function (event) {
+                    // send the rpc request to delete the page
+                    rave.api.rest.deletePage({pageId: getCurrentPageId(), successCallback: rave.viewPage});
+                });
+            }
+
+            // setup the move page menu item if it is not disabled
+            if (!$menuItemMove.hasClass("menu-item-disabled")) {
+                $menuItemMove.bind('click', function (event) {
+                    $movePageDialog.modal('show');
+                });
+            }
+
+            // setup the export page menu item if it is not disabled
+            if (!$MenuItemExport.hasClass("hidden")) {
+                $MenuItemExport.bind('click', function (event) {
+                    window.open(rave.getContext() + "api/rest/" + "page/" + getCurrentPageId() + "/omdl");
+                });
+            }
+
+            // setup the revoke share page menu item
+            if (!$menuItemRevokeShare.hasClass("menu-item-disabled")) {
+                $menuItemRevokeShare.bind('click', function (event) {
+                    rave.models.currentPage.removeForSelf();
+                });
+            }
+        }
+
+        return {
+            init: init
+        }
+    })();
+
+    // functions associated with the user search for sharing pages
+
+    // widget menu related functions
+    var widgetMenu = (function () {
+        var $menu;
+        var $menuItemMove;
+        var $menuItemDelete;
+        var $menuItemMaximize;
+        var $menuItemAbout;
+        var $menuItemComment;
+        var $menuItemRate;
+
+        /**
+         * Hides the widget menu for a specific widget
+         * @param widgetId the id of the widget to hide the menu for
+         */
+        function hideMenu(widgetId) {
+            $("#widget-" + widgetId + "-menu").hide();
+            $(".iframe-overlay").remove();
+        }
+
+        /**
+         * Hides all widget menus
+         */
+        function hideAllMenus() {
+            $(".widget-menu").hide();
+            $(".iframe-overlay").remove();
+        }
+
+        /**
+         * Shows the widget menu for a specific widget
+         * @param widgetId the id of the widget to show the menu for
+         */
+        function showMenu(widgetId) {
+            $("#widget-" + widgetId + "-menu").show();
+        }
+
+        /**
+         * Initializes a single widgets private widgetMenu closure
+         * - binds click event handler to menu button
+         * - binds menu item click event handlers
+         * - binds body click event handler to close the menu
+         */
+        function bindWidgetMenu(widgetId) {
+            // setup the move to page menu item
+            $menuItemMove = $("#widget-" + widgetId + "-menu-move-item");
+            if (!$menuItemMove.hasClass("menu-item-disabled")) {
+                $menuItemMove.bind('click', function (event) {
+                    var regionWidgetId = rave.getObjectIdFromDomId(this.id);
+                    // Clear the dropdown box; needing to do this may be a bug?
+                    $('.dropdown').removeClass('open');
+                    // Open the modal
+                    $("#moveWidgetModal").data('regionWidgetId', regionWidgetId);
+                    $("#moveWidgetModal").modal('show');
+
+                    // prevent the menu button click event from bubbling up to parent
+                    // DOM object event handlers such as the page tab click event
+                    event.stopPropagation();
+                });
+            }
+
+            // setup the delete widget menu item
+            $menuItemDelete = $("#widget-" + widgetId + "-menu-delete-item");
+            if (!$menuItemDelete.hasClass("menu-item-disabled")) {
+                $menuItemDelete.bind('click', function (event) {
+                    var regionWidgetId = rave.getObjectIdFromDomId(this.id);
+
+                    // invoke the rpc call to remove the widget from the page
+                    rave.layout.deleteRegionWidget(regionWidgetId);
+
+                    // prevent the menu button click event from bubbling up to parent
+                    // DOM object event handlers such as the page tab click event
+                    event.stopPropagation();
+                });
+            }
+
+            // setup the maximize widget menu item
+            $menuItemMaximize = $("#widget-" + widgetId + "-menu-maximize-item");
+            if (!$menuItemMaximize.hasClass("menu-item-disabled")) {
+                $menuItemMaximize.bind('click', function (event) {
+                    var regionWidgetId = rave.getObjectIdFromDomId(this.id);
+
+                    // maximize the widget
+                    rave.maximizeWidget({data: {id: regionWidgetId}});
+                    // prevent the menu button click event from bubbling up to parent
+                    // DOM object event handlers such as the page tab click event
+                    event.stopPropagation();
+                });
+            }
+
+            // setup the about this widget menu item
+            $menuItemAbout = $("#widget-" + widgetId + "-menu-about-item");
+            if (!$menuItemAbout.hasClass("menu-item-disabled")) {
+                $menuItemAbout.bind('click', function (event) {
+                    var regionWidget = rave.getRegionWidgetById(rave.getObjectIdFromDomId(this.id));
+
+                    // go to the widget detail page
+                    rave.viewWidgetDetail(regionWidget.widgetId, getCurrentPageId());
+                    // prevent the menu button click event from bubbling up to parent
+                    // DOM object event handlers such as the page tab click event
+                    event.stopPropagation();
+                });
+            }
+
+            // setup the comment on this widget menu item
+            $menuItemComment = $("#widget-" + widgetId + "-menu-comment-item");
+            if (!$menuItemComment.hasClass("menu-item-disabled")) {
+                $menuItemComment.bind('click', function (event) {
+                    var regionWidget = rave.getRegionWidgetById(rave.getObjectIdFromDomId(this.id));
+
+                    // go to the widget detail page
+                    rave.viewWidgetDetail(regionWidget.widgetId, getCurrentPageId(), 'widgetComments');
+                    // prevent the menu button click event from bubbling up to parent
+                    // DOM object event handlers such as the page tab click event
+                    event.stopPropagation();
+                });
+            }
+
+            // setup the Rate this widget menu item
+            $menuItemRate = $("#widget-" + widgetId + "-menu-rate-item");
+            if (!$menuItemRate.hasClass("menu-item-disabled")) {
+                $menuItemRate.bind('click', function (event) {
+                    var regionWidget = rave.getRegionWidgetById(rave.getObjectIdFromDomId(this.id));
+
+                    // go to the widget detail page
+                    rave.viewWidgetDetail(regionWidget.widgetId, getCurrentPageId(), 'widgetRatings');
+                    // prevent the menu button click event from bubbling up to parent
+                    // DOM object event handlers such as the page tab click event
+                    event.stopPropagation();
+                });
+            }
+        }
+
+        /**
+         * Initializes ALL widgets private widgetMenu closure
+         */
+        function init() {
+            // loop over each widget-menu and initialize the menu items
+            // note: the edit prefs menu item is by default rendered disabled
+            //       and it is up to the provider code for that widget to
+            //       determine if the widget has preferences, and to enable
+            //       the menu item
+            $(".widget-menu").each(function (index, element) {
+                var widgetId = rave.getObjectIdFromDomId(element.id);
+                bindWidgetMenu(widgetId);
+            });
+        }
+
+        /**
+         * Enables the Edit Prefs including the Preferences view (Custom Edit Prefs)
+         * menu item in the widget menu to be clicked.
+         * Widget providers should use this function when initializing their
+         * widgets after determining if the widget has preferences to modify.
+         *
+         * @param regionWidgetId the regionWidgetId of the regionWidget menu to enable
+         * @param isPreferencesView boolean to indicate whether "preferences" view or the default prefs view
+         */
+        function enableEditPrefsMenuItem(regionWidgetId, isPreferencesView) {
+            // setup the edit prefs widget menu item
+            var $menuItemEditPrefs = $("#widget-" + regionWidgetId + "-menu-editprefs-item");
+            $menuItemEditPrefs.removeClass("menu-item-disabled");
+            $menuItemEditPrefs.on('click', function (event) {
+                var regionWidgetId = rave.getObjectIdFromDomId(this.id);
+
+                // show the regular edit prefs or the Custom Edit Prefs(preferences) region
+                if (isPreferencesView) {
+                    rave.editCustomPrefs({data: {id: regionWidgetId}});
+                }
+                else {
+                    rave.editPrefs(regionWidgetId);
+                }
+                // prevent the menu button click event from bubbling up to parent
+                // DOM object event handlers such as the page tab click event
+                return false;
+            });
+        }
+
+        return {
+            init: init,
+            bindWidgetMenu: bindWidgetMenu,
+            hideAll: hideAllMenus,
+            hide: hideMenu,
+            show: showMenu,
+            enableEditPrefsMenuItem: enableEditPrefsMenuItem
+        }
+    })();
+
+    function addIframeOverlays(event) {
+        //e.preventDefault();
+
+        var i = 0;
+        $(".widget").each(function () {
+            var W = $(this).outerWidth(),
+                H = $(this).outerHeight(),
+                X = $(this).position().left,
+                Y = $(this).position().top;
+
+            $(this).after('<div class="iframe-overlay" onclick="rave.layout.hideWidgetMenu()" />');
+            $(this).next('.iframe-overlay').css({
+                width: W,
+                height: H,
+                position: "absolute",
+                top: Y,
+                left: X
+            });
+
+        });
+
+        // Remove any overlays onclick of all the things!!!
+        $("*:not(.dropdown-toggle)").on("click", function () {
+            $(".iframe-overlay").remove();
+        });
+    }
+
+    /**
+     * Submits the RPC call to move the widget to a new page
+     */
+    function moveWidgetToPage(regionWidgetId) {
+        var toPageId = $("#moveToPageId").val();
+        var args = { toPageId: toPageId,
+            regionWidgetId: regionWidgetId,
+            successCallback: function () {
+                rave.viewPage(toPageId);
+            }
+        };
+        // send the rpc request to move the widget to new page
+        rave.api.rpc.moveWidgetToPage(args);
+    }
+
+    /**
+     * Submits the RPC call to add a new page if form validation passes
+     */
+    function addPage() {
+        if (showImportExportUI) {
+            if ($pageFormTabbed.valid()) {
+                var newPageTitle = $("#tab_titleTabbed1").val();
+                var newPageLayoutCode = $("#pageLayoutTabbed").val();
+                // send the rpc request to create the new page
+                rave.api.rpc.addPage({pageName: newPageTitle,
+                    pageLayoutCode: newPageLayoutCode,
+                    errorLabel: 'pageFormErrorsTabbed1',
+                    successCallback: function (result) {
+                        rave.viewPage(result.result.id);
+                    }
+                });
+            }
+        } else {
+            if ($pageForm.valid()) {
+                var newPageTitle = $tab_title_input.val();
+                var newPageLayoutCode = $page_layout_input.val();
+                // send the rpc request to create the new page
+                rave.api.rpc.addPage({pageName: newPageTitle,
+                    pageLayoutCode: newPageLayoutCode,
+                    errorLabel: 'pageFormErrors',
+                    successCallback: function (result) {
+                        rave.viewPage(result.result.id);
+                    }
+                });
+            }
+        }
+    }
+
+    function importPage() {
+        if ($.browser.msie == true) {
+            alert(rave.getClientMessage("import.page.not.supported"));
+        }
+        else {
+            if ($pageFormImport.valid()) {
+                $pageFormImport.get(0).setAttribute('action', rave.getContext() + "api/rpc/page/import/omdl");
+                document.getElementById('pageFormImport').onsubmit = function () {
+                    document.getElementById('pageFormImport').target = 'file_upload_frame';
+                    document.getElementById("file_upload_frame").onload = processFileUploadResult;
+                }
+                $pageFormImport.submit();
+            }
+        }
+    }
+
+    function processFileUploadResult() {
+        // chrome & firefox a <pre> has been added to the begining of the json
+        var ret = frames['file_upload_frame'].document.getElementsByTagName("body")[0].firstChild.innerHTML;
+        var data = eval("(" + ret + ")");
+        if (data.error) {
+            if (data.errorCode == 'DUPLICATE_ITEM') {
+                $("#pageFormErrorsTabbed2").html(rave.getClientMessage("page.duplicate_name"));
+            }
+            else if (data.errorCode == 'INTERNAL_ERROR' && data.errorMessage.indexOf("BadOmdlXmlFormatException") != -1) {
+                var msg = data.errorMessage.substr(data.errorMessage.indexOf("BadOmdlXmlFormatException"), data.errorMessage.length)
+                $("#pageFormErrorsTabbed2").html(msg);
+            }
+            else {
+                alert(rave.getClientMessage("api.rpc.error.internal"));
+            }
+        }
+        else {
+            rave.viewPage(data.result.id);
+        }
+    }
+
+    function addOrImportPage() {
+        var selectedTab = $("#page-tabs").tabs('option', 'selected');
+        if (selectedTab == 0) {
+            addPage();
+        } else {
+            importPage();
+        }
+    }
+
+    /**
+     * Submits the RPC call to move the page to a new render sequence
+     */
+    function movePage() {
+        var moveAfterPageId = $("#moveAfterPageId").val();
+        var args = { pageId: $("#currentPageId").val(),
+            successCallback: function (result) {
+                rave.viewPage(result.result.id);
+            }
+        };
+
+        if (moveAfterPageId != MOVE_PAGE_DEFAULT_POSITION_IDX) {
+            args["moveAfterPageId"] = moveAfterPageId;
+        }
+
+        // send the rpc request to move the new page
+        rave.api.rpc.movePage(args);
+    }
+
+    function updatePage() {
+        if ($pageForm.valid()) {
+            // send the rpc request to update the page
+            rave.api.rpc.updatePagePrefs({pageId: $tab_id.val(),
+                title: $tab_title_input.val(),
+                layout: $page_layout_input.val(),
+                errorLabel: 'pageFormErrors',
+                successCallback: function (result) {
+                    rave.viewPage(result.result.id);
+                }});
+        }
+    }
+
+    function closePageDialog() {
+        $pageForm[0].reset();
+        $tab_id.val('');
+        $("#pageFormErrors").text('');
+        $("#pageMenuDialog").modal("hide");
+    }
+
+    function closePageDialogTabbed() {
+        $pageForm[0].reset();
+        $("#pageFormErrors").text('');
+        $("#pageFormErrorsTabbed1").text('');
+        $("#pageFormErrorsTabbed2").text('');
+        $pageFormTabbed[0].reset();
+        $pageFormImport[0].reset();
+        $("#pageMenuDialogTabbed").modal("hide");
+    }
+
+    /**
+     * Invokes the RPC call to delete a regionWidget from a page
+     *
+     * @param regionWidgetId the regionWidgetId to delete
+     */
+    function deleteRegionWidget(regionWidgetId) {
+        if (confirm(rave.getClientMessage("widget.remove_confirm"))) {
+            rave.api.rpc.removeWidget({
+                regionWidgetId: regionWidgetId,
+                successCallback: function () {
+                    // remove the widget from the dom and the internal memory map
+                    $("#widget-" + this.regionWidgetId + "-wrapper").remove();
+                    rave.removeWidgetFromMap(this.regionWidgetId);
+                    if (rave.isPageEmpty()) {
+                        rave.displayEmptyPageMessage();
+                    }
+                }
+            });
+        }
+    }
+
+    /**
+     * Returns the pageId of the currently viewed page
+     */
+    function getCurrentPageId() {
+        return $("#currentPageId").val();
+    }
+
+    /**
+     * Determines if the widget should be rendered as part of the initial page view.  This can be used to help optimize
+     * page loads as widgets located on non-active sub pages will not be rendered initially.  The function will return
+     * false if one of the following criteria is met, and true otherwise:
+     *
+     * 1) the widget is on a top level page (not a sub page)
+     * 2) the widget is on a sub page that is currently requested in the URL via the hash tag
+     *    ie /app//person/canoniocal#My%20Activity
+     * 3) the widget is on the default sub page and the page request URL doesn't contain a sub-page hash tag
+     *    ie /app/person/canonical
+     *
+     * @return boolean
+     */
+    function isWidgetOnHiddenTab(widget) {
+        var hash = decodeURIComponent(location.hash);
+        var subPage = widget.subPage;
+        return !(subPage.id === null ||
+            ("#" + subPage.name) === hash ||
+            (hash === "" && subPage.isDefault));
+    }
+
+    /***
+     * initializes the rave.layout namespace code
+     */
+    function init(showImportExport) {
+        pageMenu.init(showImportExport);
+        //widgetMenu.init();
+        // initialize the bootstrap dropdowns
+        $(".dropdown-toggle").dropdown();
+    }
+
+    // public rave.layout API
+    return {
+        init: init,
+        getCurrentPageId: getCurrentPageId,
+        hideWidgetMenu: widgetMenu.hide,
+        deleteRegionWidget: deleteRegionWidget,
+        enableEditPrefsMenuItem: widgetMenu.enableEditPrefsMenuItem,
+        bindWidgetMenu: widgetMenu.bindWidgetMenu,
+        addPage: addPage,
+        addOrImportPage: addOrImportPage,
+        updatePage: updatePage,
+        movePage: movePage,
+        importPage: importPage,
+        closePageDialog: closePageDialog,
+        closePageDialogTabbed: closePageDialogTabbed,
+        moveWidgetToPage: moveWidgetToPage,
+        isWidgetOnHiddenTab: isWidgetOnHiddenTab,
+        addIframeOverlays: addIframeOverlays
+    };
+})();

Added: rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_models.js
URL: http://svn.apache.org/viewvc/rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_models.js?rev=1460762&view=auto
==============================================================================
--- rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_models.js (added)
+++ rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_models.js Mon Mar 25 17:00:18 2013
@@ -0,0 +1,277 @@
+var rave = rave || {};
+
+rave.models = (function () {
+
+    /*
+     User model. Further implementation pending.
+     */
+    var User = rave.Model.extend({
+
+    });
+
+    /*
+     Collection of users. Currently used for the share page users search.
+     */
+    var Users = rave.Collection.extend({
+        model: User,
+        pageSize: 10,
+
+        //empty pagination data, is filled in on requests
+        paginationData: {
+            start:0,
+            finish: 0,
+            total: 0,
+            prevLink: {},
+            nextLink: {},
+            pages: []
+        },
+
+        initialize: function(){
+            //ensure that parse is always invoked in the context of this object
+            _.bindAll(this, 'parse');
+        },
+
+        //filter collection with a search term
+        filter: function (term) {
+            this.searchTerm = term;
+
+            if (this.searchTerm) {
+                rave.api.rpc.searchUsers({searchTerm: this.searchTerm, offset: 0, successCallback: this.parse });
+            }
+            else {
+                rave.api.rpc.getUsers({offset: 0, successCallback: this.parse });
+            }
+        },
+
+        //used for pagination
+        fetchPage: function (page) {
+            var self = this;
+
+            var offset = page?(page-1):0;
+            offset *= this.pageSize;
+
+            if (this.searchTerm) {
+                rave.api.rpc.searchUsers({searchTerm: this.searchTerm, offset: offset, successCallback: this.parse });
+            }
+            else {
+                rave.api.rpc.getUsers({offset: offset, successCallback: this.parse });
+            }
+        },
+
+        //parse return data from the rpc call into a usable data model
+        parse: function (data) {
+            var result = data.result;
+            this.pageSize = result.pageSize || 10;
+
+            this.paginationData = {
+                start: result.offset + 1,
+                finish: result.resultSet.length + result.offset,
+                total: result.totalResults,
+                pageSize: result.pageSize,
+                prevLink: {
+                    show: result.currentPage > 1 ? true : false,
+                    pageNumber: result.currentPage - 1
+                },
+                nextLink: {
+                    show: result.currentPage < result.numberOfPages ? true : false,
+                    pageNumber: result.currentPage + 1
+                },
+                //pages will be an array of objects from 1 to number of pages
+                pages: _.map(_.range(1, result.numberOfPages + 1), function (pageNumber) {
+                    return {
+                        pageNumber: pageNumber,
+                        current: pageNumber == result.currentPage
+                    }
+                })
+            }
+
+            this.reset(result.resultSet);
+        },
+
+        //When toViewModel is invoked, also provide pagination and filter data
+        toViewModel: function () {
+            return {
+                searchTerm: this.searchTerm,
+                pagination: this.paginationData,
+                users: this.constructor.__super__.toViewModel.apply(this)
+            }
+        }
+    });
+
+    /*
+     Page model. Used for managing most of the sharing functionality.
+     */
+    var Page = rave.Model.extend({
+
+        defaults: {
+            members: {}
+        },
+
+        /*
+         TODO: currently this is used to silently bootstrap the page model from the page view. Once
+         the jsp views are lightened up we should be able to provide a full representation of the page
+         model to pass to .set() and this should not be needed.
+         */
+        addInitData: function (userId, isEditor) {
+            var members = this.get('members');
+
+            members[userId] = {
+                userId: userId,
+                editor: isEditor
+            }
+
+            this.set('members', members, {silent:true});
+        },
+
+        isUserOwner: function (userId) {
+            return userId == this.get('ownerId');
+        },
+
+        isUserView: function(userId) {
+            return userId == this.get('viewerId');
+        },
+
+        isUserMember: function (userId) {
+            return this.get('members')[userId] ? true : false;
+        },
+
+        isUserEditor: function (userId) {
+            var member = this.get('members')[userId];
+            return member && member.editor;
+        },
+
+        addMember: function (userId) {
+            var self = this;
+
+            rave.api.rpc.addMemberToPage({pageId: self.get('id'), userId: userId,
+                successCallback: function (result) {
+                    var members = self.get('members');
+
+                    members[userId] = {
+                        userId: userId,
+                        editor: false
+                    }
+
+                    self.set('members', members);
+                    /*
+                     The model does not manage or care about views. Instead it fires events
+                     that views can subscribe to for ui representation.
+                     TODO: solidify and document eventing model
+                     */
+                    self.trigger('share', 'member:add', userId);
+                }
+            });
+
+        },
+
+        removeMember: function (userId) {
+            var self = this;
+
+            rave.api.rpc.removeMemberFromPage({pageId: self.get('id'), userId: userId,
+                successCallback: function (result) {
+                    var members = self.get('members');
+
+                    delete members[userId];
+
+                    self.set('members', members);
+                    self.trigger('share', 'member:remove', userId);
+                }
+            });
+        },
+
+        removeForSelf: function(){
+            var self = this;
+
+            rave.api.rpc.removeMemberFromPage({pageId: self.get('id'), userId: self.get('viewerId'),
+                successCallback: function () {
+                    self.trigger('declineShare', self.get('id'));
+                }
+            });
+        },
+
+        addEditor: function (userId) {
+            var self = this;
+            //updatePageEditingStatus
+            rave.api.rpc.updatePageEditingStatus({pageId: self.get('id'), userId: userId, isEditor: true,
+                successCallback: function () {
+                    var members = self.get('members');
+
+                    members[userId] = {
+                        userId: userId,
+                        editor: true
+                    }
+
+                    self.set('members', members);
+                    self.trigger('share', 'editor:add', userId);
+                }
+            });
+        },
+
+        removeEditor: function (userId) {
+            var self = this;
+            rave.api.rpc.updatePageEditingStatus({pageId: self.get('id'), userId: userId, isEditor: false,
+                successCallback: function () {
+
+                    var members = self.get('members');
+
+                    members[userId] = {
+                        userId: userId,
+                        editor: false
+                    }
+
+                    self.set('members', members);
+                    self.trigger('share', 'editor:remove', userId);
+                }
+            });
+        },
+
+        cloneForUser: function (userId, pageName) {
+            pageName = pageName || null;
+            var self =this;
+            rave.api.rpc.clonePageForUser({pageId: this.get('id'), userId: userId, pageName: pageName,
+                successCallback: function(result){
+                    if(result.error) {
+                        /*
+                         TODO: this is a weird error handling condition used by clone to catch duplicate
+                         named pages. Firing an event and letting the view handle for now, but the api
+                         should be managing errors better.
+                         */
+                        return self.trigger('error', result.errorCode, userId);
+                    }
+                    self.trigger('share', 'clone', userId);
+                }
+            });
+        },
+
+        acceptShare: function(){
+            var self = this;
+            rave.api.rpc.updateSharedPageStatus({pageId: this.get('id'), shareStatus: 'accepted',
+                successCallback: function (result) {
+                    self.trigger('acceptShare', self.get('id'));
+                }
+            });
+        },
+
+        declineShare: function(){
+            var self = this;
+
+            rave.api.rpc.updateSharedPageStatus({pageId: this.get('id'), shareStatus: 'refused',
+                successCallback: function (result) {
+                    rave.api.rpc.removeMemberFromPage({pageId: self.get('id'), userId: self.get('viewerId'),
+                        successCallback: function (result) {
+                            self.trigger('declineShare', self.get('id'));
+                        }
+                    });
+                }
+            })
+        }
+    });
+
+    return {
+        currentPage: new Page(),
+        users: new Users()
+    }
+
+})();
+
+

Added: rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_person_profile.js
URL: http://svn.apache.org/viewvc/rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_person_profile.js?rev=1460762&view=auto
==============================================================================
--- rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_person_profile.js (added)
+++ rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_person_profile.js Mon Mar 25 17:00:18 2013
@@ -0,0 +1,536 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+var rave = rave || {};
+rave.personprofile = rave.personprofile || (function() {
+    // map of {subpage name, boolean} tracking whether or not a sub page has been viewed at least once
+    var subPagesViewedStatus = {};
+    function initSubPages() {
+        var $tabs = $('#personProfileSubPages a[data-toggle="tab"]');
+        //If the implementation does not use bootstrap tabs / subpages, skip this method
+        if($tabs.length == 0){
+            return;
+        }
+
+        //Make the tab identified by hash url active, defaulting to the first tab (Twitter Bootstrap)
+        var activeSubPage = decodeURIComponent(location.hash).slice(1);
+        activeSubPage = activeSubPageExists(activeSubPage, $tabs) ? activeSubPage : "";
+        if (activeSubPage===''){
+            activeSubPage = $tabs.first().text();
+            location.hash = encodeURIComponent(activeSubPage);
+        }
+
+        $tabs.on('shown', function(event, ui) {
+            //on tab click, change the url hash
+            var page = $(this).text();
+            var target = $(this).attr('href');
+            location.hash = encodeURIComponent(page);
+
+            // refresh the widgets on the sub page when selected to ensure proper sizing
+            if (subPagesViewedStatus[page] == false) {
+                // mark that this sub page has been viewed at least once and there is no need to refresh
+                // the widgets in future views
+                subPagesViewedStatus[page] = true;
+            }
+        });
+
+        // build the subPageViewedStatus map to track if a given sub page has been viewed yet to determine if we need
+        // to refresh the widgets upon first viewing to ensure they are sized properly.  Set the default active tab to
+        // true since it will be rendered and sized properly as part of the initial page load
+        $.each($tabs, function(i, el){
+            var $tab = $(el);
+            var page = $tab.text();
+            var isActive =  (page == activeSubPage);
+            subPagesViewedStatus[page] = false;
+            //show the initial tab
+            if(isActive){
+                $tab.tab('show');
+            }
+        });
+    }
+
+    function activeSubPageExists(activeSubPage, tabs){
+        var exists = false;
+        $.each(tabs, function(i, el){
+            if(el.innerHTML === activeSubPage){
+                exists = true;
+            }
+        });
+
+        return exists;
+    }
+
+    function updateParamsInString(i18nStr, itemsToReplace){
+        for(var i=0;i<itemsToReplace.length;i++){
+            var token = '{'+i+'}';
+            i18nStr = i18nStr.replace(token, itemsToReplace[i]);
+        }
+        return i18nStr;
+    }
+
+    function dealWithUserResults(userResults){
+        var currentUser = $("#addRemoveFriend").get(0).value;
+        var searchTerm = $('#searchTerm').get(0).value;
+        if(searchTerm == undefined || searchTerm == ""){
+            $('#clearSearchButton').hide();
+        }else{
+            $('#clearSearchButton').show();
+        }
+        var legend;
+        if(userResults.result.resultSet.length < 1){
+            legend = rave.getClientMessage("no.results.found");
+        }else{
+            legend = updateParamsInString(rave.getClientMessage("search.list.result.x.to.y"),
+                new Array(userResults.result.offset + 1, userResults.result.resultSet.length
+                    + userResults.result.offset, userResults.result.totalResults));
+        }
+        // show the listheader
+        $('#userSearchListHeader').text(legend);
+        var $targetDiv = $('#userSearchResults');
+        $targetDiv.empty();
+        // show the paginator
+        paginate(userResults);
+        //now build the content
+        $targetDiv
+            .append(
+                $("<table/>")
+                    .addClass("searchdialogcontent")
+                    .append(
+                        $("<tr/>")
+                            .append(
+                                $("<td/>")
+                                    .addClass("textcell")
+                                    .append(
+                                        $("<b/>")
+                                            .text(rave.getClientMessage("common.username"))
+                                    )
+                            )
+                            .append(
+                                $("<td/>")
+                                    .addClass("booleancell")
+                                    .append(
+                                        $("<b/>")
+                                            .text(rave.getClientMessage("common.friend.status"))
+                                    )
+                            )
+                    )
+                    .append(
+                        $("<tbody/>")
+                            .attr("id", "searchResultsBody")
+                    )
+            );
+
+        jQuery.each(userResults.result.resultSet, function() {
+            $('#searchResultsBody')
+                .append(
+                    $("<tr/>")
+                        .attr("id", "searchResultRecord")
+                        .append(
+                            $("<td/>")
+                                .text(this.username)
+                        )
+                        .append(
+                            $("<td/>")
+                                .attr("id", "friendStatusButtonHolder" + this.id)
+                        )
+                );
+
+            if(this.username != currentUser){
+                // check if already added
+                if(rave.personprofile.isUserAlreadyFriend(this.username)){
+                    $('#friendStatusButtonHolder'+this.id)
+                        .append(
+                            $("<a/>")
+                                .attr("href", "#")
+                                .attr("id", this.entityId)
+                                .attr("onclick", "rave.personprofile.removeFriend("+this.id+", '"+this.username+"');")
+                                .text(rave.getClientMessage("common.remove"))
+                        );
+                    // check if already sent friend request
+                }else if(rave.personprofile.isFriendRequestSent(this.username)){
+                    $('#friendStatusButtonHolder'+this.id)
+                        .append(
+                            $("<a/>")
+                                .attr("href", "#")
+                                .attr("id", this.entityId)
+                                .attr("onclick", "rave.personprofile.removeFriendRequestSent("+this.id+", '"+this.username+"');")
+                                .text(rave.getClientMessage("common.cancel.request"))
+                        );
+                }else if(rave.personprofile.isFriendRequestReceived(this.username)){
+                    $('#friendStatusButtonHolder'+this.id)
+                        .append(
+                            $("<a/>")
+                                .attr("href", "#")
+                                .attr("id", this.entityId)
+                                .attr("onclick", "rave.personprofile.acceptFriendRequest("+this.entityId+", '"+this.username+"');")
+                                .text(rave.getClientMessage("common.accept")),
+                            ' / ',
+                            $("<a/>")
+                                .attr("href", "#")
+                                .attr("id", this.id)
+                                .attr("onclick", "rave.personprofile.declineFriendRequest("+this.id+", '"+this.username+"');")
+                                .text(rave.getClientMessage("common.decline"))
+                        );
+                }else {
+                    $('#friendStatusButtonHolder'+this.id)
+                        .append(
+                            $("<a/>")
+                                .attr("href", "#")
+                                .attr("id", this.id)
+                                .attr("onclick", "rave.personprofile.addFriend("+this.id+", '"+this.username+"');")
+                                .text(rave.getClientMessage("common.add"))
+                        );
+                }
+            }
+
+        });
+    }
+
+    function paginate(userResults){
+        var $pagingDiv = $('#userSearchListPaging');
+        $pagingDiv.empty();
+        if(userResults.result.pageSize < userResults.result.totalResults){
+            $pagingDiv.append('<div class="pagination"><ul id="pagingul" >');
+            if(userResults.result.currentPage > 1){
+                offset = (userResults.result.currentPage - 2) * userResults.result.pageSize;
+                $('#pagingul').append('<li><a href="#" onclick="rave.api.rpc.getUsers({offset: ' +
+                    offset+', successCallback: function(result)' +
+                    ' {rave.personprofile.dealWithUserResults(result);}});">&lt;</a></li>');
+            }
+            for(var i=1;i<=userResults.result.numberOfPages;i++){
+                if(i == userResults.result.currentPage){
+                    $('#pagingul').append('<li class="active"><a href="#">'+i+'</a></li>');
+                }else{
+                    offset = (i - 1) * userResults.result.pageSize;
+                    $('#pagingul').append('<li><a href="#" onclick="rave.api.rpc.getUsers({offset: ' +
+                        offset + ', successCallback: function(result)' +
+                        ' {rave.personprofile.dealWithUserResults(result);}});">' + i + '</a></li>');
+                }
+            }
+            if (userResults.result.currentPage < userResults.result.numberOfPages){
+                offset = (userResults.result.currentPage) * userResults.result.pageSize;
+                $('#pagingul').append('<li><a href="#" onclick="rave.api.rpc.getUsers({offset: ' +
+                    offset + ', successCallback: function(result)' +
+                    ' {rave.personprofile.dealWithUserResults(result);}});">&gt;</a></li>');
+            }
+            $pagingDiv.append('</ul></div>');
+        }
+    }
+
+    // Add a friend to the current user
+    function addFriend(userId, username){
+        $('#friendStatusButtonHolder'+userId).hide();
+        rave.api.rpc.addFriend({friendUsername : username,
+            successCallback: function(result) {
+                rave.personprofile.addFriendRequestUI(username);
+                $('#friendStatusButtonHolder'+userId).empty();
+                $('#friendStatusButtonHolder'+userId)
+                    .append(
+                        $("<a/>")
+                            .attr("href", "#")
+                            .attr("id", userId)
+                            .attr("onclick", "rave.personprofile.removeFriendRequestSent(" +
+                                userId+", '" + username+"');")
+                            .text(rave.getClientMessage("common.cancel.request"))
+                    );
+                $('#friendStatusButtonHolder'+userId).show();
+            }
+        });
+    }
+
+    // Remove a friend of the current user
+    function removeFriend(userId, username){
+        var message = updateParamsInString(rave.getClientMessage("remove.friend.confirm"),
+            new Array(username));
+        if(confirm(message)){
+            $('#friendStatusButtonHolder'+userId).hide();
+            rave.api.rpc.removeFriend({friendUsername : username,
+                successCallback: function(result) {
+                    rave.personprofile.removeFriendUI(username);
+                    $('#friendStatusButtonHolder'+userId).empty();
+                    $('#friendStatusButtonHolder'+userId)
+                        .append(
+                            $("<a/>")
+                                .attr("href", "#")
+                                .attr("id", userId)
+                                .attr("onclick", "rave.personprofile.addFriend(" +
+                                    userId+", '" + username+"');")
+                                .text(rave.getClientMessage("common.add"))
+                        );
+                    $('#friendStatusButtonHolder'+userId).show();
+                }
+            });
+        }
+    }
+
+    // Cancel the friend request already sent to a user
+    function removeFriendRequestSent(userId, username){
+        var message = updateParamsInString(rave.getClientMessage("remove.friend.request.confirm"),
+            new Array(username));
+        if(confirm(message)){
+            $('#friendStatusButtonHolder'+userId).hide();
+            rave.api.rpc.removeFriend({friendUsername : username,
+                successCallback: function(result) {
+                    rave.personprofile.removeFriendRequestSentUI(username);
+                    $('#friendStatusButtonHolder'+userId).empty();
+                    $('#friendStatusButtonHolder'+userId)
+                        .append(
+                            $("<a/>")
+                                .attr("href", "#")
+                                .attr("id", userId)
+                                .attr("onclick", "rave.personprofile.addFriend(" +
+                                    userId+", '" + username+"');")
+                                .text(rave.getClientMessage("common.add"))
+                        );
+                    $('#friendStatusButtonHolder'+userId).show();
+                }
+            });
+        }
+    }
+
+    // Accept the friend request received by user
+    function acceptFriendRequest(userId, username){
+        $('#friendStatusButtonHolder'+userId).hide();
+        rave.api.rpc.acceptFriendRequest({friendUsername : username,
+            successCallback: function(result) {
+                rave.personprofile.removeFriendRequestReceivedUI(username);
+                $('#friendStatusButtonHolder'+userId).empty();
+                $('#friendStatusButtonHolder'+userId)
+                    .append(
+                        $("<a/>")
+                            .attr("href", "#")
+                            .attr("id", userId)
+                            .attr("onclick", "rave.personprofile.removeFriend(" +
+                                userId+", '" + username+"');")
+                            .text(rave.getClientMessage("common.remove"))
+                    );
+                $('#friendStatusButtonHolder'+userId).show();
+            }
+        });
+    }
+
+    // Decline the friend request received by user
+    function declineFriendRequest(userId, username){
+        $('#friendStatusButtonHolder'+userId).hide();
+        rave.api.rpc.removeFriend({friendUsername : username,
+            successCallback: function(result) {
+                rave.personprofile.removeFriendRequestReceivedUI(username);
+                $('#friendStatusButtonHolder'+userId).empty();
+                $('#friendStatusButtonHolder'+userId)
+                    .append(
+                        $("<a/>")
+                            .attr("href", "#")
+                            .attr("id", userId)
+                            .attr("onclick", "rave.personprofile.addFriend(" +
+                                userId+", '" + username+"');")
+                            .text(rave.getClientMessage("common.add"))
+                    );
+                $('#friendStatusButtonHolder'+userId).show();
+            }
+        });
+    }
+    // Add an item to the List of friend requests sent(maintained for the UI)
+    function addFriendRequestUI(username){
+        rave.personprofile.requestsSent.push(username);
+    }
+
+    // Remove a friend from the list of friends(maintained for the UI)
+    function removeFriendUI(friendUsername){
+        rave.personprofile.friends.splice(rave.personprofile.friends.indexOf(friendUsername),1);
+    }
+
+    // Remove a friend request from the list of friend requests sent(maintained for the UI)
+    function removeFriendRequestSentUI(friendUsername){
+        rave.personprofile.requestsSent.splice(rave.personprofile.requestsSent.indexOf(friendUsername),1);
+    }
+
+    // Remove a friend request from the list of friend requests received(maintained for the UI)
+    function removeFriendRequestReceivedUI(friendUsername){
+        rave.personprofile.friendRequestsReceived.splice(rave.personprofile.friendRequestsReceived.indexOf(friendUsername),1);
+    }
+
+    // Check if the user is already a friend
+    function isUserAlreadyFriend(username){
+        if(rave.personprofile.friends.indexOf(username)>=0){
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    // Check if a friend request is already sent to a particular user
+    function isFriendRequestSent(username){
+        if(rave.personprofile.requestsSent.indexOf(username)>=0){
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    // Check if a friend request is received from a particular user
+    function isFriendRequestReceived(username){
+        if(rave.personprofile.friendRequestsReceived.indexOf(username)>=0){
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    function initButtons() {
+        // setup the edit button if it exists
+        var $editButton = $("#profileEdit");
+        if ($editButton) {
+            $editButton.click(function() {
+                rave.api.handler.userProfileEditHandler(true);
+            });
+        }
+        //user clicks add/remove friend button in the profile page
+        var $friendButton = $("#addRemoveFriend");
+        if ($friendButton) {
+            $friendButton.click(function() {
+                rave.personprofile.getFriends({successCallback : function() {
+                    rave.api.rpc.getUsers({offset: 0,
+                        successCallback: function(result) {
+                            dealWithUserResults(result);
+                            $("#userDialog").modal('show');
+                        }
+                    });
+                }});
+            });
+        }
+
+        // user clicks "search" in the find users dialog
+        $("#userSearchButton").click(function() {
+            $('#userSearchResults').empty();
+            rave.api.rpc.searchUsers({searchTerm: $('#searchTerm').get(0).value, offset: 0,
+                successCallback: function(result) {
+                    rave.personprofile.dealWithUserResults(result);
+                }
+            });
+        });
+
+        // user clicks "clear search" in the find users dialog
+        $("#clearSearchButton").click(function() {
+            $('#searchTerm').get(0).value = "";
+            $('#userSearchResults').empty();
+            rave.api.rpc.getUsers({offset: 0,
+                successCallback: function(result) {
+                    rave.personprofile.dealWithUserResults(result);
+                }
+            });
+        });
+
+        // setup the cancel button if it exists
+        var $cancelButton = $("#cancelEdit");
+        if ($cancelButton) {
+            $cancelButton.click(function() {
+                rave.api.handler.userProfileEditHandler(false);
+            });
+        }
+
+        // When the user accepts a friend request
+        var $acceptFriend = $(".acceptFriendRequest");
+        if($acceptFriend) {
+            $acceptFriend.click(function(e) {
+                rave.api.rpc.acceptFriendRequest({friendUsername : this.id});
+                var listRequestItem = $(this).parents('.requestItem');
+                var friendRequestMenu = $(listRequestItem).parent();
+                $(listRequestItem).remove();
+                $('.friendRequestDropdown').append('<li class="message">'+rave.getClientMessage("common.accepted")+'</li>');
+                $('.message').fadeOut(2000, function() {
+                    $('.message').remove();
+                    var childItems = $(friendRequestMenu).children('li');
+                    $('.friendRequestDropdownLink').html(''+rave.getClientMessage("person.profile.friend.requests")+' ('+childItems.size()+')');
+                    if(childItems.size()==0)
+                        $('.friendRequestDropdown').append('<li>'+rave.getClientMessage("person.profile.friend.requests.none")+'</li>');
+                });
+                e.stopPropagation();
+            });
+        }
+
+        // When the user declines a friend request
+        var $declineFriend = $(".declineFriendRequest");
+        if($declineFriend) {
+            $declineFriend.click(function(e) {
+                rave.api.rpc.removeFriend({friendUsername : this.id});
+                var listRequestItem = $(this).parents('.requestItem');
+                var friendRequestMenu = $(listRequestItem).parent();
+                $(listRequestItem).remove();
+                $('.friendRequestDropdown').append('<li class="message">'+rave.getClientMessage("common.declined")+'</li>');
+                $('.message').fadeOut(2000, function() {
+                    $('.message').remove();
+                    var childItems = $(friendRequestMenu).children('li');
+                    $('.friendRequestDropdownLink').html(''+rave.getClientMessage("person.profile.friend.requests")+' ('+childItems.size()+')');
+                    if(childItems.size()==0)
+                        $('.friendRequestDropdown').append('<li>'+rave.getClientMessage("person.profile.friend.requests.none")+'</li>');
+                });
+                e.stopPropagation();
+            });
+        }
+    }
+
+    // Gets the list of friends from the DB
+    function getFriends(args) {
+        rave.personprofile.friends = new Array();
+        rave.personprofile.requestsSent = new Array();
+        rave.personprofile.friendRequestsReceived = new Array();
+        rave.api.rpc.getFriends({
+            successCallback: function(result) {
+                jQuery.each(result.result.accepted, function() {
+                    if(!rave.personprofile.isUserAlreadyFriend(this.username))
+                        rave.personprofile.friends.push(this.username);
+                });
+                jQuery.each(result.result.sent, function() {
+                    if(!rave.personprofile.isFriendRequestSent(this.username))
+                        rave.personprofile.requestsSent.push(this.username);
+                });
+                jQuery.each(result.result.received, function() {
+                    if(!rave.personprofile.isFriendRequestReceived(this.username))
+                        rave.personprofile.friendRequestsReceived.push(this.username);
+                });
+                if(result !=null && typeof args.successCallback == 'function') {
+                    args.successCallback();
+                }
+            }
+        });
+    }
+
+    function init() {
+        initSubPages();
+        initButtons();
+    }
+
+    return {
+        init : init,
+        dealWithUserResults : dealWithUserResults,
+        addFriend : addFriend,
+        removeFriend : removeFriend,
+        removeFriendUI : removeFriendUI,
+        removeFriendRequestSent : removeFriendRequestSent,
+        addFriendRequestUI : addFriendRequestUI,
+        removeFriendRequestSentUI : removeFriendRequestSentUI,
+        isUserAlreadyFriend : isUserAlreadyFriend,
+        isFriendRequestSent : isFriendRequestSent,
+        isFriendRequestReceived : isFriendRequestReceived,
+        removeFriendRequestReceivedUI : removeFriendRequestReceivedUI,
+        getFriends : getFriends,
+        acceptFriendRequest : acceptFriendRequest,
+        declineFriendRequest : declineFriendRequest
+    };
+}());

Added: rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_portal.js
URL: http://svn.apache.org/viewvc/rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_portal.js?rev=1460762&view=auto
==============================================================================
--- rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_portal.js (added)
+++ rave/trunk/rave-portal-resources/src/main/webapp/static/script/portal/rave_portal.js Mon Mar 25 17:00:18 2013
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+var rave = _.extend(rave, (function () {
+    var clientMessages = {};
+    var context="";
+
+    var pageEditor = true;
+    var pageViewer = {
+        username: "Unknown",
+        id: -1
+    };
+    var pageOwner = {
+        username: "Unknown",
+        id: -1
+    };
+    // JS debug mode is off by default
+    var javaScriptDebugMode = 0;
+    //Assigning a default value of 250 if unable to get value from the DB
+    var defaultWidgetHeight = 250;
+    var onWidgetsInitializedHandlers = [];
+    var onProvidersInitializedHandlers = [];
+    var onUIInitializedHandlers = [];
+    var onPageInitializedHandlers = [];
+
+    function getClientMessage(key) {
+        return clientMessages[key];
+    }
+
+    function addClientMessage(key, message) {
+        return clientMessages[key] = message;
+    }
+
+    function renderErrorWidget(id, message) {
+        $("#widget-" + id + "-body").html(message);
+    }
+
+
+    function setJavaScriptDebugMode(debugMode) {
+        javaScriptDebugMode = debugMode;
+    }
+
+    function getJavaScriptDebugMode() {
+        return javaScriptDebugMode;
+    }
+
+    function setPageViewer(viewer) {
+        pageViewer = viewer;
+    }
+
+    function getPageViewer() {
+        return pageViewer;
+    }
+
+    function setPageOwner(owner) {
+        pageOwner = owner;
+    }
+
+    function getPageOwner() {
+        return pageOwner;
+    }
+
+    function viewPage(pageId) {
+        var fragment = (pageId != null) ? ("/" + pageId) : "";
+        window.location.href = rave.getContext() + "page/view" + fragment;
+    }
+
+    function viewWidgetDetail(widgetId, referringPageId, jumpToId) {
+        if (jumpToId) {
+            jumpToId = '#' + jumpToId;
+        }
+        else {
+            jumpToId = '';
+        }
+        window.location.href = rave.getContext() + "store/widget/" + widgetId + "?referringPageId=" + referringPageId + jumpToId;
+    }
+
+    /**
+     * Determines if a page is empty (has zero widgets)
+     */
+    function isPageEmpty() {
+        return $.isEmptyObject(widgetByIdMap);
+    }
+
+    /**
+     * Removes a regionWidgetId from the internal widget map
+     * @param regionWidgetId the region widget id to remove
+     */
+    function removeWidgetFromMap(regionWidgetId) {
+        delete widgetByIdMap[regionWidgetId];
+    }
+
+    function initPageEditorStatus(status) {
+        if (status != "undefined") {
+            pageEditor = status;
+        }
+    }
+
+    function isPageEditor() {
+        return pageEditor;
+    }
+
+    function registerOnWidgetsInitizalizedHandler(callback) {
+        if (onWidgetsInitializedHandlers !== null) {
+            onWidgetsInitializedHandlers.push(callback);
+        } else {
+            callback();
+        }
+    };
+
+    function registerOnProvidersInitizalizedHandler(callback) {
+        if (onProvidersInitializedHandlers !== null) {
+            onProvidersInitializedHandlers.push(callback);
+        } else {
+            callback();
+        }
+    };
+
+    function registerOnUIInitizalizedHandler(callback) {
+        if (onUIInitializedHandlers !== null) {
+            onUIInitializedHandlers.push(callback);
+        } else {
+            callback();
+        }
+    };
+
+    function registerOnPageInitizalizedHandler(callback) {
+        if (onPageInitializedHandlers !== null) {
+            onPageInitializedHandlers.push(callback);
+        } else {
+            callback();
+        }
+    };
+
+
+    /**
+     * Internal method should only be called from the page.jsp
+     */
+    function runOnPageInitializedHandlers() {
+        if (onPageInitializedHandlers !== null && onPageInitializedHandlers.length > 0) {
+            for (var i = 0, j = onPageInitializedHandlers.length; i < j; ++i) {
+                try {
+                    onPageInitializedHandlers[i]();
+                } catch (ex) {
+                    gadgets.warn("Could not fire onPageInitializedHandler " + ex.message);
+                }
+            }
+        }
+        onPageInitializedHandlers = null;  // No need to hold these references anymore.
+    }
+
+    function setContext(contextPath) {
+        context = contextPath;
+        rave.api.setContext(contextPath);
+    }
+
+    function getContext() {
+        return context;
+    }
+
+    function extractObjectIdFromElementId(elementId) {
+        var tokens = elementId.split("-");
+        return tokens.length > 2 && tokens[0] == "widget" || tokens[0] == "region" ? tokens[1] : null;
+    }
+
+    function showInfoMessage(message) {
+
+        var markup = rave.ui.templates['info-message']({
+            message: message
+        });
+
+        $(markup).hide()
+            .prependTo("body")
+            //TODO: add a class for flash box and attach these styles
+            .css({ position: 'fixed', top: 0, left: 0, width: 'auto', 'max-width': '60%', 'font-size': '1.25em', padding: '.6em 1em', 'z-index': 9999, 'border-radius': '0 0 4px 0'})
+            .fadeIn('fast').delay(8000)
+            .fadeOut(function () {
+                $(this).remove();
+            });
+    }
+
+    /**
+     * Public API
+     */
+    return {
+        showInfoMessage: showInfoMessage,
+
+        getObjectIdFromDomId: extractObjectIdFromElementId,
+        /**
+         * Sets the context path for the Rave web application
+         *
+         * @param contextPath the context path of the rave webapp
+         */
+        setContext: setContext,
+
+        /**
+         * Gets the current context
+         */
+        getContext: getContext,
+        /**
+         * Renders an error in place of the widget
+         *
+         * @param id the RegionWidgetId of the widget to render in error mode
+         * @param message The message to display to the user
+         */
+        errorWidget: renderErrorWidget,
+
+        /**
+         * Gets the value of the JavaScriptDebugMode flag
+         * 0 = off
+         * 1 = on
+         */
+        getJavaScriptDebugMode: getJavaScriptDebugMode,
+
+        /**
+         * Sets the value of the JavaScriptDebugMode flag
+         * 0 = off
+         * 1 = on
+         */
+        setJavaScriptDebugMode: setJavaScriptDebugMode,
+
+        /**
+         * Sets the authenticated page viewer for the Rave web application
+         *
+         * @param viewer an object representing the authenticated user viewing the page {username:"bob", id:"1"}
+         */
+        setPageViewer: setPageViewer,
+
+        /**
+         * Gets the current viewer
+         */
+        getPageViewer: getPageViewer,
+
+        /**
+         * Sets the owner of the current page
+         *
+         * @param owner an object representing the owner of the page
+         */
+        setPageOwner: setPageOwner,
+
+        /**
+         * Gets the page owner
+         */
+        getPageOwner: getPageOwner,
+
+        /**
+         * View a page
+         *
+         * @param pageId the pageId to view, or if null, the user's default page
+         */
+        viewPage: viewPage,
+
+        /**
+         * View the widget detail page of a widget
+         *
+         * @param widgetId to widgetId to view
+         * @param referringPageId the id of the page the call is coming from
+         */
+        viewWidgetDetail: viewWidgetDetail,
+
+        /**
+         * Determines if a page is empty (has zero widgets)
+         * @param widgetByIdMap the map of widgets on the page
+         */
+        isPageEmpty: isPageEmpty,
+
+        /**
+         * Returns a language specific message based on the supplied key
+         *
+         * @param key the key of the message
+         */
+        getClientMessage: getClientMessage,
+
+        /**
+         * Adds a message to the internal client message map
+         *
+         * @param key
+         * @param message
+         */
+        addClientMessage: addClientMessage,
+
+        /**
+         * Set if user of a page has editing permission
+         * Used to stop sending UI events back to the server, rather
+         * than actually implementing any permission rules
+         * (which are set on the server)
+         */
+        initPageEditorStatus: initPageEditorStatus,
+
+        /**
+         * Returns a boolean indicating if the user
+         * should be treated as an page editor or not
+         */
+        isPageEditor: isPageEditor,
+
+        /**
+         * Registration methods for initialization events
+         */
+        registerOnWidgetsInitizalizedHandler: registerOnWidgetsInitizalizedHandler,
+        registerOnProvidersInitizalizedHandler: registerOnProvidersInitizalizedHandler,
+        registerOnUIInitizalizedHandler: registerOnUIInitizalizedHandler,
+        registerOnPageInitizalizedHandler: registerOnPageInitizalizedHandler,
+        runOnPageInitializedHandlers: runOnPageInitializedHandlers
+    }
+})()
+);