//Handle actions which can be executed on search results
function checkAll(fieldArray, checked) {
  if (fieldArray == null) return;
  selectedTable = fieldArray;
  nbEntries = selectedTable.length;
  if (nbEntries != null) {
    for (i = 0;i < nbEntries; i++) {
      selectedTable[i].checked = checked;
    }
  }
  else {
    selectedTable.checked = checked;
  }
//  if (!checked) submitForm('');
}

function sortBy(encodedSort) {
  
  decodedSort = encodedSort.replace(/#/gi,"'");
  document.iabform.sortby.value = decodedSort;
  document.iabform.firstentry.value = 1;
  document.iabform.stopsearch.value = 1;
  submitForm('');
}

function expandGroup(entryID)
{
  document.iabform.expandgroup.value = entryID;

  if( document.iabform.wcfg_groupmode != null )
  if(document.iabform.type.value == "group" || (document.iabform.wcfg_groupmode != null && document.iabform.wcfg_groupmode.value == "true"))
    document.iabform.wcfg_groupview.value = "expandgroup";

  document.iabform.action="search.xml";
  document.iabform.stopsearch.value = 1;

  submitForm('');
}

function collapseGroup(entryID)
{
  expandedgroup = document.iabform.expandedgroup;
  document.iabform.action="search.xml";
  if(document.iabform.type.value == "group" || (document.iabform.wcfg_groupmode != null && document.iabform.wcfg_groupmode.value == "true"))
    document.iabform.wcfg_groupview.value = "collapsegroup";

  if (expandedgroup != null)
  {
    if (expandedgroup.length == null) {
      if ((expandedgroup.value == entryID) || (entryID.length == 0))
        expandedgroup.value = '';
    }
    else {
      for(i=0; i<expandedgroup.length; i++) {
        if ((entryID.length == 0) || (expandedgroup[i].value == entryID))
          expandedgroup[i].value = '';
      }
    }
  }
  
  document.iabform.stopsearch.value = 1;
  submitForm('');
}

//function buildArrayFromSelected(entryArray, fieldName)
//first arg is selectedentry array from which the resultset to be created,
// second arg is entryArray can be single dimension or 2 dimensional based on number of arguments.
//if argc is > 2 then entryArray is 2 dimensional if argc == 2 then it is single dimensional

function buildArrayFromSelected()
{
  var needsExpand = false;
  var argv = buildArrayFromSelected.arguments;
  var argc = argv.length;
  var inserted;
 
  var entryArray = argv[1];
  if (argc < 3) {
     if(entryArray) entryArray.length = 0;
     return needsExpand;
  }

  var lastEntryIndex = entryArray.length;
  sEntry = argv[0];

  if (sEntry == null) {
    return needsExpand;
  }

  var selectedTable = sEntry;
  var nbEntries = selectedTable.length;
  var selectedEntry = null;
  if (nbEntries != null) {
    selectedEntry = selectedTable[0];
  }
  else {
    nbEntries = 1;
    selectedEntry = selectedTable;
  }

  for (var i = 0;i < nbEntries; i++) {
    inserted = false;
    if (nbEntries == 1)
      selectedEntry = selectedTable;
    else
      selectedEntry = selectedTable[i];

    if (selectedEntry.checked) {
      var entryID = selectedEntry.value;
      var entryType = 'abperson';
      var entryField = null;
      var entryTypeObj = document.iabform['id_' + entryID + '_entrytype'];
      if (entryTypeObj != null) {
          if ((entryTypeObj.length != null) && (entryTypeObj.length > 0)) {
            entryType = entryTypeObj[0].value;
          }
          else
            entryType = entryTypeObj.value;
      }

      if(argc > 3 && !entryArray[lastEntryIndex])
        entryArray[lastEntryIndex] = new Array(argc - 1);

      for(j = 2; j < argc; j++) {
        var entryFieldObj = document.iabform['id_' + entryID + '_' + argv[j]];
        if (entryFieldObj != null) {
          if ((entryFieldObj.length != null) && (entryFieldObj.length > 0)) {
            entryField = entryFieldObj[0].value;
          }
          else
            entryField = entryFieldObj.value;
        }
        if ((entryType == 'group')) {
          needsExpand = true;
          break;
        }
        if (entryField != null){
          if(argc > 3)
            entryArray[lastEntryIndex][j-2] = entryField;
          else if(argc == 3)
           entryArray[lastEntryIndex] = entryField;
           inserted = true;
        }
      }
    }
    if(inserted) lastEntryIndex++;
  }
  return needsExpand;
}

function sendMailFromSelected(mailURL, mailType)
{
  var entryArray = new Array();
  var flag = buildArrayFromSelected(document.iabform.selectedentry, entryArray, 'email_1');
  var flagAS =  buildArrayFromSelected(document.iabform.alreadyselectedentry, entryArray, 'email_1');

  if (flag == false && flagAS == false) {
    if (entryArray.length > 0) {
      sendMail(mailURL, mailType, entryArray);
    }
    else {
      alert(i18n['No entry containing an email address selected']);
    }
  }
  else {
    document.iabform.action="search.xml";
    document.iabform.expandselectedgroup.value=1;
    document.iabform.expandonmissing.value='mail';
    document.iabform.stopsearch.value = 1;
    
    submitForm('sendemail');
  }
}

function sendiPlanetIMFromSelected()
{
  var entryArray = new Array();
  var needsExpand = buildArrayFromSelected(entryArray, 'iim');
  if (needsExpand == false) {
    if (entryArray.length > 0) {
      sendIM('iPlanet', entryArray);
    }
    else {
      alert(i18n['No entry containing an iPlanet IM selected']);
    }
  }
  else {
    document.iabform.expandselectedgroup.value=1;
    document.iabform.expandonmissing.value="im[service='iPlanet']";
    document.iabform.stopsearch.value = 1;
    submitForm('startconference');
  }
}


function viewCalendarFromSelected(contexturi)
{
  var entryArray = new Array();
  var flag = buildArrayFromSelected(document.iabform.selectedentry, entryArray, 'email_1');
  var flagAS = buildArrayFromSelected(document.iabform.alreadyselectedentry, entryArray, 'email_1');
    
  if (flag == false && flagAS == false) {
    if (entryArray.length > 0)
      viewUWCCalendar(entryArray, contexturi);
    else {
      alert(i18n["No entry containing an email address selected"]);
    }
  }
  else {
    document.iabform.action="search.xml";
    document.iabform.stopsearch.value = 1;
    document.iabform.expandselectedgroup.value=1;
    document.iabform.expandonmissing.value='mail';
    submitForm('viewcalendar');
  }
}

function checkSelected(selectedEntries) {
  if (selectedEntries != null) {
    if ((selectedEntries.length != null) && (selectedEntries.length > 0)) 
    {
      for (var i = 0; i < selectedEntries.length; i++) {
        if(selectedEntries[i].checked) {
           return true;
        }
      }
    }
    else {
      if(selectedEntries.checked) {
          return true;
      }
    }
  }
 
  return false;
}

function deleteSelected() {
  var sEntries = document.iabform.selectedentry;
  var aEntries = document.iabform.alreadyselectedentry;
 
  bSelected = checkSelected (sEntries); 

  if( !bSelected )
    bSelected = checkSelected (aEntries);

  if (bSelected ) {
    if( confirm(i18n['Delete Selected Cards']) )
    {      
      document.iabform.stopsearch.value          = "1";      
      document.iabform.firstentry.value          = "1";
      document.iabform.stopalreadyselected.value = "1";
      if( document.iabform.wcfg_searchmode != null )
        document.iabform.wcfg_searchmode.value = "";

      submitForm('deleteselection');        
    }    
  }
  else {
    alert(i18n['Selection is empty, please select entries to delete.'])
  }
}

function copySelected() {
  var sEntries = document.iabform.selectedentry;
  var aEntries = document.iabform.alreadyselectedentry;

  bSelected = checkSelected (sEntries); 

  if( !bSelected ) 
    bSelected = checkSelected (aEntries);

  if (bSelected ) {
     document.iabform.firstentry.value          = "1";
     document.iabform.stopalreadyselected.value = "1";
     submitForm('copyselection');
  }
  else {
    alert(i18n['Selection is empty, please select entries to copy.'])
  }
}

function updateSelected() {
  bSelected = false;
  if (document.iabform.selectedentry != null) {
    if ((document.iabform.selectedentry.length != null) && (document.iabform.selectedentry.length > 0)) {
      for (var i = 0; i < document.iabform.selectedentry.length; i++) {
        if(document.iabform.selectedentry[i].checked) {
          var entryTypeObj = document.iabform['id_' + document.iabform.selectedentry[i].value + '_entrytype'];
          if (entryTypeObj != null) {
            if ((entryTypeObj.length != null) && (entryTypeObj.length > 0)) {
            entryType = entryTypeObj[0].value;
          }
          else
            entryType = entryTypeObj.value;
          }

          if(entryType == "group") {
            alert("This operation is not supported for groups!!");
            return;
          }
          bSelected = true;
          break;
        }
      }
    }
    else {
      if(document.iabform.selectedentry.checked) {
        bSelected = true;
      }
    }
  }

  if (bSelected) {
    goToUsingForm('updatemembership.xml');
  }
  else {
    alert(i18n['Selection is empty, please select entries to update.'])
  }
}

function launchSearch(searchString) {
  if (document.iabform.searchbookid != null) {
    document.iabform.bookid.value = getFieldValue(document.iabform.searchbookid);
  }

  if( searchString != null ) {
    var pat = /\S+/g;
    var result = pat.test(searchString);
    if( result == false )
      searchString = "";
  }
     
  if(searchString==null || searchString=="") 
  {
    alert(i18n["Enter search string first"]);
    document.iabform.searchstring.focus();
    return;
  }
    
  setFilter(searchString,'contains');
  if( document.iabform.action.indexOf("select-popup.xml") < 0 &&
      document.iabform.action.indexOf("addressing-popup.xml") < 0 &&
      document.iabform.action.indexOf("search.xml") < 0) 
    document.iabform.action = "search.xml";

  if( document.iabform.wcfg_groupmode != null )
    document.iabform.wcfg_groupmode.value='';
  submitForm('');
}

//Sets the current search filter
function setFilter(searchString, type) {
  if ((searchString == null) || (searchString.length <= 0)) return;

  var filter = "entry/displayname=";  
  if( searchString == "*" ) //=> all entries
    filter += searchString;
  else {
      searchString = searchString.replace(/\\/gi,"\\\\");
      searchString = searchString.replace(/\*/gi,"\\2a");
      searchString = searchString.replace(/=/gi,"\\3d");
      searchString = searchString.replace(/\(/gi,"\\(");
      searchString = searchString.replace(/\)/gi,"\\)");
      
      switch (type) {
        case 'equals':
         filter += encode(searchString);
         break; 
        case 'startsWith':
         filter += encode(searchString) + '*';
         break; 
        case 'allEntries':
         filter += '*';
         break;
        case 'contains':
        default:
         //** replace all spaces with * so as to get the 'contain' effect 
         searchString = searchString.replace(/\s+/gi,"\*");
         filter += '*' + encode(searchString) + '*';
         break; 
      }
  }
  document.iabform.filter.value = filter;
  document.iabform.firstentry.value = 1;
  document.iabform.stopsearch.value = 1;
  if( document.iabform.wcfg_searchmode != null )
    document.iabform.wcfg_searchmode.value = "true";
}

function extractMatchFromFilter(filter)
{
    var match = filter.match(/entry\/displayname=\*(.*)\*/);
    if (match != null) {                    
      match[1]=match[1].replace(/\\\*/gi,"%STAR%");                        
      match[1]=match[1].replace(/\%STAR\%/g, "*");
      match[1]=match[1].replace(/\*/gi," ");
      match[1]=match[1].replace(/\\\)/gi,")");
      match[1]=match[1].replace(/\\\(/gi,"(");
      match[1]=match[1].replace(/\\2a/gi,"*");
      match[1]=match[1].replace(/\\3d/gi,"=");
      return match[1];
    }
    return "";
}

function encode(str)
{
   //we assume browserversion is already been called
   //if( is_ie5up ) 
      return encodeURI(str);
   //else
   //   return escape(str);
   //Note: It seems netscape 7, mozilla and IE 6 atleast supports encodeUri
}
