
var is_ie = window.external && document.all && !window.opera && !window.XMLHttpRequest && window.ActiveXObject;

try
{
   SetupHandlers(document.getElementsByTagName("input"));
}
catch (e)
{
}

function SetupHandlers(in_Buttons)
{
   var l_Button;
   for (var i = 0; (l_Button = in_Buttons[i]); ++i)
   {
      switch(l_Button.type)
      {
         case "submit":
         case "reset":
         case "button":
         l_Button.onmouseover = HandleMouseover;
         l_Button.onmouseout = HandleMouseout;
         l_Button.hideFocus = true;
         if (l_Button.disabled && is_ie)
         {
            l_Button.style.backgroundColor = "#c0c0c0";
         }
      }
   }
}

function IAmSure(IAmSureCheckbox)
{
   var l_Disabled = !IAmSureCheckbox.checked;
   var l_Form = IAmSureCheckbox.form;
   var l_Arg;
   for (var i = 1; (l_Arg = arguments[i]); ++i)
   {
      var l_Button = l_Form.elements[l_Arg];
      l_Button.disabled = l_Disabled;
      if (is_ie)
      {
         l_Button.style.backgroundColor = l_Disabled ? "#c0c0c0" : "";
      }
   }
}

function HandleMouseover()
{
   this.className = "btn btnhigh";
}

function HandleMouseout()
{
   this.className = "btn";
}

function prepareBrowser()
{
   var i;
   var li = document.getElementsByTagName("li");
   if (window.opener)
   {
      for (i = 0; i < li.length; ++i)
      {
         li[i].pathpart = getInnerText(li[i].childNodes[0]);
         var span = document.createElement("span");
         span.innerHTML = '<a hidefocus href="#" class="action" onclick="return goodmbx(this)">g</a>-<a hidefocus href="#" class="action" onclick="return spammbx(this)">s</a>-<a hidefocus href="#" class="action" onclick="return ignorembx(this)">i</a>&nbsp;&nbsp;';
         li[i].insertBefore(span, li[i].childNodes[0]);
      }
   }
   li = document.getElementsByName("dom");
   for (i = 0; i < li.length; ++i)
   {
      li[i].parentNode.isDom = true;
   }

   li = document.getElementsByName("mbx");
   for (i = 0; i < li.length; ++i)
   {
      var a = li[i];
      a.pathpart = getInnerText(a);
      var tx = "";
      var pos = 0;
      while((pos = a.innerHTML.indexOf("/", pos + 1)) != -1)
      {
         tx += "\xA0\xA0\xA0";
      }
      pos = a.innerHTML.lastIndexOf("/");
      if (pos != -1)
      {
         a.parentNode.insertBefore(document.createTextNode(tx), a);
         a.innerHTML = a.innerHTML.substr(pos + 1);
      }

      a.onclick = openweb;
      a.href = "#";
   }
}

function getInnerText(obj)
{
   if (obj.innerText)
   {
      return obj.innerText;
   }
   if (obj.childNodes[0])
   {
      return obj.childNodes[0].nodeValue;
   }
   return obj.innerHTML;
}

function openweb()
{
   window.open("open?path=" + getAccount(this) + "&mailbox=" + encodeURI(this.pathpart).replace(/&/g, "%2526"));
   return false;
}

function getAccount(src)
{
   src = src.parentNode.parentNode.parentNode;
   return src.pathpart + "@" + src.parentNode.parentNode.pathpart;
}

function getPath(src)
{
   if (src.isDom)
   {
      return src.pathpart;
   }
   else
   {
      return getPath(src.parentNode.parentNode) + "/" + src.pathpart;
   }
}

function goodmbx(src)
{
   return appendbox("w_traingood", getPath(src.parentNode.parentNode));
}

function spammbx(src)
{
   return appendbox("w_trainspam", getPath(src.parentNode.parentNode));
}

function ignorembx(src)
{
   return appendbox("w_trainignore", getPath(src.parentNode.parentNode));
}

function appendbox(boxname, text)
{
   try
   {
      var obj = window.opener.document.getElementsByName(boxname)[0];
      if (obj.value.length && (obj.value.charAt(obj.value.length-1) != "\n"))
      {
         obj.value += "\n";
      }
      obj.value += text + "\n";
   }
   catch(err)
   {
      alert("Unable to interface with the configuration wizard page.\n\nPlease try to close and reopen the Mailboxes browser");
   }

   return false;
}

String.prototype.trim = function()
{
   return this.replace(/^\s+/, '').replace(/\s+$/, '');
};


function disableWrap(in_TextArea)
{
   var l_Parent = in_TextArea.parentNode;
   var l_NextSib = in_TextArea.nextSibling;
   l_Parent.removeChild(in_TextArea);
   in_TextArea.wrap = "off";
   in_TextArea.setAttribute("wrap", "off");
   in_TextArea.style.display = 'none';
   if (l_NextSib)
   {
      l_Parent.insertBefore(in_TextArea, l_NextSib);
   }
   else
   {
      l_Parent.appendChild(in_TextArea);
   }
   in_TextArea.style.display = '';
}

function trimLicense(in_TextArea)
{
   var l_Lines = in_TextArea.value.replace(/\r/, "").split(/\n/);
   for (var i = 0; i < l_Lines.length; ++i)
   {
      l_Lines[i] = l_Lines[i].trim();
      if (!l_Lines[i].length)
      {
         l_Lines.splice(i,1);
         --i;
      }
   }
   in_TextArea.value = l_Lines.join("\n");
}

function returnFalse()
{
   return false;
}

function replaceBySpan(in_Object, in_Html)
{
   var node = document.createElement("span");
   node.innerHTML = in_Html;
   node.style.fontWeight = "bold";
   node.style.border = "1px solid #c0c0c0";
   node.style.color = "#A0A0A0";
   node.style.padding = "1px";
   node.style.margin = "1px";
   node.style.display="inline-block";
   node.style.width = in_Object.offsetWidth + "px";
   in_Object.parentNode.insertBefore(node, in_Object);
   in_Object.parentNode.removeChild(in_Object);
}

function disableInputs()
{
   var l_Form = document.forms[0];
   if (l_Form)
   {
      var l_Element;
      var l_ElementArray = [];
      var i;
      for (i = 0; (l_Element = l_Form.elements[i]); ++i)
      {
         l_ElementArray.push(l_Element);
      }

      for (i = 0; (l_Element = l_ElementArray[i]); ++i)
      {
         switch (l_Element.type)
         {
            case "select-one":
               replaceBySpan(l_Element, l_Element.options[l_Element.selectedIndex].innerHTML);
               break;
            case "text":
            case "password":
               replaceBySpan(l_Element, l_Element.value);
               break;
            case "submit":
            case "button":
            case "reset":
               l_Element.parentNode.removeChild(l_Element);
               break;
            case "checkbox":
            case "radio":
               l_Element.disabled = true;
         }
      }
   }
}

function keepSessionActive()
{
   var l_Object = createXmlHttp();
   if (!l_Object)
   {
      return;
   }
   l_Object.onreadystatechange = returnFalse;
   l_Object.open("GET", "./noop", true);
   l_Object.setRequestHeader("Cache-Control","no-cache");
   l_Object.send(null);

   setTimeout(keepSessionActive, 150000);
}

function createXmlHttp()
{
   return window.XMLHttpRequest ? new XMLHttpRequest() : window.ActiveXObject ? new ActiveXObject("Msxml2.XMLHTTP") : null;
}

function checkUpgrade()
{
   var l_xml = createXmlHttp();
   if (!l_xml)
   {
      return;
   }

   var l_Object;
   for (var i = 0; (l_Object = document.getElementsByTagName("fieldset")[i]); ++i)
   {
      l_Object.style.display = "none";
   }

   document.getElementById("statuscode").innerHTML = '<fieldset><legend>File downloaded and unpacked, upgrade in progress...</legend><p>When the upgrade is complete, you should be brought back to the main page</p><p>The upgrade process should take less than a minute. After this delay, please monitor the CGP logs to verify if the restart happened properly, or <a href="/">click here</a> to try to load the main page</p><p><input id="countdown" type=text size=2 value=60 readonly></fieldset>';

   setTimeout(upgradeLoop, 1000);
}

function upgradeLoop()
{
   var l_Countdown = document.getElementById("countdown");
   var l_Current = parseInt(l_Countdown.value) - 1;
   l_Countdown.value = l_Current;

   if (l_Current <= 0)
   {
      document.getElementById("statuscode").innerHTML = '<fieldset><legend>Update status unknown</legend><p>60 seconds elapsed, PolluStop doesn\'t seem to be up yet. Please check the CGP logs to verify that PolluStop restarted successfully. If you have problems starting the new version of PolluStop, you can restore the previous version which was automatically backuped in a subdirectory of the PolluStop installation directory. You can also contact Niversoft for assitance.</fieldset>';
      return;
   }

   if ((l_Current < 52) && (l_Current % 2))
   {
      var l_Object = createXmlHttp();
      l_Object.onreadystatechange = function()
      {
         if ((l_Object.readyState == 4) && (l_Object.status == 200))
         {
            l_Object.onreadystatechange = returnFalse;
            if (!window.gotIt)
            {
               window.gotIt = true;
               alert("Upgrade completed successfully");
               window.location.href = "/";
            }
         }
      };
      l_Object.open("GET", "/version", true);
      l_Object.setRequestHeader("Cache-Control","no-cache");
      l_Object.send(null);
   }
   if (!window.gotIt)
   {
      setTimeout(upgradeLoop, 1000);
   }
}

function InitRegex()
{
   window.l_Template = document.getElementById("obj_template");
   window.l_Parent = l_Template.parentNode;
   window.l_NextCellId = document.getElementsByName("num").length - 1;
   l_Parent.removeChild(l_Template);
   AddRow();
}

function AddRow()
{
   var l_Cloned = l_Template.cloneNode(true);
   l_Parent.appendChild(l_Cloned);
   l_Cloned.cells[0].childNodes[0].value = l_NextCellId;
   l_Cloned.cells[0].childNodes[1].name = "name_" + l_NextCellId;
   l_Cloned.cells[1].childNodes[0].name = "regex_" + l_NextCellId;
   l_Cloned.cells[2].childNodes[0].name = "nocase_" + l_NextCellId;
   l_Cloned.cells[3].childNodes[0].name = "value_" + l_NextCellId;
   l_Cloned.cells[1].childNodes[0].onchange = VerifyRegex;
   ++l_NextCellId;
}

function DelRow(in_src)
{
   if (confirm("Click OK to delete this regex"))
   {
      in_src.parentNode.parentNode.removeChild(in_src.parentNode);
   }
}

function VerifyRegex(in_This)
{
   in_This = in_This || this;
   try
   {
      new RegExp(in_This.value);
   }
   catch (in_error)
   {
      in_This.style.backgroundColor = "#ff8080";
   }
   in_This.onfocus = ResetBG;
}

function VerifySyntax(in_Alert, in_Color)
{
   var l_Return = true;
   var l_num;
   for (var r = 0; (l_num = document.getElementsByName("num")[r]); ++r)
   {
      l_num = l_num.value;
      var l_Error = false;
      var l_Namefield = document.getElementsByName("name_" + l_num)[0];
      var l_Regexfield = document.getElementsByName("regex_" + l_num)[0];
      if (l_Regexfield.value.length || l_Namefield.value.length)
      {
         l_Error = !l_Namefield.value.length || !l_Regexfield.value.length;

         if (in_Color)
         {
            l_Namefield.style.backgroundColor = l_Namefield.value.length ? "#80ff80" : "#ff8080";
         }

         try
         {
            new RegExp(l_Regexfield.value);
            if (in_Color)
            {
               l_Regexfield.style.backgroundColor = l_Regexfield.value.length ? "#80ff80" : "#ff8080";
            }
         }
         catch (in_error)
         {
            if (in_Color)
            {
               l_Regexfield.style.backgroundColor = "#ff8080";
            }
            l_Error = true;
         }
      }

      l_Return = l_Return && !l_Error;
      l_Regexfield.onfocus = ResetBG;
      l_Namefield.onfocus = ResetBG;
   }

   if (in_Alert && !l_Return)
   {
      alert('Please verify your entries');
   }
   return l_Return;
}

function ResetBG()
{
   this.style.backgroundColor = "";
   this.onfocus = null;
}

function MatchRegex()
{
   if (!VerifySyntax(false, false))
   {
      VerifySyntax(true, true);
      return false;
   }

   var l_Text = document.getElementById("customtext").value.replace(/\r/g, "").split("\n");
   var l_Results = [];
   var l_num;
   for (var r = 0; (l_num = document.getElementsByName("num")[r]); ++r)
   {
      l_num = l_num.value;
      var l_Name = document.getElementsByName("name_" + l_num)[0].value;
      var l_Regex = document.getElementsByName("regex_" + l_num)[0].value;
      var l_Nocase = document.getElementsByName("nocase_" + l_num)[0].checked;

      if (l_Regex.length)
      {
         try
         {
            l_Regex = new RegExp(l_Regex, l_Nocase ? "i" : "");
         }
         catch (in_error) { continue; }

         for (var i = 0; i < l_Text.length; ++i)
         {
            if (l_Regex.test(l_Text[i]))
            {
               l_Results.push("Matched regex named '" + l_Name + "'");
               break;
            }
         }
      }
   }
   if (!l_Results.length)
   {
      l_Results.push ("No regex matched");
   }
   document.getElementById("testresults").innerHTML = "Results:<ul><li>" + l_Results.join("</li><li>") + "</li></ul>";
}

function TestLists()
{
   var l_Object = createXmlHttp();
   if (!l_Object)
   {
      return true;
   }

   var l_test_result = document.getElementById("test_result");
   var l_test_address = document.getElementById("test_address");
   l_test_address.readOnly = true;
   l_test_result.value = "Searching, one moment please...";
   l_test_result.style.display = "";

   l_Object.open("POST", "./whiteblacklists", true)
   l_Object.onreadystatechange = function()
   {
      if (l_Object.readyState == 4)
      {
         l_Object.onreadystatechange = returnFalse;
         l_test_address.readOnly = false;
         if ((l_Object.status == 200) && (l_Object.responseText.substr(0, 7) == "<!html>"))
         {
            l_test_result.value = l_Object.responseText.substr(7);
         }
         else
         {
            l_test_result.value = "An error occured, please try again";
         }
      }
   }
   l_Object.setRequestHeader("Cache-Control","no-cache");
   l_Object.send("test_senders=&json=1&test_address=" + encodeURIComponent(l_test_address.value));


   return false;
}

function AddBox(ul)
{
   ul = document.getElementById(ul);
   while (!ul.lastChild.tagName)
   {
      ul.removeChild(ul.lastChild);
   }
   var l_Child = ul.lastChild.cloneNode(true);
   l_Child.childNodes[0].value = "";
   ul.appendChild(l_Child);
}

function PrepareLists()
{
   window.sortfunction = SortByDomain;
   window.sortreverse = false;
   window.ListExisting = [document.getElementById("obj_blacklist"), document.getElementById("obj_whitelist")];
   window.ListNewEntries = [document.getElementsByName("blacklist")[0], document.getElementsByName("whitelist")[0]];
   window.m_Lists = [];

   for (var list = 0; list < 2; ++list)
   {
      var l_List = m_Lists[list] = ListNewEntries[list].value.split(/\n/);
      var l_Entry;
      for (var i = 0; (l_Entry = l_List[i]); ++i)
      {
         l_Entry = l_Entry.split(/;/);
         var l_Address = l_Entry[0].split(/@/);
         l_List[i] =
         {
            a: l_Address[1] ? l_Address[0] : "*",
            d: l_Address[1] ? l_Address[1] : l_Address[0],
            c: l_Entry[1]
         };
      }
      ListNewEntries[list].value = "";
      ListNewEntries[list].rows = 5;

      disableWrap(ListNewEntries[list]);
      FillList(list);
   }

   document.getElementById("obj_whitelistholder").style.display = "";
   document.getElementById("obj_blacklistholder").style.display = "";
}

function FillList(list, sortfunc)
{
   if (sortfunc)
   {
      if (sortfunc == sortfunction)
      {
         sortreverse = !sortreverse;
      }
      else
      {
         sortreverse = false;
         sortfunction = sortfunc;
      }
   }

   var l_List = m_Lists[list];
   l_List.sort(sortfunction);

   var l_tx = ['<table cellspacing="0"><col width="220"><col width="220"><col width="210"><tbody>'];
   var l_entry;
   for (var i = 0; (l_entry = l_List[i]); ++i)
   {
      l_tx.push('<tr class="', l_entry.e ? 'deleted' : '', '" onclick="var e = m_Lists[', list, '][', i, ']; e.e = !e.e; this.className = e.e ? \'deleted\' : \'\'" onmouseover="this.style.backgroundColor=\'#f0f0f0\'" onmouseout="this.style.backgroundColor=\'\'">'
      ,  '<td><div>', l_entry.a, '</div></td>'
      ,  '<td><div>', l_entry.d, '</div></td>'
      ,  '<td><div style="font-size:x-small;">', l_entry.c, '</div></td>'
      ,  '</tr>');
   }
   l_tx.push('</tbody></table>');
   ListExisting[list].innerHTML = l_tx.join("");
}

function SortByDomain(in_First, in_Second)
{
   return (sortreverse ? -1 : 1) * (in_First.d + in_First.a).localeCompare(in_Second.d + in_Second.a);
}

function SortByAccount(in_First, in_Second)
{
   return (sortreverse ? -1 : 1) * (in_First.a + in_First.d).localeCompare(in_Second.a + in_Second.d);
}

function MoveExisting(list, isonsubmit)
{
   var l_List = m_Lists[list];
   var l_tx = ListNewEntries[list].value.replace(/\r/, "").split("\n");
   for (var i = 0; (l_entry = l_List[i]); ++i)
   {
      if (!l_entry.e)
      {
         var l_Address = l_entry.a == "*" ? "" : l_entry.a + "@";
         l_tx.push(l_Address + (l_entry.d || "") + ((l_entry.c || "").length ? " ; " + l_entry.c : ""));
      }
   }
   m_Lists[list] = [];
   l_tx = l_tx.join("\n");

   ListNewEntries[list].value = l_tx.replace(/^\n+/gm, "");
   if (!isonsubmit)
   {
      ListNewEntries[list].rows=15;
      document.getElementById(list ? "obj_whitelistholder" : "obj_blacklistholder").style.display = "none";
      FillList(list);
   }
}

function UpdateLists()
{
   MoveExisting(0, true);
   MoveExisting(1, true);
}
