/*          e ... the current entry
 *        tfr ... the url or form for transfering data to and from the server
 *      state ... {init, POST, entry, more, notes, groups, delete, conflict}
 * stateFocal ... the form element having focus in each state
 *       dups ... an array of objects with the same cn as e
 *     MAXLEN ... restrict text inputs to this many characters
 */
var e, tfr, un, flag, state = 'init', stateFocal = new Array(4), dups, MAXLEN = 128,current_givenname,current_sn,deletedvalues,valid_email=true;

stateFocal['entry'] = null;
stateFocal['more'] = null;
stateFocal['notes'] = null;
stateFocal['groups'] = null;
stateFocal['conflict'] = null;

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

function setUp() {
  var sender;
  var FullName;
  var s = window.location.search;
  un = getArg('un', s);
  flag = getArg('flag', s); 
  var i,j = 0

  if (un) {
    tfr = main.msgHREF + 'ldap.msc?sid=' + main.sid + '&ldapurl=pab&filter=' + encode('cmd=PAB_CMD_GET_ENTRY|old=' + main.pabAttrs['un'].name + ':' + un + '\n\n|');
  } else if (!flag) {
    e = new Object();
    deletedvalues = new Object()
    e.givenname = i18n_pe['no givenname'];
    e.sn = i18n_pe['no sn'];
    e.cn = i18n_pe['no cn'];
    e.objectclass = 'pabperson';
    e.memberofpab = main.curPab;
    if (main.curPabGrp && (isNaN(main.curPabGrp)? true : main.curPabGrp > 2)) {
      e.memberofpabgroup = new Array();
      e.memberofpabgroup[e.memberofpabgroup.length] = main.curPabGrp
    }
    state = 'entry';
  } else {
    e = new Object();
    deletedvalues = new Object()
    e.objectclass = 'pabperson';
    e.memberofpab = main.curPab;
    if (main.curPabGrp && (isNaN(main.curPabGrp)? true : main.curPabGrp > 1)) {
      e.memberofpabgroup = new Array();
      e.memberofpabgroup[e.memberofpabgroup.length] = main.curPabGrp
    }
    state ='entry';

    sender  = getArg('sender',s);
    j=0;
    for(i=0; sender.charAt(i) == ' '; i++) 
      j++;
    sender = sender.substring(j,sender.length)
     
    if (sender.indexOf("<") >= 0) {
      e.mail = sender.substring(sender.indexOf("<")+1, sender.lastIndexOf(">"));
      stDblQuot = sender.indexOf('"');
      if (stDblQuot == 0) {
        fullName = sender.substring(stDblQuot+1, sender.lastIndexOf('"'));
        parseComment(e, fullName);

      } else if (stDblQuot < 0 && sender.indexOf("<") > 0 ) {
        fullName = sender.substring(0, sender.lastIndexOf("<")-1);
        parseComment(e, fullName);

      } else if (stDblQuot < 0 && sender.indexOf("<") == 0) {
        fullName = sender.substring(sender.lastIndexOf(">")+1, sender.length);
        if(fullName=='') fullName = e.mail;
          parseComment(e, fullName);
      }
    } else if (sender.indexOf("(") >= 0) {
      fullName = sender.substring(sender.indexOf("(")+1, sender.lastIndexOf(")"));
      if (sender.indexOf("(") > 0) {
        e.mail = sender.substring(0, sender.indexOf("("));
        deletedvalues.mail = 1
        fullName = sender.substring(sender.indexOf("(")+1, sender.lastIndexOf(')'));
        parseComment(e, fullName);

      } else if (sender.indexOf("(") == 0) {
        e.mail = sender.substring(sender.indexOf(")")+1, sender.length);
        deletedvalues.mail = 1
        fullName = sender.substring(sender.indexOf("(")+1, sender.lastIndexOf(")")-1);
        parseComment(e, fullName);
      }
    } else {
      if (sender.indexOf("@") >=0 && (sender.indexOf(" ") < 0 && sender.indexOf(",") < 0)) {
        e.mail = sender;
        deletedvalues.mail = 1
        fullName = sender;
        e.givenname = sender;
        e.sn = sender;
      } else { 
        fullName = sender;
        parseComment(e,fullName);
      }
    }
    if(typeof(fullName) == "undefined" && stDblQuot > 0 ){
      fullName = sender.substring(0,sender.indexOf("<")-1)
      parseComment(e,fullName)
    }
    e.cn = fullName;
    current_givenname = e.givenname; 
    current_sn = e.sn; 
  }
}

function parseComment(e, fullName) {
  var blank = fullName.lastIndexOf(' ')
  var comma = fullName.lastIndexOf(',')
  if (blank >= 0) {
    if( comma < blank) {
      e.givenname = fullName.substring(0, blank);
      comma = fullName.lastIndexOf(',');
    }

    blank = fullName.lastIndexOf(' ');
    e.sn = fullName.substring(blank+1, fullName.length);
  }else if( comma >=0 && blank < 0 ) {
    e.givenname = fullName.substring(0, comma);
    comma = fullName.lastIndexOf(',');
    e.sn = fullName.substring(comma +1, fullName.length);
  }
  else {
    e.givenname = fullName;
    e.sn = fullName;
  }
}

function tabHTML() {
  if (state == 'init')
    return '';
  var s = '<TABLE border=0 cellspacing=0 cellpadding=0 width=100%>' +
    '<TR bgcolor=' + main.chrome0 + '><TD>' + 
    '<TABLE border=0 cellspacing=1 cellpadding=1 width=100%>' +
    '<TR align="center" bgcolor="' + main.chrome1 + '">' +
    (state != 'conflict' 
      ?
      main.tab(
        i18n_pe['new entry'],
        state == 'entry',
        'javascript:parent.displayPanel(\'entry\')',
        window.name) +
      main.tab(
        i18n_pe['more'],
        state == 'more',
        'javascript:parent.displayPanel(\'more\')',
        window.name) +
      main.tab(
        i18n_pe['notes'],
        state == 'notes',
        'javascript:parent.displayPanel(\'notes\')',
        window.name) +
      main.tab(
        i18n_pe['groups'],
        state == 'groups',
        'javascript:parent.displayPanel(\'groups\')',
        window.name)
      :
      main.tab(
        i18n_pe['conflict'],
        state == 'conflict',
        '',
        window.name)
    ) +
    '<TD>' + main.font() + nbsp + '</FONT></TD></TR></TABLE></TD></TR></TABLE>';

  return main.getBody(main.chrome2, true, false, false, false, main.black) + s;
}

function dataHTML() {
  return main.getBody(main.chrome2, true) + (tfr && state == 'POST' ? tfr : '');
}

function dataInit() {
  if (state == 'POST' && data.form)
    data.form.submit();
}

function idxHTML() {
  if (state == 'init')
    return '';
  if (state == 'entry')
    return entryIHTML();
  if (state == 'more')
    return entryIIHTML();
  if (state == 'notes')
    return notesHTML();
  if (state == 'groups')
    return groupsHTML();
  if (state == 'conflict'){
    if( !un )
      i18n_pe['conflicttext'] = 'Create a new entry.';
    else
      i18n_pe['conflicttext'] = 'Rename the entry';
    return conflictHTML();
  }

}

function oneRow(n1, n2, w) {
  var rv

  if (n1=='mail') 
    rv = (e.mail ? ((typeof(e.mail)=='string')? e.mail : e.mail.join('; ')) : '')
  else
    rv = eval('e.'+n1)
 
  return '<TR><TD align=right' + main.base_line + '>' + main.font() + n2.bold()+ '</TD>' + 
    '<TD><input type=text name="' + n1 + '" size="' + w +
    '" maxlength=' + MAXLEN + ' value="' + (rv ? html(rv) : '') + 
    '" onFocus="parent.requestFocus(this);" onChange="parent.checkValue(this);"></TD></TR>'
}

function entryHTML(ss) {
  var width1 = (NN > 0 && NN < 5) ? 15 : 35
  var s = ''
  for (var i in ss) {    
    s += oneRow(ss[i], i18n_pe[ss[i]], width1);
  }
  return main.getBody(main.chrome2, true, false, false, false, false, 9, 12) +
    '<form Accept-Charset="UTF-8" name=form><TABLE border=0 cellpadding=3 cellspacing=1>' + s + '</TABLE></FORM>';
}

function entryIHTML(ss) {
  var ss = new Array('givenname', 'sn', 'cn', 'mail', 'telephonenumber',
                     'homephone', 'mobile', 'pager',
                     'facsimiletelephonenumber');
  return entryHTML(ss);
}

function entryIIHTML() {
  var s, ss = new Array('street', 'l', 'st', 'postalcode',
                        'co', 'labeleduri', 'dateofbirth');
  return entryHTML(ss);
}

function notesHTML() {
  var s = '<CENTER><TABLE border=0 cellpadding=3 cellspacing=1>';
  // notes
  s += '<TR><TD><TEXTAREA name=description cols=50 rows=15 onFocus="parent.requestFocus(this);" onChange="parent.checkValue(this);">' + (e.description ? e.description : '') + '</TEXTAREA></TD></TR>';
  s += '</TABLE></CENTER>';
  return main.getBody(main.chrome2, true, false, false, false, false, 9, 12) +
    '<form Accept-Charset="UTF-8" name=form>' + s + '</FORM>';
}

function groupsHTML() {
  var i, j, g = main.pabFrame.groups;
  var s = '<TABLE border=0 cellpadding=3 cellspacing=1 width=100%><TR><TD colspan=4>' + main.font() + s_Mog() + '</FONT></TD></TR>';

  // sep
  s += '<TR><TD colspan=4><hr size=1></TD></TR>';
  // &! pabFrame must contain a valid PAB, groups and entries for this to work.
  for (i = 0; i < g.length; i += 2) {
    s += '<TR><TD width=1% nowrap><NOBR><input type=checkbox name=memberofpabgroup onClick="parent.checkValue(this);" value="' + g[i].un + '"' + (indexOfGroup(g[i].un) != -1 ? ' checked' : '') + '></NOBR></TD>' +
      '<TD width=40% nowrap><NOBR>' + main.font() + main.unescape_crlf(g[i].cn).bold() + '</FONT></NOBR></TD>';
    if (i + 1 < g.length)
      s += '<TD width=1% nowrap><NOBR><input type=checkbox name=memberofpabgroup onClick="parent.checkValue(this);" value="' + g[i + 1].un + '"' + (indexOfGroup(g[i + 1].un) != -1 ? ' checked' : '') + '></NOBR></TD>' +
      '<TD width=45% nowrap><NOBR>' + main.font() + main.unescape_crlf(g[i + 1].cn).bold() + '</FONT></NOBR></TD></TR>';
    else
      s += '<TD width=1% nowrap><NOBR>' + main.font() + nbsp + '</FONT></NOBR></TD>' +
      '<TD width=45% nowrap><NOBR>' + main.font() + nbsp + '</FONT></NOBR></TD></TR>';
  }
  if (!g.length)
    s += '<TR><TD colspan=4>' + main.font(2, main.chrome0) + i18n_pe['no groups'] + '</FONT></TD></TR>';
  s += '</TABLE>';
  return main.getBody(main.chrome2, true, false, false, false, false, 9, 12) +
    '<form Accept-Charset="UTF-8" name=form>' + s + '</FORM>';
}

function idxInit() {
  idx.focus();
  if (focal) {
    if (IE > 0)
      focal = idx.form[focal.name];
    if(focal.type=='text')
    {
      focal.focus();
      requestFocus(focal);
    }
  } else if (idx.form && idx.form.elements[0]) {
    if(idx.form.elements[0].type=='text')
    {
      idx.form.elements[0].focus();
      requestFocus(idx.form.elements[0]);
    }
  }
}

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

  if (un && state != 'conflict')
    s += '<TD height=100%>' + '<font>' + nbsp + nbsp + nbsp +
      main.nbutton('delete', i18n_pe['delete'], "parent.delEntry()", '', 'Btn2') + '</FONT></TD>';
  s += '<TD height=100% align=right>' + '<font>' + nbsp + nbsp + nbsp +
    main.nbutton('ok', (state != 'conflict' ? i18n_pe['ok'] : i18n_pe['continue']), "parent.ok()") + nbsp +
    main.nbutton('esc', i18n_pe['cancel'], "parent.cancel()", '', 'Btn2') + nbsp +
    main.nbutton('help', i18n_pe['help'], "main.help()", '', 'Btn2') +
    nbsp + nbsp + nbsp + '</FONT></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 displayPanel(s) {
  if (forceCheck())
    return;
  stateFocal[state] = focal;
  state = s;
  focal = stateFocal[state];
  // requestFocus(stateFocal[state]);
  focal = null;
  reload(idx);
  reload(tab);
}

function indexOfGroup(n) {
  if (!e.memberofpabgroup)
    return -1;
  for (var i = 0; i < e.memberofpabgroup.length; i++) {
    if (e.memberofpabgroup[i] == n)
      return i;
  }
  return -1;
}

function delEntry() {
  if (delEntryConfirm()) {
    state = 'delete';
    tfr = main.msgHREF + 'ldap.msc?sid=' + main.sid + '&ldapurl=pab&filter=' +
          encode('cmd=PAB_CMD_DEL_ENTRY|old=' + main.pabAttrs['un'].name + ':' + e.un + '\n' + 
          main.pabAttrs['objectclass'].name + ':' + e.objectclass + '\n\n|')
    load(data, tfr);
  }
}

function getDuplicates() {
  var i, a = new Array();

  if (!main.pabFrame.pab_cmd || main.pabFrame.pab_cmd == 'PAB_CMD_ADD_ENTRY') {
    state = 'pabinit';
    //main.fetchPab();
  } else {
    state = 'pab';
    //mailFrame.refresh();
  }

  if (!main.curPab) {
    load(main.pabFrame, main.msgHREF + 'ldap.msc?sid=' + main.sid + '&ldapurl=pab&filter=' +
      main.encode('cmd=PAB_CMD_EDIT|pab=' + main.curPab + '|from=0|len=999|'));
  }

  for (i = 0; i < main.pabFrame.people.length; i++) {
   if(main.people[i].cn && e.cn && main.people[i].mail && e.mail)
   {
    var primaryEmail = isArray(e.mail)? e.mail[0] : e.mail
    if ((main.people[i].cn.toLowerCase() == e.cn.toLowerCase()) && 
        (main.people[i].mail[0].toLowerCase() == primaryEmail.toLowerCase()))
      a[a.length] = main.people[i];
   }
  }
  return a;
}

function quickCheck(fe) {
  fe.value = trim(fe.value);

  if(e[fe.name] != fe.value)
    deletedvalues[fe.name] = 1;

  if (fe.value.length > 0)
    e[fe.name] = fe.value;
  else
    e[fe.name] = '';
}

// Entry validation routines
// givennameCheck and snCheck defined in <lang>/editPabEntry_fs.html
function cnCheck(fe) {
  var s = '';
  fe.value = trim(fe.value)
  if(e[fe.name] != fe.value)
    deletedvalues[fe.name] = 1;

  if(fe.value.length > 0)
      e[fe.name] = fe.value;
  else {
      fe.value = e[fe.name];
    s = s_NonBlank(fe.name);
  }
  reload(tab);
  return s;
}

function cleanAddr(addr) {
  var a, i, q = false

  a = split(addr, '')
  for (i = 0; i < addr.length; i++) {
    if (a[i] == '"')
      q = !q

    if ((a[i] > '~' || a[i] == ':' || a[i] == ';' || a[i] == ',' ) && !q)
      return i18n['invalid addr'];

  }
  return join(compressArray(a), '')
}

function mailCheck(fe) {
  if (trim(fe.value).length < 1) {
    fe.value = e.mail = '';
    deletedvalues.mail = 1
    return '';
  }
  var i, tmp = cleanAddr(fe.value);
  if(tmp==i18n['invalid addr']){
    valid_email=false;
    reload(tab);
    return tmp;
  }

  tmp = split(tmp, '\n');
  tmp = compressArray(tmp);
  e.mail = new Array(tmp.length);
  for (i = 0; i < tmp.length; i++) {
    e.mail[i] = tmp[i];
  }
  fe.value = join(e.mail, '; ');
  deletedvalues.mail = 1
  valid_email=true;
  return '';
}

var telephonenumberCheck = quickCheck;
var homephoneCheck = quickCheck;
var mobileCheck = quickCheck;
var pagerCheck = quickCheck;
var facsimiletelephonenumberCheck = quickCheck;

// More validation routines
var streetCheck = quickCheck;
var lCheck = quickCheck;
var stCheck = quickCheck;
var postalcodeCheck = quickCheck;
var coCheck = quickCheck;
var labeleduriCheck = quickCheck;
var dateofbirthCheck = quickCheck;

// Notes validation routines
var descriptionCheck = quickCheck;

// Groups validation routines
function memberofpabgroupCheck(fe) {
  if (fe.checked) {
    if (!e.memberofpabgroup)
      e.memberofpabgroup = new Array();
//    alert(fe.name + '\n\n' + fe.value);
    if (indexOfGroup(fe.value) == -1)
      e.memberofpabgroup[e.memberofpabgroup.length] = fe.value;
  } else if (e.memberofpabgroup) {
    var i = indexOfGroup(fe.value);
    if (i != -1) {
      e.memberofpabgroup[i] = '';
      e.memberofpabgroup = compressArray(e.memberofpabgroup);
    }
  }
}

function dupCheck(fe) {
  un = e.un = fe.value;
  // &! IE thinks that focal is non-null when we get here, and I don't know why.
  // When forceCheck() fires in ok() it checks the value of focal, which in the
  // case of a conflict is empty, and so sets un to empty even when it contains
  // a value. This forces IE to behave and provide the correct value for e.un.
  focal = null;
}

function ok() {
  if (forceCheck())
    return;
    
  if(valid_email==false){
    alert(i18n['invalid addr']);
    return;
  }

  if (state != 'conflict') {
    dups = getDuplicates();
    if ((!un && dups.length) || (un && ( deletedvalues.cn || deletedvalues.mail ) && dups.length)) {
      alert(i18n_pe['entry exists']);
      return; 
    }
  }
  var i;
  var criteria = un
    ? 'cmd=PAB_CMD_MOD_ATTRIBUTES|old=' + main.pabAttrs['un'].name + ':' + e.un + '\n\n|new='
    : 'cmd=PAB_CMD_ADD_ENTRY|new=';
  if(!un) {
    for (p in e) {
      if (e[p]) {
        if ((main.pabAttrs[p].type & 8) && isArray(e[p])) {
          if(p.toLowerCase()=='memberofpabgroup' && e[p].length==0) {
            criteria += main.pabAttrs[p].name + ':' + main.escape_crlf(e[p]) +'\n'
          }
          for (i = 0; i < e[p].length; i++) {
            // in case replacing a group, do not be a member of that group
            if (p.toLowerCase() != 'memberofpabgroup' || e[p][i] != un) {
              criteria += main.pabAttrs[p].name + ':' + main.escape_crlf(e[p][i]) + '\n';
            }
          }
        } else {
          criteria += main.pabAttrs[p].name + ':' + main.escape_crlf(e[p]) + '\n';
        }
      }
      else if(deletedvalues[p] == 1) criteria += main.pabAttrs[p].name + ':' + main.escape_crlf(e[p]) + '\n'; 
    }
  }
  else{
    for(p in deletedvalues){
      if(deletedvalues[p] == 1) {
        if ((main.pabAttrs[p].type & 8) && isArray(e[p])) {
          for (i = 0; i < e[p].length; i++) 
            criteria += main.pabAttrs[p].name + ':' + main.escape_crlf(e[p][i]) + '\n';
        }
          else criteria += main.pabAttrs[p].name + ':' + main.escape_crlf(e[p]) + '\n';
      }
    }
  }
  criteria += '\n|';

  tfr = '<form Accept-Charset="UTF-8" name=form method=post action="' + main.msgHREF + 'ldap.msc">' +
    '<INPUT type=hidden name=sid value="' + main.sid + '">' +
    '<INPUT type=hidden name=security value="' + main.security + '">' +
    '<INPUT type=hidden name=ldapurl value="pab">' +
    main.get_form_charset() +
    '<INPUT type=hidden name=filter value="' + criteria + '"></FORM>';
  state = 'POST';
  reload(data);
}

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

function pabCB() {

  if ( data.people) {
    if(data.pab_cmd!='PAB_CMD_DEL_ENTRY')
    {
      current_givenname=data.people[0].givenname;
      current_sn=data.people[0].sn;
    }
  }
  tfr = '';
  if (data.color)
    data.color(main.chrome2);
  if (data.errno != 0) {
    alert(data.errstr);
    return;
  }
  if (state == 'init') {
    if (data.people.length) {
      e = data.people[0];
      deletedvalues = cloneObject(data.people[0])
      for (p in e) {
        if ((main.pabAttrs[p].type & 8) && isArray(e[p])) {
          deletedvalues[p] = 0
          for (var i = 0; i < e[p].length; i++)
            e[p][i] = main.unescape_crlf(e[p][i]);
        } else {
          e[p] = main.unescape_crlf(e[p]);
          deletedvalues[p] = 0
        }
      }
    }
    state = 'entry';
    reload(idx);
    reload(tab);
    reload(btn);
  } else if (state == 'POST' || state == 'delete') {
    if (main.state == 'pab')
      main.state = 'pabinit';
    // If we're deleting this entry or removing it from the current group,
    // then we want to use the "next" entry as determined by the variable 
    // mark in pab.js so don't muck with lastModUn.
    if (state != 'delete' && (main.curPabGrp == 1 || indexOfGroup(main.curPabGrp) != -1))
      main.lastModUn = e.un ? e.un : data.people[0].un;
    main.fetchPab();
    window.close();
  }
}
