
jQuery.fn.extend
({ showHide : function(s) { return s && this.show() || this.hide(); }
,  checked  : function(c) {
      if (arguments.length) {
         return c ? this.attr("checked", "checked").addClass("checked") : this.removeAttr("checked").removeClass("checked");
      } else {
         return this.attr("checked");
   }}
,  addRemoveClass : function(a, c) { return a && this.addClass(c) || this.removeClass(c); }
});

$.browser.msie6 = $.browser.msie && $.browser.version < 7;

$(document).ready(function()
{
   if (window.listowner)
   {
      $("#searchone").autocomplete("listselector"
      ,  {  extraParams
         :  {  is_json : 1
            ,  listowner  : window.listowner
            }
         ,  minChars    : 2
         ,  matchContains : true
      });
   }

   if ($("#mailboxbrowser").length)
   {
      var i;
      if (window.opener)
      {
         $("li").each(function(i, li)
         {
            var l_Children = $(li).children(":eq(0)");
            $(li).attr("pathpart", l_Children.text());
            l_Children.before('<span><a hidefocus href="#" class="action g">g</a>-<a hidefocus href="#" class="action s">s</a>-<a hidefocus href="#" class="action i">i</a>&nbsp;&nbsp;</span>');
         });
      }
      $(".action.g").click(function() { return appendbox("w_traingood", getPath($(this).parent().parent())); });
      $(".action.s").click(function() { return appendbox("w_trainspam", getPath($(this).parent().parent())); });
      $(".action.i").click(function() { return appendbox("w_trainignore", getPath($(this).parent().parent())); });
      $("[name=dom]").parent().attr("isDom", true);
      $("[name=mbx]").each(function(i, l)
      {
         l = $(l);
         l.attr("pathpart", l.text());
         var deep = l.html().replace(/[^\/]/g, "").length;
         if (deep)
         {
            l.html(l.html().substr(l.html().lastIndexOf("/") + 1)).css("margin-left", deep * 20 + "px");
         }
      }).click(openweb).attr("href", "#");
   }
   window.l_Template = $("#obj_template");
   if (l_Template.length)
   {
      window.l_Parent = l_Template.parent();
      window.l_NextCellId = document.getElementsByName("num").length - 1;
      l_Template.remove();
      AddRow();
   }

   if (window.m_Lists)
   {
      window.sortfunction = SortByDomain;
      window.sortreverse = false;

      window.ListExisting = $("#obj_whitelist,#obj_blacklist,#tokenwhitelist,#itokenwhitelist");
      window.ListNewEntries = $("[name=whitelist_add],[name=blacklist_add]");

      var l_ValidEmailRegex = /^([\w!#$%&\'\+\-\/\?\^\_\`\{\|\}~\.]+(\@[\w_\-\.\[\]]+)? *(;.*)?[\r\n]+)*$/i;
      var l_ListEntries = m_Lists.slice();
      m_Lists = [];

      var l_tx = ['<table cellspacing="0"><col width="220"><col width="220"><col width="210"><tbody>'];
      var l_entry;
      for (i = 0; i < 12; ++i)
      {
         l_tx.push('<tr><td><div></div></td><td><div></div></td><td><div style="font-size:x-small;"></div></td></tr>');
      }
      l_tx.push('</tbody></table>');

      for (var list = 0; list < 2; ++list)
      {
         m_Lists[list] = PrepareList(l_ListEntries[list].split(/\n/));
         ListExisting[list].innerHTML = l_tx.join("");
         ListExisting[list].m_Table = $("table", $(ListExisting[list]));
         FillList(list);
         disableWrap(ListNewEntries[list]);
      }

      if (ListExisting[2])
      {
         ListExisting.eq(2).val(l_ListEntries[2]);
         ListExisting.eq(3).val(l_ListEntries[3]);

         window.OriginalTokens = [l_ListEntries[2], l_ListEntries[3]];
      }

      $("form").submit(function ()
      {
         var l_Form = $(this);
         var i;
         var l_ListNames = ["tokenwhitelist", "itokenwhitelist"];

         for (var list = 0; list < 2; ++list)
         {
            if (ListExisting[list + 2])
            {
               var l_New = ArrayToDict(ListExisting[list + 2].value.replace("\r", "").split("\n"));
               var l_Original = ArrayToDict(OriginalTokens[list].replace("\r", "").split("\n"));
               var l_Add = [];
               for (i in l_New)
               {
                  if (!(i in l_Original))
                  {
                     l_Add.push(l_New[i]);
                  }
               }
               for (i in l_Original)
               {
                  if (!(i in l_New))
                  {
                     l_Form.append($('<input type="hidden">').attr("name", l_ListNames[list] + '_del').val(i));
                  }
               }
               l_Form.append($('<input type="hidden">').attr("name", l_ListNames[list] + '_add').val(l_Add.join("\n")));
            }
         }

         l_ListNames = ["whitelist", "blacklist"];
         for (list = 0; list < 2; ++list)
         {
            if (ListNewEntries[list].value.length && !l_ValidEmailRegex.test(ListNewEntries[list].value + "\n"))
            {
               alert("There is invalid new entries for the " + l_ListNames[list]);
               return false;
            }

            var l_List = m_Lists[list];
            var l_entry;
            for (i = 0; (l_entry = l_List[i]); ++i)
            {
               if (l_entry.e)
               {
                  l_Form.append($('<input type="hidden">').attr("name", l_ListNames[list] + '_del').val((l_entry.a == "*" ? "" : l_entry.a + "@") + (l_entry.d || "")));
               }
            }
         }
         return true;
      });

      var l_TextBox = $(".filterlist").attr("placeholder", "Filter list...");

      $("#obj_whitelist_filter").next().data("field", $("#obj_whitelist_filter"));
      $("#obj_blacklist_filter").next().data("field", $("#obj_blacklist_filter"));
      $("#obj_whitelist_filter").next().next().data("field", $("#obj_whitelist_filter"));
      $("#obj_blacklist_filter").next().next().data("field", $("#obj_blacklist_filter"));

      $(".filterlist").val("").next().click(function()
      {
         var l_This = $(this).data("field");

         var l_Text = l_This.val().replace(l_This.attr("rel"), "");
         window.m_Filter = l_Text;

         FillList(l_This.attr("id") == "obj_whitelist_filter" ? 0 : 1);
         l_This.focus().select();
      });
      $(".filterlist").next().next().click(function()
      {
         $(this).data("field").val('');
         $(this).prev().click();
      });
      $(".filterlist").keypress(function(in_Event)
      {
         if (in_Event.keyCode == 13)
         {
            in_Event.preventDefault();
            $(this).next().click();
         }
      }).css({width:"200px"});


      var l_CurrentStyle = l_TextBox[0].currentStyle;
      if (l_CurrentStyle && !('placeholder' in document.createElement('input')))
      {
         var l_Div = $("<div></div>").css
         ({ display : "inline-block"
         ,  position : "relative"
         ,  margin : l_CurrentStyle.margin
         ,  padding : l_CurrentStyle.padding
         ,  fontSize : l_CurrentStyle.fontSize
         ,  fontFamily : l_CurrentStyle.fontFamily
         ,  width : l_CurrentStyle.width
         ,  borderWidth : l_CurrentStyle.borderWidth
         ,  borderColor : l_CurrentStyle.borderColor
         ,  borderStyle : l_CurrentStyle.borderStyle
         }).html(l_PlaceHolder);
         l_TextBox.css
         ({ border : 0
         ,  opacity : 0.75
         ,  marginLeft : 0
         ,  position: "absolute"
         ,  top: 0
         ,  left: 0
         })
         .before(l_Div)
         .focus(function() { $(this).css("opacity", 1); })
         .blur(function() { if (!this.value) { $(this).css("opacity", 0.75); } });

         l_Div.append(l_TextBox);
      }

      $("input[type=submit],input[type=reset],input[type=button]").attr("hideFocus",true);
   }

   $(".domainlist").each(function()
   {
      var l_This = $(this);
      var l_Len = l_This.children().length;
      if (l_Len >= 10)
      {
         l_This.hide().before("<div class='link'>" + l_Len + " domains - click to expand</div>").prev().click(function()
         {
            $(this).hide().next().show();
         });
      }

   });
});

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)
   {
      $(l_Form.elements[l_Arg]).attr("disabled", l_Disabled);
   }
}

function openweb()
{
   var l_Src = $(this).parent().parent().parent();
   var l_Account = l_Src.attr("pathpart") + "@" + l_Src.parent().parent().attr("pathpart");
   window.open("?account=" + l_Account + "&mailbox=" + encodeURI($(this).attr("pathpart")).replace(/&/g, "%2526"));
   return false;
}

function getPath(src)
{
   return src.attr("isDom") && src.attr("pathpart") || getPath(src.parent().parent()) + "/" + src.attr("pathpart");
}

function appendbox(boxname, text)
{
   try
   {
      var obj = $("[name=" + boxname + "]", window.opener.document);
      if (obj.val().length && (obj.val().charAt(obj.val().length-1) != "\n"))
      {
         obj.val(obj.val() + "\n");
      }
      obj.val(obj.val() + 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_Area = $(in_TextArea);
   var l_Parent = l_Area.parent();
   var l_Next = l_Area.next();

   l_Area.remove();
   l_Area.attr("wrap", "off");
   l_Area.hide();

   if (l_Next.length)
   {
      l_Next.before(l_Area);
   }
   else
   {
      l_Parent.append(l_Area);
   }
   l_Area.show();
}

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 checkUpgrade()
{
   $("fieldset").hide();
   $("#statuscode").html('<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 = $("#countdown");
   var l_Current = parseInt(l_Countdown.val(), 10) - 1;
   l_Countdown.val(l_Current);

   if (l_Current <= 0)
   {
      $("#statuscode").html('<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))
   {
      $.get("/version", null, function()
      {
         if (!window.gotIt)
         {
            window.gotIt = true;
            alert("Upgrade completed successfully");
            window.location.href = "/";
         }
      });
   }

   if (!window.gotIt)
   {
      setTimeout(upgradeLoop, 1000);
   }
}

function getReport()
{
   $.get("statistics?getreport=1&is_json=1", null, function()
   {
      alert("Partial daily report sent to the postmaster");
   });
}

function AddRow()
{
   var l_Cloned = l_Template.clone();
   l_Parent.append(l_Cloned);
   l_Cloned = l_Cloned[0];
   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).parent().remove();
   }
}

function VerifyRegex(in_This)
{
   in_This = $(in_This || this);
   try
   {
      var l_RegTest = new RegExp(in_This.val());
   }
   catch (in_error)
   {
      in_This.css("backgroundColor", "#ff8080");
   }
   in_This.focus(ResetBG);
}

function VerifySyntax(in_Alert, in_Color)
{
   var l_Return = true;
   $("[name=num]").each(function(i, in_num)
   {
      var l_num = $(in_num).val();
      var l_Error = false;
      var l_Namefield = $("[name=name_" + l_num + "]");
      var l_Regexfield = $("[name=regex_" + l_num + "]");
      var l_NameValue = l_Namefield.val();
      var l_RegexValue = l_Regexfield.val();
      if (l_RegexValue.length || l_Namefield.val().length)
      {
         l_Error = !l_NameValue.length || !l_RegexValue.length;

         if (in_Color)
         {
            l_Namefield.css("backgroundColor", l_NameValue.length ? "#80ff80" : "#ff8080");
         }

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

      l_Return = l_Return && !l_Error;
      l_Regexfield.focus(ResetBG);
      l_Namefield.focus(ResetBG);
   });

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

function ResetBG()
{
   $(this).css("backgroundColor", "");
   this.unbind("focus", ResetBG);
}

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

   var l_Text = $("#customtext").val().replace(/\r/g, "").split("\n");
   var l_Results = [];

   $("[name=num]").each(function(i, in_num)
   {
      var l_num = $(in_num).val();
      var l_Name = $("[name=name_" + l_num + "]").val();
      var l_Regex = $("[name=regex_" + l_num + "]").val();
      var l_Nocase = $("[name=nocase_" + l_num + "]").checked();

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

         for (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");
   }
   $("#testresults").html("Results:<ul><li>" + l_Results.join("</li><li>") + "</li></ul>");
}

function TestLists()
{
   var l_test_result = $("#test_result");
   var l_test_address = $("#test_address");
   l_test_address.attr("readOnly", true);
   l_test_result.val("Searching, one moment please...");
   l_test_result.show();

   $.post
   (  "./whiteblacklists"
   ,  { test_senders: "", json: "1", test_address: l_test_address.val() }
   ,  function(data, textStatus)
      {
         l_test_address.attr("readOnly", false);
         if ((textStatus == "success") && (data.substr(0, 7) == "<!html>"))
         {
            l_test_result.val(data.substr(7));
         }
         else
         {
            l_test_result.val("An error occured, please try again");
         }
      }
   ,  "text"
   );

   return false;
}

function AddBox(ul)
{
   ul = $("#" + ul);
   ul.append( ul.children(":last").clone().children(":eq(0)").val("").end() );
}

function PrepareList(in_List)
{
   var l_Entry;
   var l_List = [];
   for (var i = 0; (l_Entry = in_List[i]); ++i)
   {
      l_Entry = l_Entry.split(/;/);
      var l_Address = l_Entry[0].split(/@/);
      l_List.push({
         a: l_Address[1] ? l_Address[0] : "*",
         d: l_Address[1] ? l_Address[1] : l_Address[0],
         c: l_Entry[1]
      });
   }
   return l_List;
}

function RowByEvent(in_Event)
{
   var l_Target = in_Event.target;
   while (l_Target && l_Target.tagName != "TR")
   {
      l_Target = l_Target.parentNode;
   }
   return l_Target || null;
}


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_Length = l_List.length;
   if (window.m_Filter)
   {
      var l_Item;
      for (var i = 0; (l_Item = l_List[i]); ++i)
      {
         if (!l_Item.v)
         {
            l_Length = i;
            break;
         }
      }
   }

   var l_Table = ListExisting[list].m_Table;
   var l_Scroller = $("div.list_scroll", $(ListExisting[list]).parent());

   var ROW_HEIGHT = 16;

   l_Table.unbind().click(function(in_Event)
   {
      var l_Row = RowByEvent(in_Event);
      var l_Index = l_Row.rowIndex + parseInt($(this).attr("offset") || 0, 10);
      var l_entry = l_List[l_Index];
      if (l_entry)
      {
         l_entry.e = !l_entry.e;
         l_Row.className = l_entry.e ? 'deleted' : '';
      }
      if (top.set_modified_inline_window) { top.set_modified_inline_window(true); }
      return false;
   })
   .bind("contextmenu", function(in_Event)
   {
      var l_Row = RowByEvent(in_Event);
      var l_Index = l_Row.rowIndex + parseInt($(this).attr("offset") || 0, 10);
      var l_entry = l_List[l_Index];
      if (l_entry)
      {
         l_entry.e = true;
         l_Row.className = 'deleted';
         var l_Text = ListNewEntries[list].value.replace("\r", "").split("\n");
         l_Text.push((l_entry.a == "*" ? "" : l_entry.a + "@") + (l_entry.d || "") + (l_entry.c ? "; " + l_entry.c : ""));
         ListNewEntries[list].value = l_Text.join("\n");
      }

   	in_Event.preventDefault();
      in_Event.stopPropagation();
   })
   .mousedown(function(in_Event) { in_Event.preventDefault(); return false;})
   .mouseover(function(in_Event) {
      var l_Row = RowByEvent(in_Event);
      if (l_Row.rowIndex + parseInt($(this).attr("offset") || 0, 10) < l_Length)
      {
         l_Row.style.backgroundColor='#f0f0f0';
      }
   })
   .mouseout(function(in_Event) { RowByEvent(in_Event).style.backgroundColor=''; })
   .mousewheel( function(in_Event, in_Delta) {
      in_Delta *= 3 * -ROW_HEIGHT;
      var l_Prev = l_Scroller.scrollTop();
      if (in_Delta) {
         l_Scroller.scrollTop(parseInt((l_Scroller.scrollTop() + in_Delta) / ROW_HEIGHT, 10) * ROW_HEIGHT);
      }
      /*if (l_Prev != l_Scroller.scrollTop())
      {*/
      	in_Event.preventDefault();
         in_Event.stopPropagation();
      //}
   });

   l_Scroller.scroll(function(){
      var l_Offset = parseInt(l_Scroller.scrollTop() / ROW_HEIGHT, 10);
      if (l_Table.attr("offset") != l_Offset)
      {
         l_Table.attr("offset", l_Offset);
         UpdateListTable(l_List, l_Table);
      }
   });

   UpdateListTable(l_List, l_Table);

   l_Scroller.children().height(l_Length * ROW_HEIGHT);
}

function UpdateListTable(in_List, in_Table)
{
   var l_Offset = parseInt(in_Table.attr("offset"), 10) || 0;
   var l_entry;
   var l_Rows = $("tr", in_Table);
   for (var i = 0; ((l_entry = in_List[i + l_Offset]) && (i < 12)); ++i)
   {
      var l_Row = l_Rows.eq(i);
      l_Row.toggleClass("deleted", l_entry.e ? true : false);
      var l_Cells = $("td div", l_Row);
      if (window.m_Filter && !l_entry.v)
      {
         l_Cells.html("");
         l_Row.hide();
      }
      else
      {
         l_Cells.eq(0).html(l_entry.a);
         l_Cells.eq(1).html(l_entry.d);
         l_Cells.eq(2).html(l_entry.c || "");
         l_Row.show();
      }
   }
}

function FilterList(in_First, in_Second, in_Ret)
{
   if (window.m_Filter)
   {
      in_First.v = (in_First.a.indexOf(m_Filter) >= 0) || (in_First.d.indexOf(m_Filter) >= 0) || ((in_First.c || "").indexOf(m_Filter) >= 0);
      in_Second.v = (in_Second.a.indexOf(m_Filter) >= 0) || (in_Second.d.indexOf(m_Filter) >= 0) || ((in_Second.c || "").indexOf(m_Filter) >= 0);

      return in_First.v == in_Second.v ? in_Ret : (in_First.v ? -1 : 1);
   }
   return in_Ret;
}

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

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

function OpenTab(src, index)
{
   $(src).siblings().removeClass("active");
   $(src).addClass("active");
   $(".listholder").hide();
   $(".filterlist").val();
   $("#obj_tab" + index).show();
}

function ArrayToDict(in_Array)
{
   var l_Dict = {};
   for (var i = 0; i < in_Array.length; ++i)
   {
      var l_Value = in_Array[i].split(";")[0].trim();
      l_Dict[l_Value] = in_Array[i];
   }
   return l_Dict;
}

function GetAccountList(in_Src, in_Domain)
{
   $(in_Src).parent().parent().html('<li><a href="user?listowner=' + in_Domain + '" style="font-weight:bold">This domain\'s defaults</a></li>' + $.ajax
   ({ url: "./listselector"
   ,  async: false
   ,  data: {listowner: in_Domain, is_json : 1}
   ,  dataType: "html"
   ,  cache: false
   }).responseText);

   return false;
}

$.ajaxSetup({cache:false});

// keepSessionActive
setInterval(function() { $.get("./noop"); }, 150000);

if (top.set_modified_inline_window)
{
   $("select,textarea").bind("change keydown", function() { top.set_modified_inline_window(true); });
   top.set_modified_inline_window(false);
}

