Example usage for org.apache.wicket.ajax.markup.html AjaxLink add

List of usage examples for org.apache.wicket.ajax.markup.html AjaxLink add

Introduction

In this page you can find the example usage for org.apache.wicket.ajax.markup.html AjaxLink add.

Prototype

public MarkupContainer add(final Component... children) 

Source Link

Document

Adds the child component(s) to this container.

Usage

From source file:org.sakaiproject.delegatedaccess.tool.pages.BaseTreePage.java

License:Educational Community License

protected AjaxLink getExpandCollapseLink() {
    //Expand Collapse Link:
    final Label expandCollapse = new Label("expandCollapse", new StringResourceModel("exapndNodes", null));
    expandCollapse.setOutputMarkupId(true);
    AjaxLink expandLink = new AjaxLink("expandAll") {
        boolean expand = true;

        @Override/*from w w  w.j a va2  s .co m*/
        public void onClick(AjaxRequestTarget target) {
            if (expand) {
                getTree().getTreeState().expandAll();
                expandCollapse.setDefaultModel(new StringResourceModel("collapseNodes", null));
                collapseEmptyFolders();
            } else {
                getTree().getTreeState().collapseAll();
                expandCollapse.setDefaultModel(new StringResourceModel("exapndNodes", null));
            }
            target.addComponent(expandCollapse);
            getTree().updateTree(target);
            expand = !expand;

        }

        @Override
        public boolean isVisible() {
            return getTree().getDefaultModelObject() != null;
        }
    };
    expandLink.add(expandCollapse);
    return expandLink;
}

From source file:org.sakaiproject.delegatedaccess.tool.pages.EditablePanelAdvancedOptions.java

License:Educational Community License

public EditablePanelAdvancedOptions(String id, IModel inputModel, final NodeModel nodeModel,
        final TreeNode node, final int userType) {
    super(id);/* www. j a  v a  2s .  c om*/

    this.nodeModel = nodeModel;
    this.node = node;

    final WebMarkupContainer advancedOptionsSpan = new WebMarkupContainer("advancedOptionsSpan");
    advancedOptionsSpan.setOutputMarkupId(true);
    final String editableSpanId = advancedOptionsSpan.getMarkupId();
    add(advancedOptionsSpan);

    AjaxLink<Void> saveEditableSpanLink = new AjaxLink<Void>("saveEditableSpanLink") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("document.getElementById('" + editableSpanId + "').style.display='none';");
            //In order for the models to refresh, you have to call "expand" or "collapse" then "updateTree",
            //since I don't want to expand or collapse, I just call whichever one the node is already
            //Refreshing the tree will update all the models and information (like role) will be generated onClick
            if (((BaseTreePage) target.getPage()).getTree().getTreeState().isNodeExpanded(node)) {
                ((BaseTreePage) target.getPage()).getTree().getTreeState().expandNode(node);
            } else {
                ((BaseTreePage) target.getPage()).getTree().getTreeState().collapseNode(node);
            }
            ((BaseTreePage) target.getPage()).getTree().updateTree(target);
        }
    };
    advancedOptionsSpan.add(saveEditableSpanLink);

    Label editableSpanLabel = new Label("editableNodeTitle", nodeModel.getNode().title);
    advancedOptionsSpan.add(editableSpanLabel);

    AjaxLink<Void> restrictToolsLink = new AjaxLink<Void>("advancedOptionsLink") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("document.getElementById('" + editableSpanId + "').style.display='';");
        }
    };
    add(restrictToolsLink);

    Label advancedOptionsSpanLabel = new Label("advancedOptionsSpan",
            new StringResourceModel("advanced", null));
    restrictToolsLink.add(advancedOptionsSpanLabel);

    Label advnacedOptionsTitle = new Label("advnacedOptionsTitle",
            new StringResourceModel("advancedOptionsTitle", null));
    advancedOptionsSpan.add(advnacedOptionsTitle);

    Label advancedOptionsInstructions = new Label("advancedOptionsInstructions",
            new StringResourceModel("advancedOptionsDesc", null));
    advancedOptionsSpan.add(advancedOptionsInstructions);

    advancedOptionsSpan.add(new EditablePanelCheckbox("editablePanelCheckbox",
            new PropertyModel(node, "userObject.shoppingPeriodRevokeInstructorEditable"),
            (NodeModel) ((DefaultMutableTreeNode) node).getUserObject(), node,
            DelegatedAccessConstants.TYPE_ADVANCED_OPT));
    advancedOptionsSpan.add(new EditablePanelCheckbox("revokePublicOptCheckbox",
            new PropertyModel(node, "userObject.shoppingPeriodRevokeInstructorPublicOpt"),
            (NodeModel) ((DefaultMutableTreeNode) node).getUserObject(), node,
            DelegatedAccessConstants.TYPE_ADVANCED_OPT));
}

From source file:org.sakaiproject.delegatedaccess.tool.pages.EditablePanelAdvancedUserOptions.java

License:Educational Community License

public EditablePanelAdvancedUserOptions(String id, IModel inputModel, final NodeModel nodeModel,
        final TreeNode node, Map<String, Object> settings) {
    super(id);//from ww  w .  j a  v  a  2s  .  c om

    this.nodeModel = nodeModel;
    this.node = node;

    final WebMarkupContainer advancedOptionsSpan = new WebMarkupContainer("advancedOptionsSpan");
    advancedOptionsSpan.setOutputMarkupId(true);
    final String editableSpanId = advancedOptionsSpan.getMarkupId();
    add(advancedOptionsSpan);

    AjaxLink<Void> saveEditableSpanLink = new AjaxLink<Void>("saveEditableSpanLink") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("document.getElementById('" + editableSpanId + "').style.display='none';");
            //In order for the models to refresh, you have to call "expand" or "collapse" then "updateTree",
            //since I don't want to expand or collapse, I just call whichever one the node is already
            //Refreshing the tree will update all the models and information (like role) will be generated onClick
            if (((BaseTreePage) target.getPage()).getTree().getTreeState().isNodeExpanded(node)) {
                ((BaseTreePage) target.getPage()).getTree().getTreeState().expandNode(node);
            } else {
                ((BaseTreePage) target.getPage()).getTree().getTreeState().collapseNode(node);
            }
            ((BaseTreePage) target.getPage()).getTree().updateTree(target);
        }
    };
    advancedOptionsSpan.add(saveEditableSpanLink);

    Label editableSpanLabel = new Label("editableNodeTitle", nodeModel.getNode().title);
    advancedOptionsSpan.add(editableSpanLabel);

    AjaxLink<Void> restrictToolsLink = new AjaxLink<Void>("advancedOptionsLink") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("document.getElementById('" + editableSpanId + "').style.display='';");
        }
    };
    add(restrictToolsLink);

    Label advancedOptionsSpanLabel = new Label("advancedOptionsSpan",
            new StringResourceModel("advanced", null));
    restrictToolsLink.add(advancedOptionsSpanLabel);

    Label advnacedOptionsTitle = new Label("advnacedOptionsTitle",
            new StringResourceModel("advancedOptionsTitle", null));
    advancedOptionsSpan.add(advnacedOptionsTitle);

    Label advancedOptionsInstructions = new Label("advancedOptionsInstructions",
            new StringResourceModel("advancedOptionsDesc", null));
    advancedOptionsSpan.add(advancedOptionsInstructions);

    //Allow Become User:

    //check settings to see if user can update the allow become user checkbox:
    Boolean allowBecomeUser = Boolean.FALSE;
    if (settings.containsKey(PropertyEditableColumnAdvancedUserOptions.SETTINGS_ALLOW_SET_BECOME_USER)
            && settings.get(
                    PropertyEditableColumnAdvancedUserOptions.SETTINGS_ALLOW_SET_BECOME_USER) instanceof Boolean) {
        allowBecomeUser = (Boolean) settings
                .get(PropertyEditableColumnAdvancedUserOptions.SETTINGS_ALLOW_SET_BECOME_USER);
    }
    EditablePanelCheckbox allowBecomeUserCheckbox = new EditablePanelCheckbox("allowBecomeUserCheckbox",
            new PropertyModel(node, "userObject.allowBecomeUser"),
            (NodeModel) ((DefaultMutableTreeNode) node).getUserObject(), node,
            DelegatedAccessConstants.TYPE_ADVANCED_OPT);
    if (!allowBecomeUser) {
        allowBecomeUserCheckbox.setEnabled(false);
    }
    advancedOptionsSpan.add(allowBecomeUserCheckbox);
}

From source file:org.sakaiproject.delegatedaccess.tool.pages.EditablePanelList.java

License:Educational Community License

public EditablePanelList(String id, IModel inputModel, final NodeModel nodeModel, final TreeNode node,
        final int userType, final int fieldType) {
    super(id);//from www .  j  a  v a 2 s  .c  o m

    this.nodeModel = nodeModel;
    this.node = node;

    final WebMarkupContainer editableSpan = new WebMarkupContainer("editableSpan");
    editableSpan.setOutputMarkupId(true);
    final String editableSpanId = editableSpan.getMarkupId();
    add(editableSpan);

    AjaxLink<Void> saveEditableSpanLink = new AjaxLink<Void>("saveEditableSpanLink") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("document.getElementById('" + editableSpanId + "').style.display='none';");
            //In order for the models to refresh, you have to call "expand" or "collapse" then "updateTree",
            //since I don't want to expand or collapse, I just call whichever one the node is already
            //Refreshing the tree will update all the models and information (like role) will be generated onClick
            if (((BaseTreePage) target.getPage()).getTree().getTreeState().isNodeExpanded(node)) {
                ((BaseTreePage) target.getPage()).getTree().getTreeState().expandNode(node);
            } else {
                ((BaseTreePage) target.getPage()).getTree().getTreeState().collapseNode(node);
            }
            ((BaseTreePage) target.getPage()).getTree().updateTree(target);
        }
    };
    editableSpan.add(saveEditableSpanLink);

    Label editableSpanLabel = new Label("editableNodeTitle", nodeModel.getNode().title);
    editableSpan.add(editableSpanLabel);

    WebMarkupContainer toolTableHeader = new WebMarkupContainer("toolTableHeader") {
        @Override
        public boolean isVisible() {
            return DelegatedAccessConstants.TYPE_ACCESS_SHOPPING_PERIOD_USER == userType;
        }
    };
    editableSpan.add(toolTableHeader);

    List<ListOptionSerialized[]> listOptions = new ArrayList<ListOptionSerialized[]>();

    final ListView<ListOptionSerialized[]> listView = new ListView<ListOptionSerialized[]>("list",
            listOptions) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<ListOptionSerialized[]> item) {
            ListOptionSerialized wrapper = item.getModelObject()[0];
            item.add(new Label("name", wrapper.getName()));
            //Auth Checkbox:
            final CheckBox checkBox = new CheckBox("authCheck", new PropertyModel(wrapper, "selected"));
            checkBox.setOutputMarkupId(true);
            checkBox.setOutputMarkupPlaceholderTag(true);
            final String checkBoxId = checkBox.getMarkupId();
            final String toolId = wrapper.getId();
            checkBox.add(new AjaxFormComponentUpdatingBehavior("onClick") {
                protected void onUpdate(AjaxRequestTarget target) {
                    if (DelegatedAccessConstants.TYPE_LISTFIELD_TOOLS == fieldType) {
                        nodeModel.setAuthToolRestricted(toolId, isChecked());
                    }
                }

                private boolean isChecked() {
                    final String value = checkBox.getValue();
                    if (value != null) {
                        try {
                            return Strings.isTrue(value);
                        } catch (Exception e) {
                            return false;
                        }
                    }
                    return false;
                }
            });
            item.add(checkBox);
            if (nodeModel.isPublicToolRestricted(toolId) && !nodeModel.isAuthToolRestricted(toolId)) {
                //disable the auth option because public is already selected (only disable if it's not already selected)
                checkBox.setEnabled(false);
            }

            //Public Checkbox:
            ListOptionSerialized publicWrapper = item.getModelObject()[1];
            final CheckBox publicCheckBox = new CheckBox("publicCheck",
                    new PropertyModel(publicWrapper, "selected")) {
                @Override
                public boolean isVisible() {
                    return DelegatedAccessConstants.TYPE_ACCESS_SHOPPING_PERIOD_USER == userType;
                }
            };
            publicCheckBox.setOutputMarkupId(true);
            final String publicToolId = publicWrapper.getId();
            publicCheckBox.add(new AjaxFormComponentUpdatingBehavior("onClick") {
                protected void onUpdate(AjaxRequestTarget target) {
                    boolean checked = isPublicChecked();

                    if (DelegatedAccessConstants.TYPE_LISTFIELD_TOOLS == fieldType) {
                        nodeModel.setPublicToolRestricted(publicToolId, checked);
                    }

                    if (checked) {
                        //if public is checked, we don't need the "auth" checkbox enabled (or selected).  Disabled and De-select it
                        checkBox.setModelValue(new String[] { "false" });
                        checkBox.setEnabled(false);
                        if (DelegatedAccessConstants.TYPE_LISTFIELD_TOOLS == fieldType) {
                            nodeModel.setAuthToolRestricted(toolId, false);
                        }
                    } else {
                        checkBox.setEnabled(true);
                    }
                    target.addComponent(checkBox, checkBoxId);
                }

                private boolean isPublicChecked() {
                    final String value = publicCheckBox.getValue();
                    if (value != null) {
                        try {
                            return Strings.isTrue(value);
                        } catch (Exception e) {
                            return false;
                        }
                    }
                    return false;
                }
            });
            item.add(publicCheckBox);

        }
    };
    editableSpan.add(listView);

    AjaxLink<Void> restrictToolsLink = new AjaxLink<Void>("restrictToolsLink") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            if (!loadedFlag) {
                loadedFlag = true;
                List<ListOptionSerialized[]> listOptions = null;
                if (DelegatedAccessConstants.TYPE_LISTFIELD_TOOLS == fieldType) {
                    listOptions = getNodeModelToolsList(nodeModel);
                }
                listView.setDefaultModelObject(listOptions);
                target.addComponent(editableSpan);
            }
            target.appendJavascript("document.getElementById('" + editableSpanId + "').style.display='';");
        }
    };
    add(restrictToolsLink);

    add(new WebComponent("noToolsSelectedWarning") {
        @Override
        public boolean isVisible() {
            return DelegatedAccessConstants.TYPE_ACCESS_SHOPPING_PERIOD_USER == userType
                    && nodeModel.getSelectedRestrictedAuthTools().isEmpty()
                    && nodeModel.getSelectedRestrictedPublicTools().isEmpty();
        }

        @Override
        protected void onComponentTag(ComponentTag tag) {
            super.onComponentTag(tag);
            tag.put("title", new ResourceModel("noToolsSelected").getObject());
        }
    });

    Label restrictToolsLinkLabel = new Label("restrictToolsSpan");
    if (DelegatedAccessConstants.TYPE_LISTFIELD_TOOLS == fieldType) {
        if (DelegatedAccessConstants.TYPE_ACCESS_SHOPPING_PERIOD_USER == userType) {
            restrictToolsLinkLabel.setDefaultModel(new StringResourceModel("showToolsHeader", null));
        } else {
            restrictToolsLinkLabel.setDefaultModel(new StringResourceModel("restrictedToolsHeader", null));
        }
    }
    restrictToolsLink.add(restrictToolsLinkLabel);

    Label editToolsTitle = new Label("editToolsTitle");
    if (DelegatedAccessConstants.TYPE_LISTFIELD_TOOLS == fieldType) {
        if (DelegatedAccessConstants.TYPE_ACCESS_SHOPPING_PERIOD_USER == userType) {
            editToolsTitle.setDefaultModel(new StringResourceModel("editableShowToolsTitle", null));
        } else {
            editToolsTitle.setDefaultModel(new StringResourceModel("editableRestrictedToolsTitle", null));
        }
    }
    editableSpan.add(editToolsTitle);

    Label editToolsInstructions = new Label("editToolsInstructions");
    if (DelegatedAccessConstants.TYPE_LISTFIELD_TOOLS == fieldType) {
        if (DelegatedAccessConstants.TYPE_ACCESS_SHOPPING_PERIOD_USER == userType) {
            editToolsInstructions
                    .setDefaultModel(new StringResourceModel("editableShowToolsDescription", null));
        } else {
            editToolsInstructions
                    .setDefaultModel(new StringResourceModel("editableRestrictedToolsDescription", null));
        }
    }
    editableSpan.add(editToolsInstructions);

}

From source file:org.sakaiproject.delegatedaccess.tool.pages.UserPageSiteSearch.java

License:Educational Community License

@SuppressWarnings("unchecked")
public void buildPage(final String search, final Map<String, Object> advancedFields, final boolean statistics,
        final boolean currentStatisticsFlag) {
    this.search = search;
    this.statistics = statistics;
    this.currentStatisticsFlag = currentStatisticsFlag;
    if (statistics) {
        disableLink(shoppingStatsLink);//from w w w  .j  ava2 s  . c  o m
    }
    List<ListOptionSerialized> blankRestrictedTools = projectLogic.getEntireToolsList();
    toolsMap = new HashMap<String, String>();
    for (ListOptionSerialized option : blankRestrictedTools) {
        toolsMap.put(option.getId(), option.getName());
    }

    //Setup Statistics Links:
    Link<Void> currentLink = new Link<Void>("currentLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            setResponsePage(new UserPageSiteSearch("", null, true, true));
        }

        @Override
        public boolean isVisible() {
            return statistics;
        }
    };
    currentLink.add(new Label("currentLinkLabel", new ResourceModel("link.current")).setRenderBodyOnly(true));
    currentLink.add(new AttributeModifier("title", true, new ResourceModel("link.current.tooltip")));
    add(currentLink);

    if (currentStatisticsFlag) {
        disableLink(currentLink);
    }

    Link<Void> allLink = new Link<Void>("allLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            setResponsePage(new UserPageSiteSearch("", null, true, false));
        }

        @Override
        public boolean isVisible() {
            return statistics;
        }
    };
    allLink.add(new Label("allLinkLabel", new ResourceModel("link.all")).setRenderBodyOnly(true));
    allLink.add(new AttributeModifier("title", true, new ResourceModel("link.all.tooltip")));
    add(allLink);
    if (!currentStatisticsFlag) {
        disableLink(allLink);
    }

    termOptions = new ArrayList<SelectOption>();
    for (String[] entry : sakaiProxy.getTerms()) {
        termOptions.add(new SelectOption(entry[1], entry[0]));
    }
    Map<String, String> hierarchySearchFields = new HashMap<String, String>();
    if (advancedFields != null) {
        for (Entry<String, Object> entry : advancedFields.entrySet()) {
            if (DelegatedAccessConstants.ADVANCED_SEARCH_INSTRUCTOR.equals(entry.getKey())) {
                instructorField = entry.getValue().toString();
                selectedInstructorOption = advancedFields
                        .get(DelegatedAccessConstants.ADVANCED_SEARCH_INSTRUCTOR_TYPE).toString();
            }
            if (DelegatedAccessConstants.ADVANCED_SEARCH_TERM.equals(entry.getKey())) {
                for (SelectOption option : termOptions) {
                    if (entry.getValue().equals(option.getValue())) {
                        termField = option;
                        break;
                    }
                }
            }
            if (DelegatedAccessConstants.ADVANCED_SEARCH_HIERARCHY_FIELDS.equals(entry.getKey())) {
                hierarchySearchFields = (Map<String, String>) entry.getValue();
            }
        }
    }
    //Create Search Form:
    final PropertyModel<String> searchModel = new PropertyModel<String>(this, "search");
    final PropertyModel<String> instructorFieldModel = new PropertyModel<String>(this, "instructorField");
    final PropertyModel<SelectOption> termFieldModel = new PropertyModel<SelectOption>(this, "termField");
    final IModel<String> searchStringModel = new IModel<String>() {

        public void detach() {
        }

        public void setObject(String arg0) {
        }

        public String getObject() {
            String searchString = "";
            if (searchModel.getObject() != null && !"".equals(searchModel.getObject().toString().trim())) {
                searchString += new StringResourceModel("siteIdTitleField", null).getString() + " "
                        + searchModel.getObject();
            }
            if (instructorFieldModel.getObject() != null && !"".equals(instructorFieldModel.getObject())) {
                if (!"".equals(searchString))
                    searchString += ", ";
                String userType = new StringResourceModel("instructor", null).getString();
                if (DelegatedAccessConstants.ADVANCED_SEARCH_INSTRUCTOR_TYPE_MEMBER
                        .equals(selectedInstructorOption)) {
                    userType = new StringResourceModel("member", null).getString();
                }
                searchString += userType + " " + instructorFieldModel.getObject();
            }
            if (termFieldModel.getObject() != null && !"".equals(termFieldModel.getObject())) {
                if (!"".equals(searchString))
                    searchString += ", ";
                searchString += new StringResourceModel("termField", null).getString() + " "
                        + termFieldModel.getObject().getLabel();
            }
            //hierarchy params:
            if (hierarchySearchMap != null) {
                for (Entry<String, SelectOption> entry : hierarchySearchMap.entrySet()) {
                    if (entry.getValue() != null && !"".equals(entry.getValue().getValue().trim())) {
                        if (!"".equals(searchString))
                            searchString += ", ";
                        searchString += hierarchyLabels.get(entry.getKey()) + ": "
                                + entry.getValue().getValue().trim();
                    }
                }
            }
            return searchString;
        }
    };
    final IModel<String> permaLinkModel = new IModel<String>() {

        @Override
        public void detach() {
        }

        @Override
        public String getObject() {
            String path = "/shopping";

            Map<String, String> params = new HashMap<String, String>();
            //Search
            if (searchModel.getObject() != null) {
                params.put("search", searchModel.getObject());
            }
            //term:
            if (termFieldModel.getObject() != null && !"".equals(termFieldModel.getObject())) {
                params.put("term", termFieldModel.getObject().getValue());
            }
            //instructor
            if (instructorFieldModel.getObject() != null && !"".equals(instructorFieldModel.getObject())) {
                params.put("instructor", instructorFieldModel.getObject());
                if (DelegatedAccessConstants.ADVANCED_SEARCH_INSTRUCTOR_TYPE_MEMBER
                        .equals(selectedInstructorOption)) {
                    params.put("instructorType",
                            DelegatedAccessConstants.ADVANCED_SEARCH_INSTRUCTOR_TYPE_MEMBER);
                } else {
                    params.put("instructorType",
                            DelegatedAccessConstants.ADVANCED_SEARCH_INSTRUCTOR_TYPE_INSTRUCTOR);
                }
            }
            //hierarchy params:
            if (hierarchySearchMap != null) {
                int i = 0;
                for (Entry<String, SelectOption> entry : hierarchySearchMap.entrySet()) {
                    if (entry.getValue() != null && !"".equals(entry.getValue().getValue().trim())) {
                        params.put("hierarchyKey" + i, entry.getKey());
                        params.put("hierarchyValue" + i, entry.getValue().getValue());
                        i++;
                    }
                }
            }

            String context = sakaiProxy.siteReference(sakaiProxy.getCurrentPlacement().getContext());

            String url = "";
            try {
                String tool = "sakai.delegatedaccess";
                if (isShoppingPeriodTool()) {
                    tool += ".shopping";
                }
                url = developerHelperService.getToolViewURL(tool, path, params, context);
            } catch (Exception e) {

            }
            return url;
        }

        @Override
        public void setObject(String arg0) {
        }

    };
    final Form<?> form = new Form("form") {
        @Override
        protected void onSubmit() {
            super.onSubmit();
            if (provider != null) {
                provider.detachManually();
            }
        }
    };
    form.add(new TextField<String>("search", searchModel));
    AbstractReadOnlyModel<String> instructorFieldLabelModel = new AbstractReadOnlyModel<String>() {

        @Override
        public String getObject() {
            if (isShoppingPeriodTool()) {
                return new StringResourceModel("instructor", null).getObject() + ":";
            } else {
                return new StringResourceModel("user", null).getObject() + ":";
            }
        }
    };
    form.add(new Label("instructorFieldLabel", instructorFieldLabelModel));
    form.add(new TextField<String>("instructorField", instructorFieldModel));
    //Instructor Options:
    RadioGroup group = new RadioGroup("instructorOptionsGroup",
            new PropertyModel<String>(this, "selectedInstructorOption")) {
        @Override
        public boolean isVisible() {
            //only show if its not shopping period
            return !isShoppingPeriodTool();
        }
    };
    group.add(new Radio("instructorOption",
            Model.of(DelegatedAccessConstants.ADVANCED_SEARCH_INSTRUCTOR_TYPE_INSTRUCTOR)));
    group.add(new Radio("memberOption",
            Model.of(DelegatedAccessConstants.ADVANCED_SEARCH_INSTRUCTOR_TYPE_MEMBER)));
    form.add(group);

    final ChoiceRenderer choiceRenderer = new ChoiceRenderer("label", "value");
    DropDownChoice termFieldDropDown = new DropDownChoice("termField", termFieldModel, termOptions,
            choiceRenderer) {
        @Override
        public boolean isVisible() {
            return !sakaiProxy.isSearchHideTerm();
        }
    };
    //keeps the null option (choose one) after a user selects an option
    termFieldDropDown.setNullValid(true);
    form.add(termFieldDropDown);
    add(form);

    //hierarchy dropdown:
    String[] hierarchyTmp = sakaiProxy
            .getServerConfigurationStrings(DelegatedAccessConstants.HIERARCHY_SITE_PROPERTIES);
    if (hierarchyTmp == null || hierarchyTmp.length == 0) {
        hierarchyTmp = DelegatedAccessConstants.DEFAULT_HIERARCHY;
    }
    final String[] hierarchy = hierarchyTmp;
    WebMarkupContainer hierarchyDiv = new WebMarkupContainer("hierarchyFields");
    final Comparator<SelectOption> optionComparator = new SelectOptionComparator();
    if (hierarchySelectOptions == null || hierarchySelectOptions.size() == 0) {
        nodeSelectOrder = new ArrayList<String>();
        hierarchySearchMap = new HashMap<String, SelectOption>();
        for (String s : hierarchy) {
            hierarchySearchMap.put(s, null);
            nodeSelectOrder.add(s);
            hierarchyLabels.put(s, sakaiProxy.getHierarchySearchLabel(s));
        }
        Map<String, String> searchParams = new HashMap<String, String>();
        for (Entry<String, SelectOption> entry : hierarchySearchMap.entrySet()) {
            String value = entry.getValue() == null ? "" : entry.getValue().getValue();
            //in case user passed in a parameter, set it:
            if (hierarchySearchFields.containsKey(entry.getKey())) {
                value = hierarchySearchFields.get(entry.getKey());
            }
            searchParams.put(entry.getKey(), value);
        }
        Map<String, Set<String>> hierarchyOptions = projectLogic.getHierarchySearchOptions(searchParams);
        hierarchySelectOptions = new HashMap<String, List<SelectOption>>();
        for (Entry<String, Set<String>> entry : hierarchyOptions.entrySet()) {
            List<SelectOption> options = new ArrayList<SelectOption>();
            for (String s : entry.getValue()) {
                SelectOption o = new SelectOption(s, s);
                options.add(o);
                if (searchParams.containsKey(entry.getKey()) && s.equals(searchParams.get(entry.getKey()))) {
                    hierarchySearchMap.put(entry.getKey(), o);
                }
            }
            Collections.sort(options, optionComparator);
            hierarchySelectOptions.put(entry.getKey(), options);
        }
    }
    DataView dropdowns = new DataView("hierarchyDropdowns", new IDataProvider<String>() {

        @Override
        public void detach() {

        }

        @Override
        public Iterator<? extends String> iterator(int first, int count) {
            return nodeSelectOrder.subList(first, first + count).iterator();
        }

        @Override
        public IModel<String> model(final String arg0) {
            return new AbstractReadOnlyModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    return arg0;
                }
            };
        }

        @Override
        public int size() {
            return nodeSelectOrder.size();
        }

    }) {

        @Override
        protected void populateItem(Item item) {
            final String hierarchyLevel = item.getModelObject().toString();
            item.add(new Label("hierarchyLabel",
                    hierarchyLabels.containsKey(hierarchyLevel) ? hierarchyLabels.get(hierarchyLevel)
                            : hierarchyLevel));
            final DropDownChoice choice = new DropDownChoice("hierarchyLevel",
                    new NodeSelectModel(hierarchyLevel), hierarchySelectOptions.get(hierarchyLevel),
                    choiceRenderer);
            //keeps the null option (choose one) after a user selects an option
            choice.setNullValid(true);
            choice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
                protected void onUpdate(AjaxRequestTarget target) {
                    Map<String, String> searchParams = new HashMap<String, String>();
                    for (Entry<String, SelectOption> entry : hierarchySearchMap.entrySet()) {
                        searchParams.put(entry.getKey(),
                                entry.getValue() == null ? "" : entry.getValue().getValue());
                    }
                    Map<String, Set<String>> hierarchyOptions = projectLogic
                            .getHierarchySearchOptions(searchParams);
                    hierarchySelectOptions = new HashMap<String, List<SelectOption>>();
                    for (Entry<String, Set<String>> entry : hierarchyOptions.entrySet()) {
                        List<SelectOption> options = new ArrayList<SelectOption>();
                        for (String s : entry.getValue()) {
                            options.add(new SelectOption(s, s));
                        }
                        Collections.sort(options, optionComparator);
                        hierarchySelectOptions.put(entry.getKey(), options);
                    }

                    //refresh everything:
                    target.addComponent(form);
                }
            });
            item.add(choice);
        }

    };
    hierarchyDiv.add(dropdowns);
    form.add(hierarchyDiv);

    //show user's search (if not null)
    add(new Label("searchResultsTitle", new StringResourceModel("searchResultsTitle", null)) {
        @Override
        public boolean isVisible() {
            return (searchModel.getObject() != null && !"".equals(searchModel.getObject()))
                    || (instructorFieldModel.getObject() != null
                            && !"".equals(instructorFieldModel.getObject()))
                    || (termFieldModel.getObject() != null && !"".equals(termFieldModel.getObject()))
                    || hierarchyOptionSelected();
        }
    });
    add(new Label("searchString", searchStringModel) {
        @Override
        public boolean isVisible() {
            return (searchModel.getObject() != null && !"".equals(searchModel.getObject()))
                    || (instructorFieldModel.getObject() != null
                            && !"".equals(instructorFieldModel.getObject()))
                    || (termFieldModel.getObject() != null && !"".equals(termFieldModel.getObject()))
                    || hierarchyOptionSelected();
        }
    });
    add(new TextField("permaLink", permaLinkModel) {
        @Override
        public boolean isVisible() {
            return (searchModel.getObject() != null && !"".equals(searchModel.getObject()))
                    || (instructorFieldModel.getObject() != null
                            && !"".equals(instructorFieldModel.getObject()))
                    || (termFieldModel.getObject() != null && !"".equals(termFieldModel.getObject()))
                    || hierarchyOptionSelected();
        }
    });
    //search result table:
    //Headers
    final Link<Void> siteTitleSort = new Link<Void>("siteTitleSortLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            changeOrder(DelegatedAccessConstants.SEARCH_COMPARE_SITE_TITLE);
        }

        @Override
        public boolean isVisible() {
            return provider.size() > 0;
        }
    };
    final Label siteTitleLabel = new Label("siteTitleLabel", new StringResourceModel("siteTitleHeader", null));
    siteTitleSort.add(siteTitleLabel);
    add(siteTitleSort);

    final Link<Void> siteIdSort = new Link<Void>("siteIdSortLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            changeOrder(DelegatedAccessConstants.SEARCH_COMPARE_SITE_ID);
        }

        @Override
        public boolean isVisible() {
            return provider.size() > 0;
        }
    };
    final Label siteIdSortLabel = new Label("siteIdSortLabel", new StringResourceModel("siteIdHeader", null));
    siteIdSort.add(siteIdSortLabel);
    add(siteIdSort);

    final Link<Void> termSort = new Link<Void>("termSortLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            changeOrder(DelegatedAccessConstants.SEARCH_COMPARE_TERM);
        }

        @Override
        public boolean isVisible() {
            return provider.size() > 0;
        }
    };
    final Label termSortLabel = new Label("termSortLabel", new StringResourceModel("termHeader", null));
    termSort.add(termSortLabel);
    add(termSort);

    AbstractReadOnlyModel<String> instructorSortLabelModel = new AbstractReadOnlyModel<String>() {

        @Override
        public String getObject() {
            if (DelegatedAccessConstants.ADVANCED_SEARCH_INSTRUCTOR_TYPE_MEMBER
                    .equals(selectedInstructorOption)) {
                return new StringResourceModel("member", null).getObject();
            } else {
                return new StringResourceModel("instructor", null).getObject();
            }
        }
    };
    final Link<Void> instructorSort = new Link<Void>("instructorSortLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            changeOrder(DelegatedAccessConstants.SEARCH_COMPARE_INSTRUCTOR);
        }

        @Override
        public boolean isVisible() {
            return provider.size() > 0;
        }
    };
    final Label instructorSortLabel = new Label("instructorSortLabel", instructorSortLabelModel);
    instructorSort.add(instructorSortLabel);
    add(instructorSort);

    final Link<Void> providersSort = new Link<Void>("providersSortLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            changeOrder(DelegatedAccessConstants.SEARCH_COMPARE_PROVIDERS);
        }

        @Override
        public boolean isVisible() {
            //this helps hide all the extra columns with the wicket:enclosure in the html
            return !isShoppingPeriodTool() && sakaiProxy.isProviderIdLookupEnabled();
        }
    };
    final Label providersSortLabel = new Label("providersSortLabel",
            new StringResourceModel("providers", null));
    providersSort.add(providersSortLabel);
    add(providersSort);

    final Link<Void> publishedSort = new Link<Void>("publishedSortLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            changeOrder(DelegatedAccessConstants.SEARCH_COMPARE_PUBLISHED);
        }

        @Override
        public boolean isVisible() {
            //this helps hide all the extra columns with the wicket:enclosure in the html
            return !isShoppingPeriodTool();
        }
    };
    final Label publishedSortLabel = new Label("publishedSortLabel",
            new StringResourceModel("published", null));
    publishedSort.add(publishedSortLabel);
    add(publishedSort);

    final Link<Void> accessSort = new Link<Void>("accessSortLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            changeOrder(DelegatedAccessConstants.SEARCH_COMPARE_ACCESS);
        }
    };
    final Label accessSortLabel = new Label("accessSortLabel", new StringResourceModel("access", null));
    accessSort.add(accessSortLabel);
    add(accessSort);

    final Link<Void> startDateSort = new Link<Void>("startDateSortLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            changeOrder(DelegatedAccessConstants.SEARCH_COMPARE_START_DATE);
        }

        @Override
        public boolean isVisible() {
            //this helps with the wicket:enlosure
            return statistics;
        }
    };
    final Label startDateSortLabel = new Label("startDateSortLabel",
            new StringResourceModel("startDate", null));
    startDateSort.add(startDateSortLabel);
    add(startDateSort);

    final Link<Void> endDateSort = new Link<Void>("endDateSortLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            changeOrder(DelegatedAccessConstants.SEARCH_COMPARE_END_DATE);
        }

        @Override
        public boolean isVisible() {
            return statistics;
        }
    };
    final Label endDateSortLabel = new Label("endDateSortLabel", new StringResourceModel("endDate", null));
    endDateSort.add(endDateSortLabel);
    add(endDateSort);

    final Label showAuthToolsHeader = new Label("showAuthToolsHeader",
            new StringResourceModel("showAuthToolsHeader", null)) {
        @Override
        public boolean isVisible() {
            return statistics;
        }
    };
    add(showAuthToolsHeader);

    final Label showPublicToolsHeader = new Label("showPublicToolsHeader",
            new StringResourceModel("showPublicToolsHeader", null)) {
        @Override
        public boolean isVisible() {
            return statistics;
        }
    };
    add(showPublicToolsHeader);

    final Link<Void> accessModifiedBySort = new Link<Void>("accessModifiedBySortLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            changeOrder(DelegatedAccessConstants.SEARCH_COMPARE_ACCESS_MODIFIED_BY);
        }

        @Override
        public boolean isVisible() {
            //this helps hide all the extra columns with the wicket:enclosure in the html
            return !isShoppingPeriodTool();
        }
    };
    final Label accessModifiedBySortLabel = new Label("accessModifiedBySortLabel",
            new StringResourceModel("accessModifiedBy", null));
    accessModifiedBySort.add(accessModifiedBySortLabel);
    add(accessModifiedBySort);

    final Link<Void> accessModifiedOnSort = new Link<Void>("accessModifiedOnSortLink") {
        private static final long serialVersionUID = 1L;

        public void onClick() {
            changeOrder(DelegatedAccessConstants.SEARCH_COMPARE_ACCESS_MODIFIED);
        }

        @Override
        public boolean isVisible() {
            //this helps hide all the extra columns with the wicket:enclosure in the html
            return !isShoppingPeriodTool();
        }
    };
    final Label accessModifiedOnSortLabel = new Label("accessModifiedOnSortLabel",
            new StringResourceModel("accessModifiedOn", null));
    accessModifiedOnSort.add(accessModifiedOnSortLabel);
    add(accessModifiedOnSort);

    //Data:
    provider = new SiteSearchResultDataProvider();
    final DataView<SiteSearchResult> dataView = new DataView<SiteSearchResult>("searchResult", provider) {
        @Override
        public void populateItem(final Item item) {
            final SiteSearchResult siteSearchResult = (SiteSearchResult) item.getModelObject();
            AjaxLink<Void> siteTitleLink = new AjaxLink("siteTitleLink") {
                private static final long serialVersionUID = 1L;

                public void onClick(AjaxRequestTarget target) {
                    if (siteSearchResult.getSiteUrl() != null) {
                        //redirect the user to the site
                        target.appendJavascript("popupWindow('" + siteSearchResult.getSiteUrl() + "', '"
                                + new StringResourceModel("popupBlockWarning", null).getObject() + "')");
                    }
                }
            };
            siteTitleLink.add(new Label("siteTitle", siteSearchResult.getSiteTitle()));
            item.add(siteTitleLink);
            final String siteRef = siteSearchResult.getSiteReference();
            final String siteId = siteSearchResult.getSiteId();
            item.add(new Label("siteId", siteId));
            item.add(new Label("term", siteSearchResult.getSiteTerm()));
            item.add(new Label("instructor", new AbstractReadOnlyModel<String>() {
                @Override
                public String getObject() {
                    return siteSearchResult.getInstructorsString();
                }

            }));
            item.add(new Link<Void>("instructorLookupLink") {
                private static final long serialVersionUID = 1L;

                public void onClick() {
                    boolean foundInstructors = false;
                    for (User user : sakaiProxy.getInstructorsForSite(siteId)) {
                        siteSearchResult.addInstructor(user);
                        foundInstructors = true;
                    }
                    if (!foundInstructors) {
                        siteSearchResult.setHasInstructor(false);
                    }
                }

                @Override
                public boolean isVisible() {
                    return (instructorField == null || "".equals(instructorField))
                            && siteSearchResult.isHasInstructor()
                            && siteSearchResult.getInstructors().size() == 0;
                }
            });
            item.add(new Label("providers", new AbstractReadOnlyModel<String>() {
                @Override
                public String getObject() {
                    return siteSearchResult.getProviders();
                }
            }) {
                @Override
                public boolean isVisible() {
                    return !isShoppingPeriodTool() && sakaiProxy.isProviderIdLookupEnabled();
                }
            });
            item.add(new Link<Void>("providersLookupLink") {
                private static final long serialVersionUID = 1L;

                public void onClick() {
                    String providers = sakaiProxy.getProviderId(siteRef);
                    if (providers == null || "".equals(providers)) {
                        //set it to a empty space so that the link will hide itself
                        providers = " ";
                    }
                    siteSearchResult.setProviders(providers);
                }

                @Override
                public boolean isVisible() {
                    return !isShoppingPeriodTool() && sakaiProxy.isProviderIdLookupEnabled()
                            && "".equals(siteSearchResult.getProviders());
                }
            });

            StringResourceModel publishedModel = siteSearchResult.isSitePublished()
                    ? new StringResourceModel("yes", null)
                    : new StringResourceModel("no", null);
            item.add(new Label("published", publishedModel) {
                @Override
                public boolean isVisible() {
                    return !isShoppingPeriodTool();
                }
            });
            String access = isShoppingPeriodTool() ? siteSearchResult.getAccessRoleString()
                    : siteSearchResult.getAccessString();
            item.add(new Label("access", access));
            item.add(new Label("startDate", siteSearchResult.getShoppingPeriodStartDateStr()) {
                @Override
                public boolean isVisible() {
                    //this helps hide all the extra columns with the wicket:enclosure in the html
                    return statistics;
                }
            });
            item.add(new Label("endDate", siteSearchResult.getShoppingPeriodEndDateStr()));
            item.add(new Label("showAuthTools", siteSearchResult.getAuthToolsString(toolsMap)));
            item.add(new Label("showPublicTools", siteSearchResult.getPublicToolsString(toolsMap)));
            item.add(new Label("accessModifiedBy", siteSearchResult.getModifiedBySortName()) {
                @Override
                public boolean isVisible() {
                    //this helps hide all the extra columns with the wicket:enclosure in the html
                    return !isShoppingPeriodTool();
                }
            });
            item.add(new Label("accessModified", siteSearchResult.getModifiedStr()));
        }

        @Override
        public boolean isVisible() {
            return provider.size() > 0;
        }
    };
    dataView.setItemReuseStrategy(new DefaultItemReuseStrategy());
    dataView.setItemsPerPage(DelegatedAccessConstants.SEARCH_RESULTS_PAGE_SIZE);
    add(dataView);

    IModel<File> exportSearchModel = new AbstractReadOnlyModel<File>() {

        @Override
        public File getObject() {
            List<SiteSearchResult> data = provider.getData();
            try {
                String seperator = ",";
                String lineBreak = "\n";
                File file = File.createTempFile(
                        new StringResourceModel("searchExportFileName", null).getObject(), ".csv");
                FileWriter writer = new FileWriter(file.getAbsolutePath());
                //write headers:
                StringBuffer sb = new StringBuffer();
                if (siteTitleSort.isVisible()) {
                    sb.append("\"");
                    sb.append(siteTitleLabel.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (instructorSort.isVisible()) {
                    sb.append("\"");
                    sb.append(instructorSortLabel.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (termSort.isVisible()) {
                    sb.append("\"");
                    sb.append(termSortLabel.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (siteIdSort.isVisible()) {
                    sb.append("\"");
                    sb.append(siteIdSortLabel.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (providersSort.isVisible()) {
                    sb.append("\"");
                    sb.append(providersSortLabel.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (publishedSort.isVisible()) {
                    sb.append("\"");
                    sb.append(publishedSortLabel.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (accessSort.isVisible()) {
                    sb.append("\"");
                    sb.append(accessSortLabel.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (startDateSort.isVisible()) {
                    sb.append("\"");
                    sb.append(startDateSortLabel.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (endDateSort.isVisible()) {
                    sb.append("\"");
                    sb.append(endDateSortLabel.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (showAuthToolsHeader.isVisible()) {
                    sb.append("\"");
                    sb.append(showAuthToolsHeader.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (showPublicToolsHeader.isVisible()) {
                    sb.append("\"");
                    sb.append(showPublicToolsHeader.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (accessModifiedBySort.isVisible()) {
                    sb.append("\"");
                    sb.append(accessModifiedBySortLabel.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                if (accessModifiedOnSort.isVisible()) {
                    sb.append("\"");
                    sb.append(accessModifiedOnSortLabel.getDefaultModelObjectAsString());
                    sb.append("\"");
                    sb.append(seperator);
                }
                sb.append(lineBreak);

                String yes = new StringResourceModel("yes", null).getObject();
                String no = new StringResourceModel("no", null).getObject();

                for (SiteSearchResult siteSearchResult : data) {
                    if (siteTitleSort.isVisible()) {
                        sb.append("\"");
                        sb.append(siteSearchResult.getSiteTitle());
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (instructorSort.isVisible()) {
                        if (siteSearchResult.isHasInstructor()
                                && siteSearchResult.getInstructors().size() == 0) {
                            //we need to look up instructor:
                            boolean foundInstructors = false;
                            for (User user : sakaiProxy.getInstructorsForSite(siteSearchResult.getSiteId())) {
                                siteSearchResult.addInstructor(user);
                                foundInstructors = true;
                            }
                            if (!foundInstructors) {
                                siteSearchResult.setHasInstructor(false);
                            }
                        }
                        sb.append("\"");
                        sb.append(siteSearchResult.getInstructorsString());
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (termSort.isVisible()) {
                        sb.append("\"");
                        sb.append(siteSearchResult.getSiteTerm());
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (siteIdSort.isVisible()) {
                        sb.append("\"");
                        sb.append(siteSearchResult.getSiteId());
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (providersSort.isVisible()) {
                        if ("".equals(siteSearchResult.getProviders())) {
                            //look up providers if it isn't already set
                            siteSearchResult.setProviders(
                                    sakaiProxy.getProviderId(siteSearchResult.getSiteReference()));
                        }
                        sb.append("\"");
                        sb.append(siteSearchResult.getProviders());
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (publishedSort.isVisible()) {
                        sb.append("\"");
                        sb.append((siteSearchResult.isSitePublished() ? yes : no));
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (accessSort.isVisible()) {
                        sb.append("\"");
                        sb.append((isShoppingPeriodTool() ? siteSearchResult.getAccessRoleString()
                                : siteSearchResult.getAccessString()));
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (startDateSort.isVisible()) {
                        sb.append("\"");
                        sb.append(siteSearchResult.getShoppingPeriodStartDateStr());
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (endDateSort.isVisible()) {
                        sb.append("\"");
                        sb.append(siteSearchResult.getShoppingPeriodEndDateStr());
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (showAuthToolsHeader.isVisible()) {
                        sb.append("\"");
                        sb.append(siteSearchResult.getAuthToolsString(toolsMap));
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (showPublicToolsHeader.isVisible()) {
                        sb.append("\"");
                        sb.append(siteSearchResult.getPublicToolsString(toolsMap));
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (accessModifiedBySort.isVisible()) {
                        sb.append("\"");
                        sb.append(siteSearchResult.getModifiedBySortName());
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    if (accessModifiedOnSort.isVisible()) {
                        sb.append("\"");
                        sb.append(siteSearchResult.getModifiedStr());
                        sb.append("\"");
                        sb.append(seperator);
                    }
                    sb.append(lineBreak);
                }

                writer.append(sb.toString());
                writer.flush();
                writer.close();

                return file;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                return null;
            }
        }
    };

    add(new DownloadLink("exportData", exportSearchModel) {
        @Override
        public void onClick() {
            Object fileObj = getModelObject();
            if (fileObj != null && fileObj instanceof File) {
                File file = (File) fileObj;
                IResourceStream resourceStream = new FileResourceStream(
                        new org.apache.wicket.util.file.File(file));
                getRequestCycle().setRequestTarget(
                        new ResourceStreamRequestTarget(resourceStream, file.getName()).setFileName(
                                new StringResourceModel("searchExportFileName", null).getObject() + ".csv"));
            }
        }
    });

    //Navigation
    //add a pager to our table, only visible if we have more than SEARCH_RESULTS_PAGE_SIZE items
    add(new PagingNavigator("navigatorTop", dataView) {

        @Override
        public boolean isVisible() {
            if (provider.size() > DelegatedAccessConstants.SEARCH_RESULTS_PAGE_SIZE) {
                return true;
            }
            return false;
        }

        @Override
        public void onBeforeRender() {
            super.onBeforeRender();

            //clear the feedback panel messages
            clearFeedback(feedbackPanel);
        }
    });
    add(new PagingNavigator("navigatorBottom", dataView) {

        @Override
        public boolean isVisible() {
            if (provider.size() > DelegatedAccessConstants.SEARCH_RESULTS_PAGE_SIZE) {
                return true;
            }
            return false;
        }

        @Override
        public void onBeforeRender() {
            super.onBeforeRender();

            //clear the feedback panel messages
            clearFeedback(feedbackPanel);
        }
    });

}

From source file:org.sakaiproject.profile2.tool.pages.MyPictures.java

License:Educational Community License

/**
 * Populates gallery using GalleryImageDataProvider for given user. The
 * pageToDisplay allows us to return the user to the gallery page they were
 * previously viewing after removing an image from the gallery.
 *//*from  w ww  .  j a v  a  2 s  . com*/
private void populateGallery(Form galleryForm, final String userUuid, long pageToDisplay) {

    IDataProvider dataProvider = new GalleryImageDataProvider(userUuid);

    long numImages = dataProvider.size();

    gridView = new GridView("rows", dataProvider) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(Item item) {

            final GalleryImage image = (GalleryImage) item.getModelObject();

            final GalleryImageRenderer galleryImageThumbnailRenderer = new GalleryImageRenderer(
                    "galleryImageThumbnailRenderer", image.getThumbnailResource());

            AjaxLink galleryImageLink = new AjaxLink("galleryItem") {

                public void onClick(AjaxRequestTarget target) {
                    setResponsePage(new MyPicture(userUuid, image, getCurrentPage()));
                }

            };
            galleryImageLink.add(galleryImageThumbnailRenderer);

            item.add(galleryImageLink);
        }

        @Override
        protected void populateEmptyItem(Item item) {

            Link galleryImageLink = new Link("galleryItem") {
                @Override
                public void onClick() {

                }
            };

            galleryImageLink.add(new Label("galleryImageThumbnailRenderer"));
            item.add(galleryImageLink);
        }
    };
    gridView.setRows(3);
    gridView.setColumns(4);

    galleryForm.add(gridView);

    Label noPicturesLabel;

    //pager
    if (numImages == 0) {
        galleryForm.add(new PagingNavigator("navigator", gridView).setVisible(false));
        noPicturesLabel = new Label("noPicturesLabel", new ResourceModel("text.gallery.pictures.num.none"));
    } else if (numImages <= ProfileConstants.MAX_GALLERY_IMAGES_PER_PAGE) {
        galleryForm.add(new PagingNavigator("navigator", gridView).setVisible(false));
        noPicturesLabel = new Label("noPicturesLabel");
        noPicturesLabel.setVisible(false);
    } else {
        galleryForm.add(new PagingNavigator("navigator", gridView));
        noPicturesLabel = new Label("noPicturesLabel");
        noPicturesLabel.setVisible(false);
    }

    galleryForm.add(noPicturesLabel);

    // set page to display
    if (pageToDisplay > 0) {
        if (pageToDisplay < gridView.getPageCount()) {
            gridView.setCurrentPage(pageToDisplay);
        } else {
            // default to last page for add/remove operations
            gridView.setCurrentPage(gridView.getPageCount() - 1);
        }
    } else {
        gridView.setCurrentPage(0);
    }
}

From source file:org.sakaiproject.profile2.tool.pages.MyProfile.java

License:Educational Community License

/**
 * Does the actual rendering of the page
 * @param userUuid/*from w  w w  . j av a  2s . c o m*/
 */
private void renderMyProfile(final String userUuid) {

    //don't do this for super users viewing other people's profiles as otherwise there is no way back to own profile
    if (!sakaiProxy.isSuperUserAndProxiedToUser(userUuid)) {
        disableLink(myProfileLink);
    }

    //add the feedback panel for any error messages
    FeedbackPanel feedbackPanel = new FeedbackPanel("feedbackPanel");
    add(feedbackPanel);
    feedbackPanel.setVisible(false); //hide by default

    //get the prefs record, or a default if none exists yet
    final ProfilePreferences prefs = preferencesLogic.getPreferencesRecordForUser(userUuid);

    //if null, throw exception
    if (prefs == null) {
        throw new ProfilePreferencesNotDefinedException(
                "Couldn't create default preferences record for " + userUuid);
    }

    //get SakaiPerson for this user
    SakaiPerson sakaiPerson = sakaiProxy.getSakaiPerson(userUuid);
    //if null, create one 
    if (sakaiPerson == null) {
        log.warn("No SakaiPerson for " + userUuid + ". Creating one.");
        sakaiPerson = sakaiProxy.createSakaiPerson(userUuid);
        //if its still null, throw exception
        if (sakaiPerson == null) {
            throw new ProfileNotDefinedException("Couldn't create a SakaiPerson for " + userUuid);
        }
        //post create event
        sakaiProxy.postEvent(ProfileConstants.EVENT_PROFILE_NEW, userUuid, true);
    }

    //post view event
    sakaiProxy.postEvent(ProfileConstants.EVENT_PROFILE_VIEW_OWN, "/profile/" + userUuid, false);

    //get some values from SakaiPerson or SakaiProxy if empty
    //SakaiPerson returns NULL strings if value is not set, not blank ones

    //these must come from Account to keep it all in sync
    //we *could* get a User object here and get the values.
    String userDisplayName = sakaiProxy.getUserDisplayName(userUuid);
    /*
    String userFirstName = sakaiProxy.getUserFirstName(userId);
    String userLastName = sakaiProxy.getUserLastName(userId);
    */

    String userEmail = sakaiProxy.getUserEmail(userUuid);

    //create instance of the UserProfile class
    //we then pass the userProfile in the constructor to the child panels
    final UserProfile userProfile = new UserProfile();

    //get rest of values from SakaiPerson and setup UserProfile
    userProfile.setUserUuid(userUuid);

    userProfile.setNickname(sakaiPerson.getNickname());
    userProfile.setDateOfBirth(sakaiPerson.getDateOfBirth());
    userProfile.setDisplayName(userDisplayName);
    //userProfile.setFirstName(userFirstName);
    //userProfile.setLastName(userLastName);
    //userProfile.setMiddleName(sakaiPerson.getInitials());

    userProfile.setEmail(userEmail);
    userProfile.setHomepage(sakaiPerson.getLabeledURI());
    userProfile.setHomephone(sakaiPerson.getHomePhone());
    userProfile.setWorkphone(sakaiPerson.getTelephoneNumber());
    userProfile.setMobilephone(sakaiPerson.getMobile());
    userProfile.setFacsimile(sakaiPerson.getFacsimileTelephoneNumber());

    userProfile.setDepartment(sakaiPerson.getOrganizationalUnit());
    userProfile.setPosition(sakaiPerson.getTitle());
    userProfile.setSchool(sakaiPerson.getCampus());
    userProfile.setRoom(sakaiPerson.getRoomNumber());

    userProfile.setCourse(sakaiPerson.getEducationCourse());
    userProfile.setSubjects(sakaiPerson.getEducationSubjects());

    userProfile.setStaffProfile(sakaiPerson.getStaffProfile());
    userProfile.setAcademicProfileUrl(sakaiPerson.getAcademicProfileUrl());
    userProfile.setUniversityProfileUrl(sakaiPerson.getUniversityProfileUrl());
    userProfile.setPublications(sakaiPerson.getPublications());

    // business fields
    userProfile.setBusinessBiography(sakaiPerson.getBusinessBiography());
    userProfile.setCompanyProfiles(profileLogic.getCompanyProfiles(userUuid));

    userProfile.setFavouriteBooks(sakaiPerson.getFavouriteBooks());
    userProfile.setFavouriteTvShows(sakaiPerson.getFavouriteTvShows());
    userProfile.setFavouriteMovies(sakaiPerson.getFavouriteMovies());
    userProfile.setFavouriteQuotes(sakaiPerson.getFavouriteQuotes());
    userProfile.setPersonalSummary(sakaiPerson.getNotes());

    // social networking fields
    SocialNetworkingInfo socialInfo = profileLogic.getSocialNetworkingInfo(userProfile.getUserUuid());
    if (socialInfo == null) {
        socialInfo = new SocialNetworkingInfo();
    }
    userProfile.setSocialInfo(socialInfo);

    //PRFL-97 workaround. SakaiPerson table needs to be upgraded so locked is not null, but this handles it if not upgraded.
    if (sakaiPerson.getLocked() == null) {
        userProfile.setLocked(false);
        this.setLocked(false);
    } else {
        this.setLocked(sakaiPerson.getLocked());
        userProfile.setLocked(this.isLocked());
    }

    //what type of picture changing method do we use?
    int profilePictureType = sakaiProxy.getProfilePictureType();

    //change picture panel (upload or url depending on property)
    final Panel changePicture;

    //render appropriate panel with appropriate constructor ie if superUser etc
    if (profilePictureType == ProfileConstants.PICTURE_SETTING_UPLOAD) {

        if (sakaiProxy.isSuperUserAndProxiedToUser(userUuid)) {
            changePicture = new ChangeProfilePictureUpload("changePicture", userUuid);
        } else {
            changePicture = new ChangeProfilePictureUpload("changePicture");
        }
    } else if (profilePictureType == ProfileConstants.PICTURE_SETTING_URL) {
        if (sakaiProxy.isSuperUserAndProxiedToUser(userUuid)) {
            changePicture = new ChangeProfilePictureUrl("changePicture", userUuid);
        } else {
            changePicture = new ChangeProfilePictureUrl("changePicture");
        }
    } else if (profilePictureType == ProfileConstants.PICTURE_SETTING_OFFICIAL) {
        //cannot edit anything if using official images
        changePicture = new EmptyPanel("changePicture");
    } else {
        //no valid option for changing picture was returned from the Profile2 API.
        log.error("Invalid picture type returned: " + profilePictureType);
        changePicture = new EmptyPanel("changePicture");
    }
    changePicture.setOutputMarkupPlaceholderTag(true);
    changePicture.setVisible(false);
    add(changePicture);

    //add the current picture
    add(new ProfileImage("photo", new Model<String>(userUuid)));

    //change profile image button
    AjaxLink<Void> changePictureLink = new AjaxLink<Void>("changePictureLink") {
        private static final long serialVersionUID = 1L;

        public void onClick(AjaxRequestTarget target) {

            //show the panel
            changePicture.setVisible(true);
            target.add(changePicture);

            //resize iframe to fit it
            target.appendJavaScript("resizeFrame('grow');");
        }

    };
    changePictureLink.add(new Label("changePictureLabel", new ResourceModel("link.change.profile.picture")));

    //is picture changing disabled? (property, or locked)
    if ((!sakaiProxy.isProfilePictureChangeEnabled() || userProfile.isLocked()) && !sakaiProxy.isSuperUser()) {
        changePictureLink.setEnabled(false);
        changePictureLink.setVisible(false);
    }

    //if using official images, is the user allowed to select an alternate?
    //or have they specified the official image in their preferences.
    if (sakaiProxy.isOfficialImageEnabledGlobally()
            && (!sakaiProxy.isUsingOfficialImageButAlternateSelectionEnabled() || prefs.isUseOfficialImage())) {
        changePictureLink.setEnabled(false);
        changePictureLink.setVisible(false);
    }

    add(changePictureLink);

    /* SIDELINKS */
    WebMarkupContainer sideLinks = new WebMarkupContainer("sideLinks");
    int visibleSideLinksCount = 0;

    //ADMIN: ADD AS CONNECTION
    if (sakaiProxy.isSuperUserAndProxiedToUser(userUuid)) {

        //init
        boolean friend = false;
        boolean friendRequestToThisPerson = false;
        boolean friendRequestFromThisPerson = false;
        String currentUserUuid = sakaiProxy.getCurrentUserId();
        String nickname = userProfile.getNickname();
        if (StringUtils.isBlank(nickname)) {
            nickname = "";
        }

        //setup model to store the actions in the modal windows
        final FriendAction friendActionModel = new FriendAction();

        //setup friend status
        friend = connectionsLogic.isUserXFriendOfUserY(userUuid, currentUserUuid);
        if (!friend) {
            friendRequestToThisPerson = connectionsLogic.isFriendRequestPending(currentUserUuid, userUuid);
        }
        if (!friend && !friendRequestToThisPerson) {
            friendRequestFromThisPerson = connectionsLogic.isFriendRequestPending(userUuid, currentUserUuid);
        }

        WebMarkupContainer addFriendContainer = new WebMarkupContainer("addFriendContainer");
        final ModalWindow addFriendWindow = new ModalWindow("addFriendWindow");

        //link
        final AjaxLink<Void> addFriendLink = new AjaxLink<Void>("addFriendLink") {
            private static final long serialVersionUID = 1L;

            public void onClick(AjaxRequestTarget target) {
                addFriendWindow.show(target);
            }
        };
        final Label addFriendLabel = new Label("addFriendLabel");
        addFriendLink.add(addFriendLabel);
        addFriendContainer.add(addFriendLink);

        //setup link/label and windows
        if (friend) {
            addFriendLabel.setDefaultModel(new ResourceModel("text.friend.confirmed"));
            addFriendLink.add(new AttributeModifier("class", true,
                    new Model<String>("instruction icon connection-confirmed")));
            addFriendLink.setEnabled(false);
        } else if (friendRequestToThisPerson) {
            addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested"));
            addFriendLink.add(new AttributeModifier("class", true,
                    new Model<String>("instruction icon connection-request")));
            addFriendLink.setEnabled(false);
        } else if (friendRequestFromThisPerson) {
            //TODO (confirm pending friend request link)
            //could be done by setting the content off the addFriendWindow.
            //will need to rename some links to make more generic and set the onClick and setContent in here for link and window
            addFriendLabel.setDefaultModel(new ResourceModel("text.friend.pending"));
            addFriendLink.add(new AttributeModifier("class", true,
                    new Model<String>("instruction icon connection-request")));
            addFriendLink.setEnabled(false);
        } else {
            addFriendLabel.setDefaultModel(
                    new StringResourceModel("link.friend.add.name", null, new Object[] { nickname }));
            addFriendLink.add(new AttributeModifier("class", true, new Model<String>("icon connection-add")));
            addFriendWindow.setContent(new AddFriend(addFriendWindow.getContentId(), addFriendWindow,
                    friendActionModel, currentUserUuid, userUuid));
        }

        sideLinks.add(addFriendContainer);

        //ADD FRIEND MODAL WINDOW HANDLER 
        addFriendWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
            private static final long serialVersionUID = 1L;

            public void onClose(AjaxRequestTarget target) {
                if (friendActionModel.isRequested()) {
                    //friend was successfully requested, update label and link
                    addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested"));
                    addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction")));
                    addFriendLink.setEnabled(false);
                    target.add(addFriendLink);
                }
            }
        });

        add(addFriendWindow);

        if (sakaiProxy.isConnectionsEnabledGlobally()) {
            visibleSideLinksCount++;
        } else {
            addFriendContainer.setVisible(false);
        }

        //ADMIN: LOCK/UNLOCK A PROFILE
        WebMarkupContainer lockProfileContainer = new WebMarkupContainer("lockProfileContainer");
        final Label lockProfileLabel = new Label("lockProfileLabel");

        final AjaxLink<Void> lockProfileLink = new AjaxLink<Void>("lockProfileLink") {
            private static final long serialVersionUID = 1L;

            public void onClick(AjaxRequestTarget target) {
                //toggle it to be opposite of what it currently is, update labels and icons
                boolean locked = isLocked();
                if (sakaiProxy.toggleProfileLocked(userUuid, !locked)) {
                    setLocked(!locked);
                    log.info("MyProfile(): SuperUser toggled lock status of profile for " + userUuid + " to "
                            + !locked);
                    lockProfileLabel.setDefaultModel(new ResourceModel("link.profile.locked." + isLocked()));
                    add(new AttributeModifier("title", true,
                            new ResourceModel("text.profile.locked." + isLocked())));
                    if (isLocked()) {
                        add(new AttributeModifier("class", true, new Model<String>("icon locked")));
                    } else {
                        add(new AttributeModifier("class", true, new Model<String>("icon unlocked")));
                    }
                    target.add(this);
                }
            }
        };

        //set init icon for locked
        if (isLocked()) {
            lockProfileLink.add(new AttributeModifier("class", true, new Model<String>("icon locked")));
        } else {
            lockProfileLink.add(new AttributeModifier("class", true, new Model<String>("icon unlocked")));
        }

        lockProfileLink.add(lockProfileLabel);

        //setup link/label and windows with special property based on locked status
        lockProfileLabel.setDefaultModel(new ResourceModel("link.profile.locked." + isLocked()));
        lockProfileLink.add(
                new AttributeModifier("title", true, new ResourceModel("text.profile.locked." + isLocked())));

        lockProfileContainer.add(lockProfileLink);

        sideLinks.add(lockProfileContainer);

        visibleSideLinksCount++;

    } else {
        //blank components
        WebMarkupContainer addFriendContainer = new WebMarkupContainer("addFriendContainer");
        addFriendContainer.add(new AjaxLink("addFriendLink") {
            public void onClick(AjaxRequestTarget target) {
            }
        }).add(new Label("addFriendLabel"));
        sideLinks.add(addFriendContainer);
        add(new WebMarkupContainer("addFriendWindow"));

        WebMarkupContainer lockProfileContainer = new WebMarkupContainer("lockProfileContainer");
        lockProfileContainer.add(new AjaxLink("lockProfileLink") {
            public void onClick(AjaxRequestTarget target) {
            }
        }).add(new Label("lockProfileLabel"));
        sideLinks.add(lockProfileContainer);
    }

    //hide entire list if no links to show
    if (visibleSideLinksCount == 0) {
        sideLinks.setVisible(false);
    }

    add(sideLinks);

    //status panel
    Panel myStatusPanel = new MyStatusPanel("myStatusPanel", userProfile);
    add(myStatusPanel);

    List<ITab> tabs = new ArrayList<ITab>();

    AjaxTabbedPanel tabbedPanel = new AjaxTabbedPanel("myProfileTabs", tabs) {

        private static final long serialVersionUID = 1L;

        // overridden so we can add tooltips to tabs
        @Override
        protected WebMarkupContainer newLink(String linkId, final int index) {
            WebMarkupContainer link = super.newLink(linkId, index);

            if (ProfileConstants.TAB_INDEX_PROFILE == index) {
                link.add(new AttributeModifier("title", true, new ResourceModel("link.tab.profile.tooltip")));

            } else if (ProfileConstants.TAB_INDEX_WALL == index) {
                link.add(new AttributeModifier("title", true, new ResourceModel("link.tab.wall.tooltip")));
            }
            return link;
        }
    };

    CookieUtils utils = new CookieUtils();
    Cookie tabCookie = utils.getCookie(ProfileConstants.TAB_COOKIE);

    if (sakaiProxy.isProfileFieldsEnabled()) {
        tabs.add(new AbstractTab(new ResourceModel("link.tab.profile")) {

            private static final long serialVersionUID = 1L;

            @Override
            public Panel getPanel(String panelId) {

                setTabCookie(ProfileConstants.TAB_INDEX_PROFILE);
                MyProfilePanelState panelState = new MyProfilePanelState();
                panelState.showBusinessDisplay = sakaiProxy.isBusinessProfileEnabled();
                panelState.showSocialNetworkingDisplay = sakaiProxy.isSocialProfileEnabled();
                panelState.showInterestsDisplay = sakaiProxy.isInterestsProfileEnabled();
                panelState.showStaffDisplay = sakaiProxy.isStaffProfileEnabled();
                panelState.showStudentDisplay = sakaiProxy.isStudentProfileEnabled();
                return new MyProfilePanel(panelId, userProfile, panelState);
            }

        });
    }

    if (true == sakaiProxy.isWallEnabledGlobally()) {

        tabs.add(new AbstractTab(new ResourceModel("link.tab.wall")) {

            private static final long serialVersionUID = 1L;

            @Override
            public Panel getPanel(String panelId) {

                setTabCookie(ProfileConstants.TAB_INDEX_WALL);
                if (true == sakaiProxy.isSuperUser()) {
                    return new MyWallPanel(panelId, userUuid);
                } else {
                    return new MyWallPanel(panelId);
                }
            }
        });

        if (true == sakaiProxy.isWallDefaultProfilePage() && null == tabCookie) {

            tabbedPanel.setSelectedTab(ProfileConstants.TAB_INDEX_WALL);
        }
    }

    if (null != tabCookie) {
        try {
            tabbedPanel.setSelectedTab(Integer.parseInt(tabCookie.getValue()));
        } catch (IndexOutOfBoundsException e) {
            //do nothing. This will be thrown if the cookie contains a value > the number of tabs but thats ok.
        }
    }

    add(tabbedPanel);

    //kudos panel
    add(new AjaxLazyLoadPanel("myKudos") {
        private static final long serialVersionUID = 1L;

        @Override
        public Component getLazyLoadComponent(String markupId) {
            if (sakaiProxy.isMyKudosEnabledGlobally() && prefs.isShowKudos()) {

                int score = kudosLogic.getKudos(userUuid);
                if (score > 0) {
                    return new KudosPanel(markupId, userUuid, userUuid, score);
                }
            }
            return new EmptyPanel(markupId);
        }
    });

    //friends feed panel for self - lazy loaded
    add(new NotifyingAjaxLazyLoadPanel("friendsFeed") {
        private static final long serialVersionUID = 1L;

        @Override
        public Component getLazyLoadComponent(String markupId) {
            if (sakaiProxy.isConnectionsEnabledGlobally()) {
                return new FriendsFeed(markupId, userUuid, userUuid);
            }
            return new EmptyPanel(markupId);
        }

        @Override
        public void renderHead(IHeaderResponse response) {
            response.render(OnLoadHeaderItem.forScript("resizeFrame('grow');"));
        }
    });

    //gallery feed panel
    add(new NotifyingAjaxLazyLoadPanel("galleryFeed") {
        private static final long serialVersionUID = 1L;

        @Override
        public Component getLazyLoadComponent(String markupId) {
            if (sakaiProxy.isProfileGalleryEnabledGlobally() && prefs.isShowGalleryFeed()) {
                return new GalleryFeed(markupId, userUuid, userUuid).setOutputMarkupId(true);
            } else {
                return new EmptyPanel(markupId);
            }
        }

        @Override
        public void renderHead(IHeaderResponse response) {
            response.render(OnLoadHeaderItem.forScript("resizeFrame('grow');"));
        }

    });
}

From source file:org.sakaiproject.profile2.tool.pages.MySearch.java

License:Educational Community License

public MySearch() {

    log.debug("MySearch()");

    disableLink(searchLink);/*from   w  w  w .j  a v  a  2  s. c o  m*/

    //check for current search cookie    
    CookieUtils utils = new CookieUtils();
    searchCookie = utils.getCookie(ProfileConstants.SEARCH_COOKIE);

    //setup model to store the actions in the modal windows
    final FriendAction friendActionModel = new FriendAction();

    //get current user info
    final String currentUserUuid = sakaiProxy.getCurrentUserId();
    final String currentUserType = sakaiProxy.getUserType(currentUserUuid);

    /*
     * Combined search form 
     */

    //heading
    Label searchHeading = new Label("searchHeading", new ResourceModel("heading.search"));
    add(searchHeading);

    //setup form
    final StringModel searchStringModel = new StringModel();
    Form<StringModel> searchForm = new Form<StringModel>("searchForm",
            new Model<StringModel>(searchStringModel));
    searchForm.setOutputMarkupId(true);

    //search field
    searchForm.add(new Label("searchLabel", new ResourceModel("text.search.terms.label")));
    searchField = new TextField<String>("searchField", new PropertyModel<String>(searchStringModel, "string"));
    searchField.setRequired(true);
    searchField.setMarkupId("searchinput");
    searchField.setOutputMarkupId(true);
    searchForm.add(searchField);
    searchForm.add(new IconWithClueTip("searchToolTip", ProfileConstants.INFO_IMAGE,
            new ResourceModel("text.search.terms.tooltip")));

    //by name or by interest radio group        
    searchTypeRadioGroup = new RadioGroup<String>("searchTypeRadioGroup");
    // so we can repaint after clicking on search history links
    searchTypeRadioGroup.setOutputMarkupId(true);
    searchTypeRadioGroup.setRenderBodyOnly(false);
    Radio<String> searchTypeRadioName = new Radio<String>("searchTypeName",
            new Model<String>(ProfileConstants.SEARCH_TYPE_NAME));
    searchTypeRadioName.setMarkupId("searchtypenameinput");
    searchTypeRadioName.setOutputMarkupId(true);
    searchTypeRadioName
            .add(new AttributeModifier("title", true, new ResourceModel("text.search.byname.tooltip")));
    searchTypeRadioGroup.add(searchTypeRadioName);
    Radio<String> searchTypeRadioInterest = new Radio<String>("searchTypeInterest",
            new Model<String>(ProfileConstants.SEARCH_TYPE_INTEREST));
    searchTypeRadioInterest.setMarkupId("searchtypeinterestinput");
    searchTypeRadioInterest.setOutputMarkupId(true);
    searchTypeRadioInterest
            .add(new AttributeModifier("title", true, new ResourceModel("text.search.byinterest.tooltip")));
    searchTypeRadioGroup.add(searchTypeRadioInterest);
    searchTypeRadioGroup.add(new Label("searchTypeNameLabel", new ResourceModel("text.search.byname.label")));
    searchTypeRadioGroup
            .add(new Label("searchTypeInterestLabel", new ResourceModel("text.search.byinterest.label")));
    searchForm.add(searchTypeRadioGroup);

    searchForm.add(new Label("connectionsLabel", new ResourceModel("text.search.include.connections")));
    // model is true (include connections by default)
    connectionsCheckBox = new CheckBox("connectionsCheckBox", new Model<Boolean>(true));
    connectionsCheckBox.setMarkupId("includeconnectionsinput");
    connectionsCheckBox.setOutputMarkupId(true);
    //hide if connections disabled globally
    connectionsCheckBox.setVisible(sakaiProxy.isConnectionsEnabledGlobally());
    searchForm.add(connectionsCheckBox);

    final List<Site> worksites = sakaiProxy.getUserSites();
    final boolean hasWorksites = worksites.size() > 0;

    searchForm.add(new Label("worksiteLabel", new ResourceModel("text.search.include.worksite")));
    // model is false (include all worksites by default)
    worksiteCheckBox = new CheckBox("worksiteCheckBox", new Model<Boolean>(false));
    worksiteCheckBox.setMarkupId("limittositeinput");
    worksiteCheckBox.setOutputMarkupId(true);
    worksiteCheckBox.setEnabled(hasWorksites);
    searchForm.add(worksiteCheckBox);

    final IModel<String> defaultWorksiteIdModel;
    if (hasWorksites) {
        defaultWorksiteIdModel = new Model<String>(worksites.get(0).getId());
    } else {
        defaultWorksiteIdModel = new ResourceModel("text.search.no.worksite");
    }

    final LinkedHashMap<String, String> worksiteMap = new LinkedHashMap<String, String>();

    if (hasWorksites) {
        for (Site worksite : worksites) {
            worksiteMap.put(worksite.getId(), worksite.getTitle());
        }
    } else {
        worksiteMap.put(defaultWorksiteIdModel.getObject(), defaultWorksiteIdModel.getObject());
    }

    IModel worksitesModel = new Model() {

        public ArrayList<String> getObject() {
            return new ArrayList<String>(worksiteMap.keySet());
        }
    };

    worksiteChoice = new DropDownChoice("worksiteChoice", defaultWorksiteIdModel, worksitesModel,
            new HashMapChoiceRenderer(worksiteMap));
    worksiteChoice.setMarkupId("worksiteselect");
    worksiteChoice.setOutputMarkupId(true);
    worksiteChoice.setNullValid(false);
    worksiteChoice.setEnabled(hasWorksites);
    searchForm.add(worksiteChoice);

    /* 
     * 
     * RESULTS
     * 
     */

    //search results label/container
    numSearchResultsContainer = new WebMarkupContainer("numSearchResultsContainer");
    numSearchResultsContainer.setOutputMarkupPlaceholderTag(true);
    numSearchResults = new Label("numSearchResults");
    numSearchResults.setOutputMarkupId(true);
    numSearchResults.setEscapeModelStrings(false);
    numSearchResultsContainer.add(numSearchResults);

    //clear results button
    Form<Void> clearResultsForm = new Form<Void>("clearResults");
    clearResultsForm.setOutputMarkupPlaceholderTag(true);

    clearButton = new AjaxButton("clearButton", clearResultsForm) {
        private static final long serialVersionUID = 1L;

        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            // clear cookie if present    
            if (null != searchCookie) {
                CookieUtils utils = new CookieUtils();
                utils.remove(ProfileConstants.SEARCH_COOKIE);
            }

            //clear the fields, hide self, then repaint
            searchField.clearInput();
            searchField.updateModel();

            numSearchResultsContainer.setVisible(false);
            resultsContainer.setVisible(false);
            clearButton.setVisible(false);

            target.add(searchField);
            target.add(numSearchResultsContainer);
            target.add(resultsContainer);
            target.add(this);
        }
    };
    clearButton.setOutputMarkupPlaceholderTag(true);
    if (null == searchCookie) {
        clearButton.setVisible(false); //invisible until we have something to clear
    }
    clearButton.setModel(new ResourceModel("button.search.clear"));
    clearResultsForm.add(clearButton);
    numSearchResultsContainer.add(clearResultsForm);

    add(numSearchResultsContainer);

    // model to wrap search results
    LoadableDetachableModel<List<Person>> resultsModel = new LoadableDetachableModel<List<Person>>() {
        private static final long serialVersionUID = 1L;

        protected List<Person> load() {
            return results;
        }
    };

    //container which wraps list
    resultsContainer = new WebMarkupContainer("searchResultsContainer");
    resultsContainer.setOutputMarkupPlaceholderTag(true);
    if (null == searchCookie) {
        resultsContainer.setVisible(false); //hide initially
    }

    //connection window
    final ModalWindow connectionWindow = new ModalWindow("connectionWindow");

    //search results
    final PageableListView<Person> resultsListView = new PageableListView<Person>("searchResults", resultsModel,
            sakaiProxy.getMaxSearchResultsPerPage()) {

        private static final long serialVersionUID = 1L;

        protected void populateItem(final ListItem<Person> item) {

            Person person = (Person) item.getModelObject();

            //get basic values
            final String userUuid = person.getUuid();
            final String displayName = person.getDisplayName();
            final String userType = person.getType();

            //get connection status
            int connectionStatus = connectionsLogic.getConnectionStatus(currentUserUuid, userUuid);
            boolean friend = (connectionStatus == ProfileConstants.CONNECTION_CONFIRMED) ? true : false;

            //image wrapper, links to profile
            Link<String> friendItem = new Link<String>("searchResultPhotoWrap") {
                private static final long serialVersionUID = 1L;

                public void onClick() {
                    setResponsePage(new ViewProfile(userUuid));
                }
            };

            //image
            ProfileImage searchResultPhoto = new ProfileImage("searchResultPhoto", new Model<String>(userUuid));
            searchResultPhoto.setSize(ProfileConstants.PROFILE_IMAGE_THUMBNAIL);
            friendItem.add(searchResultPhoto);

            item.add(friendItem);

            //name and link to profile (if allowed or no link)
            Link<String> profileLink = new Link<String>("searchResultProfileLink",
                    new Model<String>(userUuid)) {
                private static final long serialVersionUID = 1L;

                public void onClick() {
                    //if user found themself, go to own profile, else show other profile
                    if (userUuid.equals(currentUserUuid)) {
                        setResponsePage(new MyProfile());
                    } else {
                        //gets userUuid of other user from the link's model
                        setResponsePage(new ViewProfile((String) getModelObject()));
                    }
                }
            };

            profileLink.add(new Label("searchResultName", displayName));
            item.add(profileLink);

            //status component
            ProfileStatusRenderer status = new ProfileStatusRenderer("searchResultStatus", person,
                    "search-result-status-msg", "search-result-status-date") {
                @Override
                public boolean isVisible() {
                    return sakaiProxy.isProfileStatusEnabled();
                }
            };
            status.setOutputMarkupId(true);
            item.add(status);

            /* ACTIONS */
            boolean isFriendsListVisible = privacyLogic.isActionAllowed(userUuid, currentUserUuid,
                    PrivacyType.PRIVACY_OPTION_MYFRIENDS);
            boolean isConnectionAllowed = sakaiProxy.isConnectionAllowedBetweenUserTypes(userType,
                    currentUserType);

            //ADD CONNECTION LINK
            final WebMarkupContainer c1 = new WebMarkupContainer("connectionContainer");
            c1.setOutputMarkupId(true);

            if (!isConnectionAllowed && !sakaiProxy.isConnectionsEnabledGlobally()) {
                //add blank components - TODO turn this into an EmptyLink component
                AjaxLink<Void> emptyLink = new AjaxLink<Void>("connectionLink") {
                    private static final long serialVersionUID = 1L;

                    public void onClick(AjaxRequestTarget target) {
                    }
                };
                emptyLink.add(new Label("connectionLabel"));
                c1.add(emptyLink);
                c1.setVisible(false);
            } else {
                //render the link
                final Label connectionLabel = new Label("connectionLabel");
                connectionLabel.setOutputMarkupId(true);

                final AjaxLink<String> connectionLink = new AjaxLink<String>("connectionLink",
                        new Model<String>(userUuid)) {
                    private static final long serialVersionUID = 1L;

                    public void onClick(AjaxRequestTarget target) {

                        //get this item, reinit some values and set content for modal
                        final String userUuid = (String) getModelObject();
                        connectionWindow.setContent(new AddFriend(connectionWindow.getContentId(),
                                connectionWindow, friendActionModel, currentUserUuid, userUuid));

                        // connection modal window handler 
                        connectionWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
                            private static final long serialVersionUID = 1L;

                            public void onClose(AjaxRequestTarget target) {
                                if (friendActionModel.isRequested()) {
                                    connectionLabel.setDefaultModel(new ResourceModel("text.friend.requested"));
                                    add(new AttributeModifier("class", true,
                                            new Model<String>("instruction icon connection-request")));
                                    setEnabled(false);
                                    target.add(c1);
                                }
                            }
                        });
                        //in preparation for the window being closed, update the text. this will only
                        //be put into effect if its a successful model update from the window close
                        //connectionLabel.setModel(new ResourceModel("text.friend.requested"));
                        //this.add(new AttributeModifier("class", true, new Model("instruction")));
                        //this.setEnabled(false);
                        //friendActionModel.setUpdateThisComponentOnSuccess(this);

                        connectionWindow.show(target);
                        target.appendJavaScript("fixWindowVertical();");

                    }
                };

                connectionLink.add(connectionLabel);

                //setup 'add connection' link
                if (StringUtils.equals(userUuid, currentUserUuid)) {
                    connectionLabel.setDefaultModel(new ResourceModel("text.friend.self"));
                    connectionLink.add(new AttributeModifier("class", true,
                            new Model<String>("instruction icon profile")));
                    connectionLink.setEnabled(false);
                } else if (friend) {
                    connectionLabel.setDefaultModel(new ResourceModel("text.friend.confirmed"));
                    connectionLink.add(new AttributeModifier("class", true,
                            new Model<String>("instruction icon connection-confirmed")));
                    connectionLink.setEnabled(false);
                } else if (connectionStatus == ProfileConstants.CONNECTION_REQUESTED) {
                    connectionLabel.setDefaultModel(new ResourceModel("text.friend.requested"));
                    connectionLink.add(new AttributeModifier("class", true,
                            new Model<String>("instruction icon connection-request")));
                    connectionLink.setEnabled(false);
                } else if (connectionStatus == ProfileConstants.CONNECTION_INCOMING) {
                    connectionLabel.setDefaultModel(new ResourceModel("text.friend.pending"));
                    connectionLink.add(new AttributeModifier("class", true,
                            new Model<String>("instruction icon connection-request")));
                    connectionLink.setEnabled(false);
                } else {
                    connectionLabel.setDefaultModel(new ResourceModel("link.friend.add"));
                }
                connectionLink.setOutputMarkupId(true);
                c1.add(connectionLink);
            }

            item.add(c1);

            //VIEW FRIENDS LINK
            WebMarkupContainer c2 = new WebMarkupContainer("viewFriendsContainer");
            c2.setOutputMarkupId(true);

            final AjaxLink<String> viewFriendsLink = new AjaxLink<String>("viewFriendsLink") {
                private static final long serialVersionUID = 1L;

                public void onClick(AjaxRequestTarget target) {
                    //if user found themself, go to MyFriends, else, ViewFriends
                    if (userUuid.equals(currentUserUuid)) {
                        setResponsePage(new MyFriends());
                    } else {
                        setResponsePage(new ViewFriends(userUuid));
                    }
                }
            };
            final Label viewFriendsLabel = new Label("viewFriendsLabel",
                    new ResourceModel("link.view.friends"));
            viewFriendsLink.add(viewFriendsLabel);

            //hide if not allowed
            if (!isFriendsListVisible && !sakaiProxy.isConnectionsEnabledGlobally()) {
                viewFriendsLink.setEnabled(false);
                c2.setVisible(false);
            }
            viewFriendsLink.setOutputMarkupId(true);
            c2.add(viewFriendsLink);
            item.add(c2);

            WebMarkupContainer c3 = new WebMarkupContainer("emailContainer");
            c3.setOutputMarkupId(true);

            ExternalLink emailLink = new ExternalLink("emailLink", "mailto:" + person.getProfile().getEmail(),
                    new ResourceModel("profile.email").getObject());

            c3.add(emailLink);

            if (StringUtils.isBlank(person.getProfile().getEmail())
                    || false == privacyLogic.isActionAllowed(person.getUuid(), currentUserUuid,
                            PrivacyType.PRIVACY_OPTION_CONTACTINFO)) {
                c3.setVisible(false);
            }
            item.add(c3);

            WebMarkupContainer c4 = new WebMarkupContainer("websiteContainer");
            c4.setOutputMarkupId(true);

            // TODO home page, university profile URL or academic/research URL (see PRFL-35)
            ExternalLink websiteLink = new ExternalLink("websiteLink", person.getProfile().getHomepage(),
                    new ResourceModel("profile.homepage").getObject()).setPopupSettings(new PopupSettings());

            c4.add(websiteLink);

            if (StringUtils.isBlank(person.getProfile().getHomepage())
                    || false == privacyLogic.isActionAllowed(person.getUuid(), currentUserUuid,
                            PrivacyType.PRIVACY_OPTION_CONTACTINFO)) {

                c4.setVisible(false);
            }
            item.add(c4);

            // TODO personal, academic or business (see PRFL-35)

            if (true == privacyLogic.isActionAllowed(person.getUuid(), currentUserUuid,
                    PrivacyType.PRIVACY_OPTION_BASICINFO)) {

                item.add(new Label("searchResultSummary", StringUtils
                        .abbreviate(ProfileUtils.stripHtml(person.getProfile().getPersonalSummary()), 200)));
            } else {
                item.add(new Label("searchResultSummary", ""));
            }
        }
    };

    resultsListView.add(new MySearchCookieBehavior(resultsListView));
    resultsContainer.add(resultsListView);

    final PagingNavigator searchResultsNavigator = new PagingNavigator("searchResultsNavigator",
            resultsListView);
    searchResultsNavigator.setOutputMarkupId(true);
    searchResultsNavigator.setVisible(false);

    resultsContainer.add(searchResultsNavigator);

    add(connectionWindow);

    //add results container
    add(resultsContainer);

    /*
     * SEARCH HISTORY
     */

    final WebMarkupContainer searchHistoryContainer = new WebMarkupContainer("searchHistoryContainer");
    searchHistoryContainer.setOutputMarkupPlaceholderTag(true);

    Label searchHistoryLabel = new Label("searchHistoryLabel", new ResourceModel("text.search.history"));
    searchHistoryContainer.add(searchHistoryLabel);

    IModel<List<ProfileSearchTerm>> searchHistoryModel = new LoadableDetachableModel<List<ProfileSearchTerm>>() {

        private static final long serialVersionUID = 1L;

        @Override
        protected List<ProfileSearchTerm> load() {
            List<ProfileSearchTerm> searchHistory = searchLogic.getSearchHistory(currentUserUuid);
            if (null == searchHistory) {
                return new ArrayList<ProfileSearchTerm>();
            } else {
                return searchHistory;
            }
        }

    };
    ListView<ProfileSearchTerm> searchHistoryList = new ListView<ProfileSearchTerm>("searchHistoryList",
            searchHistoryModel) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final ListItem<ProfileSearchTerm> item) {

            AjaxLink<String> link = new AjaxLink<String>("previousSearchLink") {

                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    if (null != target) {

                        // post view event
                        sakaiProxy.postEvent(ProfileConstants.EVENT_SEARCH_BY_NAME,
                                "/profile/" + currentUserUuid, false);

                        ProfileSearchTerm searchTerm = item.getModelObject();
                        // this will update its position in list
                        searchLogic.addSearchTermToHistory(currentUserUuid, searchTerm);

                        searchStringModel.setString(searchTerm.getSearchTerm());
                        searchTypeRadioGroup.setModel(new Model<String>(searchTerm.getSearchType()));
                        connectionsCheckBox.setModel(new Model<Boolean>(searchTerm.isConnections()));

                        if (null == searchTerm.getWorksite()) {
                            worksiteCheckBox.setModel(new Model<Boolean>(false));
                            worksiteChoice.setModel(new Model(defaultWorksiteIdModel));
                        } else {
                            worksiteCheckBox.setModel(new Model<Boolean>(true));
                            worksiteChoice.setModel(new Model(searchTerm.getWorksite()));
                        }

                        setSearchCookie(searchTerm.getSearchType(), searchTerm.getSearchTerm(),
                                searchTerm.getSearchPageNumber(), searchTerm.isConnections(),
                                searchTerm.getWorksite());

                        if (ProfileConstants.SEARCH_TYPE_NAME.equals(searchTerm.getSearchType())) {

                            searchByName(resultsListView, searchResultsNavigator, searchHistoryContainer,
                                    target, searchTerm.getSearchTerm(), searchTerm.isConnections(),
                                    searchTerm.getWorksite());

                        } else if (ProfileConstants.SEARCH_TYPE_INTEREST.equals(searchTerm.getSearchType())) {

                            searchByInterest(resultsListView, searchResultsNavigator, searchHistoryContainer,
                                    target, searchTerm.getSearchTerm(), searchTerm.isConnections(),
                                    searchTerm.getWorksite());
                        }
                    }
                }

            };
            link.add(new Label("previousSearchLabel", item.getModelObject().getSearchTerm()));
            item.add(link);
        }
    };

    searchHistoryContainer.add(searchHistoryList);
    add(searchHistoryContainer);

    if (null == searchLogic.getSearchHistory(currentUserUuid)) {
        searchHistoryContainer.setVisible(false);
    }

    //clear button
    Form<Void> clearHistoryForm = new Form<Void>("clearHistory");
    clearHistoryForm.setOutputMarkupPlaceholderTag(true);

    clearHistoryButton = new AjaxButton("clearHistoryButton", clearHistoryForm) {
        private static final long serialVersionUID = 1L;

        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            searchLogic.clearSearchHistory(currentUserUuid);

            //clear the fields, hide self, then repaint
            searchField.clearInput();
            searchField.updateModel();

            searchHistoryContainer.setVisible(false);
            clearHistoryButton.setVisible(false);

            target.add(searchField);
            target.add(searchHistoryContainer);
            target.add(this);
        }
    };
    clearHistoryButton.setOutputMarkupPlaceholderTag(true);

    if (null == searchLogic.getSearchHistory(currentUserUuid)) {
        clearHistoryButton.setVisible(false); //invisible until we have something to clear
    }
    clearHistoryButton.setModel(new ResourceModel("button.search.history.clear"));
    clearHistoryForm.add(clearHistoryButton);
    searchHistoryContainer.add(clearHistoryForm);

    /*
     * Combined search submit
     */
    IndicatingAjaxButton searchSubmitButton = new IndicatingAjaxButton("searchSubmit", searchForm) {

        private static final long serialVersionUID = 1L;

        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            if (target != null) {
                //get the model and text entered
                StringModel model = (StringModel) form.getModelObject();
                //PRFL-811 - dont strip this down, we will lose i18n chars.
                //And there is no XSS risk since its only for the current user.
                String searchText = model.getString();

                //get search type
                String searchType = searchTypeRadioGroup.getModelObject();

                log.debug("MySearch search by " + searchType + ": " + searchText);

                if (StringUtils.isBlank(searchText)) {
                    return;
                }

                // save search terms
                ProfileSearchTerm searchTerm = new ProfileSearchTerm();
                searchTerm.setUserUuid(currentUserUuid);
                searchTerm.setSearchType(searchType);
                searchTerm.setSearchTerm(searchText);
                searchTerm.setSearchPageNumber(0);
                searchTerm.setSearchDate(new Date());
                searchTerm.setConnections(connectionsCheckBox.getModelObject());
                // set to worksite or empty depending on value of checkbox
                searchTerm.setWorksite(
                        (worksiteCheckBox.getModelObject() == true) ? worksiteChoice.getValue() : null);

                searchLogic.addSearchTermToHistory(currentUserUuid, searchTerm);

                // set cookie for current search (page 0 when submitting new search)
                setSearchCookie(searchTerm.getSearchType(), URLEncoder.encode(searchTerm.getSearchTerm()),
                        searchTerm.getSearchPageNumber(), searchTerm.isConnections(), searchTerm.getWorksite());

                if (ProfileConstants.SEARCH_TYPE_NAME.equals(searchType)) {

                    searchByName(resultsListView, searchResultsNavigator, searchHistoryContainer, target,
                            searchTerm.getSearchTerm(), searchTerm.isConnections(), searchTerm.getWorksite());

                    //post view event
                    sakaiProxy.postEvent(ProfileConstants.EVENT_SEARCH_BY_NAME, "/profile/" + currentUserUuid,
                            false);
                } else if (ProfileConstants.SEARCH_TYPE_INTEREST.equals(searchType)) {

                    searchByInterest(resultsListView, searchResultsNavigator, searchHistoryContainer, target,
                            searchTerm.getSearchTerm(), searchTerm.isConnections(), searchTerm.getWorksite());

                    //post view event
                    sakaiProxy.postEvent(ProfileConstants.EVENT_SEARCH_BY_INTEREST,
                            "/profile/" + currentUserUuid, false);
                }
            }
        }
    };
    searchSubmitButton.setModel(new ResourceModel("button.search.generic"));
    searchForm.add(searchSubmitButton);
    add(searchForm);

    if (null != searchCookie) {

        String searchString = getCookieSearchString(searchCookie.getValue());
        searchStringModel.setString(searchString);

        Boolean filterConnections = getCookieFilterConnections(searchCookie.getValue());
        String worksiteId = getCookieFilterWorksite(searchCookie.getValue());
        Boolean filterWorksite = (null == worksiteId) ? false : true;

        connectionsCheckBox.setModel(new Model<Boolean>(filterConnections));
        worksiteCheckBox.setModel(new Model<Boolean>(filterWorksite));
        worksiteChoice.setModel(new Model((null == worksiteId) ? defaultWorksiteIdModel : worksiteId));

        if (searchCookie.getValue().startsWith(ProfileConstants.SEARCH_TYPE_NAME)) {
            searchTypeRadioGroup.setModel(new Model<String>(ProfileConstants.SEARCH_TYPE_NAME));
            searchByName(resultsListView, searchResultsNavigator, searchHistoryContainer, null, searchString,
                    filterConnections, worksiteId);

        } else if (searchCookie.getValue().startsWith(ProfileConstants.SEARCH_TYPE_INTEREST)) {
            searchTypeRadioGroup.setModel(new Model<String>(ProfileConstants.SEARCH_TYPE_INTEREST));
            searchByInterest(resultsListView, searchResultsNavigator, searchHistoryContainer, null,
                    searchString, filterConnections, worksiteId);
        }
    } else {
        // default search type is name
        searchTypeRadioGroup.setModel(new Model<String>(ProfileConstants.SEARCH_TYPE_NAME));
    }
}

From source file:org.sakaiproject.profile2.tool.pages.panels.ConfirmedFriends.java

License:Educational Community License

public ConfirmedFriends(final String id, final String userUuid) {
    super(id);/* ww  w  . j  av  a 2  s  .  co m*/

    log.debug("ConfirmedFriends()");

    //setup model to store the actions in the modal windows
    final FriendAction friendActionModel = new FriendAction();

    //get info for user viewing this page (will be the same if user is viewing own list, different if viewing someone else's)
    final String currentUserUuid = sakaiProxy.getCurrentUserId();
    //User currentUser = sakaiProxy.getUserQuietly(currentUserUuid);
    //final String currentUserType = currentUser.getType(); //to be used for checking if connection between users is allowed, when this is added

    //if viewing own friends, you can manage them.
    if (userUuid.equals(currentUserUuid)) {
        ownList = true;
    }

    //get our list of confirmed friends as an IDataProvider
    ConfirmedFriendsDataProvider provider = new ConfirmedFriendsDataProvider(userUuid);

    //init number of friends
    numConfirmedFriends = (int) provider.size();

    //model so we can update the number of friends
    IModel<Integer> numConfirmedFriendsModel = new Model<Integer>() {
        private static final long serialVersionUID = 1L;

        public Integer getObject() {
            return numConfirmedFriends;
        }
    };

    //heading
    final WebMarkupContainer confirmedFriendsHeading = new WebMarkupContainer("confirmedFriendsHeading");
    Label confirmedFriendsLabel = new Label("confirmedFriendsLabel");
    //if viewing own list, "my friends", else, "their name's friends"
    if (ownList) {
        confirmedFriendsLabel.setDefaultModel(new ResourceModel("heading.friends.my"));
    } else {
        String displayName = sakaiProxy.getUserDisplayName(userUuid);
        confirmedFriendsLabel.setDefaultModel(
                new StringResourceModel("heading.friends.view", null, new Object[] { displayName }));
    }
    confirmedFriendsHeading.add(confirmedFriendsLabel);
    confirmedFriendsHeading.add(new Label("confirmedFriendsNumber", numConfirmedFriendsModel));
    confirmedFriendsHeading.setOutputMarkupId(true);
    add(confirmedFriendsHeading);

    // actions
    Form<Void> confirmedFriendsButtonForm = new Form<Void>("confirmedFriendsButtonForm");
    add(confirmedFriendsButtonForm);

    //create worksite panel
    final CreateWorksitePanel createWorksitePanel = new CreateWorksitePanel("createWorksitePanel",
            connectionsLogic.getConnectionsForUser(userUuid));
    //create placeholder and set invisible initially
    createWorksitePanel.setOutputMarkupPlaceholderTag(true);
    createWorksitePanel.setVisible(false);

    confirmedFriendsButtonForm.add(createWorksitePanel);

    final AjaxButton createWorksiteButton = new AjaxButton("createWorksiteButton", confirmedFriendsButtonForm) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            createWorksitePanel.setVisible(true);
            target.add(createWorksitePanel);
            target.appendJavaScript("fixWindowVertical();");
        }

    };
    createWorksiteButton.setModel(new ResourceModel("link.worksite.create"));
    createWorksiteButton
            .add(new AttributeModifier("title", true, new ResourceModel("link.title.worksite.create")));
    createWorksiteButton.setVisible(sakaiProxy.isUserAllowedAddSite(userUuid));
    confirmedFriendsButtonForm.add(createWorksiteButton);

    //search for connections
    AjaxButton searchConnectionsButton = new AjaxButton("searchConnectionsButton", confirmedFriendsButtonForm) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            setResponsePage(new MySearch());
        }
    };
    searchConnectionsButton.setModel(new ResourceModel("link.my.friends.search"));
    confirmedFriendsButtonForm.add(searchConnectionsButton);

    //container which wraps list
    final WebMarkupContainer confirmedFriendsContainer = new WebMarkupContainer("confirmedFriendsContainer");
    confirmedFriendsContainer.setOutputMarkupId(true);

    //connection window
    final ModalWindow connectionWindow = new ModalWindow("connectionWindow");

    //results
    DataView<Person> confirmedFriendsDataView = new DataView<Person>("connections", provider) {
        private static final long serialVersionUID = 1L;

        protected void populateItem(final Item<Person> item) {

            Person person = (Person) item.getDefaultModelObject();
            final String personUuid = person.getUuid();

            //setup values
            String displayName = person.getDisplayName();
            boolean friend;

            //get friend status
            if (ownList) {
                friend = true; //viewing own page of conenctions, must be friend!
            } else {
                friend = connectionsLogic.isUserXFriendOfUserY(userUuid, personUuid); //other person viewing, check if they are friends
            }

            //get other objects
            ProfilePrivacy privacy = person.getPrivacy();
            ProfilePreferences prefs = person.getPreferences();

            //image wrapper, links to profile
            Link<String> friendItem = new Link<String>("connectionPhotoWrap", new Model<String>(personUuid)) {
                private static final long serialVersionUID = 1L;

                public void onClick() {
                    setResponsePage(new ViewProfile(getModelObject()));
                }
            };

            //image            
            ProfileImage connectionPhoto = new ProfileImage("connectionPhoto", new Model<String>(personUuid));
            connectionPhoto.setSize(ProfileConstants.PROFILE_IMAGE_THUMBNAIL);
            friendItem.add(connectionPhoto);

            item.add(friendItem);

            //name and link to profile
            Link<String> profileLink = new Link<String>("connectionLink", new Model<String>(personUuid)) {
                private static final long serialVersionUID = 1L;

                public void onClick() {
                    setResponsePage(new ViewProfile(getModelObject()));
                }

            };
            profileLink.add(new Label("connectionName", displayName));
            item.add(profileLink);

            //status component
            ProfileStatusRenderer status = new ProfileStatusRenderer("connectionStatus", person,
                    "connection-status-msg", "connection-status-date");
            status.setOutputMarkupId(true);
            item.add(status);

            /* ACTIONS */

            WebMarkupContainer c1 = new WebMarkupContainer("removeConnectionContainer");
            c1.setOutputMarkupId(true);

            //REMOVE FRIEND LINK AND WINDOW
            final AjaxLink<String> removeConnectionLink = new AjaxLink<String>("removeConnectionLink",
                    new Model<String>(personUuid)) {
                private static final long serialVersionUID = 1L;

                public void onClick(AjaxRequestTarget target) {

                    //get this item, and set content for modalwindow
                    String friendUuid = getModelObject();
                    connectionWindow.setContent(new RemoveFriend(connectionWindow.getContentId(),
                            connectionWindow, friendActionModel, userUuid, friendUuid));

                    //modalwindow handler 
                    connectionWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
                        private static final long serialVersionUID = 1L;

                        public void onClose(AjaxRequestTarget target) {
                            if (friendActionModel.isRemoved()) {

                                //decrement number of friends
                                numConfirmedFriends--;

                                //remove friend item from display
                                target.appendJavaScript("$('#" + item.getMarkupId() + "').slideUp();");

                                //update label
                                target.add(confirmedFriendsHeading);

                                //if none left, hide whole thing
                                if (numConfirmedFriends == 0) {
                                    target.appendJavaScript(
                                            "$('#" + confirmedFriendsContainer.getMarkupId() + "').fadeOut();");
                                }
                            }
                        }
                    });

                    connectionWindow.show(target);
                    target.appendJavaScript("fixWindowVertical();");
                }
            };
            //ContextImage removeConnectionIcon = new ContextImage("removeConnectionIcon",new Model<String>(ProfileConstants.DELETE_IMG));
            removeConnectionLink.add(new AttributeModifier("alt", true, new StringResourceModel(
                    "accessibility.connection.remove", null, new Object[] { displayName })));
            //removeConnectionLink.add(removeConnectionIcon);
            removeConnectionLink
                    .add(new AttributeModifier("title", true, new ResourceModel("link.title.removefriend")));
            removeConnectionLink
                    .add(new Label("removeConnectionLabel", new ResourceModel("button.friend.remove"))
                            .setOutputMarkupId(true));
            c1.add(removeConnectionLink);
            item.add(c1);

            //can only delete if own connections
            if (!ownList) {
                removeConnectionLink.setEnabled(false);
                removeConnectionLink.setVisible(false);
            }

            WebMarkupContainer c2 = new WebMarkupContainer("viewFriendsContainer");
            c2.setOutputMarkupId(true);

            final AjaxLink<String> viewFriendsLink = new AjaxLink<String>("viewFriendsLink") {
                private static final long serialVersionUID = 1L;

                public void onClick(AjaxRequestTarget target) {
                    // always ViewFriends because a user isn't connected to himself
                    setResponsePage(new ViewFriends(personUuid));
                }
            };
            final Label viewFriendsLabel = new Label("viewFriendsLabel",
                    new ResourceModel("link.view.friends"));
            viewFriendsLink.add(viewFriendsLabel);

            //hide if not allowed
            if (!privacyLogic.isActionAllowed(userUuid, currentUserUuid,
                    PrivacyType.PRIVACY_OPTION_MYFRIENDS)) {
                viewFriendsLink.setEnabled(false);
                c2.setVisible(false);
            }
            viewFriendsLink.setOutputMarkupId(true);
            c2.add(viewFriendsLink);
            item.add(c2);

            WebMarkupContainer c3 = new WebMarkupContainer("emailContainer");
            c3.setOutputMarkupId(true);

            ExternalLink emailLink = new ExternalLink("emailLink", "mailto:" + person.getProfile().getEmail(),
                    new ResourceModel("profile.email").getObject());

            c3.add(emailLink);

            if (StringUtils.isBlank(person.getProfile().getEmail())
                    || false == privacyLogic.isActionAllowed(person.getUuid(), currentUserUuid,
                            PrivacyType.PRIVACY_OPTION_CONTACTINFO)) {

                c3.setVisible(false);
            }
            item.add(c3);

            WebMarkupContainer c4 = new WebMarkupContainer("websiteContainer");
            c4.setOutputMarkupId(true);

            // TODO home page, university profile URL or academic/research URL (see PRFL-35)
            ExternalLink websiteLink = new ExternalLink("websiteLink", person.getProfile().getHomepage(),
                    new ResourceModel("profile.homepage").getObject()).setPopupSettings(new PopupSettings());

            c4.add(websiteLink);

            if (StringUtils.isBlank(person.getProfile().getHomepage())
                    || false == privacyLogic.isActionAllowed(person.getUuid(), currentUserUuid,
                            PrivacyType.PRIVACY_OPTION_CONTACTINFO)) {

                c4.setVisible(false);
            }
            item.add(c4);

            // basic info can be set to 'only me' so still need to check
            if (true == privacyLogic.isActionAllowed(person.getUuid(), currentUserUuid,
                    PrivacyType.PRIVACY_OPTION_BASICINFO)) {

                item.add(new Label("connectionSummary", StringUtils
                        .abbreviate(ProfileUtils.stripHtml(person.getProfile().getPersonalSummary()), 200)));
            } else {
                item.add(new Label("connectionSummary", ""));
            }

            item.setOutputMarkupId(true);
        }

    };
    confirmedFriendsDataView.setOutputMarkupId(true);
    confirmedFriendsDataView.setItemsPerPage(ProfileConstants.MAX_CONNECTIONS_PER_PAGE);

    confirmedFriendsContainer.add(confirmedFriendsDataView);

    //add results container
    add(confirmedFriendsContainer);

    //add window
    add(connectionWindow);

    //add pager
    AjaxPagingNavigator pager = new AjaxPagingNavigator("navigator", confirmedFriendsDataView);
    add(pager);

    //initially, if no friends, hide container and pager
    if (numConfirmedFriends == 0) {
        confirmedFriendsContainer.setVisible(false);
        pager.setVisible(false);
    }

    //also, if num less than num required for pager, hide it
    if (numConfirmedFriends <= ProfileConstants.MAX_CONNECTIONS_PER_PAGE) {
        pager.setVisible(false);
    }

}

From source file:org.sakaiproject.profile2.tool.pages.panels.GalleryFeed.java

License:Educational Community License

@SuppressWarnings("unchecked")
public GalleryFeed(String id, final String ownerUserId, final String viewingUserId) {

    super(id);/*from   w w w.j  a v a 2s.  c o  m*/

    log.debug("GalleryFeed()");

    Label heading;
    if (viewingUserId.equals(ownerUserId)) {
        heading = new Label("heading", new ResourceModel("heading.widget.my.pictures"));
    } else {
        heading = new Label("heading", new StringResourceModel("heading.widget.view.pictures", null,
                new Object[] { sakaiProxy.getUserDisplayName(ownerUserId) }));
    }
    add(heading);

    IDataProvider dataProvider = new GalleryImageRandomizedDataProvider(ownerUserId);

    GridView dataView = new GridView("rows", dataProvider) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void populateEmptyItem(Item item) {
            // TODO make "fake" clickable
            Link emptyImageLink = new Link("galleryFeedItem") {
                public void onClick() {
                }

            };

            Label galleryFeedPicture = new Label("galleryImageThumbnailRenderer", "");
            emptyImageLink.add(galleryFeedPicture);

            item.add(emptyImageLink);
        }

        @Override
        protected void populateItem(Item item) {

            final GalleryImage image = (GalleryImage) item.getModelObject();

            GalleryImageRenderer galleryImageThumbnailRenderer = new GalleryImageRenderer(
                    "galleryImageThumbnailRenderer", image.getThumbnailResource());

            AjaxLink galleryFeedItem = new AjaxLink("galleryFeedItem") {

                @Override
                public void onClick(AjaxRequestTarget target) {
                    // view-only (i.e. no edit functionality)
                    setResponsePage(new ViewPicture(image));
                }
            };
            galleryFeedItem.add(galleryImageThumbnailRenderer);

            item.add(galleryFeedItem);

        }

    };
    // limit gallery to 3x2 thumbnails
    dataView.setColumns(3);
    dataView.setRows(2);

    add(dataView);

    AjaxLink viewPicturesLink = new AjaxLink("viewPicturesLink") {

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {

            if (sakaiProxy.isSuperUserAndProxiedToUser(ownerUserId)) {
                setResponsePage(new ViewPictures(ownerUserId));
            } else if (viewingUserId.equals(ownerUserId)) {
                setResponsePage(new MyPictures());
            } else {
                setResponsePage(new ViewPictures(ownerUserId));
            }
        }

    };

    Label numPicturesLabel = new Label("numPicturesLabel");
    add(numPicturesLabel);

    Label viewPicturesLabel;

    if (dataView.getItemCount() == 0) {
        numPicturesLabel.setDefaultModel(new ResourceModel("text.gallery.feed.num.none"));
        viewPicturesLabel = new Label("viewPicturesLabel", new ResourceModel("link.gallery.feed.addnew"));

        if (!viewingUserId.equals(ownerUserId) || sakaiProxy.isSuperUserAndProxiedToUser(ownerUserId)) {
            viewPicturesLink.setVisible(false);
        }

    } else {
        numPicturesLabel.setVisible(false);
        viewPicturesLabel = new Label("viewPicturesLabel", new ResourceModel("link.gallery.feed.view"));
    }

    viewPicturesLink.add(viewPicturesLabel);

    add(viewPicturesLink);
}