/* NEW JS START */
SEN =
   {
      getCookie:
         function(name) {
            return ( document.cookie.match(new RegExp( "(?:^|;\\s+)" + name + "=([^\\b]*?)(?:;|$)" ,"")) || ["",false])[1];
         },
      setCookie:
         function(name , value , sticky) {

            // These variables are defined by PHP using a
            // raw SCRIPT tag written to the page:
            // 
            // 	cookie_expire_date
            // 	cookie_domain

            return document.cookie = name + "=" + value + ";expires=" + cookie_expire_date + " 12:00:00 UTC;domain=" + cookie_domain + ";path=/";
         },

      Utilities:
         {
            makeStringArrayUnique:
               function(arr) {
                  var _items = {}, i = 0, l = arr.length, newArr = [];
                  for(;i<l;i++)
                     if (!_items[arr[i]]) {
                        newArr.push(arr[i]);
                        _items[arr[i]] = 1;
                     }
                  return newArr
               }
         },

      GUI:
         {
            Collapse:
               {

                  // All CSS classNames used by this script should be prefixed
                  // with "jcollapse-"  to avoid conflicts with other collapse
                  // scripts, be they old SEN scripts or other code libraries.
                  //
                  // The same  standard need not be adhered to for custom HTML
                  // attributes,  but they should start with "data-collapse-",
                  // the  "data-"  portion  being  mandated by the HTML5 spec.
                  // Old  SEN  scripts don't use the  "data-" prefix on custom
                  // HTML  attributes,  so the "j" in "jcollapse" isn't needed
                  // as the "data-" prefix alone prevents scripting conflicts.

                  _collapse: // event handler, do not call
                     function(e, s) { // event, force_state
                        var undefined;
                        var T = $(this);
                        var S = (s != undefined && s >= 0 && s <= 1) ? !!s + 0 : !T.hasClass("jcollapsed-target") + 0;
                        if (T.data("collapse-target")) {
                           T [( [ "remove" , "add" ][ S ] + "Class" )]("jcollapsed-target");
                           if (!T.hasClass("jcollapse-do-not-change-text"))
                              T.html( [ "[collapse]" , "[expand]" ][ S ] );
                           $(T.data("collapse-target")) [( [ "remove" , "add" ][ S ] + "Class" )] ("jcollapsed");


                           if (T.data("collapse-save-state") && T.attr("id")) {
                              var SwitchID = T.attr("id");
                              if (S)
                                 SEN.setCookie("jcollapsed" , SEN.Utilities.makeStringArrayUnique(SEN.getCookie("jcollapsed").replace(/;[^\b]*$/,"").split(",").concat([SwitchID])).join(",") , 1);
                              else
                                 SEN.setCookie(
                                    "jcollapsed",
                                    $.grep(
                                       SEN.getCookie("jcollapsed").replace(/;[^\b]*$/,"").split(",").concat([SwitchID]),
                                       function(value) {
                                          return value != SwitchID;
                                       }
                                    ).join(","),
                                    1
                                 );
                           }

                           T.trigger(
                              {
                                 type: "CollapseStateChanged",
                                 collapsed: $(this).hasClass("jcollapsed-target"),
                                 switch_node: this
                              }
                           );
                        }
                        if (e)
                           e.preventDefault();
                        return false;
                     },
                  setCollapseState:
                     function(switch_node, state) {
                        if (!switch_node)
                           throw "SEN.GUI.Collapse.setCollapseState: invalid first argument!";
                        SEN.GUI.Collapse._collapse.call(switch_node, null, state);
                        return $(switch_node).hasClass("jcollapsed-target");
                     },
                  loadCollapseState:
                     function(switch_node) {
                        if (!switch_node)
                           throw "SEN.GUI.Collapse.setCollapseState: invalid first argument!";
                        if (!$(switch_node).data("collapse-save-state") || !$(switch_node).attr("id"))
                           return;
                        var jCollapseCookieList = SEN.getCookie("jcollapsed");
                        if (("," + jCollapseCookieList + ",").indexOf("," + $(switch_node).attr("id") + ",") >= 0)
                           SEN.GUI.Collapse._collapse.call(switch_node, null, 1);
                        return $(switch_node).hasClass("jcollapsed-target");
                     },
                  registerNode:
                     function(switch_node, target_node) {
                        var D = [];

                        if ($(switch_node).data("collapse-target"))
                           D = $(switch_node).data("collapse-target");

                        if ($(switch_node).attr("data-collapse-target"))
                           D = D.concat($.makeArray( $( $(switch_node).attr("data-collapse-target") , switch_node ) ));

                        if (target_node) {
                           if (target_node.length)
                              D = D.concat(target_node);
                           else
                              D = D.concat([target_node]);
                        }

                        $(switch_node).removeAttr("data-collapse-target").removeClass("jcollapse-do-not-auto-register").data( "collapse-target" , D ).click(this._collapse);

                        if ($(switch_node).attr("data-collapse-save-state")) { // Save this element's collapse state in a cookie?
                           $(switch_node).data("collapse-save-state" , $(switch_node).attr("data-collapse-save-state")).removeAttr("data-collapse-save-state");
                           this.loadCollapseState(switch_node); // load state from cookie
                        }

                        if ($(switch_node).hasClass("jcollapsed-target")) // if the set is already collapsed and we're adding a new target, re-collapse
                           SEN.GUI.Collapse.setCollapseState(switch_node, 1);
                     },
                  init:
                     function() {
                      if (!SEN.getCookie("jcollapsed"))
                         SEN.setCookie("jcollapsed","")
                        $(".jcollapse.jcollapse-create-link").append("<a class=\"jcollapse-link\" href=\"#\">[collapse]</a>");
                        $(".jcollapse.jcollapse-create-link").each(
                           function() {
                              $(this).removeClass("jcollapse-create-link").find(">a.jcollapse-link:last-child").attr("data-collapse-target", $(this).attr("data-collapse-target"));
                              $(this).removeAttr("data-collapse-target");
                           }
                        );
                        $(".jcollapse-convert-link").each(
                           function() {
                              $(this).append("<span>[collapse]</span>").removeClass("jcollapse-convert-link").addClass("jcollapse-link");
                           }
                        );

                        $(".jcollapse-link:not(.jcollapse-do-not-auto-register)").each(function(i,e){SEN.GUI.Collapse.registerNode(e)});
                     }
               },
            Dialogs:
               {
                  spawn:
                     function(d) {
                        return new SEN.GUI.Dialogs._Dialog(d);
                     },
                  list: { length: 0 },
                  named_list: {},
                  current_modal: null,
                  _fade:document.createElement("div"),
                  Drag: // drag functionality for modeless draggable dialogs
                     {
                        currently_dragging: null,
                        offsetLeft: 0, // mouse offset from the drag button
                        offsetTop: 0,
                        onmousedown:
                           function(e) {
                              var e = e || window.event;
                              var m = $(this).data("modal");
                              SEN.GUI.Dialogs.Drag.currently_dragging = m.id;
                              var c = $(m.node).offset();
                              SEN.GUI.Dialogs.Drag.offsetLeft = (e.clientX || 0) - c.left + $(window).scrollLeft();
                              SEN.GUI.Dialogs.Drag.offsetTop = (e.clientY || 0) - c.top + $(window).scrollTop();

                              $(m.node).mousedown(); // focus modal

                              if (e.preventDefault)
                                 e.preventDefault();
                              return false;
                           },
                        onmousemove:
                           function(e) {
                              if (SEN.GUI.Dialogs.Drag.currently_dragging == null)
                                 return;
                              var e = e || window.event;
                              var m = SEN.GUI.Dialogs.list[SEN.GUI.Dialogs.Drag.currently_dragging],
                                  x = e.clientX || 0,
                                  y = e.clientY || 0,
                                  ox = SEN.GUI.Dialogs.Drag.offsetLeft || 0,
                                  oy = SEN.GUI.Dialogs.Drag.offsetTop || 0;
                              var new_x = Math.min(Math.max(0, x - ox), $(window).width() - m.node.offsetWidth),
                                  new_y = Math.min(Math.max(0, y - oy), $(window).height() - m.node.offsetHeight);
                              m.node.style.left = new_x + "px";
                              m.node.style.top = new_y + "px";
                              m.dragLeft = new_x;
                              m.dragTop = new_y;
                           },
                        onmouseup:
                           function() {
                              SEN.GUI.Dialogs.Drag.currently_dragging = null;
                           }
                     },
                  _Dialog:
                     (function() {
                        var x =
                           function Dialog(d) {
                              var d = d || {}; // settings/data object

                              // Unique identifier functionality
                              // (for dialogs that should not be duplicated)
                              if (d.string_id || d.name) {
                                 var string_id = d.string_id || d.name;

                                 if (SEN.GUI.Dialogs.named_list[string_id])
                                    return SEN.GUI.Dialogs.named_list[string_id];

                                 // ^ returning an object from within a constructor
                                 // means that "this" is unused and the returned 
                                 // object is used. This does not happen when 
                                 // returning things that aren't EXPLICITLY objects, 
                                 // like numbers or functions.

                                 this.string_id = string_id;
                                 SEN.GUI.Dialogs.named_list[this.string_id] = this;
                              }

                              if (SEN.GUI.Dialogs.current_modal && !d.modeless)
                                 throw "SEN.GUI.Dialogs: An attempt was made to create a modal when one already exists. Only one modal may be shown at a time.";

                              SEN.GUI.Dialogs.list[(this.id = SEN.GUI.Dialogs.list.length++)] = this;

                              // Note that while default values are provided for the innerHTML 
                              // and buttons settings (when unspecified), default listeners 
                              // are not provided for buttons. Failure to add "ButtonClicked" 
                              // listeners will make it impossible to close the modal!

                              this._event_listeners = {}; // events

                              this.modeless = d.modeless || false;
                              this.adaptive_size = d.adaptive_size || false;
                              this.draggable = d.modeless && !d.adaptive_size ? d.draggable || false : false;

                              if (!this.modeless)
                                 SEN.GUI.Dialogs.current_modal = this;

                              this.default_button = d.default_button;
                              if (!this.default_button && this.default_button != 0)
                                 this.default_button = NaN;

                              // Use a FORM if there's a default button, so that Enter triggers that button.
                              this.node = document.createElement( isNaN(this.default_button) ? "div" : "form" );
                              $(this.node)[0].setAttribute("onsubmit", "javascript:return false"); // Google Chrome blocks "polite" (non-attribute-based) event listening for "submit", and you can't use jQuery to set the attribute. Broken browser...
                              this.node.className = "dialog " + (this.modeless ? "modeless" : "modal") + (this.adaptive_size ? " stretch" : "") + (d.className ? " " + d.className : "");
                              $(this.node).data("modal", this);

                              this.contentNode = this.node.appendChild(document.createElement("div"));
                              this.contentNode.innerHTML = d.innerHTML || "dialog contents not specified!";
                              this.buttonsNode = this.node.appendChild(document.createElement("div"));
                              d.buttons = d.buttons || ["OK"];
                              for(var i=0;i<d.buttons.length;i++)
                                 $(this.buttonsNode).append("<input type='" + ( this.default_button == i ? "submit" : "button" ) + "' value=''>").find("input:last-child").attr("value", d.buttons[i]).data("modal", this).data("index", i).click(this._onbuttonclicked);

                              document.body.appendChild(this.node);

                              this.width = d.width || "auto";

                              this.node.style.width = this.adaptive_size ? "auto" : d.width || this.node.offsetWidth + "px"; // give the modal some rigidity.
                              if (!this.modeless && !this.adaptive_size) {
                                 this.node.style.marginLeft = this.node.offsetWidth / -2 + "px";
                                 this.node.style.marginTop = this.node.offsetHeight / -2 + "px";
                              } else if (this.modeless) {
                                 this.dragLeft = this.left = d.left || d.x || null;
                                 this.dragTop = this.top = d.top || d.y || null;
                                 this.right = d.right || "auto";
                                 this.bottom = d.bottom || "auto";
                                 this.node.style.left = d.left || d.x || this.node.offsetWidth / 2 + "px";
                                 this.node.style.top = d.top || d.y || this.node.offsetHeight / 2 + "px";
                                 this.node.style.right = d.right || "auto";
                                 this.node.style.bottom = d.bottom || "auto";

                                 $(this.node).mousedown(
                                    function() {
                                       if ($(this).hasClass("focused"))
                                          return;
                                       /*var i=0, l = SEN.GUI.Dialogs.list, ll = l.length;
                                       for(;i<ll;i++) {
                                          if (!l[i])
                                             continue; // closed dialogs are not removed from the list, they're set to null
                                          if ($(l[i].node).hasClass("focused")) {
                                             $(l[i].node).removeClass("focused");
                                             break
                                          }
                                       }*/
                                       $(".dialog.focused").removeClass("focused");
                                       $(this).addClass("focused");
                                    }
                                 );
                              }

                              if (this.draggable)
                                 this.dragNode = $(this.node).append("<a class='drag'>[drag]</a>").find("a.drag").data("modal", this).mousedown(SEN.GUI.Dialogs.Drag.onmousedown)[0];

                              var m = this;
                              $(window).resize(function(){m._onresize()});
                              this._onresize();

                              delete i;
                              if (!this.modeless && SEN.GUI.Dialogs._fade.style.display == "none")
                                 SEN.GUI.Dialogs._fade.style.display = "block";

                              $(this.contentNode).find(":input").eq(0).select().focus();
                              $(this.contentNode).find(".default-focus").eq(0).select().focus();
                              // remove focus from whatever opened the dialog
                              // very important for modals; prevents the user
                              // from duplicating the modal by pressing Enter
                           };
                        x.prototype =
                           {
                              _onbuttonclicked:
                                 function() {
                                    $($(this).data("modal")).trigger("ButtonClicked",[{modal:$(this).data("modal"), index:$(this).data("index")}]);
                                 },
                              _onresize:
                                 function() {
                                    this.updateDisplay();
                                 },
                              updateDisplay:
                                 function() {
                                    $(this).trigger("BeforeDisplayUpdate",[{modal:this}]);

                                    var N = $(this.node);
                                    var C = $(this.contentNode);
                                    var S = $(SEN.GUI.Dialogs._fade);

                                    if (!this.adaptive_size && N.width() >= S.width())
                                       C.css("max-width", S.outerWidth() - $(this.buttonsNode).outerWidth() - (C.outerWidth() - C.width()) + "px");
                                    if (!this.adaptive_size && N.height() >= S.height())
                                       C.css("max-height", S.outerHeight() - $(this.buttonsNode).outerHeight() - (C.outerHeight() - C.height()) + "px");

                                    if (!this.modeless && !this.adaptive_size) {
                                       N.css("margin-left", N.width() / -2 + "px");
                                       N.css("margin-top", N.height() / -2 + "px");
                                    } else if (this.modeless) {
                                       var nLeft = this.draggable ? this.dragLeft : this.left;
                                       var nTop = this.draggable ? this.dragTop : this.top;
                                       N.css("left" , nLeft ? (parseInt(nLeft) + N.outerWidth() > S.outerWidth() ? S.outerWidth() - N.outerWidth() : nLeft) : N.width() / 2 + "px");
                                       N.css("top" , nTop ? (parseInt(nTop) + N.outerHeight() > S.outerHeight() ? S.outerHeight() - N.outerHeight() : nTop) : N.height() / 2 + "px");
                                       N.css("right" , this.right || "auto");
                                       N.css("bottom" , this.bottom || "auto");
                                    }

                                    $(this).trigger("AfterDisplayUpdate",[{modal:this}]);
                                 },
                              close:
                                 function() {
                                    $(this.node).remove();
                                    $(this).trigger("Close",[{modal:this}]);
                                    SEN.GUI.Dialogs._fade.style.display = "none";

                                    if (SEN.GUI.Dialogs.current_modal == this)
                                       SEN.GUI.Dialogs.current_modal = null;

                                    // Remove unused modal from all listings 
                                    // so that it may be garbage-collected.
                                    SEN.GUI.Dialogs.list[this.id] = null;
                                    if (this.string_id)
                                       delete SEN.GUI.Dialogs.named_list[this.string_id];
                                    this.id = this.string_id = null;
                                 }
                           };
                        return x
                     })(),
                  init:
                     function() {
                        this._fade.style.display = "none";
                        this._fade.id = "dialog-modal-fade";
                        document.body.appendChild(this._fade);
                        $(document).mousemove(this.Drag.onmousemove); // $(window) does not work in IE
                        $(document).mouseup(this.Drag.onmouseup);
                        //window.onunload = this.die;
                     }
               },
            init:
               function() {
                  for(var i in this)
                     if (this && this[i] && this[i].init && this[i].init.call)
                        this[i].init();
               }
         },
      AJAX:
         {
            showError:
               function(responseText) {
               }
         },
      Shoutbox:
         {
            shouting_from: null,
            _update:
               function(sending) {
                  var shout_text = "",
                      shout_color = "",
                      site = "";
                  if (sending) {
                     shout_text = encodeURIComponent($("#shout_text").val());
                     shout_color = $("#shout_color").val();
                     $("#shout_text").val("");
                     site = $("#shout_site").val();
                  }
                  $.ajax(
                     {
                        type: "POST",
                        url: "/ajax/shoutbox.php?",
                        data: "ze=" + ajaxsession + "&ajaxmid=" + ajaxmid + "&itime=" + shoutbox_last + "&shout_from=" + this.shouting_from + "&color=" + encodeURI(shout_color) + "&channel= "+ site + "&shout=" + shout_text,
                        beforeSend:
                           function() {
                              $("#shout_refresh, #shout_submit").attr("disabled", "disabled").attr("class", "disabled");
                           },
                        complete:
                           function(req) {
                              $("#shout_refresh, #shout_submit").removeAttr("disabled").attr("class", "submit");
                              if (req.responseText.indexOf("&Error:") < 0) {
                                 var temp = req.responseText.indexOf(";");
                                 shoutbox_last = req.responseText.substring(0, temp);
                                 data = req.responseText.substring( temp + 1 );

                                 if (data.match(/^\s*$/))
                                    return;

                                 if (SEN.Shoutbox.shouting_from == "main" && data.indexOf("td") < 0) {
                                    $("#shoutbox_return").prepend("<tr><td style='width:100px'>&nbsp;</td><td>" + data + "</td></tr>");

                                    // Client-side workaround for layout errors caused by
                                    // /shouts [user]
                                    // The real error is that the server-side ignores the shout_from
                                    // parameter when generating the output for that command.

                                 } else
                                    $("#shoutbox_return").prepend(data);

                              } else {
                                 SEN.AJAX.showError(req.responseText);
                              }
                           }
                     }
                  );
               },
            refresh:
               function() {
                  SEN.Shoutbox._update(0);
               },
            send:
               function() {
                  SEN.Shoutbox._update(1);
               },
            init:
               function() {
                  this.shouting_from = $("#shout_from").val(); // "main" / "global"
               }
         },
      init:
         function() {
            for(var i in this)
               if (this && this[i] && this[i].init && this[i].init.call)
                  this[i].init();
         }
   };

/*if (new Date() < new Date("Jul 27 2010 00:00:00")) {
   SEN.SCIICountdownTimer =
      {
         node: document.createElement("div"),
         reference_date: new Date("Jul 27 2010 00:00:00"),
         updateClock:
            function() {
               var current_date = new Date();

               var remaining_date = this.reference_date.getTime() - current_date.getTime();

               var H = remaining_date / (60000*60);
               var M = (H - Math.floor(H)) * 60;
               var S = (M - Math.floor(M)) * 60;

               $(this.node).find("span+span").html(
                  [
                     Math.floor(H),
                     Math.floor(M),
                     Math.floor(S)
                  ].join(":").replace(/\:(\d)(\:|$)/g,":0$1$2").replace(/^(\d)(\:|$)/g,"0$1$2")
               );
               window.setTimeout(function(){SEN.SCIICountdownTimer.updateClock()}, 500);
            },
         init:
            function() {
               $(this.node).html("<span>SCII will be released in:</span><span class='clock'>??:??:??:??</span>")
                           .css("background-color","#000000")
                           .css("background-color","rgba(0,0,0,.7)")
                           .css("position", "absolute")
                           .css("left", "50%")
                           .css("top","78px")
                           .css("padding","5px")
                           .css("border","1px solid #444")
                           .css("width","260px")
                           .css("margin-left","-135px")
                           .css("z-index","50")
                           .css("text-align","center");
               $(this.node).find("span").css("display","block");
               $(this.node).find("span:first-child").css("font-weight","bold") .css("display","none") .find("+span").css("font-size","1.5em");
               document.body.appendChild(this.node);
               $(this.node).css("top", (100 - $(this.node).height()) + "px");
               $("#top #logo").css("top", "-30px");
               this.updateClock();
            }
      };
}*/

$(document).ready(function(){SEN.init()});
/* END   NEW JS */

var httpreqs = [];
var httpcounts = 0;
var do_shout = 1;
var refresh_time = 20000;
var ajax_status = '';
var ajax_working = 1;
var post_unparsed = '';
var mapnight_timer = null;

var browser = null;
var newbrowser = true;
var check = false;

var current_scroll_height = 0;
var current_scroll_length = 0;
var current_view_height = 0;
var current_view_width = 0;
var in_popup_mode = 0;

function alter_forums(group) {
   if(SEN.getCookie('hforums'+group) == 1)
      SEN.setCookie('hforums'+group, 0, 0); //should be destroying cookie
   else
      SEN.setCookie('hforums'+group, 1, 1);
   window.location = window.location; // refresh?
}
function menuOut() {
   hide($("#nav4"));
   hide($("#nav5"));
}
function event_onscroll() {
   if(in_popup_mode)
      realign_popup();
}
function portal_switch(obj, link) {
   hide($("#maps"));
   hide($("#news"));
   hide($("#contests"));
   show($("#" + obj));
   $("#maps_link, #news_link, #cons_link").attr("class","por_tab");
   $("#" + link).attr("class","por_tab_sel");
}
function hide_switch(obj) {
   ele = $("#" + obj);
   if (ele.css("display") == 'none')
      ele.css("display","");
   else
      ele.css("display","none");
}
function bbcode_collapse(lolbox) {
   obj = $("#" + lolbox);
   if (obj.css("display") == 'none')
      show(obj);
   else
      hide(obj);
}
function clear_field(start, obj) {
   if (start.toString() == $(obj).val())
      $(obj).val("");
}
function unhelp() {
   $("#help").fadeOut("fast");
}
function seeing_stars(name, i) {
   var z = 0;
   for(var j=1;j<i+1;j++)
      $("#" + name + j).attr("src", "/images/star.png");
}
function no_stars(name) {
   var i = 5;
   for(var j=1;j<i+1;j++)
      $("#" + name + j).attr("src", "/images/graystar.png");
}
function inline_popup (loc, text, return_obj) {
   popup = $("#inlinepopup");
   show(popup);
   //$(popup).fadeIn("slow");
   scroll(0, 0); 
   popup.html('<div class="centered padding"><a href="javascript:destroy_popup(&#39;' + return_obj + '&#39;);"><img src="' + loc + '" alt="Image" />aaaa</a>aaa<br />'+text+'</div>');
}

function inline_popup_2(id) {

   var m = SEN.GUI.Dialogs.spawn(
      {
         adaptive_size: true,
         buttons: ["Previous", "Close", "Next", "Shrink to fit window"],
         innerHTML: "<img src='" + $("#"+id).attr("src") + "' data-old-id='" + id + "'>"
      }
   );
   $(m.buttonsNode).find("input[value=Next]+input").css("position","absolute").css("left","0");
   $(m.contentNode).css("text-align","center");
   $(m.buttonsNode).append("<span>Image " + ($("img.bbcode[id^=img]").index($("#"+id)) + 1) + " of " + $("img.bbcode[id^=img]").length + "</span>").find("span").css("position","absolute").css("right","0");

   m.__lol_image_sizing = 0;
   m.__lol_image_sizing_function =
      function() {
         var our_image = $(this.contentNode).find("img");
         if (!this.__lol_image_sizing) {
            our_image.css("width","auto").css("height","auto");
            return;
         }
         our_image.css("width","auto").css("height","auto");
         var modal_content = $(this.contentNode);
         var image_dimensions = [our_image.width() , our_image.height()];
         var modal_dimensions = [modal_content.width(), modal_content.height()];
         if (modal_content[0] > modal_content[1]) {
            our_image.width(modal_dimensions[0]);
            our_image.height( image_dimensions[1] / image_dimensions[0] * our_image.width() );
         } else {
            our_image.height(modal_dimensions[1]);
            our_image.width( image_dimensions[0] / image_dimensions[1] * our_image.height() );
         }
      };

   $(m).bind(
      "ButtonClicked",
      function(e, d) {
         if (d.index == 1)
            return this.close();

         if (d.index == 3) {
            d.modal.__lol_image_sizing = !d.modal.__lol_image_sizing;
            $(d.modal.buttonsNode).find("input[value^=Sh]").attr( "value" , ["Shrink to fit window" , "Show image at full size"][d.modal.__lol_image_sizing + 0] );
            d.modal.__lol_image_sizing_function();
            return;
         }

	 var list_of_images = $("img.bbcode[id^=img], #file_basic img[id^=dlddimg]");
         var img_index = list_of_images.index( $("#" + $(d.modal.contentNode).find("img").attr("data-old-id")) );
         var our_image = $(d.modal.contentNode).find("img");

         if (img_index && d.index == 0) {
            img_index -= 1;
         } else if (!img_index && d.index == 0)
            img_index = list_of_images.length - 1;
         else if (img_index < list_of_images.length - 1 && d.index == 2)
            img_index += 1;
         else if (img_index == list_of_images.length - 1 && d.index == 2)
            img_index = 0;

         our_image.attr("src", list_of_images[img_index].src).attr("data-old-id", list_of_images[img_index].id);
         $(d.modal.buttonsNode).find("span").text("Image " + (img_index + 1) + " of " + list_of_images.length);

         d.modal.__lol_image_sizing_function();
      },
      false
   );
   $(m).bind(
      "AfterDisplayUpdate",
      function(e, d) {
         d.modal.__lol_image_sizing_function();
      },
      false
   );

   var list_of_images = $("img.bbcode[id^=img]");
   var index = list_of_images.index($("#"+id));

   $(m.node).find("img").click(function(){$(this).closest(".modal").data("modal").close()}).css("cursor","pointer");
}

function inline_popup_3(header, text, script) {
   popup2 = $("#inlinepopup2");
   show(popup2);
   popup2.html('<div class="centered padding"><h1>'+ header + '</h1>' + text + '<br><div class="righted"><a href="javascript:destroy_popup2(&#39;&#39;);">Close</a></div></div>');
}

function destroy_popup(return_obj, x, y) {
   $("#inlinepopup").css("display","none").css("visibility","hidden");
   var coords = $("#"+return_obj).offset();
   coords.top -= 150;
   if (x || y)
      window.scroll(x, y);
   else
      scroll(0, coords.top);
}
function destroy_popup2(return_obj) {
   //hide(get_by_id("inlinepopup2"));
   $("#inlinepopup2").fadeOut("slow");
}

function destroy_popup2ok(script) {
   hide($("#inlinepopup2"));
   var vars = $("#vars1")[0];
   if(!vars)
      vars = 0;
   script(vars);
}

function get_offsets(obj) {
	return_array = Array();
	return_array['top'] = obj.offsetTop;
	return_array['left'] = offleft = obj.offsetLeft;
	
	pelement = obj.offsetParent;
	while (pelement!=null)
	{
		return_array['top'] += pelement.offsetTop;
		pelement = pelement.offsetParent;
	}
	
	pelement = obj.offsetParent;
	while (pelement!=null)
	{
		return_array['left'] += pelement.offsetLeft;
		pelement = pelement.offsetParent;
	}
	return return_array;
}
function view_error(input) {
   arr = get_offsets($("#" + input));
   arr['top'] -= 150;
   scroll(arr['left'], arr['top']); 
}

// custom tooltips shown when hovering over a "?" graphic.
// unhelp() is used to hide these. only one can be shown at a time.
function help(msg, obj) {
   help_text = msg.replace("#39;", "&#39;"); // can this be done better?
   var obj_help = get_by_id("help");

   obj_help.innerHTML = help_text;

   arr = get_offsets(obj);
   obj_help.style.left = arr["left"] + "px";
   obj_help.style.top = (arr["top"] + 20) + "px";

   $(obj_help).fadeIn("fast");

   if ( parseInt(obj_help.style.left) + obj_help.offsetWidth > document.body.offsetWidth )
      obj_help.style.left = ( document.body.offsetWidth - obj_help.offsetWidth - 5 ) + "px";

   //show(obj_help);
}

function mapnight(box) {
   mapnight_timer = setTimeout("hide(get_by_id('mp_comments'));hide(get_by_id('mp_plays'));hide(get_by_id('mp_screenshots'));show(get_by_id('"+box+"'))", 650);
}

function hide_save_shouts() {
   for (var i=0;i<document.xform.elements.length;i++) {
      objec = document.xform.elements[i];
      str = objec.id;
      if (str.substring(0, 4) == "save" && objec.type=='checkbox' && objec.style.visibility=='visible')
         hide(objec);
      else if (str.substring(0, 4) == "save" && objec.type=='checkbox' && objec.style.visibility=='hidden')
         show(objec);
   }
}

function init() { // old code is old
   if (document.layers) {
      layerRef="document.layers";
      styleSwitch="";
      visibleVar="show";
      browser ="ns";
   }  else if(document.all) {
      layerRef="document.all";
      styleSwitch=".style";
      visibleVar="visible";
      browser ="ie";
   }  else if(document.getElementById) {
      layerRef="document.getElementById";
      styleSwitch=".style";
      visibleVar="visible";
      browser="dom";
   } else {
      browser="none";
      newbrowser = false;
   } 
   check = true; 
}
function attach(id) {
   $('#xtext')[0].value += "[attach=" + id + "]"
}
function open_image(html) { // FIXME should be broken due to HTML changes!!
   body = get_by_id('body_screen');
   hide(body);
   hbs = get_by_id('huge_black_screen');
   hbs.innerHTML = 'Click image to go back<br /><a href="javascript:close_image();"><img src="uploads/database/images/' + html + '"></a>';
   $(hbs).fadeIn("slow");
}
function close_image() { // FIXME should be broken due to HTML changes!!
   body = get_by_id('body_screen');
   show(body);
   hbs = get_by_id('huge_black_screen');
   //hide(hbs);
   $(hbs).fadeOut("slow");
}
function locations() {
   if (window.scrollY) {
      current_scroll_height = window.scrollY;
      current_scroll_length = window.scrollX;
   } else if (window.pageYOffset) {
      current_scroll_height = window.pageYOffset;
      current_scroll_length = window.pageXOffset;
   } else if (document.documentElement.scrollTop) {
      current_scroll_height = document.documentElement.scrollTop;
      current_scroll_length = document.documentElement.scrollLeft;
   }
   if (window.innerWidth) {
      current_view_width = window.innerWidth;
      current_view_height = window.innerHeight;
   } else if (document.documentElement.offsetHeight) {
      current_view_height = document.documentElement.offsetHeight;
      current_view_width = document.documentElement.offsetWidth;
   }
}
function ajax_follow_start()
{ 
	if(ajax_working)
	{
	if(!ajax_status) ajax_status="Loading..."; 
	obj=get_by_id("ajax_move");
	objstatus=get_by_id("ajax_status");
	objstatus.innerHTML=ajax_status;
	obj.style.visibility='visible';
	show(obj);
	}
}

function ajax(script, vars)
{
	if (!ajax_working) { ajax_working = 1; get_by_id("ajax_move").style.width = "300px"; }
	eval ("var cla = new ajax_"+script+"();");
	/*
	if (script == "shoutbox") var cla = new ajax_shoutbox();
	else if (script=="mark") var cla = new ajax_mark();
	else if (script=="multimod") var cla = new ajax_multimod();
	else if (script=="report") var cla = new ajax_report();
	else if (script=="more_posts") var cla = new ajax_more_posts();
	else if (script=="postedit") var cla = new ajax_postedit();
	else if (script=="postdelete") var cla = new ajax_postdelete();
	else if (script=="shout_delete") var cla = new ajax_shout_delete();
	else if (script=="mapnight_rating") var cla = new ajax_mapnight_rating();
	else if (script=="karma") var cla = new ajax_karma();
	else if (script=="get_unparsed_post") var cla = new ajax_get_unparsed_post();
	else if (script=="postdelete_minor") var cla = new ajax_postdelete_minor();
	else if (script=="scp_member_upgrade_ignore") var cla = new ajax_scp_member_upgrade_ignore();
	else if (script=="scp_member_upgrade_promote") var cla = new ajax_scp_member_upgrade_promote();
	*/
	cla.limit();
	httpcounts++;
	i = httpcounts;
	httpreqs[i] = ajax_object();
	var params = cla.params(ajaxsession, ajaxmid, vars);
	httpreqs[i].onreadystatechange = function()
	{
		ajax_status = get_ajax_status(httpreqs[i]);
		if (cla.no_global_start != 1)
			ajax_follow_start();
		if (ajax_status == "Completed!")
		{
			errored = httpreqs[i].responseText.substr(0,5);
			//alert(errored);
			// alert(httpreqs[i].responseText);
			if (httpreqs[i].responseText.substr(0, 8) == '&Error: ')
			{
			// if(errored.toString() == 'Error')
				ajax_working = 0;
				get_by_id("ajax_move").style.width = "600px";
				get_by_id("ajax_status").innerHTML = httpreqs[i].responseText.substr(1);
				eval("setTimeout(\"ajax_close('"+i+"');\", 5000);");
			}
			else
			{	
				// alert (httpreqs[i].responseText);

					cla.parser(httpreqs[i].responseText, vars);

				if (cla.no_global_start != 1)
					eval("setTimeout(\"ajax_close('"+i+"');\", 1700);");
			}
		}
		cla.status(ajax_status);
	}
	httpreqs[i].open("POST", cla.url(), true);
	httpreqs[i].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpreqs[i].setRequestHeader("Content-length", params.length);
	httpreqs[i].setRequestHeader("Connection", "close");
	httpreqs[i].send(params);
	eval("setTimeout(\"clear('"+script+"');\", 2500);");
}

function shoutbox_enable_refresh(t) {
   refresh_time=t*1000;
   eval("setTimeout(\"shoutbox_refresh('"+refresh_time+"');\", "+refresh_time+");");
}

function shoutbox_refresh(t) {
   eval("setTimeout(\"shoutbox_refresh('"+refresh_time+"');\", "+refresh_time+");");
   do_shout=0;
   ajax("shoutbox");
}

function ajax_close(k) {
   delete httpreqs[k];
   ajax_status="";
   $("#ajax_move").css("visibility", "hidden");
}

function clear(script) {
   if (script=="shoutbox")
      var cla = new ajax_shoutbox;
   else if (script=="multimod")
      var cla = new ajax_multimod;
   else
      return;
   cla.cleared();
}

function ajax_object() {
   var http_object = null;
   try {
      http_object = new XMLHttpRequest();
   } catch (e) {
      try {
         http_object = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         http_object = new ActiveXObject("Microsoft.XMLHTTP");
      }
   }
   return http_object;
}

function get_ajax_status(tmp) {
   var rS = tmp.readyState;
   if (rS < 4 && rS == Math.floor(rS)) {
      return (
         [
            "Uninitialized",
            "Loading...",
            "Loaded...",
            "Interacting..."
         ]
      )[rS];
   } else if (rS == 4) {
      if (tmp.status == 200)
         return "Completed!";
      else
         return "Unknown (" + tmp.status + ")";
   } else {
      return "Unknown";
   }
}

function ajax_shout_delete() {
   this.params=params;
   this.parser=parser;
   this.status=status;
   this.url=url;
   this.limit=limit;
   this.cleared=cleared;

   function status(tmp) {}
   function limit() {}
   function cleared() {}
   function url() {
      return "/ajax/shoutbox_delete.php";
   }
   function params(ze, amid, vars) {
      return "ze="+ze+"&ajaxmid="+amid+"&id="+vars;
   }

   function parser(html) {
      if (html != 0)
         hide($("#shout_" + html));
      else {
         alert("An unspecified error has occurred on this page. Please report this to a staff member.\n\nError details: ajax_shout_delete, parser");
         throw "ajax_shout_delete() parser(): Unknown error. (html == 0)";
      }
   }
}

function ajax_suspension_remove()
{
   this.params=params;
   this.parser=parser;
   this.status=status;
   this.url=url;
   this.limit=limit;
   this.cleared=cleared;

   function status(tmp) {}
   function limit() {}
   function cleared() {}
   function url() {
      return "/ajax/suspension_remove.php";
   }
   function params(ze, amid, vars) {
      return "ze="+ze+"&ajaxmid="+amid+"&id="+vars;
   }
   function parser(html) {
      if (html != 0)
         hide($("#sus_" + html));
      else {
         alert("An unspecified error has occurred on this page. Please report this to a staff member.\n\nError details: ajax_suspension_remove, parser");
         throw "ajax_suspension_remove() parser(): Unknown error. (html == 0)";
      }
   }
}

function ajax_getmembers() { // members for what?
   this.params=params;
   this.parser=parser;
   this.status=status;
   this.url=url;
   this.limit=limit;
   this.cleared=cleared;

   function status(tmp) {}
   function limit() {}
   function cleared() {}
   function url() {
      return "/ajax/get_members.php";
   }
   function params(ze, amid, vars) {
      return "ze="+ze+"&ajaxmid="+amid+"&id="+vars;
   }
   function parser(html) {
      if (html != 0)
         $("#members").html(html);
      else {
         alert("An unspecified error has occurred on this page. Please report this to a staff member.\n\nError details: ajax_getmembers, parser");
         throw "ajax_getmembers() parser(): Unknown error. (html == 0)";
      }
   }
}

function ajax_mapnight_rating() {
   this.params=params;
   this.parser=parser;
   this.status=status;
   this.url=url;
   this.limit=limit;
   this.cleared=cleared;

   function status(tmp) {}
   function limit() {}
   function cleared() {}
   function url() {
      return "/ajax/mapnight_rating.php";
   }
   function params(ze, amid, vars) {
      return "ze="+ze+"&ajaxmid="+amid+vars;
   }
   function parser(html) {
      if (html != 0)
         hide($("#ss_rating_" + html));
      else {
         alert("An unspecified error has occurred on this page. Please report this to a staff member.\n\nError details: ajax_mapnight_rating, parser");
         throw "ajax_mapnight_rating() parser(): Unknown error. (html == 0)";
      }
   }
}
function ajax_shoutbox() {
   this.params=params;
   this.parser=parser;
   this.status=status;
   this.url=url;
   this.limit=limit;
   this.cleared=cleared;

   this.no_global_start = 1;

   function status(tmp) {
      $("#shoutbox_status").html(tmp);
   }
   function limit() {
      sb_refresh = $("#shout_refresh, #shout_submit").attr("disabled", "disabled").attr("class", "disabled");
   }
   function cleared() {
      sb_refresh = $("#shout_refresh, #shout_submit").removeAttr("disabled").attr("class", "submit");
   }
   function url() {
      return "/ajax/shoutbox.php";
   }
   function params(ze, amid, vars) {
      shout_from = $("#shout_from").val();
      if (do_shout) {
         textual = encodeURIComponent($("#shout_text").val());
         $("#shout_text").val("");
         shout_color = $("#shout_color").val();
         site = $("#shout_site").val();
      } else {
         textual="";
         shout_color="";
         site="";
      }
      do_shout = 1;
      return "ze="+ze+"&ajaxmid="+amid+"&itime="+shoutbox_last+"&shout_from="+shout_from+"&color="+encodeURI(shout_color)+"&channel="+site+"&shout="+textual;
   }
   function parser(html) {
      var temp = html.indexOf(";");
      shoutbox_last = html.substring(0, temp);
      data = html.substring(temp+1);
      if (!data.match(/^\s*$/))
         $("#shoutbox_return").prepend(data);
   }
}

function hover(div_id, var_name) {
   $(div_id).html(eval(var_name));
}
function form_submit(xid) {
   $("#" + xid).submit();
}
function over(name, n) {
   $("#" + name).attr("class", "tdlink" + n);
}
function hide(obj) {
   $(obj).css("display", "none").css("visibility", "hidden");
}
function show(obj) {
   $(obj).css("display", "").css("visibility", "visible");
}
function cleartext(obj) {
   obj.value = '';
}
function disable_reclick(mbutton) {
   alert(mbutton);
}
function check_all() {
   for (var i=0;i<document.xform.elements.length;i++) {
      var objec = document.xform.elements[i];
      if ((objec.name != 'checkall') && (objec.type=='checkbox'))
         objec.checked = document.xform.selectall.checked;
   }
}
function small_window(location, name, width, height) {
   var width = width || 400,
       height = height || 250,
       name = name || location;
   url = href_base+"small.php?p="+location+"&skin="+skin_base;
   dimensions = "width="+width+",height="+height;
   window.open(url, name, dimensions + 'resizable=yes, scrollbars=yes'); 
}

function eat_cookie(name) {
   // just in case anything is still using this function
   return SEN.getCookie(name);
}
function give_cookie(name, value, sticky) {
   // just in case anything is still using this function
   return SEN.setCookie(name, value, sticky);
   document.cookie = name + "=" + value + ";expires=" + cookie_expire_date +" 12:00:00 UTC;domain=" + cookie_domain + ";path=/";
}

function get_by_id(name) {
   object = null;
   if (document.getElementById)
      object = document.getElementById(name);
   else if (document.all) 
      object = document.all[name];
   else if (document.layers)
      object = document.layers[name];
   return object;
}

function check_id_for_existance(in_parent, id_name) {
   if(in_parent)
      return window.opener.document.getElementById(id_name) != null;
   else
      return !!$("#" + id_name).length;
}
function collapse(id, type, tablets, save) {
   var mycurrent = [],
       newcookie = [],
       tablet_arr = [],
       do_tabs = false,
       i,
       temp;
   if (temp = SEN.getCookie('collapsed'))
      mycurrent = temp.split(",");
   if (tablets != "") {
      do_tabs = true;
      tablet_arr = tablets.split(",");
   }
   if (type == "expand") {
      if (save)
         for(i=0;i<mycurrent.length;i++)
            if ( mycurrent[i] != id && mycurrent[i] != "" )
               newcookie[newcookie.length] = mycurrent[i];
      hide($("#hide_" + id));
      show($("#show_" + id));
      if (do_tabs)
         for(i = 0;i < tablet_arr.length;i++)
            show($("#tab_" + tablet_arr[i]));
   } else {
      if (save) {
         newcookie = mycurrent;
         newcookie[newcookie.length] = id;
      }
      show($("#hide_" + id));
      hide($("#show_" + id));
      if (do_tabs)
         for(i=0;i < tablet_arr.length;i++)
            hide($("#tab_" + tablet_arr[i]));
   }
   if (save)
      SEN.setCookie('collapsed', newcookie.join(','), 1);
}
function show_attachments(vars) {
   show = prompt('Attachment BBCode:', '[attach='+vars+']');
   return false;
}

function test() {
   $("#shout_text").css("color", "#"+$("#shout_color").val());   
   $("#shout_color").css("color", "#"+$("#shout_color").val());   
   $("#shout_text").focus();
}

/* "Add this to /support/global.js. It runs through the cookie used by the old collapse code,
and collapses all referenced elements when the page loads. I tested; with this new code,
Forum Index collapse state is remembered on Epic. It should work for anything that uses the
old collapse code.*/
$(function() {
  var e = SEN.getCookie('collapsed').replace(/;[^\b]*$/,"").split(",");
  var i=0, el = e.length;
  for(;i<el;i++) {
     if (e[i]) {
        hide($("#show_"+e[i]));
        show($("#hide_"+e[i]));
     }
  }
});
