/*
 * Copyright 1999 Netscape Communications Corp, a subsidiary of America Online
 */

/*   ldap_step ... the number of matches to show per page
 *   ldap_from ... the current begging of range for the ldap search
 *     ldap_to ... the current end of range for the ldap search
 * ldap_filter ... the current ldap regular expression
 *    ldap_url ... the directory and base dn to search
 *       state ... {init, POST, fetchPab}
 *       isPab ... boolean - was this search initiated in the PAB UI?
 *         tfr ... the url that fetches items from LDAP
 *       addrs ... the number of addressable search results
 */
var ldap_step = 100, ldap_from = 0, ldap_to = ldap_from + ldap_step, ldap_filter = '', ldap_url = '', state = 'init', isPab, tfr, addrs = 0, target;
var forGroup = false

function setUp() {
  var srch = window.location.search;
  isPab = getArg('isPab', srch) ? true : false;
  forGroup = getArg('action',srch) ? true : false;
  if(forGroup == null ) forGroup = false
  if (main.cfgFrame.pabEnabled && !main.curPab)
    main.fetchPab();
}

function setFrames() {
  ctrl = window.frames[0];
  data = window.frames[1];
  idx = window.frames[2];
  btn = window.frames[3];
}

function ctrlHTML() {
  return main.getBody(main.chrome2, true, main.black) +
    '<form Accept-Charset="UTF-8" name="form" method="post" action=javascript:parent.noop() onSubmit="return parent.doSearch()">\n' +
    s_SearchCtrl() + '</form>\n'
}

function ctrlInit() {
  if (NN > 0)
    ctrl.focus();
  ctrl.form.string.focus();
  ctrl.form.string.select();
}

function dataHTML() {
  return main.getBody(main.chrome2, true);
}

function idxHTML() {
  return main.getBody(main.white, true, main.black) + getSearchResults();
}

function idxInit() {
  if (state == 'results')
    idx.focus();
}

function btnHTML() {
  var s = '<TABLE border=0 cellpadding=2 cellspacing=0 width=100% height=100%><TR bgcolor=' + main.chrome0 + '>';
  var w = NN > 0 ? ' width=72' : '';

  s += '<TD height=100% align=right>' + '<font>' + nbsp + nbsp + nbsp

  if(addrs > 0 && forGroup )
  {
     s += main.nbutton('ok',i18n_lu['ok'],"parent.okGroups(\'ok\')") + '&nbsp;' 
     s += main.nbutton('apply', i18n_lu['apply'], "parent.okGroups(\'apply\')") + '&nbsp;' 
  }

  else if(addrs > 0 && window.opener.name != 'mailFrame')  {
     s += main.nbutton('ok',i18n_lu['ok'],"parent.okGroups(\'ok\')") + '&nbsp;' 
     s += main.nbutton('apply', i18n_lu['apply'], "parent.okGroups(\'apply\')") + '&nbsp;' 
  }

  else if (addrs > 0) {
    s += main.nbutton('apply', i18n_lu['new msg'], "parent.ok(\'newMsg\')") + '&nbsp;'
  }


   s += main.nbutton('esc', i18n_lu['cancel'], "parent.cancel()", '', 'Btn2') + nbsp +
        main.nbutton('help', i18n_lu['help'], "main.help()", '', 'Btn2') +
        nbsp + nbsp + nbsp + '</TD></TR></TABLE>';
  
  return main.getBody(main.chrome0, true, main.white, false, false, false, 1, 1) +
    '<form Accept-Charset="UTF-8" name=FORM>' + s + '</FORM>';
}


function getSingleFilter(rule, a, v) {
  var s = new String()
  if (rule == '$a=*$v*')
    s += v != '' ? '(' + a + '=*' + v + '*)' : s += '(' + a + '=*)';
  else if (rule == '$a=$v')
    s += '(' + a + '=' + v + ')' 
  else if (rule == '$a~=$v')
    s += '(' + a + '~=' + v + ')' 
  else if (rule == '$a=*$v')
    s += '(' + a + '=*' + v + ')' 
  else if (rule == '$a=$v*')
    s += '(' + a + '=' + v + '*)' 
  return s
}

function getFilter(rule, a, v, not, ldapurl) {
  var s = new String()
  v = main.escape_ldapfilter(v);
  if (not)
    s += '(!'
  var x = new Array();
  /* PAB doesn't like composite filters */
  if (ldapurl != "3 200 1") {
      if (a == "mail") {
	  /* if searching for email also search for aliases */
	  x = new Array("mailalternateaddress", "unused");
      } else {
	  /* if searching for lang attribute also search for
	   * non language-tagged version */
	  x = a.split(";");
      }
  }
  if (x.length > 1) {
    s += "(|";
    s += getSingleFilter(rule, x[0], v);
    s += getSingleFilter(rule, a, v);
    s += ")";
  } else {
    s += getSingleFilter(rule, a, v);
  }
  if (not)
    s += ')'
  return s
}

function doSearch() {
  var f = ctrl.form;
  var rule = f.rule.options[f.rule.selectedIndex].value;
  var a = f.attr.options[f.attr.selectedIndex].value;
  var v = deleteSpace(f.string.value);
  if(forGroup) ldap_url = "3 200 1"
  else ldap_url = f.dir.options[f.dir.selectedIndex].value;
  if(ldap_url==i18n['localdirsearch']){a=a.split(";")[0]} 
  if (!v && f.dir.options[f.dir.selectedIndex].value.indexOf)
    return false;
  if (rule == 'contains')
    ldap_filter = getFilter('$a=*$v*', a, v, false, ldap_url);
  else if (rule == 'does not')
    ldap_filter = getFilter('$a=*$v*', a, v, true, ldap_url);
  else if (rule == 'equal')
    ldap_filter = getFilter('$a=$v', a, v, false, ldap_url);
  else if (rule == 'not equal')
    ldap_filter = getFilter('$a=$v', a, v, true, ldap_url);
  else if (rule == 'sound')
    ldap_filter = getFilter('$a~=$v', a, v, false, ldap_url);
  else if (rule == 'begin')
    ldap_filter = getFilter('$a=$v*', a, v, false, ldap_url);
  else if (rule == 'end')
    ldap_filter = getFilter('$a=*$v', a, v, false, ldap_url);
  else
    ldap_filter = getFilter('$a=*$v*', a, v, false, ldap_url);

  ldap_from = 0;
  submit();
  return false;
}

function getSearchResults() {
  if (state == 'init')
    return ''; // ELSE

  var f = ctrl.form;
  var s;
  var list = data.addr;
  var num_results = 0;
  var blank = '<td>' + nbsp + '</td>\n';
  var a = split(ldap_url, ' ');
  var pab = a.length == 3 && ldap_url.indexOf('ldap://') == -1;
  var noOfEntries = 0 

  if( data.addr && data.addr.length > 0)
    num_results = data.addr.length;

  if (state == 'post')
    return '<table width=100% height=100%><tr><td align=center>' +
    main.font() + i18n['ldap searching'] + '</font></td></tr></table>'; // ELSE
  if (!data.addr || data.addr.length == 0) {
    return '<table border=0 cellpadding=2 cellspacing=1 width=100%>\n' +
      '<tr bgcolor=' + main.chrome2 + '><td width=1%>&nbsp;</td></tr>\n' +
      '<tr ' + main.cellBgString + '>' +
      '<td align=center width=1% nowrap>' + main.font() +
      main.i18n_ldap_no_match(
        f.attr.options[f.attr.selectedIndex].text,
	f.rule.options[f.rule.selectedIndex].text,
	f.string.value) +
      '</tr>\n' +
      '<tr bgcolor=' + main.chrome2 + '><td width=1%>&nbsp;</td></tr>\n' +
      '</table>\n';
  }

  if(forGroup)
   s = '<form Accept-Charset="UTF-8" name="form">\n' + main.tableStart +
    '<tr bgcolor=' + main.chrome2 + '>\n' +
    '<td width=1% nowrap>' + main.font() + i18n_lu['selectLogo'] + '</td>\n' +
    '<td width=49% nowrap>' + main.font() + i18n['ldap cn'] + '</td>\n' +
    '<td width=49% nowrap>' + main.font() + i18n['ldap mail'] + '</td>\n' +
    '<td width=1% nowrap><nobr>' + main.font() + (pab ? i18n_lu['work'] : i18n['ldap phone']) +
    '</td></tr>\n'  
  else s = '<form Accept-Charset="UTF-8" name="form">\n' + main.tableStart +
    '<tr bgcolor=' + main.chrome2 + '>\n' +
    '<td width=1% nowrap>' + main.font() + i18n_lu['to'] + '</td>\n' +
    '<td width=1% nowrap>' + main.font() + i18n_lu['cc'] + '</td>\n' +
    '<td width=1% nowrap>' + main.font() + i18n_lu['bcc'] + '</td>\n' +
    '<td width=49% nowrap>' + main.font() + i18n['ldap cn'] + '</td>\n' +
    '<td width=49% nowrap>' + main.font() + i18n['ldap mail'] + '</td>\n' +
    '<td width=1% nowrap><nobr>' + main.font() + (pab ? i18n_lu['work'] : i18n['ldap phone']) +
    '</td></tr>\n'

  // count the number of checkbox groups
  addrs = 0;
  noOfEntries = (num_results > ldap_step) ? ldap_step : num_results

  for (var i = 0; i < noOfEntries; i++) {
    s += '<tr' + main.base_line + ' ' + main.cellBgString + '>\n';
    if (list[i].mail) {

	  if(forGroup)
	    s += '<td align=center>' + main.font() + '<input type=checkbox name=t value="' +
        i + '" onClick="parent.radioTypeGroup(this,' + addrs + ')"></td>\n';
	  else {
      s += '<td align=center>' + main.font() + '<input type=checkbox name=t value="' +
        i + '" onClick="parent.radioType(this,' + addrs + ')"></td>\n';
      s += '<td align=center>' + main.font() + '<input type=checkbox name=c value="' +
        i + '" onClick="parent.radioType(this,' + addrs + ')"></td>\n';
      s += '<td align=center>' + main.font() + '<input type=checkbox name=b value="' +
        i + '" onClick="parent.radioType(this,' + addrs + ')"></td>\n';
	  }
// Same as above, but will mark the addresses that are already included in
// the message. Not including this stuff because I'd rather do the wrong
// interaction than do the interaction wrong.
//      s += '<td align=center>' + main.font() + '<input type=checkbox name=t value="' +
//      i + '" onClick="parent.radioType(this,' + j + ')"' + (!isPab && inList(list[i], 't') ? ' checked' : '') + '></td>\n';
//      s += '<td align=center>' + main.font() + '<input type=checkbox name=c value="' +
//        i + '" onClick="parent.radioType(this,' + j + ')"' + (!isPab && inList(list[i], 'c') ? ' checked' : '') + '></td>\n';
//      s += '<td align=center>' + main.font() + '<input type=checkbox name=b value="' +
//        i + '" onClick="parent.radioType(this,' + j + ')"' + (!isPab && inList(list[i], 'b') ? ' checked' : '') + '></td>\n';
      addrs++;
    }
    else
      s += '<td colspan=3>' + nbsp + '</td>';
    if (list[i].cn)
      s += '<td nowrap>' + main.font() +
      (pab && main.curPab
        ? '<A href="javascript:parent.mod' +
        (list[i].objectclass == 'pabperson' ? 'Entry' : 'Group') +
        '(\'' + list[i].un + '\')">'
        : '') +
      html(main.unescape_crlf(list[i].cn)) + (pab && main.curPab ? '</A>' : '') + '</td>\n';
    else
      s += blank;
    if (list[i].mail)
      s += '<td nowrap>' + main.font() + html(main.unescape_crlf(split(list[i].mail, ',').join('; ')) + (list[i].objectclass == 'pabgroup' ? ' ...' : '')) + '</td>\n';
    else
      s += blank;
    if (list[i].telephoneNumber) 
      s += '<td nowrap>' + main.font() + main.unescape_crlf(list[i].telephoneNumber) + '</td>\n';
    else if (list[i].telephonenumber)
      s += '<td nowrap>' + main.font() + main.unescape_crlf(list[i].telephonenumber) + '</td>\n';
    else
      s += blank;
    s += '</tr>\n';
  }
  s += '<tr bgcolor=' + main.chrome2 + '><td colspan=6>' + 
    main.font() + nbsp + main.tableEnd +
    '<table border=0 cellpadding=3 cellspacing=1>\n<tr>';
  if (list.length >= ldap_step || data.start > 0)
    s += '<td>' +
    (ldap_from > 0
      ? '<a href="javascript:parent.ldapBack()" onMouseOver="return hint()">' +
      '<img src="imx/back_btn.gif" width=20 height=24 border=0></a>'
      : '<img src="imx/back_not.gif" width=20 height=24 border=0>') +
    '</td>\n' + '<td>' +
    (num_results > ldap_step
      ? '<a href="javascript:parent.ldapForward()" onMouseOver="return hint()">' +
      '<img src="imx/next_btn.gif" width=20 height=24 border=0></a>'
      : '<img src="imx/next_not.gif" width=20 height=24 border=0>') + '</td>\n';
  s += '<td nowrap><nobr>' + main.font() + (list.length == ldap_step || ldap_from > 0 ? (ldap_from + 1) + ' - ' : '') +
    main.i18n_ldap_match(noOfEntries + ldap_from,
      f.attr.options[f.attr.selectedIndex].text,
      f.rule.options[f.rule.selectedIndex].text,
      f.string.value) +
    '</td>\n<tr>\n</table>\n</form>\n';
  reload(btn);
  return s;
}

function inList(a, t) {
  var pab = split(ldap_url, ' ').length == 3 && ldap_url.indexOf('ldap://') == -1;
  // Set t to the appropriate array in parent (t - to_list, c - cc_list, b - bcc_list).
  t = (t == 't' ? window.opener.to_list : (t == 'c' ? window.opener.cc_list : window.opener.bcc_list));
  if (pab && isArray(a.mail)) {
    //    alert(a.mail[0] + '\n\n' + t + '\n\n' + window.opener.inList(a.mail[0], t));
    return window.opener.inList(a.cn + ' <' + a.mail[0] + '>', t) != -1; // ELSE
  }
  if (a.mail.indexOf(',') != -1) {
    a = split(a, ',');
    for (var i = 0; i < a.length; i++) {
      if (window.opener.inList(a[i], t) == -1)
        return false;
    }
    return true;
  } // ELSE
  return window.opener.inList(a.cn + ' <' + a.mail + '>', t) != -1;
}

function submit() {
  if (orphaned()) {
    self.close();
  } else {
    addrs = 0;
    reload(btn);
    var a = split(ldap_url, ' ');
    var pab = a.length == 3 && ldap_url.indexOf('ldap://') == -1;
    state = 'post';
    reload(idx);
    tfr = pab ? 'cmd=PAB_CMD_ADDRESS|pab=' + main.curPab + '|from=' + ldap_from + '|len=' + ldap_step + '|old=' + ldap_filter + '|' : ldap_filter;
//    if (!confirm(tfr))
//      return;
    load(data, main.msgHREF + 'ldap.msc?sid=' + main.sid +
      (pab ? '' : '&start=' + ldap_from) +
      (pab ? '' : '&count=' + (ldap_step + 1)) +
      '&filter=' + encode(tfr) +
      '&ldapurl=' + (pab ? 'pab' : (a.length < 3 ? '' : a[2])) +
      '&version=' + a[0]);
  }
}

function ldapForward() {
  ldap_from += ldap_step;
  submit();
}

function ldapBack() {
  if ((ldap_from -= ldap_step) < 0)
    ldap_from = 0;
  submit();
}

function getCnByUn(n) {
  var i;
  for (i = 0; i < main.pabFrame.people.length; i++) {
    if (main.pabFrame.people[i].un == n)
      return main.pabFrame.people[i].cn;
  }
  for (i = 0; i < main.pabFrame.groups.length; i++) {
    if (main.pabFrame.groups[i].un == n)
      return main.pabFrame.groups[i].cn;
  }
  return '';
}

function okGroups(what) {
  var tempData;
  var mailData

  if (state == 'init' || state == 'fetchPab' || data.addr.length == 0)
    return;
  var pab = split(ldap_url, ' ').length == 3 && ldap_url.indexOf('ldap://') == -1;
  /* i ... iterator
   * j ... iterator
   * a ... an array of checkboxes
   * s ... the string of emails to be added to the message's envelope
   * t ... the type of address (t - to, c - cc, b - bcc)
   */
  var i, j, a, t, s = '';
    
  // We don't want to write this code three times over so iterate,
  // making t the appropriate type each pass.
  var types = new Array('t', 'c', 'b');
  for (var q in types) {
    t = types[q];
    if (!isPab)
      s = '';
    else
      s += (s ? '&' : '') + t + '=';
    a = idx.form.elements[t];
    if (!isArray(a)) {
      a = new Array(a);
    }
    for (j = 0; j < a.length; j++) {
      if (a[j].checked) {
        // Is this a normal address or a PAB address?
        // if (!isArray(data.addr[a[j].value].mail)) 
        // Is this a normal address or PAB group address?
        // &! In the rare case that a group contains only one member, the
        // group looks exactly like a normal LDAP address.
	mailData = (isArray(data.addr[a[j].value].mail) ? data.addr[a[j].value].mail[0] : split(data.addr[a[j].value].mail, ',')[0]);
        if (data.addr[a[j].value].objectclass == 'pabperson')
          s += (s.charAt(s.length-1) == '=' ? '' : ',') + s_EmailEntry(data.addr[a[j].value].cn,
            mailData, true)
        else
          s += encode((s.charAt(s.length-1) == '=' ? '' : ',') + data.addr[a[j].value].mail);
        a[j].checked = false;
	if(!isPab) 
  	{
		tempData = data.addr[a[j].value];
		if(!data.addr[a[j].value].un) tempData.un = data.addr[a[j].value].mail;  // temporary ,should be un
		else tempData.un = data.addr[a[j].value].un
		if(!data.addr[a[j].value].objectclass)
			tempData.objectclass="pabperson"		// assuming it is person 
		else  tempData.objectclass=data.addr[a[j].value].objectclass
		if(isArray(data.addr[a[j].value].mail))
			tempData.mail = data.addr[a[j].value].mail
		else tempData.mail = data.addr[a[j].value].mail.split(',')
		window.opener.parent.fromLookup(t,tempData); 
	} 
     }
  }
 }
  window.opener.parent.reloadIdx() 
  if(what =='ok') self.close()
}


function ok(what)
{
  var tempData;
  var mailData

  if (state == 'init' || state == 'fetchPab' || data.addr.length == 0)
    return;
  var pab = split(ldap_url, ' ').length == 3 && ldap_url.indexOf('ldap://') == -1;
  /* i ... iterator
   * j ... iterator
   * a ... an array of checkboxes
   * s ... the string of emails to be added to the message's envelope
   * t ... the type of address (t - to, c - cc, b - bcc)
   */
  var i, j, a, t, s = '';
    
  // We don't want to write this code three times over so iterate,
  // making t the appropriate type each pass.
  for (i = 0; i < 3; i++) {
    t = (i == 0 ? 'b' : (i == 1 ? 'c' : 't'));
    if (!isPab)
      s = '';
    else
      s += (s ? '&' : '') + t + '=';
    a = idx.form.elements[t];
    if (!isArray(a)) {
      a = new Array(a);
    }
    for (j = 0; j < a.length; j++) {
      if (a[j].checked) {
        // Is this a normal address or a PAB address?
        // if (!isArray(data.addr[a[j].value].mail)) {
        // Is this a normal address or PAB group address?
        // &! In the rare case that a group contains only one member, the
        // group looks exactly like a normal LDAP address.
		mailData = (isArray(data.addr[a[j].value].mail) ? data.addr[a[j].value].mail[0] : split(data.addr[a[j].value].mail, ',')[0]);
        if (data.addr[a[j].value].objectclass == 'pabperson')
          s += (s.charAt(s.length-1) == '=' ? '' : ',') + s_EmailEntry(data.addr[a[j].value].cn,
            mailData, true)
        else
          s += encode((s.charAt(s.length-1) == '=' ? '' : ',') + data.addr[a[j].value].mail);
        a[j].checked = false;
	if(!isPab) 
  	{
		tempData = data.addr[a[j].value];
		if(!data.addr[a[j].value].un) tempData.un = data.addr[a[j].value].mail;  // temporary ,should be un
		else tempData.un = data.addr[a[j].value].un
		if(!data.addr[a[j].value].objectclass)
			tempData.objectclass="pabperson"		// assuming it is person 
		else  tempData.objectclass=data.addr[a[j].value].objectclass
		if(isArray(data.addr[a[j].value].mail))
			tempData.mail = data.addr[a[j].value].mail
		else tempData.mail = data.addr[a[j].value].mail.split(',')
		window.opener.parent.fromLookup(t,tempData); 
	} 
      }
    }
  }

  if (isPab)
      main.compose('new', s);
  else window.opener.parent.reloadIdx();
  if(what =='ok') self.close()
}

function radioType(fe, i) {

  return ; // do away with radiobutton simulation 

  var t = idx.form.elements['t'], c = idx.form.elements['c'], b = idx.form.elements['b'];
  if (!isArray(t)) {
    t = new Array(t);
    c = new Array(c);
    b = new Array(b);
  }
  if (fe.checked) {
    if (fe.name == 't') {
      c[i].checked = false;
      b[i].checked = false;
    } else if (fe.name == 'c') {
      t[i].checked = false;
      b[i].checked = false;
    } else {
      t[i].checked = false;
      c[i].checked = false;
    }
  }
}

function radioTypeGroup(fe,i) {
  var t = idx.form.elements['t']
  if (!isArray(t)) {
    t = new Array(t);
  }
}
  

function noop() {
}

function cancel() {
  self.close();
}

function ldapCB() {
  data.color(main.chrome2);
  if (data.errno)
    alert(data.errstr);
  if (orphaned()) {
    self.close();
  } else if (state != 'fetchPab') {
    addrs = 0; 
    state = 'results';
    reload(idx);
  }
}

function timeoutCB() {
  self.close();
}

function change() {
  data.color(main.chrome2);
  handleResize()
}

function afterFetch() {
  doSearch();
} 

function deleteSpace(s) {
for(n=0;n<s.length;n++) {
if(s.charAt(n)!=" "){
var ind1= n;
break;
}
}
for(a=s.length-1;a>=0;a--){
if(s.charAt(a)!=" "){
var ind2=a;
break;
}
}
s=s.substring(ind1,ind2+1)
return s;
}







