///////////////////////////////////////////////////////////////////////////////
// Copyright (C) 1999-2005 Siebel Systems, Inc.  All rights reserved.
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// Editor for selection set permissions
///////////////////////////////////////////////////////////////////////////////

function SavedSelectionPermissionsEditor(eid)
{
	this.eid = eid;
	this.universeRecipients = document.getElementById(this.eid + 'Unsel');
	this.selectedRecipients = document.getElementById(this.eid + 'Sel');
}

SavedSelectionPermissionsEditor.prototype = new XUIEditor();

//-------------------
SavedSelectionPermissionsEditor.prototype.showEveryone = function(b)
{
   this.bShowEveryone = b;
}

//-------------------
SavedSelectionPermissionsEditor.prototype.hideUser = function(s)
{
   this.sHideUser = s.toLowerCase();
}

//-------------------
SavedSelectionPermissionsEditor.prototype.load = function(xmlElement)
{
	this.element = xmlElement;

	this.universeRecipients.innerHTML = '';
	this.selectedRecipients.innerHTML = '';

	this.bShowEveryone = false;
	this.bDefaultsDisabled = XUIGetAttributeBool(xmlElement, "defaultsDisabled", false);
	this.sHideUser = '';

	// populate selected list with above xml and ask universe list to update
	// since we expect load to be called only once we can assume we want
	// universe list to show groups

	this.populateRecipients(xmlElement, this.selectedRecipients);
	this.changeUniverse('groups');

    //alert(this.element.xml);
}

//-------------------
SavedSelectionPermissionsEditor.prototype.apply = function()
{
	var tSel = this.selectedRecipients;

	var tContainer = this.element;

	// clear all old children
	for (var iNode = tContainer.firstChild; iNode != null;)
	{
		var tTemp = iNode;
		iNode = iNode.nextSibling;
		tContainer.removeChild(tTemp);
	}

	// here is new list
	for (var iNode = tSel.firstChild; iNode != null; iNode = iNode.nextSibling)
	{
		var tRecipNode = null;

		if (iNode.getAttribute('accountType') == 'group')
			tRecipNode = XUICreateElement(saw.xml.kSawNamespace, 'group');
		else if (iNode.getAttribute('accountType') == 'user')
			tRecipNode = XUICreateElement(saw.xml.kSawNamespace, 'user');
		else if (iNode.getAttribute('accountType') == 'webAccount')
			tRecipNode = XUICreateElement(saw.xml.kSawNamespace, 'webAccount');

		if (tRecipNode == null)
			continue;

		tRecipNode.setAttribute('name', iNode.getAttribute('accountName'));
		XUISetAttributeBool(tRecipNode, 'defaultSelection', iNode.getAttribute('accountChecked') == "true");

		tContainer.appendChild(tRecipNode);
	}

    //alert(tContainer.xml);

	return true;
}

//-------------------
SavedSelectionPermissionsEditor.prototype.discard = function()
{
	// called when user clicks cancel on dialog
}

//-------------------
SavedSelectionPermissionsEditor.kRecipTypeGroup = 0;
SavedSelectionPermissionsEditor.kRecipTypeUser = 1;
SavedSelectionPermissionsEditor.kRecipTypeAccount = 2;
SavedSelectionPermissionsEditor.ksHtml1 = "<div unselectable=\"on\" class=\"RecipList";
SavedSelectionPermissionsEditor.ksHtml2 = "\" accountType=\"";
SavedSelectionPermissionsEditor.ksHtml3 = "\" accountName=\"";
SavedSelectionPermissionsEditor.ksHtml4 = "\" accountChecked=\"";
SavedSelectionPermissionsEditor.ksHtml5 = "\"><input type=\"checkbox\" onclick=\"SavedSelectionPermissionsEditor.onAccountCheckbox(event);\" ";
SavedSelectionPermissionsEditor.ksHtml6 = ">&nbsp;<span unselectable=\"on\" onclick=\"SavedSelectionPermissionsEditor.onAccountClick(event);return false;\"><img unselectable=\"on\" src=\"";
SavedSelectionPermissionsEditor.ksHtml6_5 = "\" alt=\"";
SavedSelectionPermissionsEditor.ksHtml7 = "\">&nbsp;";
SavedSelectionPermissionsEditor.ksHtml8 = "</span></div>";

SavedSelectionPermissionsEditor.prototype.prepareRecipientNode = function(tNode, sName, eType, aSeen, bSelected, bChecked, bDisabled)
{
	var sLowerName = sName.toLowerCase();

	if (((sLowerName == 'everyone') && (this.bShowEveryone != true)) || (sLowerName == this.sHideUser))
	   return null;

	if (aSeen[sName])
		return null;

   var sTypeStr = null;
   var sTypeImg = null;
   var sATypeStr = null;
   var sAltStr = kmsgAdminSysUser;

   // Adding universe class hides checkbox
   var sUniverseClass = bSelected ? "" : " RecipUniverse";
   var sChecked = bChecked ? "checked" : "";
   var sAcctChecked = bChecked ? "true" : "false";
   var sDisabled = bDisabled ? " disabled=\"true\"" : "";

   switch (eType)
   {
   case SavedSelectionPermissionsEditor.kRecipTypeGroup:
      {
         sTypeStr = "Group" + sUniverseClass;
         sATypeStr = "group";
         sTypeImg = kimgCatalogGroupIcon;
         sAltStr = kmsgManageAccountsGroup;
         break;
      }

   case SavedSelectionPermissionsEditor.kRecipTypeUser:
      {
         sTypeStr = "User" + sUniverseClass;
         sATypeStr = "user";
         sTypeImg = kimgCatalogUserIcon;
         break;
      }

   case SavedSelectionPermissionsEditor.kRecipTypeAccount:
      {
         sTypeStr = "Account" + sUniverseClass;
         sATypeStr = "webAccount";
         sTypeImg = kimgCatalogAccountIcon;
         break;
      }
   }

   var sEncName = saw.encodeHTML(sName);

   var sHtml = (SavedSelectionPermissionsEditor.ksHtml1 + sTypeStr +
               SavedSelectionPermissionsEditor.ksHtml2 + sATypeStr +
               SavedSelectionPermissionsEditor.ksHtml3 + sEncName +
               SavedSelectionPermissionsEditor.ksHtml4 + sAcctChecked +
               SavedSelectionPermissionsEditor.ksHtml5 + sChecked + sDisabled +
               SavedSelectionPermissionsEditor.ksHtml6 + sTypeImg +
               SavedSelectionPermissionsEditor.ksHtml6_5 + sAltStr +
               SavedSelectionPermissionsEditor.ksHtml7 + sEncName +
               SavedSelectionPermissionsEditor.ksHtml8);

//   alert(sHtml);

   return sHtml;
}

//-------------------
SavedSelectionPermissionsEditor.prototype.populateRecipArray = function(vDest, vRecips, eType, vSeen, bSelected, bDisableCheckbox)
{
	for (var i = 0; i != vRecips.length; ++i)
	{
	   var tNode = vRecips[i];
	   var sName = XUIGetAttributeString(tNode, 'name', '');
	   var bChecked = XUIGetAttributeBool(tNode, 'defaultSelection');
           var bDisabled = XUIGetAttributeBool(tNode, 'disabled', false) || bDisableCheckbox;
		var sNew = this.prepareRecipientNode(tNode, sName, eType, vSeen, bSelected, bChecked, bDisabled);
		if (sNew != null)
		{
		   var a = new Object();
		   a.accountType = eType;
		   a.accountName = sName;
		   a.accountHtml = sNew;
		   a.accountChecked = bChecked ? "true" : "false"; // is this saved selection the default for this group
		   vDest.push(a);
		}
	}
}

//-------------------
SavedSelectionPermissionsEditor.prototype.showWaitCursor = function(bShow)
{
   if (bShow)
   {
      document.body.style.cursor = "wait";
	   this.universeRecipients.style.cursor = "wait";
	   this.selectedRecipients.style.cursor = "wait";
	}
	else
	{
      document.body.style.cursor = "auto";
	   this.universeRecipients.style.cursor = "auto";
	   this.selectedRecipients.style.cursor = "auto";
	}
}

//-------------------
SavedSelectionPermissionsEditor.prototype.populateRecipients = function(xmlElement, tDest, tSkipThese)
{
   this.showWaitCursor(true);

	// list of current selections
	tDest.hotList = new Array();

	// xmlElement contains the list of groups/users
	var tGroups = xmlElement.selectNodes(".//saw:group");
	var tUsers = xmlElement.selectNodes(".//saw:user");
	var tAccounts = xmlElement.selectNodes(".//saw:webAccount");

	// short circuit everything else
	if (tGroups.length == 0 && tUsers.length == 0 && tAccounts.length == 0)
	   return;

	// Build up associative array for lookup. We suspect this will
	// be faster than O(n^2) algorithm where we scan tSel each time
	// we are looking at a candidate to insert into tUnsel.
	var aSeenAccounts = new Array();

	if (tSkipThese != null)
	{
		for (var j = tSkipThese.firstChild; j != null; j = j.nextSibling)
		{
			aSeenAccounts[j.getAttribute('accountName')] = true;
		}
	}

	var aNodes = new Array();

	// Only groups right now, and show checkboxes in selected list (skipthese is null when populating selected list)
	var bSelected = (tSkipThese == null);

	this.populateRecipArray(aNodes, tGroups, SavedSelectionPermissionsEditor.kRecipTypeGroup, aSeenAccounts, bSelected, this.bDefaultsDisabled);
	//this.populateRecipArray(aNodes, tUsers, SavedSelectionPermissionsEditor.kRecipTypeUser, aSeenAccounts);
	//this.populateRecipArray(aNodes, tAccounts, SavedSelectionPermissionsEditor.kRecipTypeAccount, aSeenAccounts);

	aNodes.sort(SavedSelectionPermissionsEditor.sortAccounts);

	var aHtml = new Array();

	for (var i = 0; i != aNodes.length; ++i)
	{
	   aHtml.push(aNodes[i].accountHtml);
	}

	// assign to sHtml instead of innerHTML directly as this helps in profiling
	var sHtml = aHtml.join('');

	tDest.innerHTML = sHtml;

   this.showWaitCursor(false);
}

//-------------------
SavedSelectionPermissionsEditor.prototype.changeUniverse = function(sQuery)
{
	// first see if we can get the necessary list from the parent
	if (this.parentEditor && this.parentEditor.recipientCache)
	{
		var tCache = this.parentEditor.recipientCache;

		var tQueryEl = null;

		if (((sQuery == 'groups') && tCache.groups) ||
			((sQuery == 'both') && tCache.groups && tCache.users))
		{
			tQueryEl = XUICreateElement(saw.xml.kSawNamespace, 'accounts');

			for (var i = 0; i != tCache.groups.length; ++i)
				tQueryEl.appendChild(tCache.groups[i]);
		}

		if (((sQuery == 'users') && tCache.users) ||
			((sQuery == 'both') && tCache.groups && tCache.users))
		{
			if (!tQueryEl)
				tQueryEl = XUICreateElement(saw.xml.kSawNamespace, 'accounts');

			for (var i = 0; i != tCache.users.length; ++i)
				tQueryEl.appendChild(tCache.users[i]);
		}

		if (tQueryEl)
		{
			this.populateRecipients(tQueryEl, this.universeRecipients, this.selectedRecipients);
			return;
		}
	}

	var tForm = this.form;

	if (tForm == null)
		tForm = document.forms[this.eid + 'Form'];

	if (tForm == null)
	{
		var tDiv = document.createElement('div');

		var sForm = '<form name="' + this.eid + 'Form" method="post" action="' + saw.commandToURL('GetWebAccountsXML');
		sForm += '" style="margin: 0px;"><input type="hidden" name="Query"></form>';

		tDiv.innerHTML = sForm;

		var tForm = tDiv.firstChild;

		this.form = tForm;

		// form must be in the body for browser to post it
		document.body.appendChild(tForm);
	}

	tForm.elements.Query.value = sQuery;

	var tServerCall = new XUIServerCall(this.eid+'ServerCall');
	tServerCall.execute(this, tForm, null, sQuery);
}

//-------------------
SavedSelectionPermissionsEditor.prototype.serverResponse = function(bOK, result, tContext)
{
	if (!bOK)
	{
		if (result == null)
			alert('Unable to issue server call.');
		else
			alert(result);

      this.showWaitCursor(false);
	}
	else
	{
		// cache result
		if (this.parentEditor)
		{
			var tCache = this.parentEditor.recipientCache;

			if (!tCache)
				tCache = this.parentEditor.recipientCache = new Object();

			if (tContext == 'groups' || tContext == 'both')
				tCache.groups = result.selectNodes(".//saw:group");

			if (tContext == 'users' || tContext == 'both')
				tCache.users = result.selectNodes(".//saw:user");
		}

		this.populateRecipients(result, this.universeRecipients, this.selectedRecipients);
	}
}

//-------------------
SavedSelectionPermissionsEditor.onAccountClick = function(evt)
{
	var tDIV = saw.findAncestorElement(saw.getEventTarget(evt), 'DIV');

	if (tDIV && tDIV.getAttribute('accountType') != null)
	{
	   var hotList = tDIV.parentNode.hotList;

	   var activeNode = tDIV.parentNode.activeNode;

		if (evt.shiftKey && activeNode)
		{
	      var startNode = activeNode;
	      var endNode = startNode;

	      while (endNode != null && endNode != tDIV)
	         endNode = endNode.nextSibling;

	      if (endNode == null)
	      {
	         startNode = tDIV;
	         endNode = activeNode;
	      }

	      // move one after
	      endNode = endNode.nextSibling;

	      var oldHotList = hotList;
	      hotList = tDIV.parentNode.hotList = new Array();

	      var aRemoveSel = new Array();

	      while (startNode != endNode)
	      {
	         // apply selected style
				if (!NQWHasClassName(startNode, 'RecipListEntrySelected'))
					NQWAddClassName(startNode, 'RecipListEntrySelected');

				// remove from old hot list (if it exists)
			   delete oldHotList[startNode.getAttribute('accountName')];

			   // add to new hot list
			   hotList[startNode.getAttribute('accountName')] = startNode;

            // move to next
			   startNode = startNode.nextSibling;
	      }

	      // unselect all old ones
	      for (var x in oldHotList)
	      {
	         NQWRemoveClassName(oldHotList[x], 'RecipListEntrySelected');
	      }

	      // make old active node inactive
	      NQWRemoveClassName(activeNode, 'RecipListEntryActive');

	      // make new node active
	      NQWAddClassName(tDIV, 'RecipListEntryActive');

	      tDIV.parentNode.activeNode = tDIV;
		}
		else
		{
		   var bIsSelected = NQWHasClassName(tDIV, 'RecipListEntrySelected');

		   if (bIsSelected)
		      NQWRemoveClassName(activeNode, 'RecipListEntrySelected');
		   else
		      NQWAddClassName(tDIV, 'RecipListEntrySelected');

         // make clicked item active
			if (!NQWHasClassName(tDIV, 'RecipListEntryActive'))
				NQWAddClassName(tDIV, 'RecipListEntryActive');

			// if there was an old active node, disable it
			if (activeNode && activeNode != tDIV)
			   NQWRemoveClassName(activeNode, 'RecipListEntryActive');

			// set new active node
			tDIV.parentNode.activeNode = tDIV;

			if (bIsSelected)
			{
			   // removed clicked item from hot list
			   delete hotList[tDIV.getAttribute('accountName')];
			}
			else
			{
			   // add clicked item to hot list
			   hotList[tDIV.getAttribute('accountName')] = tDIV;
			}

			// if ctrl key was not pressed, unselect everything else in hot list
			if (!evt.ctrlKey)
			{
			   for (x in hotList)
			   {
			      var tNode = hotList[x];

			      if (tNode != tDIV)
			      {
			         NQWRemoveClassName(tNode, 'RecipListEntrySelected');
			         delete hotList[x];
			      }
			   }
			}
		}
	}
}

//-------------------
SavedSelectionPermissionsEditor.onAccountCheckbox = function(evt)
{
	var tDIV = saw.findAncestorElement(saw.getEventTarget(evt), 'DIV');

	if (tDIV && tDIV.getAttribute('accountType') != null)
	   tDIV.setAttribute('accountChecked', saw.getEventTarget(evt).checked ? "true" : "false");
}

//-------------------
SavedSelectionPermissionsEditor.sortAccounts = function(lhs,rhs)
{
	if (lhs.accountType < rhs.accountType)
		return -1;
	else if (rhs.accountType < lhs.accountType)
		return +1;

	if (lhs.accountName < rhs.accountName)
		return -1;
	else if (rhs.accountName < lhs.accountName)
		return +1;

	return 0;
}

//-------------------
SavedSelectionPermissionsEditor.moveSelectedRecipients = function(tSrc, tDest, bSelected)
{
	var aNodes = new Array();

	var hotList = tSrc.hotList;

	var active = tSrc.activeNode

	for (x in hotList)
	{
	   var iNode = hotList[x];

		aNodes.push(iNode);

		NQWRemoveClassName(iNode, 'RecipListEntrySelected');

		if (active == iNode)
			NQWRemoveClassName(iNode, 'RecipListEntryActive');

      if (bSelected)
			NQWRemoveClassName(iNode, 'RecipUniverse');
	   else
			NQWAddClassName(iNode, 'RecipUniverse');

		tSrc.removeChild(iNode);
	}

	if (aNodes.length == 0)
	   return;

	tSrc.hotList = new Array();
	tSrc.activeNode = null;

	aNodes.sort(SavedSelectionPermissionsEditor.sortAccounts);

	var i = 0;
	var aNode = aNodes[i];

	var cmp = 0;

	for (var iNode = tDest.firstChild; iNode != null; )
	{
	   cmp = SavedSelectionPermissionsEditor.sortAccounts(aNode, iNode);

	   if (cmp < 0)
	   {
	      tDest.insertBefore(aNode, iNode);

	      ++i;

	      if (i < aNodes.length)
	         aNode = aNodes[i];
	      else
	         break;
	   }
	   else
	      iNode = iNode.nextSibling
	}

	for (var j = i; j < aNodes.length; ++j)
	   tDest.appendChild(aNodes[j]);
}

//-------------------
SavedSelectionPermissionsEditor.selectRecipients = function(eid)
{
	var tEditor = XUIPanel.getEditor(eid);
	SavedSelectionPermissionsEditor.moveSelectedRecipients(tEditor.universeRecipients, tEditor.selectedRecipients, true);
}

//-------------------
SavedSelectionPermissionsEditor.deleteRecipients = function(eid)
{
	var tEditor = XUIPanel.getEditor(eid);
	SavedSelectionPermissionsEditor.moveSelectedRecipients(tEditor.selectedRecipients, tEditor.universeRecipients, false);
}

///////////////////////////////////////////////////////////////////////////////
// Editor for Saved Selections g_sSavedSelectonsEditor;
///////////////////////////////////////////////////////////////////////////////

function SavedSelectionsEditor()
{
	this.selectionsTable = document.getElementById('SavedSelsTable');
	this.selectedRecipients = document.getElementById(this.eid + 'Sel');
	this.div = document.getElementById('SavedSelsDiv');
	this.panel = new XUIInline('SavedSels',this,null);

   this.permissionsEditor == null;
   this.xmlNode = XUICreateElement(saw.xml.kSawdNamespace, 'activeSelection');
}

SavedSelectionsEditor.prototype = new XUIEditor();

//-------------------
SavedSelectionsEditor.prototype.displaySelections = function(sDefaultItem)
{
   var bResetDefault = false;

   var tRows = this.selectionsTable.rows;
   for (var r = 0; r != tRows.length; ++r)
   {
      var tR = tRows[r];
      if (tR.cells.length >= 2)
      {
         var tImgC = tR.cells[0];
         var tImg = saw.findFirstChildElement(tImgC, "IMG");
         if (tImg != null)
         {
            var tC = tR.cells[1];
            if (sDefaultItem == null) // just check for deletes
            {
               if (tC.getAttribute('deleted') == 'true')
               {
                  tR.style.display = "none";
                  if (tC.getAttribute('myDefault') == 'true')
                     bResetDefault = true;
               }
            }
            else if (tC.getAttribute('itemPath') == sDefaultItem)
            {
               tC.setAttribute('myDefault','true');
               tC.className = "XUIPromptSelectedItem";
               tImg.src = kimgSelected;
            }
            else
            {
               tC.setAttribute('myDefault','false');
               tC.className = "XUIPromptItem";
               tImg.src = kimgSelectedOff;
            }
         }
      }
   }

   if (bResetDefault) // I deleted my default item
      this.displaySelections("_none_");
}

//-------------------
SavedSelectionsEditor.prototype.renameSelection = function(tCell, evt)
{
   this.activeCell = tCell;

	var sName = tCell.getAttribute('newName');
	if (sName == null)
	   sName = tCell.getAttribute('itemName');

	var tCapParent = new XUICaptionParent(this.xmlNode);
   tCapParent.setCaptionText(sName);

	var tCaptionEditor = new CaptionEditor('idSelectionRenameDlg');
	var tDialog = new XUIDialog('idSelectionRenameDlg', tCaptionEditor, g_sSavedSelectonsEditor);
	tDialog.show(this.xmlNode, evt.clientX, evt.clientY);
}

//-------------------
SavedSelectionsEditor.prototype.deleteSelection = function(tCell)
{
   tCell.setAttribute('deleted', 'true');

   this.displaySelections(null);
}

//-------------------
SavedSelectionsEditor.prototype.onChildApply = function(sourceEditor)
{
    if (sourceEditor.eid == 'idSelectionRenameDlg')
    {
        var tCapParent = new XUICaptionParent(this.xmlNode);
        var sName = tCapParent.getCaptionText();

        if (sName == "")
        {
            this.activeCell.innerHTML = "";
            this.activeCell.removeAttribute('newName');
            this.activeCell.appendChild(document.createTextNode(this.activeCell.getAttribute('itemName'))); 
        }
        else if (this.activeCell.getAttribute('newName') || 
                 this.activeCell.getAttribute('itemName') != sName)
        {
            this.activeCell.innerHTML = "";
            this.activeCell.setAttribute('newName', sName);
            this.activeCell.appendChild(document.createTextNode(sName));        
        }
    }
}

//-------------------
SavedSelectionsEditor.onDefault = function(evt)
{
	var tR = saw.findAncestorElement(saw.getEventTarget(evt), 'TR');
	var tD = tR.cells[1];

   g_sSavedSelectonsEditor.displaySelections(tD.getAttribute('itemPath'));
}

//-------------------
SavedSelectionsEditor.onRename = function(evt)
{
	var tR = saw.findAncestorElement(saw.getEventTarget(evt), 'TR');

   g_sSavedSelectonsEditor.renameSelection(tR.cells[1], evt);
}

//-------------------
SavedSelectionsEditor.onDelete = function(evt)
{
	var tR = saw.findAncestorElement(saw.getEventTarget(evt), 'TR');

   g_sSavedSelectonsEditor.deleteSelection(tR.cells[1]);
}

//-------------------
SavedSelectionsEditor.onPermissions = function(evt)
{
	var tR = saw.findAncestorElement(saw.getEventTarget(evt), 'TR');
	var tD = tR.cells[1];
	if (!saw.checkObjectReference(tD.permissionsNode))
	{
	   // See if server sent us some info
	   var sSelectionXml = tD.getAttribute('selectionXml');
	   if ((sSelectionXml != null) && (sSelectionXml != ""))
	   {
         var tSelectionIsland = saw.getXmlIsland();
	      tSelectionIsland.loadXML(sSelectionXml);

         tD.permissionsNode = tSelectionIsland.selectSingleNode("sawd:savedSelection/sawd:selectionPermissions");
	   }

	   // if not, start with nothing
	   if (!saw.checkObjectReference(tD.permissionsNode))
	      tD.permissionsNode = XUICreateElement(saw.xml.kSawdNamespace, 'selectionPermissions');
	}
//alert(tD.permissionsNode.xml);

	if (g_sSavedSelectonsEditor.permissionsEditor == null)
	   g_sSavedSelectonsEditor.permissionsEditor = new SavedSelectionPermissionsEditor('idSelsPermissionsDlg');

	var tDialog = new XUIDialog('idSelsPermissionsDlg', g_sSavedSelectonsEditor.permissionsEditor, g_sSavedSelectonsEditor);

	tDialog.show(tD.permissionsNode, evt.clientX, evt.clientY);
}

//-------------------
SavedSelectionsEditor.applyChanges = function()
{
   var sResult = "<savedSelections xmlns:" + saw.xml.kSawdNamespace.prefix +
                     "='" + saw.xml.kSawdNamespace.uri + "' xmlns:" + saw.xml.kSawNamespace.prefix +
                     "='" + saw.xml.kSawNamespace.uri + "'>";

   // Build up results for server and submit
   var tRows = g_sSavedSelectonsEditor.selectionsTable.rows;
   for (var r = 0; r != tRows.length; ++r)
   {
      var tR = tRows[r];
      if (tR.cells.length >= 2)
      {
         var tImgC = tR.cells[0];
         var tImg = saw.findFirstChildElement(tImgC, "IMG");
         if (tImg != null)
         {
            var tC = tR.cells[1];
            sDeleted = tC.getAttribute('deleted');
            if (sDeleted != null)
            {
               sResult += "<sawd:savedSelection ";

               sResult += 'itemPath="' + saw.encodeHTMLAttrValue(tC.getAttribute('itemPath')) + '" ';
               sResult += 'deleted="true" ';

               sResult += " />";
            }
            else
            {
               sDefault = tC.getAttribute('myDefault');
               sNewName = tC.getAttribute('newName');

               if ((sDefault == "true") || (sNewName != null) || saw.checkObjectReference(tC.permissionsNode))
               {
                  sResult += "<sawd:savedSelection ";

                  sResult += 'itemPath="' + saw.encodeHTMLAttrValue(tC.getAttribute('itemPath')) + '" ';
                  if (sDefault == 'true')
                     sResult += 'myDefault="true" ';
                  if (sNewName != null)
                  {
                     sResult += 'newName="' + saw.encodeHTMLAttrValue(sNewName) + '" ';
                     if (!saw.checkObjectReference(tC.permissionsNode))
                     {// Send permissions so the group permissions are preserved when the selection is renamed
	                   var sSelectionXml = tC.getAttribute('selectionXml');
	                   if ((sSelectionXml != null) && (sSelectionXml != ""))
	                   {
                         var tSelectionIsland = saw.getXmlIsland();
	                      tSelectionIsland.loadXML(sSelectionXml);

                         tC.permissionsNode = tSelectionIsland.selectSingleNode("sawd:savedSelection/sawd:selectionPermissions");
	                   }
	                 }
	              }

                  sResult += ">";

                  if (saw.checkObjectReference(tC.permissionsNode))
                     sResult += saw.getXmlText(tC.permissionsNode);

                  sResult += "</sawd:savedSelection>";
               }
            }
         }
      }
   }
   sResult += "</savedSelections>";

   //alert(sResult);

	var tForm = document.getElementById('idSavedSelsForm');
	if (tForm != null)
	{
	   tForm.XmlText.value = sResult;
	   tForm.submit();
	}
	else
	   alert('Save Selections form not found in page');
}

//-------------------
//-------------------
// Entry point for the Saved Selections Editor
//-------------------
//-------------------
SavedSelectionsEditor.onOpen = function(sPageIdentifier,sPortalPath,sPageName)
{
	var sURL = saw.commandToURL("EditSavedSelections");
	sURL += "&PortalPath=" + saw.encodeURIComponent(sPortalPath);
	sURL += "&PageID=" + saw.encodeURIComponent(sPageIdentifier);
    sURL += "&Page=" + saw.encodeURIComponent(sPageName);
    
	saw.popupWindow(sURL,'SAWEditSelections',800,600);
	saw.clearActiveMenu();
}


//-------------------
//-------------------
// Temporary entry point
//-------------------
//-------------------

function DashboardShowSavedSelectionPermissionDialog()
{
	var tEditor = new SavedSelectionPermissionsEditor('idSelsPermissionsDlg');
	var tDialog = new XUIDialog('idSelsPermissionsDlg', tEditor);

	var tXmlNode = XUICreateElement(saw.xml.kSawdNamespace, 'savedSelection');

	tDialog.show(tXmlNode, event.clientX, event.clientY);
}