/*       g ... the group object instance
 *      un ... universal name (used to select initial group view)
 *   state ... {init, list}
 *     exc ... an array of entry objects not included in this recipient list
 *      to ... an array of entry objects to whom this mail should be sent
 *      cc ... an array of entry objects that should be cc'd
 *     bcc ... an array of entry objects that should be bcc'd
 */
var un, state = 'init', inc = new Array(), exc = new Array(), to = new Array(), cc = new Array(), bcc = new Array(), PAB_GRP_ALL = 1, PAB_GRP_UNFILED = 2, curPabGrp = PAB_GRP_ALL;
var viewAllGroups=false;
var PAB_ONLY_GRP = 3
var x;
var lookupWindow;

function P(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
  this.cn = a0
  this.sn = a1
  this.givenname = a2
  this.mail = a3
  this.description = a4
  this.telephonenumber = a5
  this.homephone = a6
  this.memberofpab = a7
  this.memberofpabgroup = a8
  this.un = a9
  this.objectclass = a10
}


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

function setUp() {
  var s = window.location.search;
  if ((un = getArg('un', s)) != null)
    curPabGrp = un;
  if(main.cfgFrame.pabEnabled == 1)
  	setUpMembers();
  state = 'list';
}

function setUpMembers() {
  var a = main.pabFrame.people;
  // Iterate over the entries array in pabFrame, selecting only those entries with an email address.
  for (var i = 0; i < a.length; i++) {
    if (a[i].mail && a[i].mail[0])
     {
       exc[exc.length] = a[i];
       exc[exc.length - 1].whereAmI = 'e';
       exc[exc.length - 1].ptr = exc.length - 1;
     }
  }

  var a= main.pabFrame.groups;
  for (var i = 0; i < a.length; i++) {
      exc[exc.length] = a[i];
      exc[exc.length - 1].whereAmI = 'e';
      exc[exc.length - 1].ptr = exc.length - 1;
  }

}

function lookup() {

  lookupWindow = new Window(main.srcHREF + main.lang + '/lookup_fs.html?'+main.clientargs(), 
      'lookupWindow' + main.unique++, 'resizable,' +
      (mac ? 'width=540,height=280' : 'width=620,height=370'))
}

function tabHTML() {
  if (state == 'init')
    return '';
  var s = '<TABLE border=0 cellspacing=0 cellpadding=0 width=100%>' +
    '<TR bgcolor=' + main.chrome1 + '><TD>' + 
    '</TD></TR></TABLE>'
  
  s = ''
  return main.getBody(main.chrome2, true, false, false, false, main.black) + s;
}

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

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

function idxHTML() {
  if (state == 'init')
    return '';
  if (state == 'list')
    return listHTML();
}

function listHTML() {
   var s = '<CENTER><TABLE border=0 cellpadding=0 cellspacing=3 width=100%>';
  // display name
  if(main.cfgFrame.pabEnabled == 1) {
  	s += '<TR><TD colspan=3>' + main.font() + i18n_cr['pab entries'] + '</FONT></TD></TR>';
  	s += '<tr><td bgcolor="'+main.chrome2+'" colspan="3"><img src="imx/spacer.gif" width="1" height="6"></td></tr>'
  	s += '<TR><TD colspan=2>' + main.font() + emitGroupList() + '</FONT></TD><TD nowrap>' + main.font() + i18n_cr['inc'] + '</FONT></TD></TR>';
  }
  s += '<tr><td bgcolor="'+main.chrome2+'" colspan="3"><img src="imx/spacer.gif" width="1" height="6"></td></tr>'
  s += '<TR>' + swapEntriesCtrl() + '</TR>';
  s += '<tr><td bgcolor="'+main.chrome2+'" colspan="3"><img src="imx/spacer.gif" width="1" height="6"></td></tr>'
  s += '</TABLE></CENTER>';
  return main.getBody(main.chrome2, true, false, false, false, false, 0, 0) +
    '<FORM name=form>' + s + '</FORM>';
}

function swapEntriesCtrl() {
// replace i18n for search

  var s =''
  var w = NN > 0 ? ' width=64' : ' width=106';

  var exitFlag = 'false';
  var groupLength = 0;
 
  s += '<TD valign=top nowrap width="25%">' + main.font() + '<SELECT size=13 multiple name=excludes>';

  if(main.cfgFrame.pabEnabled == 1) {
  var mygrouplist = main.pabFrame.groups;
  for ( var j=0;j < mygrouplist.length && exitFlag=='false'; j++ ) 
	if( curPabGrp == mygrouplist[j].un ) 
	{
		for ( k=0; k< exc.length && exitFlag=='false';k++)
			if ( curPabGrp == exc[k].un )
		        {
				s += '<OPTION value="' + exc[k].ptr + '">' + main.unescape_crlf(mygrouplist[j].cn) +'</OPTION>';
				exitFlag = 'true'
			}
	}


  for (var i = 0; i < exc.length; i++) {
    // If there is no current group, assume ALL
    // If the current group un (stored in curPabGrp) is 1, assume UNFILED
     if (curPabGrp == 1 || curPabGrp == 3 || 
      (curPabGrp == 2 && !exc[i].memberofpabgroup) ||
      ((isNaN(curPabGrp)? true : curPabGrp > 3) && indexOfGroup(exc[i], curPabGrp) > -1))
   
    {
       if(exc[i].objectclass=="pabperson" && curPabGrp != PAB_ONLY_GRP )
		s += '<OPTION value="' + exc[i].ptr + '">' + main.unescape_crlf(exc[i].cn) + '</OPTION>';
	    else if ( exc[i].objectclass=="pabgroup" && curPabGrp != 1 )
 	  s += '<OPTION value="' + exc[i].ptr + '">' + main.unescape_crlf(exc[i].cn) + '</OPTION>';  // pramod    
    }
        
  }
  }
  s += '<OPTION value="">' + i18n['scl sep'] + '</OPTION>';
  s += '</SELECT></FONT></TD>';

  s += '<TD align="center"width="150">'
    + main.nbutton('inc', i18n_cr['to'], "parent.incE(\'t\')", w) + '<BR><BR>'
    + main.nbutton('inc', i18n_cr['cc'], "parent.incE(\'c\')", w) + '<BR><BR>'
    + main.nbutton('inc', i18n_cr['bcc'], "parent.incE(\'b\')", w) + '<BR><BR>'
    + main.nbutton('exc', i18n_cr['remove'], "parent.excE()", w) + '<BR><BR><BR>'
    + main.nbutton('inc', i18n_cr['search'], "parent.lookup()", w, 'Btn2')
    + '</TD>';

  s += '<TD valign=top nowrap width="70%">' + main.font() + '<SELECT size=13 multiple name=includes>';
  s += s_recipientList();
  s += '<OPTION value="">' + i18n['scl sep'] + '</OPTION>';
  s += '</SELECT></FONT></TD>';

  viewAllGroups = false;

  return s;
}


function indexOfGroup(e, 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 emitGroupList() {
  var g = main.pabFrame.groups;
  var s = '<SELECT name=groupSel onChange="if(!this.options[this.selectedIndex].value){for (var i=0;i<this.options.length;i++){if(this.options[i].value==parent.curPabGrp)this.options[i].selected=true;}}else{parent.selExc(this.options[this.selectedIndex].value);}">';

  s += '<OPTION>' + i18n_cr['View'] + '</option><option value="' + PAB_GRP_ALL + '"' + (curPabGrp == PAB_GRP_ALL ? ' selected' : '') + '>' + i18n['list indent'] + i18n_cr['all group'] + '</OPTION>';
  s += '<OPTION value="' + PAB_ONLY_GRP + '"' + (curPabGrp == PAB_ONLY_GRP ? ' selected' : '') + '>' + i18n['list indent'] + i18n_cr['groups only'] + '</option>'
  if (g) {
    for (var i = 0; i < g.length; i++)
      s += '<OPTION value="' + g[i].un + '"' + (curPabGrp == g[i].un ? ' selected' : '') + '>' + i18n['list indent'] + main.unescape_crlf(g[i].cn) + '</OPTION>';
  }
  return s + '<OPTION value="' + PAB_GRP_UNFILED + '"' + (curPabGrp == PAB_GRP_UNFILED ? ' selected' : '') + '>' + i18n['list indent'] + i18n_cr['unfiled group'] + '</OPTION></SELECT>';
}


function idxInit() {
  idx.focus();
}

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

  s += '<TD height=100% align=right>' + nbsp + nbsp + nbsp +
    main.nbutton('ok', i18n_cr['ok'], "parent.ok()") + nbsp +
    main.nbutton('esc', i18n_cr['cancel'], "parent.cancel()", '', 'Btn2') + nbsp +
    main.nbutton('help', i18n_cr['help'], "main.help()", '', 'Btn2') +
    nbsp + nbsp + nbsp + '</TD></TR></TABLE>';
  
  return main.getBody(main.chrome0, true, main.white, false, false, false, 1, 1) +
    '<FORM name=FORM>' + s + '</FORM>';
}

function isInc(n, a) {
  for (var i = 0; i < a.length; i++) {
    if (n == a[i].un)
      return i;
  }
  return -1;
}

function isExc(n) {
  for (var i = 0; i < exc.length; i++) {
    if (n == exc[i].un)
      return i;
  }
  return -1;
}

function sortByName(a, b) {
  var s1 = a.cn;
  var s2 = b.cn;

  if (s1 < s2)
    return -1;
  else if (s1 > s2)
    return 1;
  return 0;
}

function incE(t) {
  var i, j, e = idx.form.excludes.options;
  a = (t == 'b' ? bcc : (t == 'c' ? cc : to));

  for (i = 0; i < e.length; i++) {
    if(e[i].value == "") continue;
    var sel = parseInt(e[i].value,10);
    if (e[i].selected && exc[sel].un) {
      if (exc[sel].whereAmI != t) {
        exc[sel].whereAmI = t;
        a[a.length] = exc[sel];
      }
    }
  }
  reload(idx);

}

function fromLookup(t,what)
{
  var tempMail
  a = (t == 'b' ? bcc : (t == 'c' ? cc : to));
  if(isArray(what.mail)) tempMail = what.mail[0]
  else tempMail = what.mail

  if(isInc(what.un,a) == -1)
  {
    a[a.length] =  new P(what.cn,what.sn,what.givenname,new Array(tempMail),'','','',new Array(what.memberofpab),
       new Array(what.memberofpabgroup),what.un,what.objectclass);
 
    for (var i = 0; i < exc.length; i++) {
      if (a[a.length-1].un == exc[i].un)
      {
        exc[i].whereAmI = t;
        a[a.length-1].whereAmI = t;
        a[a.length-1].ptr = exc[i].ptr;
        break;
      }
    }
  }
}

function reloadIdx()
{
  reload(idx);
}

function excE() {
  var i, j, k = -1, e = idx.form.includes.options;

  for (i = 0; i < e.length; i++) {
    if (e[i].selected && e[i].value) {
        if ((j = isInc(e[i].value, to)) != -1) {
          if (typeof(to[j].ptr) != "undefined") exc[to[j].ptr].whereAmI = 'e';
          to[j] = '';
      }
        if ((j = isInc(e[i].value, cc)) != -1) {
          if (typeof(cc[j].ptr) != "undefined") exc[cc[j].ptr].whereAmI = 'e';
          cc[j] = '';
        }
        if ((j = isInc(e[i].value, bcc)) != -1) {
          if (typeof(bcc[j].ptr) != "undefined") exc[bcc[j].ptr].whereAmI = 'e';
          bcc[j] = '';
        }
    }
  }
  to = compressArray(to);
  cc = compressArray(cc);
  bcc = compressArray(bcc);
  reload(idx);
}

function selExc(g) {
  curPabGrp = g;
  reload(idx);
}

function ok() {
  var i, k, st, s;

  s = '';
  for (i = 0; i < to.length; i++)
   if ( to[i].objectclass=="pabperson") {
		if(i==0) s += s_EmailEntry(to[i].cn, to[i].mail[0], true) 
		else s += ','+ s_EmailEntry(to[i].cn, to[i].mail[0], true);
	}
    else if( to[i].objectclass=="pabgroup") {
		if( to[i].un.indexOf(',') != -1 )
		{
			s = to[i].un
		}
		else 
		{

			if(i==0 ) s += s_EmailGroup(to[i].cn,to[i].un,true)
			else s += ','+ s_EmailGroup(to[i].cn,to[i].un,true);

		}
	}

  s = unescape(s)
  st = window.opener.compFrame.form.forTo.value
  if ( st != '')
    s = st + ', ' + s

  window.opener.saveForTo = window.opener.compFrame.form.forTo.value = s

  s = ''

  for (i = 0; i < cc.length; i++)
   if ( cc[i].objectclass=="pabperson") {
		if(i==0) s += s_EmailEntry(cc[i].cn, cc[i].mail[0], true) 
		else s += ','+ s_EmailEntry(cc[i].cn, cc[i].mail[0], true);
	}
    else if( cc[i].objectclass=="pabgroup") {
		if( cc[i].un.indexOf(',') != -1 )
		{
			s = cc[i].un
		}
		else 
		{

			if(i==0 ) s += s_EmailGroup(cc[i].cn,cc[i].un,true)
			else s += ','+ s_EmailGroup(cc[i].cn,cc[i].un,true);

		}
	}

  s = unescape(s)
  st = window.opener.compFrame.form.forCc.value
  if ( st != '')
    s = st + ', ' + s

  window.opener.saveForTo = window.opener.compFrame.form.forCc.value = s

  s = '';

  for (i = 0; i < bcc.length; i++)
    if ( bcc[i].objectclass=="pabperson") {
	if( i==0) s += s_EmailEntry(bcc[i].cn, bcc[i].mail[0], true)
	else s += ',' + s_EmailEntry(bcc[i].cn, bcc[i].mail[0], true);
	}

    else if( bcc[i].objectclass=="pabgroup") {

		if( bcc[i].un.indexOf(',') != -1 )
		{
			s = bcc[i].un
		}
		else 
		{
			if( i==0) s += s_EmailGroup(bcc[i].cn,bcc[i].un,true);
			else s += ',' + s_EmailGroup(bcc[i].cn,bcc[i].un,true)
		}
	}

  s = unescape(s)
  st = window.opener.compFrame.form.forBcc.value
  if ( st != '')
    s = st + ', ' + s

  window.opener.saveForTo = window.opener.compFrame.form.forBcc.value = s

  if (NN > 4.04 || NN < 4 || IE > 3) {
    window.close();
    main.lookupWindow = null
    if(lookupWindow) lookupWindow.close()
  }
}

function cancel() {
  window.close();
  main.lookupWindow = null 
  if(lookupWindow) lookupWindow.close()
}

function pabCB() {
  if (data.color)
    data.color(main.chrome2);
  if (data.errno != 0) {
    alert(data.errstr);
    return;
  }
}
