#*
UPDATE THIS COMMENT SECTION EVERYTIME YOU ADD/CHANGE/REMOVE A VARIABLE FROM THIS TEMPLATE !!!

-- Required action variables:
- $viewPermissionsGroups
- $viewPermissionsUsers
- $viewingRestricted
- $editPermissionsGroups
- $editPermissionsUsers
- $editingRestricted

-- Required action methods:
- $action.getViewPermissionsGroups()
- $action.getViewPermissionsUsers()
- $action.isViewingRestricted()

- $action.getEditPermissionsGroups()
- $action.getEditPermissionsUsers()
- $action.isEditingRestricted()

*#

#requireResource("confluence.web.resources:dwr")
#requireResource("confluence.web.resources:page-permissions-editor")

<!-- Copy some methods out of prototype 1.5 since we can't rev to it yet due to it causing a memory leak in jwebunit 1.2 and hence our func tests -->
<!-- this block of javascript can be removed when we rev to prototype 1.5 -->
<script type="text/javascript">
    Array.prototype.indexOf = function(object)
    {
        for (var i = 0, length = this.length; i < length; i++)
            if (this[i] == object) return i;
        return -1;
    }

    Array.prototype.without = function()
    {
        var values = $A(arguments);
        return this.select(function(value)
        {
            return !values.include(value);
        });
    }

    String.prototype.strip = function()
    {
        return this.replace(/^\s+/, '').replace(/\s+$/, '');
    }
</script>

<script type="text/javascript">

#***********************************************
Global variables
***********************************************#

var viewPagePermissions = new PagePermissions();
#if ($page && $page.getContentPermissionSet("View"))
    #foreach ($cp in $page.getContentPermissionSet("View").iterator())
        #if ($cp.isGroupPermission())
            viewPagePermissions.addGroup("$generalUtil.escapeForJavascript(${cp.groupName})");
        #else
            viewPagePermissions.addUser("$generalUtil.escapeForJavascript(${cp.userName})");
        #end
    #end
#end

var editPagePermissions = new PagePermissions();
#if ($page && $page.getContentPermissionSet("Edit"))
    #foreach ($cp in $page.getContentPermissionSet("Edit").iterator())
        #if ($cp.isGroupPermission())
            editPagePermissions.addGroup("$generalUtil.escapeForJavascript(${cp.groupName})");
        #else
            editPagePermissions.addUser("$generalUtil.escapeForJavascript(${cp.userName})");
        #end
    #end
#end

var viewPermissionManager = new PermissionManager(PagePermissionType.VIEW);
var editPermissionManager = new PermissionManager(PagePermissionType.EDIT);
var currentPermissionManager = viewPermissionManager;

#***********************************************
i18n
***********************************************#

i18n['perms.remove'] = '$generalUtil.escapeForJavascript(${action.getText("perms.remove")})';
i18n['done.name.caps'] = '$generalUtil.escapeForJavascript(${action.getText("done.name")})';
i18n['edit.name.caps'] = '$generalUtil.escapeForJavascript(${action.getText("edit.name")})';
i18n['page.perms.viewing.restricted'] = '$generalUtil.escapeForJavascript(${action.getText("page.perms.viewing.restricted")})';
i18n['page.perms.editing.restricted'] = '$generalUtil.escapeForJavascript(${action.getText("page.perms.editing.restricted")})';
i18n['page.perms.no.view.restrictions'] = '$generalUtil.escapeForJavascript(${action.getText("page.perms.no.view.restrictions")})';
i18n['page.perms.no.edit.restrictions'] = '$generalUtil.escapeForJavascript(${action.getText("page.perms.no.edit.restrictions")})';
i18n['page.perms.duplicate.names'] = '$generalUtil.escapeForJavascript(${action.getText("page.perms.duplicate.names")})';
i18n['page.perms.invalid.entity.names'] = '$generalUtil.escapeForJavascript(${action.getText("page.perms.invalid.entity.names")})';

</script>

#if ($action.hasSetPagePermissionsPermission())
<!-- Start permission section -->
<div id="permissions_tab">
    <span class="formtitle">$action.getText("restrictions.name"): </span><a href="" onclick="togglePermissions(); return false;" class="inline-control-link" id="permissions_show_hide_link">$action.getText("edit.name")</a>
</div>

<div id="permissionsSummaryDiv">

    <div id="viewPermissionsSummary" #if (!$page || !$page.getContentPermissionSet("View")) class="hidden" #end>$action.getText("restrictions.viewing"):
        <span id="commaDelimitedViewPermissions">
        #if ($page && $page.getContentPermissionSet("View"))
            #foreach ($cp in $page.getContentPermissionSet("View").iterator())#*
                *##if($velocityCount != 1), #end#*
                *##if ($cp.isUserPermission())$generalUtil.htmlEncode(${cp.userName})#else $generalUtil.htmlEncode(${cp.groupName})#end#*
            *##end
        #end
        </span>
        <br>
    </div>
    <div id="editPermissionsSummary" #if (!$page || !$page.getContentPermissionSet("Edit")) class="hidden" #end>$action.getText("restrictions.editing"):
        <span id="commaDelimitedEditPermissions">
        #if ($page && $page.getContentPermissionSet("Edit"))
            #foreach ($cp in $page.getContentPermissionSet("Edit").iterator())#*
                *##if($velocityCount != 1), #end#*
                *##if ($cp.isUserPermission())$generalUtil.htmlEncode(${cp.userName})#else $generalUtil.htmlEncode(${cp.groupName})#end#*
            *##end
        #end
        </span>
    </div>
</div>

<div id="permissionsDiv" class="toggleFormDiv editor-panel hidden">

    #if ($action.getViewInheritedContentPermissionSets().size() > 0)

    <div id="inheritedPermissionsBox" class="lightGreyBox">

        #set ($inheritedPermissionsExist = "true")
        $action.getText('inherited.view.restrictions.apply')
        <div>
            <p class="stepdesc">$action.getText('inherited.view.restrictions.explanation')</p>
            <table id="inheritedViewRestrictions" class="pagePermissionsTable"></table>
        </div>

    </div>
    #end

    <div id="currentPermissionsBox" class="lightGreyBox">
        <table width="100%" style="width:100%">
            <tr>
                <td align="left">
                    <input type="radio" value="view" name="pagePermissionTypeRadio" id="restrictViewRadio" onClick="if (this.checked) currentPermissionManager = viewPermissionManager;" checked><label for="restrictViewRadio">$action.getText('restrict.viewing.label')</label>&nbsp;
                    <input type="radio" value="edit" name="pagePermissionTypeRadio" id="restrictEditRadio" onClick="if (this.checked) currentPermissionManager = editPermissionManager;"><label
                    for="restrictEditRadio">$action.getText('restrict.editing.label')</label>
                </td>
                <td align="right">
                    <img height="16px" width="16px" id="waitImage" src="$staticResourceUrlPrefix/images/icons/wait.gif" alt="Wait Image" style="display:none"/>
                </td>
            </tr>
        </table>

        <div id="pagePermissionsErrorDiv" class="pagePermissionsErrorDiv hidden">
            $action.getText('page.restrictions.error.intro')
        </div>

        <table width="100%" class="pagePermissionsInput">
            <tr>
                <td align="left">
                    #if($remoteUser)
                    <a href=""
                       onclick="currentPermissionManager.addPermissions('$generalUtil.escapeForJavascript($remoteUser.name)');return false;"><img
                        src="$staticResourceUrlPrefix/images/icons/user_16.gif" border="0" alt="$action.getText('choose.me')"
                        align="absmiddle"/></a>
                    <a href=""
                       onclick="resetValidationErrors();currentPermissionManager.addPermissions('$generalUtil.escapeForJavascript($remoteUser.name)');return false;">$action.getText('choose.me')</a>
                    #end
                    |
                    #bodytag ("Component" "theme='custom'" "template='popup-link.vm'")
                    #param ("url" "$req.contextPath/spaces/openuserpicker.action?key=$!spaceKey&startIndex=0")
                    #param ("windowName" "EntitiesPicker")
                    #param ("imgSrc" "$staticResourceUrlPrefix/images/icons/user_16.gif")
                    #param ("windowProperties" "status=yes,resizable=yes,top=100,left=200,width=700,height=680,scrollbars=yes")
                    #param ("imgTitle" "Choose users")
                    #param ("linkText" "choose.users")
                    #param ("onPopupSubmit" "addViewPermissionsUsers")
                    #param ("linkId" "userpicker-popup-link")
                    #end
                    |
                    #bodytag ("Component" "theme='custom'" "template='popup-link.vm'")
                    #param ("url" "$req.contextPath/spaces/opengrouppicker.action?key=$!spaceKey&startIndex=0&actionName=dosearchgroups.action")
                    #param ("windowName" "EntitiesPicker")
                    #param ("imgSrc" "$staticResourceUrlPrefix/images/icons/group_16.gif")
                    #param ("imgTitle" "Choose groups")
                    #param ("linkText" "choose.groups")
                    #param ("onPopupSubmit" "addViewPermissionsGroups")
                    #param ("linkId" "grouppicker-popup-link")
                    #end
                    |
                    <span class="nobr">
                    $action.getText('enter.user.or.group.names.label')
                    <input type="text" id="commaDelimitedEntityNames" name="commaDelimitedEntityNames" onKeyPress="return handleEnter(event);" size="30">
                    <img height="16px" width="1px" src="$staticResourceUrlPrefix/images/border/spacer.gif"/>
                    <input type="button" id="addViewRestrictionsButton" value="$action.getText('add.word')" onclick="onAddPermission();">
                    </span>
                </td>
            </tr>
        </table>
        <table id="pagePermissionsTable" class="pagePermissionsTable"></table>
        <div class="hidden">
            #tag ("TextField" "id=viewPermissionsGroups" "name='viewPermissionsGroups'" "theme='notable'")
            #tag ("TextField" "id=viewPermissionsUsers" "name='viewPermissionsUsers'" "theme='notable'")
            #tag ("TextField" "id=editPermissionsGroups" "name='editPermissionsGroups'" "theme='notable'")
            #tag ("TextField" "id=editPermissionsUsers" "name='editPermissionsUsers'" "theme='notable'")
        </div>
    </div>
</div>

##TODO MOVE THIS
<script>
    #if($restrictionsShowing)
        togglePermissions();
    #end


    ## Initialise explicit and inherited page permission tables after they have been actually declared in HTML
    var permissionsTable = new PermissionsTable($('pagePermissionsTable'), true);

    #if ($page && $page.getContentPermissionSet("View"))
        #foreach ($cp in $page.getContentPermissionSet("View").iterator())
            #if ($cp.isUserPermission())
                permissionsTable.addUserPermission('$generalUtil.escapeForJavascript(${cp.userName})', PagePermissionType.VIEW);
            #else
                permissionsTable.addGroupPermission('$generalUtil.escapeForJavascript(${cp.groupName})', PagePermissionType.VIEW);
            #end
        #end
    #else
        permissionsTable.addNoPermsRowForView();
    #end

    #if ($page && $page.getContentPermissionSet("Edit"))
        #foreach ($cp in $page.getContentPermissionSet("Edit").iterator())
            #if ($cp.isUserPermission())
                permissionsTable.addUserPermission('$generalUtil.escapeForJavascript(${cp.userName})', PagePermissionType.EDIT);
            #else
                permissionsTable.addGroupPermission('$generalUtil.escapeForJavascript(${cp.groupName})', PagePermissionType.EDIT);
            #end
        #end
    #else
        permissionsTable.addNoPermsRowForEdit();
    #end

    var inheritedPermissionsTable = new PermissionsTable($('inheritedViewRestrictions'), false);

    #set ($inheritedContentPermissionSets = $action.getViewInheritedContentPermissionSets())
    #if ($inheritedContentPermissionSets)
        #foreach ($cps in $inheritedContentPermissionSets.iterator())
            #foreach ($cp in $cps.iterator())
                #if ($cp.isUserPermission())
                    inheritedPermissionsTable.addUserPermission('$generalUtil.escapeForJavascript(${cp.userName})', PagePermissionType.VIEW, '$generalUtil.escapeForJavascript(${cps.owningContent.title})');
                #else
                    inheritedPermissionsTable.addGroupPermission('$generalUtil.escapeForJavascript(${cp.groupName})', PagePermissionType.VIEW, '$generalUtil.escapeForJavascript(${cps.owningContent.title})');
                #end
            #end
         #end
    #end
</script>
#end  ## end has restrict permissions
