﻿var _errBub_Dismiss_Id = -1;
var _pmnu_open = false;
var _tmnu_open = false;
var _pmnu_twoCol_open = false;
var _tmnu_twoCol_open = false;
var _homePageUrl = "/home/";

function /*String*/ GetRedirectLoc()
{
	var redir = "/";
	var re = $("#redirect").val();

	if (typeof __redirectTo != "undefined")
	{
		if (typeof __redirectTo != null)
		{
			if (typeof __redirectTo == "string")
			{
				if(__redirectTo.length > 0)
					redir = __redirectTo;
			}
		}
	}

	if (re != null)
	{
		if (re.length > 0)
		{
			redir = re;
		}
	}

   return redir + window.location.hash.replace(/#/g, "9E0");
}

$(window).resize(function() {
   if ($("#profileIconTwoCol").position() != null)
      $(".dropContainerTwoCol").css("left", "" + $("#profileIconTwoCol").position().left + "px");

   if ($("#profileIcon").position() != null)
      $(".dropContainer").css("left", "" + $("#profileIcon").position().left + "px");
});


$(document).one("widgetsloaded", function ()
{
   if (!(window.location.search.indexOf("redir").length > 0 || window.location.search.indexOf("ret").length > 0))
      _fbTarget = GetRedirectLoc();

   $(this).click(function (event) {
      // Hide drop-downs on body click outside of the drop down divs.
      var tcn = event.target.className;
      var tid = event.target.id;
      if (tcn !== "profileIconTwoCol" && tcn !== "myTeamsCtaTwoCol" && tid != "myTeamsLinkTwo" && tid != "myTeamsTxt") {
         if (_pmnu_twoCol_open) {
            $("#profileOptionsTwoCol").animate({ top: "-45px" }, 500, "swing", function () {
               $(".dropContainerTwoCol").hide();
            });
            _pmnu_twoCol_open = !_pmnu_twoCol_open;
         } else if (_tmnu_twoCol_open) {
            $("#myTeamsOptionTwoCol").animate({ top: "-300px" }, 500, "swing", function () {
               $(".dropContainerTwoCol").hide();
            });
            _tmnu_twoCol_open = !_tmnu_twoCol_open;
         }

      }

      if (tcn !== "profileIcon" && tcn !== "myTeamsCta" && tid != "myTeamsLinkOne" && tid != "myTeamsTxt") {
         if (_pmnu_open) {
            $("#profileOptions").animate({ top: "-85px" }, 500, "swing", function () {
               $(".dropContainer").hide();
            });
            _pmnu_open = !_pmnu_open;
         } else if (_tmnu_open) {
            $("#myTeamsOption").animate({ top: "-300px" }, 500, "swing", function () {
               $(".dropContainer").hide();
            });
            _tmnu_open = !_tmnu_open;
         }
      }
   });


   $("#logo_imageL, #logo_image").click(function () {
      window.location = _homePageUrl;
   });

   //    $(this).click(function (event) {
   //        if (event.target.className == "popUpBackground") {
   //            $(".popUpContainer").hide();
   //            $(".popUpBackground").hide();
   //            $(".popUpDialog").hide();
   //        }
   //    });

   $(".formButtons").hover(
    function () {
       $(this).fadeTo("fast", .5);
       $(this).stop(true, false);
    },
    function () {
       $(this).fadeTo("fast", 1);
    });

   $("#signInBtn").click(function () {
      attemptSignIn();
   });


   $("#pword").keydown(function (e) {
      if (e.keyCode == '13') {
         attemptSignIn();
      }
   });

   $("#errDis").click(function () {
      if (_errBub_Dismiss_Id > -1)
         clearTimeout(_errBub_Dismiss_Id);
      dismissErr();
   });


   //sign in box focus and blur 
   $(".emailInput").focus(function () {

      $(this).css({ "background-image": "url(/images/emailBgTyping.png)",
         "background-position": "1px 3px"
      });

      if ($(".pwordInput").val() !== "") {
         $(".pwordInput").css({ "background-image": "url(/images/pwordBgTyping.png)",
            "background-position": "2px 2px"
         });
      }
   });

   $(".emailInput").blur(function () {
      if ($(this).val().length <= 0) {
         $(this).css(
          {
             "background-image": "url(/images/emailBg.png)",
             "background-position": "0px 2px"
          });
      }
   });

   //sign in box focus and blur 
   $(".pwordInput").focus(function () {
      $(this).css({ "background-image": "url(/images/pwordBgTyping.png)",
         "background-position": "2px 2px"
      });

      if ($(".emailInput").val() !== "") {
         $(".emailInput").css({ "background-image": "url(/images/emailBgTyping.png)",
            "background-position": "1px 3px"
         });
      }
   });

   $(".pwordInput").blur(function () {
      if ($(this).val().length <= 0) {
         $(this).css(
          {
             "background-image": "url(/images/pwordBg.png)",
             "background-position": "2px 2px"
          });
      }
   });


   //TEAM CLICK
   $(".teamContainer").click(function () {
      window.location = "/team/news/" + $(this).attr("id").split('_')[1] + "/home/";
   });

   //DROP DOWN LIST ONE COLUMN
   $("#profileIcon").click(function () {
      $("#profileOptions").stop(true, false);

      _pmnu_open = !_pmnu_open;
      $(".dropContainer").css("left", "" + $("#profileIcon").position().left + "px");

      if (_tmnu_open) {
         $("#myTeamsOption").animate({ top: "-300px" });
         _tmnu_open = !_tmnu_open;
      }

      if (_pmnu_open) {
         $(".dropContainer").show();
         $("#primaryNav").css({ "box-shadow": "0px 2px 7px #000000" });
         $("#profileOptions").animate({ top: "0px" });
      } else {
         $("#primaryNav").css({ "box-shadow": "0px 0px 0px #000000" });
         $("#profileOptions").animate({ top: "-45px" }, 500, "swing", function () {
            $(".dropContainer").hide();
         });
      }
   });

   $("#myTeamsCta,#myTeamsLinkOne").click(function () {
      $("#myTeamsOption").stop(true, false);

      _tmnu_open = !_tmnu_open;
      $(".dropContainer").css("left", "" + $("#myTeamsLinkOne").position().left + "px");

      if (_pmnu_open) {
         $("#profileOptions").animate({ top: "-45px" });
         _pmnu_open = !_pmnu_open;
      }

      if (_tmnu_open) {
         $(".dropContainer").show();
         $("#primaryNav").css({ "box-shadow": "0px 2px 7px #000000" });
         $("#myTeamsOption").animate({ top: "-45px" });
      } else {
         $("#primaryNav").css({ "box-shadow": "0px 0px 0px #000000" });
         $("#myTeamsOption").animate({ top: "-300px" }, 500, "swing", function () {
            $(".dropContainer").hide();
         });
      }
      if ($.trim($(".myTeamsOption").text()) == "") {
         $(".myTeamsOption").html("<div class='teamAlert'>You currently do not have any teams linked. Click <a title='Find Team' class='emptyTeamLink' href='/team/search/'>Find a Team</a> to start adding teams.</div>");
      }
   });

   //DROP DOWN LIST TWO COLUMN
   $("#profileIconTwoCol").click(function () {
      $("#profileOptionsTwoCol").stop(true, false);

      _pmnu_twoCol_open = !_pmnu_twoCol_open;
      $(".dropContainerTwoCol").css("left", "" + $("#profileIconTwoCol").position().left + "px");

      if (_tmnu_twoCol_open) {
         $("#myTeamsOptionTwoCol").animate({ top: "-300px" });
         _tmnu_twoCol_open = !_tmnu_twoCol_open;
      }

      if (_pmnu_twoCol_open) {
         $(".dropContainerTwoCol").show();
         $("#primaryNav").css({ "box-shadow": "0px 2px 7px #000000" });
         $("#profileOptionsTwoCol").animate({ top: "40px" });
      } else {
         $("#primaryNav").css({ "box-shadow": "0px 0px 0px #000000" });
         $("#profileOptionsTwoCol").animate({ top: "-45px" }, 500, "swing", function () {
            $(".dropContainerTwoCol").hide();
         });
      }
   });

   $("#myTeamsCtaTwoCol,#myTeamsLinkTwo").click(function () {
      $("#myTeamsOptionTwoCol").stop(true, false);

      _tmnu_twoCol_open = !_tmnu_twoCol_open;
      $(".dropContainerTwoCol").css("left", "" + $("#myTeamsLinkTwo").position().left + "px");

      if (_pmnu_twoCol_open) {
         $("#profileOptionsTwoCol").animate({ top: "-45px" });
         _pmnu_twoCol_open = !_pmnu_twoCol_open;
      }

      if (_tmnu_twoCol_open) {
         $(".dropContainerTwoCol").show();
         $("#primaryNav").css({ "box-shadow": "0px 2px 7px #000000" });
         $("#myTeamsOptionTwoCol").animate({ top: "-45px" });
      } else {
         $("#primaryNav").css({ "box-shadow": "0px 0px 0px #000000" });
         $("#myTeamsOptionTwoCol").animate({ top: "-300px" }, 500, "swing", function () {
            $(".dropContainerTwoCol").hide();
         });
      }

      if ($.trim($(".myTeamsOptionTwoCol").text()) == "") {
         $(".myTeamsOptionTwoCol").html("<div class='teamAlert'>You currently do not have any teams linked. Click <a title='Find Team' class='emptyTeamLink' href='/team/search/'>Find a Team</a> to start adding teams.</div>");
      }
   });

   $("#signInBtn").hover(
    function () {
       $(this).fadeTo("fast", .5);
       $(this).css({ cursor: "pointer" });
       $(this).stop(true, false);
    },
    function () {
       $(this).fadeTo("fast", 1);
    });
});

function dismissErr() {
	$("#errBub").animate({ "top": "45px" }, "fast");
	_errBub_Dismiss_Id = -1;
}

function attemptSignIn() {
   $("#loginForm").submit();
   /*
	$("#signInBtn").attr("disabled", "disabled");

	var prms = [];
	prms.push({ name: "e", value: $("#email").val() });
	prms.push({ name: "p", value: $("#pword").val() });
	prms.push({ name: "rememberMe", value: $("#rememberMe").prop("checked") });
	ajax("/api/Signin.aspx", prms,
		function (r) {
			var o;
			eval("o = " + r);
			if (o.ok){				
				window.location = GetRedirectLoc();
			} else {
				$("#errBub").animate({ "top": "71px" }, "fast");
				_errBub_Dismiss_Id = setTimeout(function () { dismissErr(); }, 2500);
				$("#signInBtn").removeAttr("disabled");
				$("#email").focus();
			}
		}); */
}
﻿
PopupDialog = function ()
{
   // Private Properties
   this._popupId = "";
   this._suppressAlertErrors = false;
   this._customControls = new Array();
   this._debug = false;

   if (typeof _MTS_JQUERY !== "function")
   {
      this._Alert("You must use jQuery!");
      return null;
   }
};

PopupDialog.prototype =
{
   // Private Metods
   _RandomIdString: /*string*/function (/*int*/length)
   {
      var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
      var randomString = "";
      var randomNumber = 0;

      for (var i = 0; i < length; i++)
      {
         randomNumber = Math.floor(Math.random() * chars.length);
         randomString += chars.substring(randomNumber, randomNumber + 1);
      }

      return randomString.toString();
   },

   _Alert: /*void*/function (/*string*/message)
   {
      if (this._debug)
         alert(message);
   },

   _IsValidParams: /*bool*/function (/*string*/message, /*string*/title)
   {
      if (typeof message !== "string" || message == null)
      {
         this._Alert("You must specify a valid message!");
         return false;
      }

      if (typeof title !== "string" || title == null)
      {
         this._Alert("You must specify a valid title!");
         return false;
      }

      return true;
   },

   _IsValidJsonControl: /*bool*/function (/*json*/json)
   {
      if (typeof json !== "object" || json == null)
      {
         return false;
      }

      if (typeof json.id !== "string" || json.id == null)
      {
         return false;
      }

      if (typeof json.type !== "string" || json.type == null)
      {
         return false;
      }

      if (typeof json.name !== "string" || json.name == null)
      {
         return false;
      }

      if (typeof json.text !== "string" || json.text == null)
      {
         return false;
      }

      if (json.id.length <= 0 || json.type.length <= 0 || json.name.length <= 0)
      {
         return false;
      }

      return true;
   },

   _StandardWireups: /*void*/function ()
   {
      _MTS_JQUERY(".popUpDialogButton").hover(
        function ()
        {
           _MTS_JQUERY(this).fadeTo("fast", .5);
           _MTS_JQUERY(this).css({ cursor: "pointer" });
           _MTS_JQUERY(this).stop(true, false);
        },
        function ()
        {
           _MTS_JQUERY(this).fadeTo("fast", 1);
        });
   },

   _CreateElement: /*DOM Element*/function (/*string*/element, /*optional string*/id, /*optional string*/className)
   {
      var domElement = null;

      if (typeof element !== "string" || element == null)
      {
         return null;
      }

      domElement = document.createElement(element);
      if (typeof domElement !== "object" || domElement == null)
      {
         return null;
      }

      if (typeof id === "string" && id != null)
      {
         domElement.id = id;
      }

      if (typeof className === "string" && className != null)
      {
         domElement.className = className;
      }

      return domElement;
   },

   _AddCloser: /*void*/function (/*function*/callback, /*obj*/passThrough, /*optional bool*/hide)
   {
      var me = this;

      _MTS_JQUERY("#popUpClose_" + this._popupId).click(function ()
      {
         if (typeof hide === "boolean" && hide != null)
         {
            if (hide)
            {
               me.Hide();
            }
         }

         if (typeof callback === "function" && callback != null)
         {
            callback(me, passThrough);
         }
      });
   },

   // Public Methods
   NewDialog: /*void*/function ()
   {
      var body = _MTS_JQUERY("body")[0];
      if (typeof body !== "object" && body == null)
      {
         return;
      }

      var oldDialog = _MTS_JQUERY("#popUpDialog_" + this._popupId)[0];
      if (typeof oldDialog === "object" && oldDialog != null)
      {
         body.removeChild(oldDialog);
      }

      this._customControls = new Array();
      this._popupId = this._RandomIdString(15);

      var closer = this._CreateElement("i", "popUpClose_" + this._popupId, "fas fa-times popUpClose");

      var header = this._CreateElement("div", "popUpHeader_" + this._popupId, "popUpHeader");
      header.appendChild(this._CreateElement("div", "popUpHeading_" + this._popupId, "popUpHeading"));

      var container = this._CreateElement("div", "popUpContainer_" + this._popupId, "popUpContainer");
      container.appendChild(header);
      container.appendChild(this._CreateElement("div", "popUpDescription_" + this._popupId, "popUpDescription"));
      container.appendChild(this._CreateElement("div", "popUpControls_" + this._popupId, "popUpControls"));
      container.appendChild(this._CreateElement("div", "popUpElements_" + this._popupId, "popUpElements"));
      container.appendChild(this._CreateElement("div", "popUpErrors_" + this._popupId, "popUpErrors"));
      container.appendChild(this._CreateElement("div", "popUpButtons_" + this._popupId, "popUpButtons"));
      container.appendChild(this._CreateElement("div", "popUpFooter_" + this._popupId, "popUpFooter"));

      var dialog = this._CreateElement("div", "popUpDialog_" + this._popupId, "popUpDialog");
      dialog.appendChild(closer);
      dialog.setAttribute("style", "display: none;");
      dialog.appendChild(container);
      dialog.appendChild(this._CreateElement("div", "popUpBackground_" + this._popupId, "popUpBackground"));

      body.appendChild(dialog);

   },

   // Original Show, works great! Do NOT delete! ------------------------- Do NOT delete!  --------------------------- Do NOT delete!
   //   Show: /*void*/function ()
   //   {
   //      _MTS_JQUERY("#popUpDialog_" + this._popupId).css(
   //		  {
   //		     visibility: "hidden"
   //		  });

   //      var windowWidth = _MTS_JQUERY(window).width();
   //      var windowHeight = _MTS_JQUERY(window).height();

   //      _MTS_JQUERY(".popUpBackground").css(
   //        {
   //           width: windowWidth.toString() + "px",
   //           height: windowHeight.toString() + "px"
   //        });

   //      _MTS_JQUERY(".popUpBackground").fadeTo(0, .8);

   //      _MTS_JQUERY("#popUpDialog_" + this._popupId).show();

   //      var thisContainer = _MTS_JQUERY("#popUpContainer_" + this._popupId);

   //      var outerWidth = thisContainer.outerWidth();
   //      var outerHeiht = thisContainer.outerHeight();

   //      var left = (windowWidth / 2) - (outerWidth / 2);
   //      var top = (windowHeight / 2) - (outerHeiht / 2);

   //      if (outerWidth >= windowWidth)
   //      {
   //         left = 0;

   //         thisContainer.css(
   //	      {
   //	         position: "absolute"
   //	      });
   //      }

   //      if (outerHeiht >= windowHeight)
   //      {
   //         top = 18;

   //         thisContainer.css(
   //	      {
   //	         position: "absolute"
   //	      });
   //      }

   //      thisContainer.css(
   //	   {
   //	      left: left.toString() + "px",
   //	      top: top.toString() + "px"
   //	   });

   //	   //_MTS_JQUERY(window).scrollTop(0); // A last resort for tablet
   //      _MTS_JQUERY("#popUpDialog_" + this._popupId).css(
   //		{
   //		   visibility: "visible"
   //		});
   //   },

   Show: /*void*/function ()
   {
      _MTS_JQUERY("#popUpDialog_" + this._popupId).css(
		{
		   visibility: "hidden"
		});

      _MTS_JQUERY("#popUpDialog_" + this._popupId).show();

      var thisContainer = _MTS_JQUERY("#popUpContainer_" + this._popupId);

      _MTS_JQUERY("#popUpDialog_" + this._popupId).css(
		{
		   visibility: "visible"
		});

		//For select box styles
		_MTS_JQUERY(function ()
		{
         if (_MTS_JQUERY.chosen)
		      _MTS_JQUERY("#popUpDialog_" + this._popupId + " select").chosen();
		});
      //End for select box styles

      //Set height to even number to prevent half pixel render
		//puc = _MTS_JQUERY(".popUpContainer");
		//if (puc.height() % 2 != 0)
		//{
		//   puc.css({"height": Math.floor(puc.height() + 1 + "px" });
		//}
		//if (puc.width() % 2 != 0)
		//{
		//   puc.css({ "width": Math.floor(puc.width()) + 1 + "px" });
		//}
   },

   Hide: /*void*/function ()
   {
      _MTS_JQUERY("#popUpDialog_" + this._popupId).hide();
   },

   CheckContainer: /*bool*/function (/*string*/container)
   {
      var containerTest = null;

      if (typeof container !== "string" || container == null)
      {
         this._Alert("Container must be a string!");
         return false;
      }

      if (container.length <= 0)
      {
         this._Alert("You must provide a value!");
         return false;
      }

      if (container.substr(0, 1) !== '.' && container.substr(0, 1) !== '#')
      {
         this._Alert("Your container must begin with either a dot (.) or a pound symbol (#)!");
         return false;
      }

      containerTest = _MTS_JQUERY(container);

      if (typeof containerTest !== "object" || containerTest == null)
      {
         this._Alert("The specified container does not exist!");
         return false;
      }

      if (containerTest.length <= 0)
      {
         this._Alert("The specified container is invalid!");
         return false;
      }

      return true;
   },

   GetPopupId: /*string*/function ()
   {
      return this._popupId;
   },

   AppendError: /*void*/function (/*string*/errorMessage)
   {
      var errorNo = this._RandomIdString(8);
      var errors = null;

      if (typeof errorMessage !== "string" || errorMessage == null)
      {
         return;
      }

      errors = document.getElementById("popUpErrors_" + this._popupId);
      if (typeof errors !== "object" || errors == null)
      {
         return;
      }

      errors.appendChild(this._CreateElement("div", "popUpError_" + this._popupId + "_" + errorNo, "popUpError"));
      _MTS_JQUERY("#popUpError_" + this._popupId + "_" + errorNo).html(errorMessage);
   },

   ClearErrors: /*void*/function ()
   {
      _MTS_JQUERY("#popUpErrors_" + this._popupId).html("");
   },

   GetControlData: /*json*/function ()
   {
      var customControls = this._customControls;
      var controlInfo = {};
      var json = null;

      for (var i = 0; i < customControls.length; i++)
      {
         json = customControls[i];
         if (!this._IsValidJsonControl(json))
         {
            return null;
         }

         controlInfo[json.name] =
		      {
		         id: json.id,
		         type: json.type,
		         text: json.text,
		         value: ""
		      };

         switch (json.type)
         {
            case "checkbox":
               controlInfo[json.name].value = _MTS_JQUERY("#" + json.id).prop("checked").toString();
               break;

            case "radio":
               controlInfo[json.name].value = _MTS_JQUERY("#" + json.id).val().toString();
               break;

            case "text":
               controlInfo[json.name].value = _MTS_JQUERY("#" + json.id).val().toString();
               break;

            case "password":
               controlInfo[json.name].value = _MTS_JQUERY("#" + json.id).val().toString();
               break;

            case "email":
               controlInfo[json.name].value = _MTS_JQUERY("#" + json.id).val().toString();
               break;

            case "textarea":
               controlInfo[json.name].value = _MTS_JQUERY("#" + json.id).val().toString();
               break;
            case "select":
               controlInfo[json.name].value = _MTS_JQUERY("#" + json.id).val().toString();
               break;
            default:
               return null;
         }
      }

      return controlInfo;
   },

   AddButton: /*jquery obj*/function (/*string*/buttonText, /*function*/callback, /*optional obj*/passThrough)
   {
      var container = document.getElementById("popUpButtons_" + this._popupId);
      var buttonId = "";
      var me = null;

      if (typeof container !== "object" || container == null)
      {
         this._Alert("You must create a new dialog before adding buttons! ");
         return null;
      }

      if (typeof buttonText !== "string" || buttonText == null)
      {
         this._Alert("Invalid button value!");
         return null;
      }

      if (buttonText.length <= 0)
      {
         this._Alert("You must provide a value when adding buttons!");
         return null;
      }

      buttonId += "popUpButton_" + this._popupId + "_" + this._RandomIdString(8);

      container.appendChild(this._CreateElement("div", buttonId, "mts_cc_button popUpButton"));
      _MTS_JQUERY("#" + buttonId).html(buttonText);

      this._StandardWireups();

      var me = this;
      _MTS_JQUERY("#" + buttonId).click(function ()
      {
         if (typeof callback === "function" && callback != null)
         {
            callback(me, me.GetControlData(), passThrough);
         }
      });

      return _MTS_JQUERY("#" + buttonId);
   },

   AddControl: /*void*/function (/*string*/controlType, /*string*/controlName, /*Optional string*/controlValue, /*Optional string*/controlText, /*function*/callback, /*optional obj*/passThrough, /*optional string*/className)
   {
      var container = document.getElementById("popUpControls_" + this._popupId);
      var controlId = "";
      var control = null;
      var inputControl = null;

      if (typeof container !== "object" || container == null)
      {
         this._Alert("You must create a new dialog before adding controls! ");
         return;
      }

      if (typeof controlType !== "string" || controlType == null)
      {
         this._Alert("Invalid control value!");
         return;
      }

      if (typeof controlName !== "string" || controlName == null)
      {
         this._Alert("Invalid control name!");
         return;
      }

      if (controlName.length <= 0)
      {
         this._Alert("You must provide a control name when adding controls!");
         return;
      }

      if (typeof controlValue !== "string" || controlValue == null)
      {
         controlValue = "";
      }

      if (typeof controlText !== "string" || controlText == null)
      {
         controlText = "";
      }

      controlId = "control_" + this._popupId + "_" + this._RandomIdString(8);

      control = this._CreateElement("div", "popUpControl_" + controlId, "popupControl");
      control.appendChild(this._CreateElement("div", "popUpControlText_" + controlId, "popUpControlText"));

      switch (controlType)
      {
         case "checkbox":
            inputControl = this._CreateElement("input", controlId, null);
            inputControl.setAttribute("type", "checkbox");
            inputControl.setAttribute("name", controlName);
            inputControl.setAttribute("class", "popUpControlCheckbox");
            break;

         case "radio":
            inputControl = this._CreateElement("input", controlId, null);
            inputControl.setAttribute("type", "radio");
            inputControl.setAttribute("name", controlName);
            inputControl.setAttribute("value", controlValue);
            inputControl.setAttribute("class", "popUpControlRadio");
            break;

         case "text":
            inputControl = this._CreateElement("input", controlId, null);
            inputControl.setAttribute("type", "text");
            inputControl.setAttribute("name", controlName);
            inputControl.setAttribute("value", controlValue);
            inputControl.setAttribute("class", "popUpControlText");
            break;

         case "password":
            inputControl = this._CreateElement("input", controlId, null);
            inputControl.setAttribute("type", "password");
            inputControl.setAttribute("name", controlName);
            inputControl.setAttribute("value", controlValue);
            inputControl.setAttribute("class", "popUpControlPassword");
            break;

         case "email":
            inputControl = this._CreateElement("input", controlId, null);
            inputControl.setAttribute("type", "email");
            inputControl.setAttribute("name", controlName);
            inputControl.setAttribute("value", controlValue);
            inputControl.setAttribute("class", "popUpControlEmail");
            break;

         case "textarea":
            inputControl = this._CreateElement("textarea", controlId, null);
            inputControl.setAttribute("class", "popUpControlTextArea");
            break;

         case "select":
            inputControl = this._CreateElement("select", controlId, null);
            inputControl.setAttribute("name", controlName);
            inputControl.setAttribute("class", className === null || className === "" ? "popUpControlSelect" : className);
            break;

         default:
            this._Alert("The specified control type is not valid!");
            return;
      }

      this._customControls.push(
		  {
		     id: controlId,
		     type: controlType,
		     name: controlName,
		     text: controlText
		  });

      if (typeof inputControl === "object" && inputControl != null)
      {
         control.appendChild(inputControl);
      }

      container.appendChild(control);

      _MTS_JQUERY("#popUpControlText_" + controlId).html(controlText);

      if (controlType === "textarea")
      {
         _MTS_JQUERY("#" + controlId).html(controlValue);
      }


      if (typeof callback === "function" && callback != null)
      {
         callback(_MTS_JQUERY("#popUpControls_" + this._popupId), _MTS_JQUERY("#" + controlId), _MTS_JQUERY("#popUpControlText_" + controlId), passThrough); // + "_text"
      }
   },

   AddElement: /*void*/function (/*string*/elementType, /*string*/elementData, /*optional function*/callback, /*optional obj*/passThrough, /*optional string*/className)
   {
      var container = document.getElementById("popUpElements_" + this._popupId);
      var elementId = "";
      var element = null;

      if (typeof container !== "object" || container == null)
      {
         this._Alert("You must create a new dialog before adding elements! ");
         return;
      }

      if (typeof elementType !== "string" || elementType == null)
      {
         this._Alert("Invalid element type!");
         return;
      }

      if (typeof elementData !== "string" || elementData == null)
      {
         this._Alert("Invalid element data!");
         return;
      }

      elementId = "popUpElement_" + this._popupId + "_" + this._RandomIdString(8);

      switch (elementType)
      {
         case "div":
            element = this._CreateElement("div", elementId, "popupElement");
            break;

         case "divWithClass":
            element = this._CreateElement("div", elementId, className);
            break;

         default:
            this._Alert("The specified element type is not valid!");
            return;
      }

      container.appendChild(element);

      _MTS_JQUERY("#" + elementId).html(elementData);

      if (typeof callback === "function" && callback != null)
      {
         callback(_MTS_JQUERY("#popUpElements_" + this._popupId), _MTS_JQUERY("#" + elementId), passThrough);
      }
   },

   AddFooter: /*void*/function (/*string*/elementType, /*string*/elementData, /*optional function*/callback, /*optional obj*/passThrough)
   {
      var container = document.getElementById("popUpFooter_" + this._popupId);
      var elementId = "";
      var element = null;

      if (typeof container !== "object" || container == null)
      {
         this._Alert("You must create a new dialog before adding elements! ");
         return;
      }

      if (typeof elementType !== "string" || elementType == null)
      {
         this._Alert("Invalid element type!");
         return;
      }

      if (typeof elementData !== "string" || elementData == null)
      {
         this._Alert("Invalid element data!");
         return;
      }

      elementId = "popUpFooter_" + this._popupId + "_" + this._RandomIdString(8);

      switch (elementType)
      {
         case "div":
            element = this._CreateElement("div", elementId, "popUpFooter");
            break;

         default:
            this._Alert("The specified element type is not valid!");
            return;
      }

      container.appendChild(element);

      _MTS_JQUERY("#" + elementId).html(elementData);

      if (typeof callback === "function" && callback != null)
      {
         callback(_MTS_JQUERY("#popUpFooter_" + this._popupId), _MTS_JQUERY("#" + elementId), passThrough);
      }
   },

   NewCustomDialog: /*void*/function (/*string*/message, /*string*/title, /*function*/readyCallback, /*function*/closeCallback, /*optional obj*/passThrough)
   {
      var me = this;

      if (!this._IsValidParams(message, title))
      {
         return;
      }

      this.NewDialog();

      _MTS_JQUERY("#popUpHeading_" + this._popupId).html(title);
      _MTS_JQUERY("#popUpDescription_" + this._popupId).html(message);

      this._AddCloser(closeCallback, passThrough, false);

      me._StandardWireups();

      if (typeof readyCallback === "function" && readyCallback != null)
      {
         readyCallback();
      }
   },

   NewOkayAlert: /*void*/function (/*string*/message, /*string*/title, /*optional function*/readyCallback, /*optional function*/callback, /*optional obj*/passThrough, /*optional bool*/showDialog)
   {
      var me = this;
      var okayButton = null;

      if (!this._IsValidParams(message, title))
      {
         return;
      }

      this.NewDialog();

      _MTS_JQUERY("#popUpHeading_" + this._popupId).html(title);
      _MTS_JQUERY("#popUpDescription_" + this._popupId).html(message);

      okayButton = this.AddButton("Okay", function ()
      {
         me.Hide();

         if (typeof callback === "function" && callback != null)
         {
            callback(me, passThrough);
         }
      }, null);

      this._AddCloser(callback, passThrough, true);

      this._StandardWireups();

      if (typeof showDialog !== "boolean" || showDialog == null)
      {
         showDialog = true;
      }

      if (showDialog)
      {
         this.Show();
      }

      if (typeof readyCallback === "function" && readyCallback != null)
      {
         // returns with the container, the description, and okay button jQuery Objects
         readyCallback(_MTS_JQUERY("#popUpContainer_" + this._popupId.toString()), _MTS_JQUERY("#popUpDescription_" + this._popupId), okayButton);
      }
   },

   NewYesNoPrompt: /*void*/function (/*string*/message, /*string*/title, /*optional function*/readyCallback, /*function*/callback, /*optional obj*/passThrough, /*optional bool*/showDialog)
   {
      var me = this;

      if (!this._IsValidParams(message, title))
      {
         return;
      }

      this.NewDialog();

      _MTS_JQUERY("#popUpHeading_" + this._popupId).html(title);
      _MTS_JQUERY("#popUpDescription_" + this._popupId).html(message);

      this.AddButton("Yes", function ()
      {
         me.Hide();

         if (typeof callback === "function" && callback != null)
         {
            callback(true, me, passThrough);
         }
      }, null);

      this.AddButton("No", function ()
      {
         me.Hide();

         if (typeof callback === "function" && callback != null)
         {
            callback(false, me, passThrough);
         }
      }, null);

      this._AddCloser(function ()
      {
         if (typeof callback === "function" && callback != null)
         {
            callback(false, me, passThrough);
         }
      }, null, true);

      me._StandardWireups();

      if (typeof showDialog !== "boolean" || showDialog == null)
      {
         showDialog = true;
      }

      if (showDialog)
      {
         me.Show();
      }

      if (typeof readyCallback === "function" && readyCallback != null)
      {
         readyCallback();
      }
   }
};
﻿var tTimer;
var tRefresh;

$(document).one("widgetsloaded", function ()
{
   $(".myProfile").click(function ()
   {
      window.location = "/user/edit/";
   });

   $("#navReg").click(function () { location = '/user/register/' });
   $("#tRenew").click(function ()
   {
      var status = $("#tStatus");
      status.html("");

      $.post("/api/refreshSession.aspx", null, function (data)
      {
         if (data == "success")
         {
            window.clearTimeout(tRefresh);
            window.clearTimeout(tTimer);

            tRefresh = setTimeout("refreshSession()", _timeout);
            status.html("Success!");
            status.css("color", "green");
            setTimeout(function ()
            {
               $("#timeout").css("display", "none");
            }, 600);
         }
      }).fail(function ()
      {
         status.html("Failed!");
         status.css("color", "red");
      });
   });

   tRefresh = setTimeout("refreshSession()", _timeout);
});

function refreshSession()
{
   $.post("/api/refreshSession.aspx", null, function (data)
   {
      if (data == "success")
         tRefresh = setTimeout("refreshSession()", _timeout);
   }).fail(function ()
   {
      $("#tStatus").html();
      $("#timeout").slideDown('fast');
      startCountdown(_sessionTimeout - _timeout);
   });
}

function startCountdown(/*int*/time)
{
   if (time > 0)
   {
      tTimer = setTimeout(function ()
      {
         $("#tTimer").html(time / 1000);
         startCountdown(time - 1000);
      }, 1000);
   }
   else
      $(".tText").html("Your session has expired and any changes made may not be saved.");
}
﻿_MTS_JQUERY(document).one("widgetsloaded", function ()
{
   var ep = _MTS_JQUERY(".msw");
   if (ep.length > 0)
   {
      var msp = ep.position().top;

      _MTS_JQUERY(window).scroll(function ()
      {
         if (_MTS_JQUERY(window).scrollTop() >= msp)
         {
            ep.addClass('snapIt');
         } else
         {
            ep.removeClass('snapIt');
         }
      });

      var mss = _MTS_JQUERY(".msScroller");
      var msb = _MTS_JQUERY(".msBtn");
      var sum = 0;
      var msgr = _MTS_JQUERY(".msgr");

      msgr.css({ "left": (_MTS_JQUERY(window).width() - 20) + "px" });

      msb.each(function ()
      {
         sum += _MTS_JQUERY(this).outerWidth();
      });

      mss.width(sum + "px");

      $(window).resize(function ()
      {
         mss.width(sum + "px");
      });

      _MTS_JQUERY(".mobileSelectors").scroll(function ()
      {
         if (_MTS_JQUERY(".mobileSelectors").scrollLeft() > (_MTS_JQUERY(".msBtn").outerWidth()))
         {
            var msgl = _MTS_JQUERY(".msgl");
            msgl.show();
         } else
         {
            var msgl = _MTS_JQUERY(".msgl");
            msgl.hide();
         }

         if (_MTS_JQUERY(".mobileSelectors").scrollLeft() + $(".mobileSelectors").outerWidth() == $(".msScroller").outerWidth())
         {
            var msgr = _MTS_JQUERY(".msgr");
            var msgl = _MTS_JQUERY(".msgl");
            msgr.hide();
            msgl.show();
         } else
         {
            var msgr = _MTS_JQUERY(".msgr");
            msgr.show();
         }
      });
   }
});
﻿
function trackItem(itemIdToTrack, itemTagTypeToTrack)
{
   var params = [];
   params.push({ name: "id", value: itemIdToTrack });
   params.push({ name: "tagType", value: itemTagTypeToTrack });
   //params.push({ name: "tagIdList", value: tagIdList });
   ajax("/api/tracking.aspx", params, function () { });
}
﻿
function trackItem(itemIdToTrack, itemTagTypeToTrack)
{
   var params = [];
   params.push({ name: "id", value: itemIdToTrack });
   params.push({ name: "tagType", value: itemTagTypeToTrack });
   //params.push({ name: "tagIdList", value: tagIdList });
   ajax("/api/tracking.aspx", params, function () { });
}
﻿var _loadedCat = [];
var _wiredUp = false;
var _maxResults = 15;
var _currentSeed = 0;
var _currentSearchVal = "";
var _selectedMenu = "";

var _searched = [];
var _searchInProgress = false;
var _curPage = 0;

var _searchedEv = [];
var _searchEvProgress = false;
var _curEvPage = 0;

var _searchId = -1;
var _declinedTags = [];
var _slideTimeout = null;
var _isSliding = false;

function /*void*/initTag()
{
   if (!_hasJQuery || !_hasCal)
      return false;

   if (!_wiredUp)
   {
      wireSelect();

      _cal.initialize();
   }

   //_MTS_JQUERY(".closeTag").click(function ()
   //{
   //   if (typeof window.parent.tinyMCE !== 'undefined')
   //   {
   //      var curWin = window.parent.tinyMCE.activeEditor.windowManager.windows;
   //      var winLength = curWin.length;

   //      curWin[winLength - 1].close();
   //   }
   //});
}

function /*void*/wireSelect()
{
   _wiredUp = true;

   _MTS_JQUERY(document).on("click", ".fullLink", function (ev)
   {
      var parent = _MTS_JQUERY(this).parents(".result");
      if (!parent.hasClass("highlightTag"))
      {
         parent.addClass("highlightTag");
         if (!_isSliding)
         {
            _isSliding = true;
            var tagConfirm = parent.parents(".search_widget").find(".tagConfirmation");
            tagConfirm.slideToggle(400, function ()
            {
               _slideTimeout = null;
               _slideTimeout = setTimeout(function ()
               {
                  tagConfirm.slideToggle();
                  _isSliding = false;
               }, 2000);
            });
         }
      }
   });

   _MTS_JQUERY(document).on(_event, ".tagSelect, .teamTagSelect", function (ev)
   {
      ev.stopPropagation();

      var type = this.id.split('_')[0] + "_";
      var title = _MTS_JQUERY.trim(this.innerHTML);

      var id = GetIdFrom(type, this.id);
      if (id == null)
         return;

      switch (type)
      {
         default:
            break;
         case "entry_":
            selectTag(_MTS_SITEURL + "team/schedule/details/" + _teamId + "/" + _teamUrlName + "/" + id + "/", title, id, "ScheduleEvent");
            break;
         case "team_":
            var par = _MTS_JQUERY(this).parents(".typeSelect");

            if (par.attr("id") == "typeTeam")
               selectTag(_MTS_SITEURL + "teamProfile.aspx?id=" + id, title, id, "Team");
            else
            {
               _searchId = id;

               var prms = [];
               prms.push({ name: "teamId", value: id });

               _MTS_ajaxPending = true;
               _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/getSchoolSportByTeam.aspx", prms, function (o)
               {
                  if (o.ok)
                  {
                     _schoolUrlName = o.schoolUrlName;
                     _sportUrlName = o.sportUrlName;

                     toggleNext(par[0]);
                  }
               });


            }
            break;
         case "Sports_":
            selectTag(_MTS_SITEURL + "?m=1&sm=" + id, title, id, "Sport");
            break;
         case "Schools_":
            selectTag(_MTS_SITEURL + "school/" + id + "/" + $.urlName(title) + "/", title, id, "School");
            break;
         case "Leagues_":
            selectTag(_MTS_SITEURL + "league/" + id + "/" + $.urlName(title) + "/", title, id, "League");
            break;
         case "event_":
            var master = id.split('_')[1];
            id = id.split('_')[0];
            if (master == 1)
               selectTag(_MTS_SITEURL + "master/event/" + id + "/", title, id, "MasterEvent");
            else
               selectTag(_MTS_SITEURL + "event/" + id + "/", title, id, "PortalEvent");
            break;
         case "sch_":
            selectSch(_MTS_JQUERY(this));
            break;
         case "Roster_":
            selectTag(_MTS_SITEURL + "roster/player/" + _schoolUrlName + "-" + _sportUrlName + "/" + $.urlName(title) + "/" + _searchId + "/" + id, title, id, "Roster");
            break;
         case "Videos_":
            selectTag(_MTS_SITEURL + "team/photos/" + _searchId + "/team/", title, id, "Video");
            break;
         case "pv_":
            selectTag(_MTS_SITEURL + "video/player/" + id + "/" + $.urlName(title), title, id, "PortalVideo");
            break;
         case "pl_":
            selectSch(_MTS_JQUERY(this));
            break;
         case "Albums_":
            selectTag(_MTS_SITEURL + "albums/" + $.urlName(title) + "/" + id + "/", title, id, "PhotoAlbum");
            break;
         case "Categories_":
            selectTag("javascript:void(0);", title, id, "Category");
            break;
         case "Subcategories_":
            selectTag("javascript:void(0);", title, id, "Subcategory");
            break;
      }
   });

   _MTS_JQUERY(document).on(_event, ".tagBtn", function (ev)
   {
      ev.stopPropagation();

      toggleBack(this);

   });

   _MTS_JQUERY(document).on(_event, ".typeSelect", function (ev)
   {
      ev.stopPropagation();

      var me = this;
      if (_MTS_JQUERY(me).find(".tTitle").css("display") == "none")
         return;

      _selectedMenu = me.id;
      if (_MTS_JQUERY(me).children(".tTitle").html() != "Existing Photos")
      {
         _MTS_JQUERY(".typeSelect").hide();
         _MTS_JQUERY(me).show();
      }

      if (me.id != "typePhoto")
         toggleNext(me);
      else
         togglePhoto();
   });

   _MTS_JQUERY(document).on("mouseenter mouseleave", ".tagSelect", function ()
   {
      var me = this;

      if (this.clientWidth < this.scrollWidth)
      {
         var eHoverHtml = "<div class='eHover'>" + _MTS_JQUERY.trim(me.innerHTML) + "</div>";
         _MTS_JQUERY(me).parent().append(eHoverHtml);

         _MTS_JQUERY(".eHover").css({ "top": this.offsetTop + 40 + "px", "left": this.offsetLeft + 40 + "px" });
      }
   }).on("mouseout", ".tagSelect", function ()
   {
      _MTS_JQUERY(".eHover").remove();
   });

   _MTS_JQUERY(document).delegate("#searchBar", "keyup", function ()
   {
      performSearch();
   });

   _MTS_JQUERY(document).delegate(".sDateInput, .eDateInput", "click", function ()
   {
      var me = this;
      _MTS_JQUERY(me).val("");

      GetMiniCalendar("select", "Date Range", function (m, d, y)
      {
         _MTS_JQUERY(me).val(m.toString() + "/" + d.toString() + "/" + y.toString());
      });
   });

   _MTS_JQUERY(document).delegate("#searchTeams", "click", function ()
   {
      SearchByTeam(0, _MTS_JQUERY(this).parents(".finalSelectContainer"));
   });

   _MTS_JQUERY(document).delegate(".tNext", "click", function ()
   {
      SearchByTeam(_curPage + 1, _MTS_JQUERY(this).parents(".finalSelectContainer"));
   });

   _MTS_JQUERY(document).delegate(".tPrev", "click", function ()
   {
      if (_curPage > 0)
         SearchByTeam(_curPage - 1, _MTS_JQUERY(this).parents(".finalSelectContainer"));
   });

   _MTS_JQUERY(document).delegate("#searchEvents", "click", function ()
   {
      SearchByEvent(0, _MTS_JQUERY(this).parents(".finalSelectContainer"));
   });

   _MTS_JQUERY(document).delegate("#eNext", "click", function ()
   {
      SearchByEvent(_curEvPage + 1, _MTS_JQUERY(this).parents(".finalSelectContainer"));
   });

   _MTS_JQUERY(document).delegate("#ePrev", "click", function ()
   {
      if (_curEvPage > 0)
         SearchByEvent(_curEvPage - 1, _MTS_JQUERY(this).parents(".finalSelectContainer"));
   });
}

function /*void*/SearchByEvent(/*int*/page, /*dom*/parentObj)
{
   if (_searchEvProgress == false)
   {
      _searchEvProgress = true;
      _curEvPage = page;
      _MTS_JQUERY("#searchActiveEv").show();

      var type = "typeEvent";
      var sport = _MTS_JQUERY("#eventSportFilter").val();
      var level = _MTS_JQUERY("#eventLevelFilter").val();
      var league = _MTS_JQUERY("#eventLeagueFilter").val();
      var phrase = _MTS_JQUERY("#searchBar").val();
      var gender = _MTS_JQUERY("input[name=genderEv]:checked").val();
      var start = _MTS_JQUERY(".sDateInput").val();
      var end = _MTS_JQUERY(".eDateInput").val();
      var homeTeam = _MTS_JQUERY("#homeTeamFilter").val();
      var awayTeam = _MTS_JQUERY("#awayTeamFilter").val();
      var placeType = parentObj.parents(".typeSelect").attr("id");

      var index = FindSearchEv(type, sport, level, league, phrase, gender, start, end, homeTeam, awayTeam, page);
      if (index >= 0)
      {
         CacheSearch(type);

         if (_searchedEv[index].end)
            index = FindSearchEv(type, sport, level, league, phrase, gender, start, end, homeTeam, awayTeam, page - 1);

         if (index >= 0)
         {
            LoadBySearched(index, type, placeType);
            _searchEvProgress = false;
            _MTS_JQUERY("#searchActiveEv").hide();
            return false;
         }
      }

      var prms = [];
      prms.push({ name: "type", value: type });
      prms.push({ name: "sport", value: sport });
      prms.push({ name: "level", value: level });
      prms.push({ name: "league", value: league });
      prms.push({ name: "name", value: phrase });
      prms.push({ name: "gender", value: gender });
      prms.push({ name: "from", value: page > 0 ? page * 15 : 1 });
      prms.push({ name: "to", value: (page * 15) + (page > 0 ? 14 : 15) });
      prms.push({ name: "homeTeam", value: homeTeam });
      prms.push({ name: "awayTeam", value: awayTeam });
      prms.push({ name: "start", value: start });
      prms.push({ name: "end", value: end });

      _MTS_ajaxPending = true;
      _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/getTagSelectCat.aspx", prms, function (o)
      {
         if (o.ok)
         {
            CacheSearch(type);

            var isEnd = false;
            if (o.tagSelect.indexOf("No Results Found") >= 0)
               isEnd = true;

            _MTS_JQUERY("<div id='" + type + "_" + _searchedEv.length + "' class='cache'>" + o.tagSelect + "</div>").insertBefore(_MTS_JQUERY("#" + type)
               .find(".finalSelectContainer .buttonContainer"));

            _searchedEv.push({ "type": type, "sport": sport, "level": level, "league": league, "phrase": phrase,
               "gender": gender, "dtStart": start, "dtEnd": end, "homeTeam": homeTeam, "awayTeam": awayTeam, "page": page, "end": isEnd
            });
         }

         _searchEvProgress = false;
         _MTS_JQUERY("#searchActiveEv").hide();
      });
   }
}

function /*void*/SearchByTeam(/*int*/page, /*dom*/parentObj)
{
   if (_searchInProgress == false)
   {
      _searchInProgress = true;
      _curPage = page;

      var type = "typeTeam",
         placeType = parentObj.parents(".typeSelect").attr("id"),
         title = placeType.substr(4),
         sport = parentObj.find("#sportFilter").val(),
         level = parentObj.find("#levelFilter").val(),
         league = parentObj.find("#leagueFilter").val(),
         phrase = _MTS_JQUERY("#searchBar").val(),
         gender = _MTS_JQUERY("input[name=gender" + title + "]:checked").val();

      _MTS_JQUERY("#searchActive" + title).show();
      var index = FindSearch(type, sport, level, league, phrase, gender, page);
      if (index >= 0)
      {
         CacheSearch(placeType);

         if (_searched[index].end)
            index = FindSearch(type, sport, level, league, phrase, gender, page - 1);

         if (index >= 0)
         {
            LoadBySearched(index, type, placeType);
            _searchInProgress = false;
            _MTS_JQUERY("#searchActive" + title).hide();
            return false;
         }
      }

      var p = [];
      p.push
      (
         { name: "type", value: type },
         { name: "sport", value: sport },
         { name: "level", value: level },
         { name: "league", value: league },
         { name: "name", value: phrase },
         { name: "gender", value: gender },
         { name: "from", value: page > 0 ? page * 15 : 1 },
         { name: "to", value: (page * 15) + (page > 0 ? 14 : 15) }
      );

      _MTS_ajaxPending = true;
      _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/getTagSelectCat.aspx", p, function (o)
      {
         if (o.ok)
         {
            CacheSearch(placeType);

            var isEnd = false;
            if (o.tagSelect == "")
            {
               isEnd = true;

               var idx = FindSearch(type, sport, level, league, phrase, gender, page - 1);
               if (idx >= 0)
                  LoadBySearched(idx, type, placeType);
            }
            else
            {
               _MTS_JQUERY("<div id='" + type + "_" + _searched.length + "' class='cache'>" + o.tagSelect + "</div>").insertBefore(_MTS_JQUERY("#" + placeType)
               .find(".finalSelectContainer .buttonContainer"));

               _MTS_JQUERY(placeType + " .teamConSel").html(_MTS_JQUERY(placeType + " .teamConSel .tContainer").sort(function (a, b)
               {
                  var aVal = _MTS_JQUERY(a).find(".tagSelect").html(); var bVal = _MTS_JQUERY(b).find(".tagSelect").html();
                  return aVal == bVal ? 0 : aVal < bVal ? -1 : 1
               }));
            }

            _searched.push({
               "type": type, "sport": sport, "level": level, "league": league, "phrase": phrase,
               "gender": gender, "page": page, "end": isEnd
            });

            CacheSearch(placeType, true);
         }

         _searchInProgress = false;
         _MTS_JQUERY("#searchActive" + title).hide();
      });
   }
}

function /*int*/FindSearch(type, sport, level, league, phrase, gender, page)
{
   for (var i = _searched.length - 1; i >= 0; i--)
   {
      if (_searched[i].type == type && _searched[i].sport == sport && _searched[i].level == level &&
         _searched[i].league == league && _searched[i].phrase == phrase && _searched[i].gender == gender &&
         _searched[i].page == page)
      {
         return i;
      }
   }

   return -1;
}

function /*int*/FindSearchEv(type, sport, level, league, phrase, gender, start, end, homeTeam, awayTeam, page)
{
   for (var i = _searchedEv.length - 1; i >= 0; i--)
   {
      if (_searchedEv[i].type == type && _searchedEv[i].sport == sport && _searchedEv[i].level == level &&
         _searchedEv[i].league == league && _searchedEv[i].phrase == phrase && _searchedEv[i].gender == gender &&
         _searchedEv[i].dtStart == start && _searchedEv[i].dtEnd == end && _searchedEv[i].homeTeam == homeTeam &&
         _searchedEv[i].awayTeam == awayTeam && _searchedEv[i].page == page)
      {
         return i;
      }
   }

   return -1;
}

function /*void*/LoadBySearched(/*int*/idx, /*string*/type, /*string*/placeType)
{
   _MTS_JQUERY("#cache").find("#" + type + "_" + idx).clone().insertBefore(_MTS_JQUERY("#" + placeType).find(".finalSelectContainer .buttonContainer"));

   if (type != "typeEvent")
      _curPage = _searched[idx].page;
   else
      _curEvPage = _searchedEv[idx].page;
}

function /*void*/CacheSearch(/*string*/type, /*bool*/keepCurrent)
{
   if (keepCurrent == undefined)
      keepCurrent = false;

   var cache = _MTS_JQUERY("#cache");
   if (cache.length == 0)
   {
      _MTS_JQUERY("body").append("<div id='cache' style='display: none'></div>");
      cache = _MTS_JQUERY("#cache");
   }

   var target = _MTS_JQUERY("#" + type).find(".cache"),
      id = target.length > 0 ? target.attr("id") : -1;

   if (target.length > 0)
   {
      for (var i = 0, j = cache.children().length; i < j; i++)
      {
         if (cache.children()[i].id == id)
         {
            if (!keepCurrent)
               target.remove();
            return false;
         }
      }

      if (!keepCurrent)
         target.appendTo(cache);
      else
         target.clone().appendTo(cache);
   }
}

function /*void*/performSearch()
{
   // Prevent several searches within x
   var currentSeed = Date.now;
   _currentSeed = currentSeed;

   setTimeout(function ()
   {
      if (currentSeed != _currentSeed)
         return false;

      var searchTxt = _MTS_JQUERY("#searchBar").val();
      var tagContainer;

      // Find current container to search within
      var sCon = _MTS_JQUERY(".finalSelectContainer");
      sCon.each(function ()
      {
         var me = _MTS_JQUERY(this);

         if (me.css("display") != "none")
         {
            tagContainer = me.find(".tagSelect");
            return false;
         }
      });

      if (tagContainer == null || tagContainer.length == 0)
         return false;

      var pClass = _MTS_JQUERY(tagContainer[0]).parent().attr("class");
      if (pClass == "tContainer" || pClass == "eventContainer")
         return false;

      var tagLength = tagContainer.length - 1;
      tagContainer.css("display", "none");

      do
      {
         var curTag = tagContainer[tagLength];
         var checkFilter = _MTS_JQUERY.trim(curTag.innerHTML.toLowerCase());

         if (searchTxt == "" || checkFilter.indexOf(searchTxt.toLowerCase()) >= 0)
            curTag.style.display = "block";
      }
      while (tagLength--)
   }, 200);
}

function /*void*/togglePhoto()
{
   window.parent.tinyMCE.activeEditor.windowManager.open({
      file: '/mce/imageSel.aspx?id=' + _teamId,
      width: 450,
      height: 300,
      inline: 1
   }, {
      plugin_url: '/'
   });
}

function /*void*/toggleNext(/*obj*/me)
{
   var found = false,
      teamSelect = ((me.id == "typeRoster" || me.id == "typePlayer" || me.id == "typeVideos") && _searchId > 0),
      teamSearch = me.id + "_" + _searchId;

   for (var i = _loadedCat.length - 1; i >= 0; i--)
   {
      if (_loadedCat[i] == me.id && !teamSelect || (teamSelect && _loadedCat[i] == teamSearch))
      {
         found = true;
         break;
      }
   }

   if (!found && me.id != "typeSch" && me.id != "typeTeam" && me.id != "typeEvent" && ((!teamSelect && me.id != "typeRoster" && me.id != "typePlayer" && me.id != "typeVideos" || teamSelect)))
   {
      _loadedCat.push(teamSelect ? teamSearch : me.id);

      var prms = [];
      prms.push({ name: "type", value: me.id });
      prms.push({ name: "isPortal", value: _isPortalTag });
      prms.push({ name: "searchId", value: _searchId });

      _MTS_ajaxPending = true;
      _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/getTagSelectCat.aspx", prms, function (o)
      {
         if (o.ok)
         {
            if (teamSelect)
            {
               o.tagSelect = "<div id='" + teamSearch + "' class='searched'>" + o.tagSelect + "</div>";
               TargetByTeam(me);
            }

            _MTS_JQUERY(o.tagSelect).insertBefore(_MTS_JQUERY(me).find(".finalSelectContainer .buttonContainer"));

            if (!teamSelect)
               NextAction(me);
         }
      });
   }
   else if (teamSelect)
   {
      TargetByTeam(me);
      _MTS_JQUERY("#" + teamSearch).show();
   }
   else
      NextAction(me);
}

function /*void*/TargetByTeam(/*obj*/me)
{
   var sb = _MTS_JQUERY("#searchBar");

   if (sb.val().length > 0)
   {
      sb.val("");
      performSearch("");
   }

   _MTS_JQUERY("#sBarTitle").html("Type name of " + (me.id == "typeRoster" || me.id == "typePlayer" ? "player" : "video") + " to narrow results:");
   _MTS_JQUERY(me).find(".filterOptions, .tNext, .tPrev, .cache, .searched").hide();
}

function /*void*/NextAction(/*obj*/me)
{
   var firstSelect = _MTS_JQUERY(me).find(".firstSelectContainer"),
      fSelect = _MTS_JQUERY(me).find(".finalSelectContainer"),
      tagTitle = _MTS_JQUERY(".tTitle"),
      searchBar = _MTS_JQUERY(".sBar"),
      sbTitle = _MTS_JQUERY("#sBarTitle");

   _MTS_JQUERY("#selCat").hide();

   if (me.id != "typeEvent" && me.id != "typeSch")
      searchBar.show();

   switch (me.id)
   {
      case "typePortalVideos":
      case "typePlayer":
      case "typeRoster":
      case "typeVideos":
      case "typeTeam":
         sbTitle.html("Enter team name to narrow search:");
         break;
      case "typeSports":
         sbTitle.html("Type name of sport to narrow results:");
         break;
      case "typeLeagues":
         sbTitle.html("Type name of league to narrow results:");
         break;
      case "typeSchools":
         sbTitle.html("Type name of school to narrow results:");
         break;
      case "typeCategories":
         sbTitle.html("Type name of the category/subcategory to narrow results:");
         break;
      default:
         break;
   }

   if (tagTitle.css("display") != "none" && firstSelect.length > 0)
      firstSelect.show();
   else
   {
      firstSelect.hide();
      fSelect.show();
      fSelect.children().show();
   }

   ToggleCustomDropdowns();

   tagTitle.hide();

   _MTS_JQUERY(me).find(".buttonContainer")[0].style.display = "block";

   performSearch(_MTS_JQUERY("#searchBar").val());

   _MTS_JQUERY(".searched").hide();

   switch (me.id)
   {
      case "typeRoster":
      case "typeVideos":
         var tags = getTagsByType("Team"),
            previousTags = $("#typeTeam_-1");

         previousTags.remove();
         CacheSearch(me.id);

         if (tags.length > 0)
         {
            var html = "<div id='typeTeam_-1' class='cache'>";
            for (var i = tags.length - 1; i >= 0; i--)
            {
               html +=
               "<div class='tContainer'>" +
                  "<div id='team_" + tags[i].id.split('_')[2] + "' class='teamTagSelect'>" + $.trim(_MTS_JQUERY(tags[i]).find(".tagTitle").html()) + "</div>" +
               "</div>";
            }

            html += "</div>";

            $(html).insertBefore(_MTS_JQUERY("#" + me.id).find(".finalSelectContainer .buttonContainer"));
         }
         break;
      default:
         break;
   }
}

function /*void*/toggleBack(/*obj*/me)
{
   _MTS_JQUERY(".sBar").hide();
   _MTS_JQUERY(".searched").hide();
   _MTS_JQUERY(".tPrev, .tNext").show();
   _MTS_JQUERY("#searchBar").val("");
   var dblParent = _MTS_JQUERY(me).parent().parent();

   var isShown = dblParent.filter(":visible").length > 0;

   dblParent.hide();

   if (dblParent.attr("class") == "firstSelectContainer" || dblParent.parent().parent().find(".firstSelectContainer").length == 0 || !isShown)
   {
      _MTS_JQUERY(".tTitle").show();
      _MTS_JQUERY("#selCat").show();
   }
   else
   {
      _MTS_JQUERY(".sBar").show();
      dblParent.parent().parent().find(".firstSelectContainer").show();
   }

   _MTS_JQUERY(".typeSelect").hide();
   _MTS_JQUERY("#" + _selectedMenu).show();
   _MTS_JQUERY(".tTitle").each(function ()
   {
      if (_MTS_JQUERY(this).css("display") !== "none")
      {
         _MTS_JQUERY(this).parent().show();
      }
   });

   _searchId = -1;
}

function /*void*/selectSch(/*obj*/me)
{
   me.parent().parent().find(".scheduleContainer").each(function ()
   {
      if (this.id.split('_')[1] == me.attr("id").split('_')[1])
         this.style.display = "block";
      else
         this.style.display = "none";
   });

   me.parent().hide();
   me.parent().parent().find(".finalSelectContainer").show();
   me.parent().parent().find(".buttonContainer")[1].style.display = "block";
}

function findTag(linkType, id)
{
   var winPar = window.parent,
      tagChildren = _MTS_JQUERY(winPar.document.getElementsByClassName("tagContainer")[0]).find(".tagBlock, .imageTag");

   for (var i = 0; i < tagChildren.length; i++)
   {
      var curTag = tagChildren[i], firstId = curTag.id.split('_')[1];
      if (curTag.id != null && curTag.id.split('_')[0] == "tag" && firstId == linkType && curTag.id.split('_')[2] == id)
      {
         return true;
      }
      else if (firstId == id) // Used on portalVideoFinalize.aspx
      {
         curTag = _MTS_JQUERY(curTag);
         if (curTag.children("input")[0].value == linkType)
            return true;
      }
   }

   if (typeof _currentImage != 'undefined' && typeof _currentImage != 'object')
   {
      for (var i = 0; i < _currentImage.links.length; i++)
      {
         if (_currentImage.links[i].linkId == id && _currentImage.links[i].tagType == linkType)
            return true;
      }
   }

   return false;
}

function getTagsByType(linkType)
{
   var winPar = window.parent,
      tagChildren = _MTS_JQUERY(winPar.document.getElementsByClassName("tagContainer")[0]).find(".tagBlock, .imageTag"),
      tags = [];

   for (var i = 0; i < tagChildren.length; i++)
   {
      var curTag = tagChildren[i], firstId = curTag.id.split('_')[1];
      if (curTag.id != null && curTag.id.split('_')[0] == "tag" && firstId == linkType)
      {
         tags.push(curTag);
      }
   }

   if (typeof _currentImage != 'undefined' && typeof _currentImage != 'object')
   {
      for (var i = 0; i < _currentImage.links.length; i++)
      {
         if (_currentImage.links[i].tagType == linkType)
            tags.push(_currentImage.links[i]);
      }
   }

   return tags;
}

function /*void*/selectTag(/*string*/hyperLink, /*string*/title, /*string*/id, /*string*/linkType)
{
   var winPar = window.parent,
      tagContainer = winPar.document.getElementsByClassName("tagContainer")[0],
      linkHtml = "<a href=\"" + hyperLink + "\" data-mce-href=\"" + hyperLink + "\">" + unescape(title) + "</a>";

   if (_MTS_JQUERY(tagContainer).length > 0)
   {
      if (!findTag(linkType, id))
      {
         var tagHtml =
         (tagContainer.childNodes.length < 1 ? "<div class='portalText'>Current Tags</div>" : "") +
         "<div class='tagBlock' id='tag_" + id + "'>" +
            "<div class='tagTitle'>" + unescape(title) + "</div>" +
            "<div class='tagOptions'>" +
               "<div class='mts_cc_button tagButton' id='tagAdd_" + id + "'>Add Link</div>" +
               "<img class='tagButton' id='tagRem_" + id + "' src='" + _mediaUrl + "images/gratsClose.png' title='remove' />" +
            "</div>" +
            "<input type='hidden' id='linkType_" + id + "' value='" + linkType + "' />" +
         "</div>";

         _MTS_JQUERY(tagContainer).append(tagHtml);
         winPar.WireUpTag(id, linkHtml, linkType);

         _MTS_JQUERY(winPar.document.getElementsByClassName("noTagsYet")).hide();

         if (_MTS_JQUERY(winPar.document.getElementById("useAutoTagger")).length < 0 || !_MTS_JQUERY(winPar.document.getElementById("useAutoTagger")).prop("checked"))
         {
            if ((typeof _DoNotSuggestRelated === 'undefined') || !_DoNotSuggestRelated)
               FindRelatedTag(id, linkType);
         }
      }
   }
   else if (typeof (winPar.AddTagHtml) === "function")
   {
      winPar.AddTagHtml(id, title, linkHtml, linkType);
   }

   if (winPar.tinymce != null && (typeof winPar._autoLink !== "boolean" || winPar._autoLink))
   {
      if (linkType != "Image")
      {
         var contentLink = linkType == "PortalVideo" ? "<iframe src='/api/getPortalVideoPlayer.aspx?videoId=" + id + "' frameborder='0' allowFullScreen='true' webkitallowfullscreen='true' mozallowfullscreen='true' width='100%' height='450px' scrolling='no'></iframe>" : linkHtml;
         winPar.tinymce.execCommand('mceInsertContent', false, contentLink);
      }
      else
      {
         var imageHtml = "<img src=\"" + hyperLink + "\" alt=\"[Image]\" />";
         winPar.insertPhotoCaptionTable(id, imageHtml);
      }
   }
}

function FindRelatedTag(id, type)
{
   var p = [];
   p.push({ name: "id", value: id });
   p.push({ name: "type", value: type });

   ajax("/api/getRelatedTags.aspx", p, function (ret)
   {
      var o;
      eval("o = " + ret);
      if (o.tags.length > 0)
         SuggestTags(o.tags);
   });
}

function SuggestTags(tags)
{
   var tagHtml = "";
   for (var i = tags.length - 1; i >= 0; i--)
   {
      if (!findTag(tags[i].type, tags[i].id) && !isDeclinedTag(tags[i]))
      {
         var p = confirm("Would you like to add " + tags[i].title + " (" + tags[i].type + ") as a tag to this story?")
         {
            if (p != null && p)
               selectTag(tags[i].link, tags[i].title, tags[i].id, tags[i].type);
            else
               _declinedTags.push(tags[i]);
         }
      }
   }
}

function isDeclinedTag(tag)
{
   for (var i = _declinedTags.length - 1; i >= 0; i--)
   {
      if (tag.id == _declinedTags[i].id && tag.type == _declinedTags[i].type)
         return true;
   }

   return false;
}

function /*void*/GetMiniCalendar(/*string*/mode, /*string*/title, /*function*/callback, /*optional*/multiSelected)
{
   var eventYear = -1;
   var eventMonth = -1;
   var eventDay = -1;

   var dte = new Date();

   _cal.clearRecycle();
   _cal.mode = mode;
   _cal.wndTitle = title;
   _cal.setContract(dte.getFullYear() - 1, 0, 0);
   _cal.maxYear = (_cal.startContractYear + 5);
   _cal.setCallback(callback);

   _cal.setSelection(dte.getMonth() + 1, dte.getDate(), dte.getFullYear());
   _cal.show(100, 100);

   _MTS_JQUERY(".listingBg").css({ "height": _MTS_JQUERY(document).height(), "zIndex": 113 });
   _MTS_JQUERY(".listingBg").show();
}

function /*string*/GetIdFrom(/*string*/prefix, /*string*/mangledId)
{
   if (typeof prefix !== "string" || prefix == null)
      return null;

   if (typeof mangledId !== "string" || mangledId == null)
      return null;

   if (prefix.length >= mangledId.length)
      return null;

   var id = null;
   try
   {
      id = mangledId.substring(prefix.length);
   }
   catch (e)
   {
      return null;
   }

   return id;
}

﻿// Ajax
//

var _TIMING_ = 10000;
var _ajax_map = [];
function ajax(url, params, callback, method, next, random, ignoreAjaxMap)
{
   if (method == null)
      method = "POST";

   if (ignoreAjaxMap !== true)
      ignoreAjaxMap = false;

   // For IE8 and earlier version.
   if (!Date.now)
   {
      Date.now = function ()
      {
         return new Date().valueOf();
      }
   }

   if (typeof (_ajax_map) === "undefined")
      _ajax_map = [];

   if (!ignoreAjaxMap)
   {
      var ts = Date.now();
      for (var i = 0; i < _ajax_map.length; i++)
      {
         if (_ajax_map[i].Url == url)
         {
            var dt = Date.now() - _ajax_map[i].Time;
            if (dt < _TIMING_)
               return;
         }
      }
   }

   _ajax_map.push(new ajaxMapEntry(url, ts)); // ignoreAjaxMap is per call, so we need to keep this

   var http = createAjax();
   http.onreadystatechange = function ()
   {
      if (http.readyState != 4 || http.status != 200)
         return;

      var si = -1;
      for (var i = 0; i < _ajax_map.length; i++)
      {
         if (_ajax_map[i].Url == url)
         {
            si = i;
            break;
         }
      }

      if (si > -1)
         _ajax_map.splice(si, 1);

      if (typeof callback === "function" && callback != null)
         callback(http.responseText);

      if (next != null && next != 'undefined')
      {
         if (typeof next !== "function")
         {
            console.log("An error occurred calling next().\nUrl: " + url + "\ndata: " + data);
         }
         else
         {
            next();
         }
      }
   };

   if ((typeof (event) !== "undefined" && event.which) || (typeof (_MTS_ajaxPending) === "boolean" && _MTS_ajaxPending))
   {
      http.onloadstart = function ()
      {
         MTS_startAjax();
      };

      http.onloadend = function ()
      {
         MTS_endAjax();
         _MTS_ajaxPending = false;
      }
   };

   var qs = "ajax=1";
   for (i = 0; i < params.length; i++)
   {
      qs += "&" + params[i].name + "=" + encodeURIComponent(params[i].value);
   }

   if (method == "GET")
   {
      http.open("GET", url + "?" + qs, true);
   }
   else
   {
      http.open("POST", url + (random != undefined && !random ? "" : "?" + Date.now() + "=r"), true);
      http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   }

   http.send(qs);
   return http;
}

function createAjax()
{
   var x = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
   if (x == null)
   {
      alert("Your browser does not support the functionality to complete this request.");
      return;
   }

   return x;
}

function ajaxMapEntry(url, ts)
{
   this.Url = url;
   this.Time = ts;
}
﻿/*! jQuery UI - v1.12.1 - 2021-08-03
* http://jqueryui.com
* Includes: widget.js, data.js, disable-selection.js, keycode.js, scroll-parent.js, widgets/draggable.js, widgets/resizable.js, widgets/sortable.js, widgets/mouse.js, widgets/slider.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */

(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define([ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

$.ui = $.ui || {};

var version = $.ui.version = "1.12.1";


/*!
 * jQuery UI Widget 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: http://api.jqueryui.com/jQuery.widget/
//>>demos: http://jqueryui.com/widget/



var widgetUuid = 0;
var widgetSlice = Array.prototype.slice;

$.cleanData = ( function( orig ) {
	return function( elems ) {
		var events, elem, i;
		for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
			try {

				// Only trigger remove when necessary to save time
				events = $._data( elem, "events" );
				if ( events && events.remove ) {
					$( elem ).triggerHandler( "remove" );
				}

			// Http://bugs.jquery.com/ticket/8235
			} catch ( e ) {}
		}
		orig( elems );
	};
} )( $.cleanData );

$.widget = function( name, base, prototype ) {
	var existingConstructor, constructor, basePrototype;

	// ProxiedPrototype allows the provided prototype to remain unmodified
	// so that it can be used as a mixin for multiple widgets (#8876)
	var proxiedPrototype = {};

	var namespace = name.split( "." )[ 0 ];
	name = name.split( "." )[ 1 ];
	var fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	if ( $.isArray( prototype ) ) {
		prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
	}

	// Create selector for plugin
	$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {

		// Allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// Allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	// Extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,

		// Copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),

		// Track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	} );

	basePrototype = new base();

	// We need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( !$.isFunction( value ) ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = ( function() {
			function _super() {
				return base.prototype[ prop ].apply( this, arguments );
			}

			function _superApply( args ) {
				return base.prototype[ prop ].apply( this, args );
			}

			return function() {
				var __super = this._super;
				var __superApply = this._superApply;
				var returnValue;

				this._super = _super;
				this._superApply = _superApply;

				returnValue = value.apply( this, arguments );

				this._super = __super;
				this._superApply = __superApply;

				return returnValue;
			};
		} )();
	} );
	constructor.prototype = $.widget.extend( basePrototype, {

		// TODO: remove support for widgetEventPrefix
		// always use the name + a colon as the prefix, e.g., draggable:start
		// don't prefix for widgets that aren't DOM-based
		widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name
	}, proxiedPrototype, {
		constructor: constructor,
		namespace: namespace,
		widgetName: name,
		widgetFullName: fullName
	} );

	// If this widget is being redefined then we need to find all widgets that
	// are inheriting from it and redefine all of them so that they inherit from
	// the new version of this widget. We're essentially trying to replace one
	// level in the prototype chain.
	if ( existingConstructor ) {
		$.each( existingConstructor._childConstructors, function( i, child ) {
			var childPrototype = child.prototype;

			// Redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
				child._proto );
		} );

		// Remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );

	return constructor;
};

$.widget.extend = function( target ) {
	var input = widgetSlice.call( arguments, 1 );
	var inputIndex = 0;
	var inputLength = input.length;
	var key;
	var value;

	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {

				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :

						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );

				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string";
		var args = widgetSlice.call( arguments, 1 );
		var returnValue = this;

		if ( isMethodCall ) {

			// If this is an empty collection, we need to have the instance method
			// return undefined instead of the jQuery instance
			if ( !this.length && options === "instance" ) {
				returnValue = undefined;
			} else {
				this.each( function() {
					var methodValue;
					var instance = $.data( this, fullName );

					if ( options === "instance" ) {
						returnValue = instance;
						return false;
					}

					if ( !instance ) {
						return $.error( "cannot call methods on " + name +
							" prior to initialization; " +
							"attempted to call method '" + options + "'" );
					}

					if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) {
						return $.error( "no such method '" + options + "' for " + name +
							" widget instance" );
					}

					methodValue = instance[ options ].apply( instance, args );

					if ( methodValue !== instance && methodValue !== undefined ) {
						returnValue = methodValue && methodValue.jquery ?
							returnValue.pushStack( methodValue.get() ) :
							methodValue;
						return false;
					}
				} );
			}
		} else {

			// Allow multiple hashes to be passed on init
			if ( args.length ) {
				options = $.widget.extend.apply( null, [ options ].concat( args ) );
			}

			this.each( function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} );
					if ( instance._init ) {
						instance._init();
					}
				} else {
					$.data( this, fullName, new object( options, this ) );
				}
			} );
		}

		return returnValue;
	};
};

$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	defaultElement: "<div>",

	options: {
		classes: {},
		disabled: false,

		// Callbacks
		create: null
	},

	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = widgetUuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();
		this.classesElementLookup = {};

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			} );
			this.document = $( element.style ?

				// Element within the document
				element.ownerDocument :

				// Element is window or document
				element.document || element );
			this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
		}

		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this._create();

		if ( this.options.disabled ) {
			this._setOptionDisabled( this.options.disabled );
		}

		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},

	_getCreateOptions: function() {
		return {};
	},

	_getCreateEventData: $.noop,

	_create: $.noop,

	_init: $.noop,

	destroy: function() {
		var that = this;

		this._destroy();
		$.each( this.classesElementLookup, function( key, value ) {
			that._removeClass( value, key );
		} );

		// We can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.off( this.eventNamespace )
			.removeData( this.widgetFullName );
		this.widget()
			.off( this.eventNamespace )
			.removeAttr( "aria-disabled" );

		// Clean up events and states
		this.bindings.off( this.eventNamespace );
	},

	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;
		var parts;
		var curOption;
		var i;

		if ( arguments.length === 0 ) {

			// Don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {

			// Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i < parts.length - 1; i++ ) {
					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
					curOption = curOption[ parts[ i ] ];
				}
				key = parts.pop();
				if ( arguments.length === 1 ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( arguments.length === 1 ) {
					return this.options[ key ] === undefined ? null : this.options[ key ];
				}
				options[ key ] = value;
			}
		}

		this._setOptions( options );

		return this;
	},

	_setOptions: function( options ) {
		var key;

		for ( key in options ) {
			this._setOption( key, options[ key ] );
		}

		return this;
	},

	_setOption: function( key, value ) {
		if ( key === "classes" ) {
			this._setOptionClasses( value );
		}

		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this._setOptionDisabled( value );
		}

		return this;
	},

	_setOptionClasses: function( value ) {
		var classKey, elements, currentElements;

		for ( classKey in value ) {
			currentElements = this.classesElementLookup[ classKey ];
			if ( value[ classKey ] === this.options.classes[ classKey ] ||
					!currentElements ||
					!currentElements.length ) {
				continue;
			}

			// We are doing this to create a new jQuery object because the _removeClass() call
			// on the next line is going to destroy the reference to the current elements being
			// tracked. We need to save a copy of this collection so that we can add the new classes
			// below.
			elements = $( currentElements.get() );
			this._removeClass( currentElements, classKey );

			// We don't use _addClass() here, because that uses this.options.classes
			// for generating the string of classes. We want to use the value passed in from
			// _setOption(), this is the new value of the classes option which was passed to
			// _setOption(). We pass this value directly to _classes().
			elements.addClass( this._classes( {
				element: elements,
				keys: classKey,
				classes: value,
				add: true
			} ) );
		}
	},

	_setOptionDisabled: function( value ) {
		this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );

		// If the widget is becoming disabled, then nothing is interactive
		if ( value ) {
			this._removeClass( this.hoverable, null, "ui-state-hover" );
			this._removeClass( this.focusable, null, "ui-state-focus" );
		}
	},

	enable: function() {
		return this._setOptions( { disabled: false } );
	},

	disable: function() {
		return this._setOptions( { disabled: true } );
	},

	_classes: function( options ) {
		var full = [];
		var that = this;

		options = $.extend( {
			element: this.element,
			classes: this.options.classes || {}
		}, options );

		function processClassString( classes, checkOption ) {
			var current, i;
			for ( i = 0; i < classes.length; i++ ) {
				current = that.classesElementLookup[ classes[ i ] ] || $();
				if ( options.add ) {
					current = $( $.unique( current.get().concat( options.element.get() ) ) );
				} else {
					current = $( current.not( options.element ).get() );
				}
				that.classesElementLookup[ classes[ i ] ] = current;
				full.push( classes[ i ] );
				if ( checkOption && options.classes[ classes[ i ] ] ) {
					full.push( options.classes[ classes[ i ] ] );
				}
			}
		}

		this._on( options.element, {
			"remove": "_untrackClassesElement"
		} );

		if ( options.keys ) {
			processClassString( options.keys.match( /\S+/g ) || [], true );
		}
		if ( options.extra ) {
			processClassString( options.extra.match( /\S+/g ) || [] );
		}

		return full.join( " " );
	},

	_untrackClassesElement: function( event ) {
		var that = this;
		$.each( that.classesElementLookup, function( key, value ) {
			if ( $.inArray( event.target, value ) !== -1 ) {
				that.classesElementLookup[ key ] = $( value.not( event.target ).get() );
			}
		} );
	},

	_removeClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, false );
	},

	_addClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, true );
	},

	_toggleClass: function( element, keys, extra, add ) {
		add = ( typeof add === "boolean" ) ? add : extra;
		var shift = ( typeof element === "string" || element === null ),
			options = {
				extra: shift ? keys : extra,
				keys: shift ? element : keys,
				element: shift ? this.element : element,
				add: add
			};
		options.element.toggleClass( this._classes( options ), add );
		return this;
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement;
		var instance = this;

		// No suppressDisabledCheck flag, shuffle arguments
		if ( typeof suppressDisabledCheck !== "boolean" ) {
			handlers = element;
			element = suppressDisabledCheck;
			suppressDisabledCheck = false;
		}

		// No element argument, shuffle and use this.element
		if ( !handlers ) {
			handlers = element;
			element = this.element;
			delegateElement = this.widget();
		} else {
			element = delegateElement = $( element );
			this.bindings = this.bindings.add( element );
		}

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {

				// Allow widgets to customize the disabled handling
				// - disabled as an array instead of boolean
				// - disabled class as method for disabling individual parts
				if ( !suppressDisabledCheck &&
						( instance.options.disabled === true ||
						$( this ).hasClass( "ui-state-disabled" ) ) ) {
					return;
				}
				return ( typeof handler === "string" ? instance[ handler ] : handler )
					.apply( instance, arguments );
			}

			// Copy the guid so direct unbinding works
			if ( typeof handler !== "string" ) {
				handlerProxy.guid = handler.guid =
					handler.guid || handlerProxy.guid || $.guid++;
			}

			var match = event.match( /^([\w:-]*)\s*(.*)$/ );
			var eventName = match[ 1 ] + instance.eventNamespace;
			var selector = match[ 2 ];

			if ( selector ) {
				delegateElement.on( eventName, selector, handlerProxy );
			} else {
				element.on( eventName, handlerProxy );
			}
		} );
	},

	_off: function( element, eventName ) {
		eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) +
			this.eventNamespace;
		element.off( eventName ).off( eventName );

		// Clear the stack to avoid memory leaks (#10056)
		this.bindings = $( this.bindings.not( element ).get() );
		this.focusable = $( this.focusable.not( element ).get() );
		this.hoverable = $( this.hoverable.not( element ).get() );
	},

	_delay: function( handler, delay ) {
		function handlerProxy() {
			return ( typeof handler === "string" ? instance[ handler ] : handler )
				.apply( instance, arguments );
		}
		var instance = this;
		return setTimeout( handlerProxy, delay || 0 );
	},

	_hoverable: function( element ) {
		this.hoverable = this.hoverable.add( element );
		this._on( element, {
			mouseenter: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-hover" );
			},
			mouseleave: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-hover" );
			}
		} );
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-focus" );
			},
			focusout: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-focus" );
			}
		} );
	},

	_trigger: function( type, event, data ) {
		var prop, orig;
		var callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();

		// The original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// Copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( $.isFunction( callback ) &&
			callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}

		var hasOptions;
		var effectName = !options ?
			method :
			options === true || typeof options === "number" ?
				defaultEffect :
				options.effect || defaultEffect;

		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		}

		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;

		if ( options.delay ) {
			element.delay( options.delay );
		}

		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue( function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			} );
		}
	};
} );

var widget = $.widget;


/*!
 * jQuery UI :data 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :data Selector
//>>group: Core
//>>description: Selects elements which have data stored under the specified key.
//>>docs: http://api.jqueryui.com/data-selector/


var data = $.extend( $.expr[ ":" ], {
	data: $.expr.createPseudo ?
		$.expr.createPseudo( function( dataName ) {
			return function( elem ) {
				return !!$.data( elem, dataName );
			};
		} ) :

		// Support: jQuery <1.8
		function( elem, i, match ) {
			return !!$.data( elem, match[ 3 ] );
		}
} );

/*!
 * jQuery UI Disable Selection 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: disableSelection
//>>group: Core
//>>description: Disable selection of text content within the set of matched elements.
//>>docs: http://api.jqueryui.com/disableSelection/

// This file is deprecated


var disableSelection = $.fn.extend( {
	disableSelection: ( function() {
		var eventType = "onselectstart" in document.createElement( "div" ) ?
			"selectstart" :
			"mousedown";

		return function() {
			return this.on( eventType + ".ui-disableSelection", function( event ) {
				event.preventDefault();
			} );
		};
	} )(),

	enableSelection: function() {
		return this.off( ".ui-disableSelection" );
	}
} );


/*!
 * jQuery UI Keycode 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/


var keycode = $.ui.keyCode = {
	BACKSPACE: 8,
	COMMA: 188,
	DELETE: 46,
	DOWN: 40,
	END: 35,
	ENTER: 13,
	ESCAPE: 27,
	HOME: 36,
	LEFT: 37,
	PAGE_DOWN: 34,
	PAGE_UP: 33,
	PERIOD: 190,
	RIGHT: 39,
	SPACE: 32,
	TAB: 9,
	UP: 38
};


/*!
 * jQuery UI Scroll Parent 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: scrollParent
//>>group: Core
//>>description: Get the closest ancestor element that is scrollable.
//>>docs: http://api.jqueryui.com/scrollParent/



var scrollParent = $.fn.scrollParent = function( includeHidden ) {
	var position = this.css( "position" ),
		excludeStaticParent = position === "absolute",
		overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
		scrollParent = this.parents().filter( function() {
			var parent = $( this );
			if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
				return false;
			}
			return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) +
				parent.css( "overflow-x" ) );
		} ).eq( 0 );

	return position === "fixed" || !scrollParent.length ?
		$( this[ 0 ].ownerDocument || document ) :
		scrollParent;
};




// This file is deprecated
var ie = $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );

/*!
 * jQuery UI Mouse 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Mouse
//>>group: Widgets
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: http://api.jqueryui.com/mouse/



var mouseHandled = false;
$( document ).on( "mouseup", function() {
	mouseHandled = false;
} );

var widgetsMouse = $.widget( "ui.mouse", {
	version: "1.12.1",
	options: {
		cancel: "input, textarea, button, select, option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.on( "mousedown." + this.widgetName, function( event ) {
				return that._mouseDown( event );
			} )
			.on( "click." + this.widgetName, function( event ) {
				if ( true === $.data( event.target, that.widgetName + ".preventClickEvent" ) ) {
					$.removeData( event.target, that.widgetName + ".preventClickEvent" );
					event.stopImmediatePropagation();
					return false;
				}
			} );

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.off( "." + this.widgetName );
		if ( this._mouseMoveDelegate ) {
			this.document
				.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
				.off( "mouseup." + this.widgetName, this._mouseUpDelegate );
		}
	},

	_mouseDown: function( event ) {

		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// We may have missed mouseup (out of window)
		( this._mouseStarted && this._mouseUp( event ) );

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = ( event.which === 1 ),

			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = ( typeof this.options.cancel === "string" && event.target.nodeName ?
				$( event.target ).closest( this.options.cancel ).length : false );
		if ( !btnIsLeft || elIsCancel || !this._mouseCapture( event ) ) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if ( !this.mouseDelayMet ) {
			this._mouseDelayTimer = setTimeout( function() {
				that.mouseDelayMet = true;
			}, this.options.delay );
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted = ( this._mouseStart( event ) !== false );
			if ( !this._mouseStarted ) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if ( true === $.data( event.target, this.widgetName + ".preventClickEvent" ) ) {
			$.removeData( event.target, this.widgetName + ".preventClickEvent" );
		}

		// These delegates are required to keep context
		this._mouseMoveDelegate = function( event ) {
			return that._mouseMove( event );
		};
		this._mouseUpDelegate = function( event ) {
			return that._mouseUp( event );
		};

		this.document
			.on( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.on( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function( event ) {

		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {

			// IE mouseup check - mouseup happened when mouse was out of window
			if ( $.ui.ie && ( !document.documentMode || document.documentMode < 9 ) &&
					!event.button ) {
				return this._mouseUp( event );

			// Iframe mouseup check - mouseup occurred in another document
			} else if ( !event.which ) {

				// Support: Safari <=8 - 9
				// Safari sets which to 0 if you press any of the following keys
				// during a drag (#14461)
				if ( event.originalEvent.altKey || event.originalEvent.ctrlKey ||
						event.originalEvent.metaKey || event.originalEvent.shiftKey ) {
					this.ignoreMissingWhich = true;
				} else if ( !this.ignoreMissingWhich ) {
					return this._mouseUp( event );
				}
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if ( this._mouseStarted ) {
			this._mouseDrag( event );
			return event.preventDefault();
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted =
				( this._mouseStart( this._mouseDownEvent, event ) !== false );
			( this._mouseStarted ? this._mouseDrag( event ) : this._mouseUp( event ) );
		}

		return !this._mouseStarted;
	},

	_mouseUp: function( event ) {
		this.document
			.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.off( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if ( this._mouseStarted ) {
			this._mouseStarted = false;

			if ( event.target === this._mouseDownEvent.target ) {
				$.data( event.target, this.widgetName + ".preventClickEvent", true );
			}

			this._mouseStop( event );
		}

		if ( this._mouseDelayTimer ) {
			clearTimeout( this._mouseDelayTimer );
			delete this._mouseDelayTimer;
		}

		this.ignoreMissingWhich = false;
		mouseHandled = false;
		event.preventDefault();
	},

	_mouseDistanceMet: function( event ) {
		return ( Math.max(
				Math.abs( this._mouseDownEvent.pageX - event.pageX ),
				Math.abs( this._mouseDownEvent.pageY - event.pageY )
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function( /* event */ ) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function( /* event */ ) {},
	_mouseDrag: function( /* event */ ) {},
	_mouseStop: function( /* event */ ) {},
	_mouseCapture: function( /* event */ ) { return true; }
} );




// $.ui.plugin is deprecated. Use $.widget() extensions instead.
var plugin = $.ui.plugin = {
	add: function( module, option, set ) {
		var i,
			proto = $.ui[ module ].prototype;
		for ( i in set ) {
			proto.plugins[ i ] = proto.plugins[ i ] || [];
			proto.plugins[ i ].push( [ option, set[ i ] ] );
		}
	},
	call: function( instance, name, args, allowDisconnected ) {
		var i,
			set = instance.plugins[ name ];

		if ( !set ) {
			return;
		}

		if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode ||
				instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
			return;
		}

		for ( i = 0; i < set.length; i++ ) {
			if ( instance.options[ set[ i ][ 0 ] ] ) {
				set[ i ][ 1 ].apply( instance.element, args );
			}
		}
	}
};



var safeActiveElement = $.ui.safeActiveElement = function( document ) {
	var activeElement;

	// Support: IE 9 only
	// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
	try {
		activeElement = document.activeElement;
	} catch ( error ) {
		activeElement = document.body;
	}

	// Support: IE 9 - 11 only
	// IE may return null instead of an element
	// Interestingly, this only seems to occur when NOT in an iframe
	if ( !activeElement ) {
		activeElement = document.body;
	}

	// Support: IE 11 only
	// IE11 returns a seemingly empty object in some cases when accessing
	// document.activeElement from an <iframe>
	if ( !activeElement.nodeName ) {
		activeElement = document.body;
	}

	return activeElement;
};



var safeBlur = $.ui.safeBlur = function( element ) {

	// Support: IE9 - 10 only
	// If the <body> is blurred, IE will switch windows, see #9420
	if ( element && element.nodeName.toLowerCase() !== "body" ) {
		$( element ).trigger( "blur" );
	}
};


/*!
 * jQuery UI Draggable 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Draggable
//>>group: Interactions
//>>description: Enables dragging functionality for any element.
//>>docs: http://api.jqueryui.com/draggable/
//>>demos: http://jqueryui.com/draggable/
//>>css.structure: ../../themes/base/draggable.css



$.widget( "ui.draggable", $.ui.mouse, {
	version: "1.12.1",
	widgetEventPrefix: "drag",
	options: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false,

		// Callbacks
		drag: null,
		start: null,
		stop: null
	},
	_create: function() {

		if ( this.options.helper === "original" ) {
			this._setPositionRelative();
		}
		if ( this.options.addClasses ) {
			this._addClass( "ui-draggable" );
		}
		this._setHandleClassName();

		this._mouseInit();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "handle" ) {
			this._removeHandleClassName();
			this._setHandleClassName();
		}
	},

	_destroy: function() {
		if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) {
			this.destroyOnClear = true;
			return;
		}
		this._removeHandleClassName();
		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var o = this.options;

		// Among others, prevent a drag on a resizable-handle
		if ( this.helper || o.disabled ||
				$( event.target ).closest( ".ui-resizable-handle" ).length > 0 ) {
			return false;
		}

		//Quit if we're not on a valid handle
		this.handle = this._getHandle( event );
		if ( !this.handle ) {
			return false;
		}

		this._blurActiveElement( event );

		this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );

		return true;

	},

	_blockFrames: function( selector ) {
		this.iframeBlocks = this.document.find( selector ).map( function() {
			var iframe = $( this );

			return $( "<div>" )
				.css( "position", "absolute" )
				.appendTo( iframe.parent() )
				.outerWidth( iframe.outerWidth() )
				.outerHeight( iframe.outerHeight() )
				.offset( iframe.offset() )[ 0 ];
		} );
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_blurActiveElement: function( event ) {
		var activeElement = $.ui.safeActiveElement( this.document[ 0 ] ),
			target = $( event.target );

		// Don't blur if the event occurred on an element that is within
		// the currently focused element
		// See #10527, #12472
		if ( target.closest( activeElement ).length ) {
			return;
		}

		// Blur any element that currently has focus, see #4261
		$.ui.safeBlur( activeElement );
	},

	_mouseStart: function( event ) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper( event );

		this._addClass( this.helper, "ui-draggable-dragging" );

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.current = this;
		}

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css( "position" );
		this.scrollParent = this.helper.scrollParent( true );
		this.offsetParent = this.helper.offsetParent();
		this.hasFixedAncestor = this.helper.parents().filter( function() {
				return $( this ).css( "position" ) === "fixed";
			} ).length > 0;

		//The element's absolute position on the page minus margins
		this.positionAbs = this.element.offset();
		this._refreshOffsets( event );

		//Generate the original position
		this.originalPosition = this.position = this._generatePosition( event, false );
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		( o.cursorAt && this._adjustOffsetFromHelper( o.cursorAt ) );

		//Set a containment if given in the options
		this._setContainment();

		//Trigger event + callbacks
		if ( this._trigger( "start", event ) === false ) {
			this._clear();
			return false;
		}

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ( $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( this, event );
		}

		// Execute the drag once - this causes the helper not to be visible before getting its
		// correct position
		this._mouseDrag( event, true );

		// If the ddmanager is used for droppables, inform the manager that dragging has started
		// (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStart( this, event );
		}

		return true;
	},

	_refreshOffsets: function( event ) {
		this.offset = {
			top: this.positionAbs.top - this.margins.top,
			left: this.positionAbs.left - this.margins.left,
			scroll: false,
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset()
		};

		this.offset.click = {
			left: event.pageX - this.offset.left,
			top: event.pageY - this.offset.top
		};
	},

	_mouseDrag: function( event, noPropagation ) {

		// reset any necessary cached properties (see #5009)
		if ( this.hasFixedAncestor ) {
			this.offset.parent = this._getParentOffset();
		}

		//Compute the helpers position
		this.position = this._generatePosition( event, true );
		this.positionAbs = this._convertPositionTo( "absolute" );

		//Call plugins and callbacks and use the resulting position if something is returned
		if ( !noPropagation ) {
			var ui = this._uiHash();
			if ( this._trigger( "drag", event, ui ) === false ) {
				this._mouseUp( new $.Event( "mouseup", event ) );
				return false;
			}
			this.position = ui.position;
		}

		this.helper[ 0 ].style.left = this.position.left + "px";
		this.helper[ 0 ].style.top = this.position.top + "px";

		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.drag( this, event );
		}

		return false;
	},

	_mouseStop: function( event ) {

		//If we are using droppables, inform the manager about the drop
		var that = this,
			dropped = false;
		if ( $.ui.ddmanager && !this.options.dropBehaviour ) {
			dropped = $.ui.ddmanager.drop( this, event );
		}

		//if a drop comes from outside (a sortable)
		if ( this.dropped ) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if ( ( this.options.revert === "invalid" && !dropped ) ||
				( this.options.revert === "valid" && dropped ) ||
				this.options.revert === true || ( $.isFunction( this.options.revert ) &&
				this.options.revert.call( this.element, dropped ) )
		) {
			$( this.helper ).animate(
				this.originalPosition,
				parseInt( this.options.revertDuration, 10 ),
				function() {
					if ( that._trigger( "stop", event ) !== false ) {
						that._clear();
					}
				}
			);
		} else {
			if ( this._trigger( "stop", event ) !== false ) {
				this._clear();
			}
		}

		return false;
	},

	_mouseUp: function( event ) {
		this._unblockFrames();

		// If the ddmanager is used for droppables, inform the manager that dragging has stopped
		// (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStop( this, event );
		}

		// Only need to focus if the event occurred on the draggable itself, see #10527
		if ( this.handleElement.is( event.target ) ) {

			// The interaction is over; whether or not the click resulted in a drag,
			// focus the element
			this.element.trigger( "focus" );
		}

		return $.ui.mouse.prototype._mouseUp.call( this, event );
	},

	cancel: function() {

		if ( this.helper.is( ".ui-draggable-dragging" ) ) {
			this._mouseUp( new $.Event( "mouseup", { target: this.element[ 0 ] } ) );
		} else {
			this._clear();
		}

		return this;

	},

	_getHandle: function( event ) {
		return this.options.handle ?
			!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
			true;
	},

	_setHandleClassName: function() {
		this.handleElement = this.options.handle ?
			this.element.find( this.options.handle ) : this.element;
		this._addClass( this.handleElement, "ui-draggable-handle" );
	},

	_removeHandleClassName: function() {
		this._removeClass( this.handleElement, "ui-draggable-handle" );
	},

	_createHelper: function( event ) {

		var o = this.options,
			helperIsFunction = $.isFunction( o.helper ),
			helper = helperIsFunction ?
				$( o.helper.apply( this.element[ 0 ], [ event ] ) ) :
				( o.helper === "clone" ?
					this.element.clone().removeAttr( "id" ) :
					this.element );

		if ( !helper.parents( "body" ).length ) {
			helper.appendTo( ( o.appendTo === "parent" ?
				this.element[ 0 ].parentNode :
				o.appendTo ) );
		}

		// Http://bugs.jqueryui.com/ticket/9446
		// a helper function can return the original element
		// which wouldn't have been set to relative in _create
		if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) {
			this._setPositionRelative();
		}

		if ( helper[ 0 ] !== this.element[ 0 ] &&
				!( /(fixed|absolute)/ ).test( helper.css( "position" ) ) ) {
			helper.css( "position", "absolute" );
		}

		return helper;

	},

	_setPositionRelative: function() {
		if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) {
			this.element[ 0 ].style.position = "relative";
		}
	},

	_adjustOffsetFromHelper: function( obj ) {
		if ( typeof obj === "string" ) {
			obj = obj.split( " " );
		}
		if ( $.isArray( obj ) ) {
			obj = { left: +obj[ 0 ], top: +obj[ 1 ] || 0 };
		}
		if ( "left" in obj ) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ( "right" in obj ) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ( "top" in obj ) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ( "bottom" in obj ) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_isRootNode: function( element ) {
		return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ];
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		var po = this.offsetParent.offset(),
			document = this.document[ 0 ];

		// This is a special case where we need to modify a offset calculated on start, since the
		// following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the
		// next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
		// the document, which means that the scroll is included in the initial calculation of the
		// offset of the parent, and never recalculated upon drag
		if ( this.cssPosition === "absolute" && this.scrollParent[ 0 ] !== document &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if ( this._isRootNode( this.offsetParent[ 0 ] ) ) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + ( parseInt( this.offsetParent.css( "borderTopWidth" ), 10 ) || 0 ),
			left: po.left + ( parseInt( this.offsetParent.css( "borderLeftWidth" ), 10 ) || 0 )
		};

	},

	_getRelativeOffset: function() {
		if ( this.cssPosition !== "relative" ) {
			return { top: 0, left: 0 };
		}

		var p = this.element.position(),
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: p.top - ( parseInt( this.helper.css( "top" ), 10 ) || 0 ) +
				( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ),
			left: p.left - ( parseInt( this.helper.css( "left" ), 10 ) || 0 ) +
				( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 )
		};

	},

	_cacheMargins: function() {
		this.margins = {
			left: ( parseInt( this.element.css( "marginLeft" ), 10 ) || 0 ),
			top: ( parseInt( this.element.css( "marginTop" ), 10 ) || 0 ),
			right: ( parseInt( this.element.css( "marginRight" ), 10 ) || 0 ),
			bottom: ( parseInt( this.element.css( "marginBottom" ), 10 ) || 0 )
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var isUserScrollable, c, ce,
			o = this.options,
			document = this.document[ 0 ];

		this.relativeContainer = null;

		if ( !o.containment ) {
			this.containment = null;
			return;
		}

		if ( o.containment === "window" ) {
			this.containment = [
				$( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
				$( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
				$( window ).scrollLeft() + $( window ).width() -
					this.helperProportions.width - this.margins.left,
				$( window ).scrollTop() +
					( $( window ).height() || document.body.parentNode.scrollHeight ) -
					this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment === "document" ) {
			this.containment = [
				0,
				0,
				$( document ).width() - this.helperProportions.width - this.margins.left,
				( $( document ).height() || document.body.parentNode.scrollHeight ) -
					this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment.constructor === Array ) {
			this.containment = o.containment;
			return;
		}

		if ( o.containment === "parent" ) {
			o.containment = this.helper[ 0 ].parentNode;
		}

		c = $( o.containment );
		ce = c[ 0 ];

		if ( !ce ) {
			return;
		}

		isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) );

		this.containment = [
			( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) +
				( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
			( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) +
				( parseInt( c.css( "paddingTop" ), 10 ) || 0 ),
			( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
				( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) -
				this.helperProportions.width -
				this.margins.left -
				this.margins.right,
			( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
				( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) -
				this.helperProportions.height -
				this.margins.top -
				this.margins.bottom
		];
		this.relativeContainer = c;
	},

	_convertPositionTo: function( d, pos ) {

		if ( !pos ) {
			pos = this.position;
		}

		var mod = d === "absolute" ? 1 : -1,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: (

				// The absolute mouse position
				pos.top	+

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top * mod -
				( ( this.cssPosition === "fixed" ?
					-this.offset.scroll.top :
					( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod )
			),
			left: (

				// The absolute mouse position
				pos.left +

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left * mod	-
				( ( this.cssPosition === "fixed" ?
					-this.offset.scroll.left :
					( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod )
			)
		};

	},

	_generatePosition: function( event, constrainPosition ) {

		var containment, co, top, left,
			o = this.options,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ),
			pageX = event.pageX,
			pageY = event.pageY;

		// Cache the scroll
		if ( !scrollIsRootNode || !this.offset.scroll ) {
			this.offset.scroll = {
				top: this.scrollParent.scrollTop(),
				left: this.scrollParent.scrollLeft()
			};
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		// If we are not dragging yet, we won't check for options
		if ( constrainPosition ) {
			if ( this.containment ) {
				if ( this.relativeContainer ) {
					co = this.relativeContainer.offset();
					containment = [
						this.containment[ 0 ] + co.left,
						this.containment[ 1 ] + co.top,
						this.containment[ 2 ] + co.left,
						this.containment[ 3 ] + co.top
					];
				} else {
					containment = this.containment;
				}

				if ( event.pageX - this.offset.click.left < containment[ 0 ] ) {
					pageX = containment[ 0 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top < containment[ 1 ] ) {
					pageY = containment[ 1 ] + this.offset.click.top;
				}
				if ( event.pageX - this.offset.click.left > containment[ 2 ] ) {
					pageX = containment[ 2 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top > containment[ 3 ] ) {
					pageY = containment[ 3 ] + this.offset.click.top;
				}
			}

			if ( o.grid ) {

				//Check for grid elements set to 0 to prevent divide by 0 error causing invalid
				// argument errors in IE (see ticket #6950)
				top = o.grid[ 1 ] ? this.originalPageY + Math.round( ( pageY -
					this.originalPageY ) / o.grid[ 1 ] ) * o.grid[ 1 ] : this.originalPageY;
				pageY = containment ? ( ( top - this.offset.click.top >= containment[ 1 ] ||
					top - this.offset.click.top > containment[ 3 ] ) ?
						top :
						( ( top - this.offset.click.top >= containment[ 1 ] ) ?
							top - o.grid[ 1 ] : top + o.grid[ 1 ] ) ) : top;

				left = o.grid[ 0 ] ? this.originalPageX +
					Math.round( ( pageX - this.originalPageX ) / o.grid[ 0 ] ) * o.grid[ 0 ] :
					this.originalPageX;
				pageX = containment ? ( ( left - this.offset.click.left >= containment[ 0 ] ||
					left - this.offset.click.left > containment[ 2 ] ) ?
						left :
						( ( left - this.offset.click.left >= containment[ 0 ] ) ?
							left - o.grid[ 0 ] : left + o.grid[ 0 ] ) ) : left;
			}

			if ( o.axis === "y" ) {
				pageX = this.originalPageX;
			}

			if ( o.axis === "x" ) {
				pageY = this.originalPageY;
			}
		}

		return {
			top: (

				// The absolute mouse position
				pageY -

				// Click offset (relative to the element)
				this.offset.click.top -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top +
				( this.cssPosition === "fixed" ?
					-this.offset.scroll.top :
					( scrollIsRootNode ? 0 : this.offset.scroll.top ) )
			),
			left: (

				// The absolute mouse position
				pageX -

				// Click offset (relative to the element)
				this.offset.click.left -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left +
				( this.cssPosition === "fixed" ?
					-this.offset.scroll.left :
					( scrollIsRootNode ? 0 : this.offset.scroll.left ) )
			)
		};

	},

	_clear: function() {
		this._removeClass( this.helper, "ui-draggable-dragging" );
		if ( this.helper[ 0 ] !== this.element[ 0 ] && !this.cancelHelperRemoval ) {
			this.helper.remove();
		}
		this.helper = null;
		this.cancelHelperRemoval = false;
		if ( this.destroyOnClear ) {
			this.destroy();
		}
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function( type, event, ui ) {
		ui = ui || this._uiHash();
		$.ui.plugin.call( this, type, [ event, ui, this ], true );

		// Absolute position and offset (see #6884 ) have to be recalculated after plugins
		if ( /^(drag|start|stop)/.test( type ) ) {
			this.positionAbs = this._convertPositionTo( "absolute" );
			ui.offset = this.positionAbs;
		}
		return $.Widget.prototype._trigger.call( this, type, event, ui );
	},

	plugins: {},

	_uiHash: function() {
		return {
			helper: this.helper,
			position: this.position,
			originalPosition: this.originalPosition,
			offset: this.positionAbs
		};
	}

} );

$.ui.plugin.add( "draggable", "connectToSortable", {
	start: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		} );

		draggable.sortables = [];
		$( draggable.options.connectToSortable ).each( function() {
			var sortable = $( this ).sortable( "instance" );

			if ( sortable && !sortable.options.disabled ) {
				draggable.sortables.push( sortable );

				// RefreshPositions is called at drag start to refresh the containerCache
				// which is used in drag. This ensures it's initialized and synchronized
				// with any changes that might have happened on the page since initialization.
				sortable.refreshPositions();
				sortable._trigger( "activate", event, uiSortable );
			}
		} );
	},
	stop: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		} );

		draggable.cancelHelperRemoval = false;

		$.each( draggable.sortables, function() {
			var sortable = this;

			if ( sortable.isOver ) {
				sortable.isOver = 0;

				// Allow this sortable to handle removing the helper
				draggable.cancelHelperRemoval = true;
				sortable.cancelHelperRemoval = false;

				// Use _storedCSS To restore properties in the sortable,
				// as this also handles revert (#9675) since the draggable
				// may have modified them in unexpected ways (#8809)
				sortable._storedCSS = {
					position: sortable.placeholder.css( "position" ),
					top: sortable.placeholder.css( "top" ),
					left: sortable.placeholder.css( "left" )
				};

				sortable._mouseStop( event );

				// Once drag has ended, the sortable should return to using
				// its original helper, not the shared helper from draggable
				sortable.options.helper = sortable.options._helper;
			} else {

				// Prevent this Sortable from removing the helper.
				// However, don't set the draggable to remove the helper
				// either as another connected Sortable may yet handle the removal.
				sortable.cancelHelperRemoval = true;

				sortable._trigger( "deactivate", event, uiSortable );
			}
		} );
	},
	drag: function( event, ui, draggable ) {
		$.each( draggable.sortables, function() {
			var innermostIntersecting = false,
				sortable = this;

			// Copy over variables that sortable's _intersectsWith uses
			sortable.positionAbs = draggable.positionAbs;
			sortable.helperProportions = draggable.helperProportions;
			sortable.offset.click = draggable.offset.click;

			if ( sortable._intersectsWith( sortable.containerCache ) ) {
				innermostIntersecting = true;

				$.each( draggable.sortables, function() {

					// Copy over variables that sortable's _intersectsWith uses
					this.positionAbs = draggable.positionAbs;
					this.helperProportions = draggable.helperProportions;
					this.offset.click = draggable.offset.click;

					if ( this !== sortable &&
							this._intersectsWith( this.containerCache ) &&
							$.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) {
						innermostIntersecting = false;
					}

					return innermostIntersecting;
				} );
			}

			if ( innermostIntersecting ) {

				// If it intersects, we use a little isOver variable and set it once,
				// so that the move-in stuff gets fired only once.
				if ( !sortable.isOver ) {
					sortable.isOver = 1;

					// Store draggable's parent in case we need to reappend to it later.
					draggable._parent = ui.helper.parent();

					sortable.currentItem = ui.helper
						.appendTo( sortable.element )
						.data( "ui-sortable-item", true );

					// Store helper option to later restore it
					sortable.options._helper = sortable.options.helper;

					sortable.options.helper = function() {
						return ui.helper[ 0 ];
					};

					// Fire the start events of the sortable with our passed browser event,
					// and our own helper (so it doesn't create a new one)
					event.target = sortable.currentItem[ 0 ];
					sortable._mouseCapture( event, true );
					sortable._mouseStart( event, true, true );

					// Because the browser event is way off the new appended portlet,
					// modify necessary variables to reflect the changes
					sortable.offset.click.top = draggable.offset.click.top;
					sortable.offset.click.left = draggable.offset.click.left;
					sortable.offset.parent.left -= draggable.offset.parent.left -
						sortable.offset.parent.left;
					sortable.offset.parent.top -= draggable.offset.parent.top -
						sortable.offset.parent.top;

					draggable._trigger( "toSortable", event );

					// Inform draggable that the helper is in a valid drop zone,
					// used solely in the revert option to handle "valid/invalid".
					draggable.dropped = sortable.element;

					// Need to refreshPositions of all sortables in the case that
					// adding to one sortable changes the location of the other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					} );

					// Hack so receive/update callbacks work (mostly)
					draggable.currentItem = draggable.element;
					sortable.fromOutside = draggable;
				}

				if ( sortable.currentItem ) {
					sortable._mouseDrag( event );

					// Copy the sortable's position because the draggable's can potentially reflect
					// a relative position, while sortable is always absolute, which the dragged
					// element has now become. (#8809)
					ui.position = sortable.position;
				}
			} else {

				// If it doesn't intersect with the sortable, and it intersected before,
				// we fake the drag stop of the sortable, but make sure it doesn't remove
				// the helper by using cancelHelperRemoval.
				if ( sortable.isOver ) {

					sortable.isOver = 0;
					sortable.cancelHelperRemoval = true;

					// Calling sortable's mouseStop would trigger a revert,
					// so revert must be temporarily false until after mouseStop is called.
					sortable.options._revert = sortable.options.revert;
					sortable.options.revert = false;

					sortable._trigger( "out", event, sortable._uiHash( sortable ) );
					sortable._mouseStop( event, true );

					// Restore sortable behaviors that were modfied
					// when the draggable entered the sortable area (#9481)
					sortable.options.revert = sortable.options._revert;
					sortable.options.helper = sortable.options._helper;

					if ( sortable.placeholder ) {
						sortable.placeholder.remove();
					}

					// Restore and recalculate the draggable's offset considering the sortable
					// may have modified them in unexpected ways. (#8809, #10669)
					ui.helper.appendTo( draggable._parent );
					draggable._refreshOffsets( event );
					ui.position = draggable._generatePosition( event, true );

					draggable._trigger( "fromSortable", event );

					// Inform draggable that the helper is no longer in a valid drop zone
					draggable.dropped = false;

					// Need to refreshPositions of all sortables just in case removing
					// from one sortable changes the location of other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					} );
				}
			}
		} );
	}
} );

$.ui.plugin.add( "draggable", "cursor", {
	start: function( event, ui, instance ) {
		var t = $( "body" ),
			o = instance.options;

		if ( t.css( "cursor" ) ) {
			o._cursor = t.css( "cursor" );
		}
		t.css( "cursor", o.cursor );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if ( o._cursor ) {
			$( "body" ).css( "cursor", o._cursor );
		}
	}
} );

$.ui.plugin.add( "draggable", "opacity", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;
		if ( t.css( "opacity" ) ) {
			o._opacity = t.css( "opacity" );
		}
		t.css( "opacity", o.opacity );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if ( o._opacity ) {
			$( ui.helper ).css( "opacity", o._opacity );
		}
	}
} );

$.ui.plugin.add( "draggable", "scroll", {
	start: function( event, ui, i ) {
		if ( !i.scrollParentNotHidden ) {
			i.scrollParentNotHidden = i.helper.scrollParent( false );
		}

		if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] &&
				i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) {
			i.overflowOffset = i.scrollParentNotHidden.offset();
		}
	},
	drag: function( event, ui, i  ) {

		var o = i.options,
			scrolled = false,
			scrollParent = i.scrollParentNotHidden[ 0 ],
			document = i.document[ 0 ];

		if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) {
			if ( !o.axis || o.axis !== "x" ) {
				if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY <
						o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
				} else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX <
						o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
				} else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
				}
			}

		} else {

			if ( !o.axis || o.axis !== "x" ) {
				if ( event.pageY - $( document ).scrollTop() < o.scrollSensitivity ) {
					scrolled = $( document ).scrollTop( $( document ).scrollTop() - o.scrollSpeed );
				} else if ( $( window ).height() - ( event.pageY - $( document ).scrollTop() ) <
						o.scrollSensitivity ) {
					scrolled = $( document ).scrollTop( $( document ).scrollTop() + o.scrollSpeed );
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( event.pageX - $( document ).scrollLeft() < o.scrollSensitivity ) {
					scrolled = $( document ).scrollLeft(
						$( document ).scrollLeft() - o.scrollSpeed
					);
				} else if ( $( window ).width() - ( event.pageX - $( document ).scrollLeft() ) <
						o.scrollSensitivity ) {
					scrolled = $( document ).scrollLeft(
						$( document ).scrollLeft() + o.scrollSpeed
					);
				}
			}

		}

		if ( scrolled !== false && $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( i, event );
		}

	}
} );

$.ui.plugin.add( "draggable", "snap", {
	start: function( event, ui, i ) {

		var o = i.options;

		i.snapElements = [];

		$( o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap )
			.each( function() {
				var $t = $( this ),
					$o = $t.offset();
				if ( this !== i.element[ 0 ] ) {
					i.snapElements.push( {
						item: this,
						width: $t.outerWidth(), height: $t.outerHeight(),
						top: $o.top, left: $o.left
					} );
				}
			} );

	},
	drag: function( event, ui, inst ) {

		var ts, bs, ls, rs, l, r, t, b, i, first,
			o = inst.options,
			d = o.snapTolerance,
			x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for ( i = inst.snapElements.length - 1; i >= 0; i-- ) {

			l = inst.snapElements[ i ].left - inst.margins.left;
			r = l + inst.snapElements[ i ].width;
			t = inst.snapElements[ i ].top - inst.margins.top;
			b = t + inst.snapElements[ i ].height;

			if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d ||
					!$.contains( inst.snapElements[ i ].item.ownerDocument,
					inst.snapElements[ i ].item ) ) {
				if ( inst.snapElements[ i ].snapping ) {
					( inst.options.snap.release &&
						inst.options.snap.release.call(
							inst.element,
							event,
							$.extend( inst._uiHash(), { snapItem: inst.snapElements[ i ].item } )
						) );
				}
				inst.snapElements[ i ].snapping = false;
				continue;
			}

			if ( o.snapMode !== "inner" ) {
				ts = Math.abs( t - y2 ) <= d;
				bs = Math.abs( b - y1 ) <= d;
				ls = Math.abs( l - x2 ) <= d;
				rs = Math.abs( r - x1 ) <= d;
				if ( ts ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: t - inst.helperProportions.height,
						left: 0
					} ).top;
				}
				if ( bs ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: b,
						left: 0
					} ).top;
				}
				if ( ls ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: l - inst.helperProportions.width
					} ).left;
				}
				if ( rs ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: r
					} ).left;
				}
			}

			first = ( ts || bs || ls || rs );

			if ( o.snapMode !== "outer" ) {
				ts = Math.abs( t - y1 ) <= d;
				bs = Math.abs( b - y2 ) <= d;
				ls = Math.abs( l - x1 ) <= d;
				rs = Math.abs( r - x2 ) <= d;
				if ( ts ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: t,
						left: 0
					} ).top;
				}
				if ( bs ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: b - inst.helperProportions.height,
						left: 0
					} ).top;
				}
				if ( ls ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: l
					} ).left;
				}
				if ( rs ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: r - inst.helperProportions.width
					} ).left;
				}
			}

			if ( !inst.snapElements[ i ].snapping && ( ts || bs || ls || rs || first ) ) {
				( inst.options.snap.snap &&
					inst.options.snap.snap.call(
						inst.element,
						event,
						$.extend( inst._uiHash(), {
							snapItem: inst.snapElements[ i ].item
						} ) ) );
			}
			inst.snapElements[ i ].snapping = ( ts || bs || ls || rs || first );

		}

	}
} );

$.ui.plugin.add( "draggable", "stack", {
	start: function( event, ui, instance ) {
		var min,
			o = instance.options,
			group = $.makeArray( $( o.stack ) ).sort( function( a, b ) {
				return ( parseInt( $( a ).css( "zIndex" ), 10 ) || 0 ) -
					( parseInt( $( b ).css( "zIndex" ), 10 ) || 0 );
			} );

		if ( !group.length ) { return; }

		min = parseInt( $( group[ 0 ] ).css( "zIndex" ), 10 ) || 0;
		$( group ).each( function( i ) {
			$( this ).css( "zIndex", min + i );
		} );
		this.css( "zIndex", ( min + group.length ) );
	}
} );

$.ui.plugin.add( "draggable", "zIndex", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;

		if ( t.css( "zIndex" ) ) {
			o._zIndex = t.css( "zIndex" );
		}
		t.css( "zIndex", o.zIndex );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;

		if ( o._zIndex ) {
			$( ui.helper ).css( "zIndex", o._zIndex );
		}
	}
} );

var widgetsDraggable = $.ui.draggable;


/*!
 * jQuery UI Resizable 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Resizable
//>>group: Interactions
//>>description: Enables resize functionality for any element.
//>>docs: http://api.jqueryui.com/resizable/
//>>demos: http://jqueryui.com/resizable/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/resizable.css
//>>css.theme: ../../themes/base/theme.css



$.widget( "ui.resizable", $.ui.mouse, {
	version: "1.12.1",
	widgetEventPrefix: "resize",
	options: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		classes: {
			"ui-resizable-se": "ui-icon ui-icon-gripsmall-diagonal-se"
		},
		containment: false,
		ghost: false,
		grid: false,
		handles: "e,s,se",
		helper: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,

		// See #7960
		zIndex: 90,

		// Callbacks
		resize: null,
		start: null,
		stop: null
	},

	_num: function( value ) {
		return parseFloat( value ) || 0;
	},

	_isNumber: function( value ) {
		return !isNaN( parseFloat( value ) );
	},

	_hasScroll: function( el, a ) {

		if ( $( el ).css( "overflow" ) === "hidden" ) {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	},

	_create: function() {

		var margins,
			o = this.options,
			that = this;
		this._addClass( "ui-resizable" );

		$.extend( this, {
			_aspectRatio: !!( o.aspectRatio ),
			aspectRatio: o.aspectRatio,
			originalElement: this.element,
			_proportionallyResizeElements: [],
			_helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
		} );

		// Wrap the element if it cannot hold child nodes
		if ( this.element[ 0 ].nodeName.match( /^(canvas|textarea|input|select|button|img)$/i ) ) {

			this.element.wrap(
				$( "<div class='ui-wrapper' style='overflow: hidden;'></div>" ).css( {
					position: this.element.css( "position" ),
					width: this.element.outerWidth(),
					height: this.element.outerHeight(),
					top: this.element.css( "top" ),
					left: this.element.css( "left" )
				} )
			);

			this.element = this.element.parent().data(
				"ui-resizable", this.element.resizable( "instance" )
			);

			this.elementIsWrapper = true;

			margins = {
				marginTop: this.originalElement.css( "marginTop" ),
				marginRight: this.originalElement.css( "marginRight" ),
				marginBottom: this.originalElement.css( "marginBottom" ),
				marginLeft: this.originalElement.css( "marginLeft" )
			};

			this.element.css( margins );
			this.originalElement.css( "margin", 0 );

			// support: Safari
			// Prevent Safari textarea resize
			this.originalResizeStyle = this.originalElement.css( "resize" );
			this.originalElement.css( "resize", "none" );

			this._proportionallyResizeElements.push( this.originalElement.css( {
				position: "static",
				zoom: 1,
				display: "block"
			} ) );

			// Support: IE9
			// avoid IE jump (hard set the margin)
			this.originalElement.css( margins );

			this._proportionallyResize();
		}

		this._setupHandles();

		if ( o.autoHide ) {
			$( this.element )
				.on( "mouseenter", function() {
					if ( o.disabled ) {
						return;
					}
					that._removeClass( "ui-resizable-autohide" );
					that._handles.show();
				} )
				.on( "mouseleave", function() {
					if ( o.disabled ) {
						return;
					}
					if ( !that.resizing ) {
						that._addClass( "ui-resizable-autohide" );
						that._handles.hide();
					}
				} );
		}

		this._mouseInit();
	},

	_destroy: function() {

		this._mouseDestroy();

		var wrapper,
			_destroy = function( exp ) {
				$( exp )
					.removeData( "resizable" )
					.removeData( "ui-resizable" )
					.off( ".resizable" )
					.find( ".ui-resizable-handle" )
						.remove();
			};

		// TODO: Unwrap at same DOM position
		if ( this.elementIsWrapper ) {
			_destroy( this.element );
			wrapper = this.element;
			this.originalElement.css( {
				position: wrapper.css( "position" ),
				width: wrapper.outerWidth(),
				height: wrapper.outerHeight(),
				top: wrapper.css( "top" ),
				left: wrapper.css( "left" )
			} ).insertAfter( wrapper );
			wrapper.remove();
		}

		this.originalElement.css( "resize", this.originalResizeStyle );
		_destroy( this.originalElement );

		return this;
	},

	_setOption: function( key, value ) {
		this._super( key, value );

		switch ( key ) {
		case "handles":
			this._removeHandles();
			this._setupHandles();
			break;
		default:
			break;
		}
	},

	_setupHandles: function() {
		var o = this.options, handle, i, n, hname, axis, that = this;
		this.handles = o.handles ||
			( !$( ".ui-resizable-handle", this.element ).length ?
				"e,s,se" : {
					n: ".ui-resizable-n",
					e: ".ui-resizable-e",
					s: ".ui-resizable-s",
					w: ".ui-resizable-w",
					se: ".ui-resizable-se",
					sw: ".ui-resizable-sw",
					ne: ".ui-resizable-ne",
					nw: ".ui-resizable-nw"
				} );

		this._handles = $();
		if ( this.handles.constructor === String ) {

			if ( this.handles === "all" ) {
				this.handles = "n,e,s,w,se,sw,ne,nw";
			}

			n = this.handles.split( "," );
			this.handles = {};

			for ( i = 0; i < n.length; i++ ) {

				handle = $.trim( n[ i ] );
				hname = "ui-resizable-" + handle;
				axis = $( "<div>" );
				this._addClass( axis, "ui-resizable-handle " + hname );

				axis.css( { zIndex: o.zIndex } );

				this.handles[ handle ] = ".ui-resizable-" + handle;
				this.element.append( axis );
			}

		}

		this._renderAxis = function( target ) {

			var i, axis, padPos, padWrapper;

			target = target || this.element;

			for ( i in this.handles ) {

				if ( this.handles[ i ].constructor === String ) {
					this.handles[ i ] = this.element.children( this.handles[ i ] ).first().show();
				} else if ( this.handles[ i ].jquery || this.handles[ i ].nodeType ) {
					this.handles[ i ] = $( this.handles[ i ] );
					this._on( this.handles[ i ], { "mousedown": that._mouseDown } );
				}

				if ( this.elementIsWrapper &&
						this.originalElement[ 0 ]
							.nodeName
							.match( /^(textarea|input|select|button)$/i ) ) {
					axis = $( this.handles[ i ], this.element );

					padWrapper = /sw|ne|nw|se|n|s/.test( i ) ?
						axis.outerHeight() :
						axis.outerWidth();

					padPos = [ "padding",
						/ne|nw|n/.test( i ) ? "Top" :
						/se|sw|s/.test( i ) ? "Bottom" :
						/^e$/.test( i ) ? "Right" : "Left" ].join( "" );

					target.css( padPos, padWrapper );

					this._proportionallyResize();
				}

				this._handles = this._handles.add( this.handles[ i ] );
			}
		};

		// TODO: make renderAxis a prototype function
		this._renderAxis( this.element );

		this._handles = this._handles.add( this.element.find( ".ui-resizable-handle" ) );
		this._handles.disableSelection();

		this._handles.on( "mouseover", function() {
			if ( !that.resizing ) {
				if ( this.className ) {
					axis = this.className.match( /ui-resizable-(se|sw|ne|nw|n|e|s|w)/i );
				}
				that.axis = axis && axis[ 1 ] ? axis[ 1 ] : "se";
			}
		} );

		if ( o.autoHide ) {
			this._handles.hide();
			this._addClass( "ui-resizable-autohide" );
		}
	},

	_removeHandles: function() {
		this._handles.remove();
	},

	_mouseCapture: function( event ) {
		var i, handle,
			capture = false;

		for ( i in this.handles ) {
			handle = $( this.handles[ i ] )[ 0 ];
			if ( handle === event.target || $.contains( handle, event.target ) ) {
				capture = true;
			}
		}

		return !this.options.disabled && capture;
	},

	_mouseStart: function( event ) {

		var curleft, curtop, cursor,
			o = this.options,
			el = this.element;

		this.resizing = true;

		this._renderProxy();

		curleft = this._num( this.helper.css( "left" ) );
		curtop = this._num( this.helper.css( "top" ) );

		if ( o.containment ) {
			curleft += $( o.containment ).scrollLeft() || 0;
			curtop += $( o.containment ).scrollTop() || 0;
		}

		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };

		this.size = this._helper ? {
				width: this.helper.width(),
				height: this.helper.height()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.originalSize = this._helper ? {
				width: el.outerWidth(),
				height: el.outerHeight()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.sizeDiff = {
			width: el.outerWidth() - el.width(),
			height: el.outerHeight() - el.height()
		};

		this.originalPosition = { left: curleft, top: curtop };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		this.aspectRatio = ( typeof o.aspectRatio === "number" ) ?
			o.aspectRatio :
			( ( this.originalSize.width / this.originalSize.height ) || 1 );

		cursor = $( ".ui-resizable-" + this.axis ).css( "cursor" );
		$( "body" ).css( "cursor", cursor === "auto" ? this.axis + "-resize" : cursor );

		this._addClass( "ui-resizable-resizing" );
		this._propagate( "start", event );
		return true;
	},

	_mouseDrag: function( event ) {

		var data, props,
			smp = this.originalMousePosition,
			a = this.axis,
			dx = ( event.pageX - smp.left ) || 0,
			dy = ( event.pageY - smp.top ) || 0,
			trigger = this._change[ a ];

		this._updatePrevProperties();

		if ( !trigger ) {
			return false;
		}

		data = trigger.apply( this, [ event, dx, dy ] );

		this._updateVirtualBoundaries( event.shiftKey );
		if ( this._aspectRatio || event.shiftKey ) {
			data = this._updateRatio( data, event );
		}

		data = this._respectSize( data, event );

		this._updateCache( data );

		this._propagate( "resize", event );

		props = this._applyChanges();

		if ( !this._helper && this._proportionallyResizeElements.length ) {
			this._proportionallyResize();
		}

		if ( !$.isEmptyObject( props ) ) {
			this._updatePrevProperties();
			this._trigger( "resize", event, this.ui() );
			this._applyChanges();
		}

		return false;
	},

	_mouseStop: function( event ) {

		this.resizing = false;
		var pr, ista, soffseth, soffsetw, s, left, top,
			o = this.options, that = this;

		if ( this._helper ) {

			pr = this._proportionallyResizeElements;
			ista = pr.length && ( /textarea/i ).test( pr[ 0 ].nodeName );
			soffseth = ista && this._hasScroll( pr[ 0 ], "left" ) ? 0 : that.sizeDiff.height;
			soffsetw = ista ? 0 : that.sizeDiff.width;

			s = {
				width: ( that.helper.width()  - soffsetw ),
				height: ( that.helper.height() - soffseth )
			};
			left = ( parseFloat( that.element.css( "left" ) ) +
				( that.position.left - that.originalPosition.left ) ) || null;
			top = ( parseFloat( that.element.css( "top" ) ) +
				( that.position.top - that.originalPosition.top ) ) || null;

			if ( !o.animate ) {
				this.element.css( $.extend( s, { top: top, left: left } ) );
			}

			that.helper.height( that.size.height );
			that.helper.width( that.size.width );

			if ( this._helper && !o.animate ) {
				this._proportionallyResize();
			}
		}

		$( "body" ).css( "cursor", "auto" );

		this._removeClass( "ui-resizable-resizing" );

		this._propagate( "stop", event );

		if ( this._helper ) {
			this.helper.remove();
		}

		return false;

	},

	_updatePrevProperties: function() {
		this.prevPosition = {
			top: this.position.top,
			left: this.position.left
		};
		this.prevSize = {
			width: this.size.width,
			height: this.size.height
		};
	},

	_applyChanges: function() {
		var props = {};

		if ( this.position.top !== this.prevPosition.top ) {
			props.top = this.position.top + "px";
		}
		if ( this.position.left !== this.prevPosition.left ) {
			props.left = this.position.left + "px";
		}
		if ( this.size.width !== this.prevSize.width ) {
			props.width = this.size.width + "px";
		}
		if ( this.size.height !== this.prevSize.height ) {
			props.height = this.size.height + "px";
		}

		this.helper.css( props );

		return props;
	},

	_updateVirtualBoundaries: function( forceAspectRatio ) {
		var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
			o = this.options;

		b = {
			minWidth: this._isNumber( o.minWidth ) ? o.minWidth : 0,
			maxWidth: this._isNumber( o.maxWidth ) ? o.maxWidth : Infinity,
			minHeight: this._isNumber( o.minHeight ) ? o.minHeight : 0,
			maxHeight: this._isNumber( o.maxHeight ) ? o.maxHeight : Infinity
		};

		if ( this._aspectRatio || forceAspectRatio ) {
			pMinWidth = b.minHeight * this.aspectRatio;
			pMinHeight = b.minWidth / this.aspectRatio;
			pMaxWidth = b.maxHeight * this.aspectRatio;
			pMaxHeight = b.maxWidth / this.aspectRatio;

			if ( pMinWidth > b.minWidth ) {
				b.minWidth = pMinWidth;
			}
			if ( pMinHeight > b.minHeight ) {
				b.minHeight = pMinHeight;
			}
			if ( pMaxWidth < b.maxWidth ) {
				b.maxWidth = pMaxWidth;
			}
			if ( pMaxHeight < b.maxHeight ) {
				b.maxHeight = pMaxHeight;
			}
		}
		this._vBoundaries = b;
	},

	_updateCache: function( data ) {
		this.offset = this.helper.offset();
		if ( this._isNumber( data.left ) ) {
			this.position.left = data.left;
		}
		if ( this._isNumber( data.top ) ) {
			this.position.top = data.top;
		}
		if ( this._isNumber( data.height ) ) {
			this.size.height = data.height;
		}
		if ( this._isNumber( data.width ) ) {
			this.size.width = data.width;
		}
	},

	_updateRatio: function( data ) {

		var cpos = this.position,
			csize = this.size,
			a = this.axis;

		if ( this._isNumber( data.height ) ) {
			data.width = ( data.height * this.aspectRatio );
		} else if ( this._isNumber( data.width ) ) {
			data.height = ( data.width / this.aspectRatio );
		}

		if ( a === "sw" ) {
			data.left = cpos.left + ( csize.width - data.width );
			data.top = null;
		}
		if ( a === "nw" ) {
			data.top = cpos.top + ( csize.height - data.height );
			data.left = cpos.left + ( csize.width - data.width );
		}

		return data;
	},

	_respectSize: function( data ) {

		var o = this._vBoundaries,
			a = this.axis,
			ismaxw = this._isNumber( data.width ) && o.maxWidth && ( o.maxWidth < data.width ),
			ismaxh = this._isNumber( data.height ) && o.maxHeight && ( o.maxHeight < data.height ),
			isminw = this._isNumber( data.width ) && o.minWidth && ( o.minWidth > data.width ),
			isminh = this._isNumber( data.height ) && o.minHeight && ( o.minHeight > data.height ),
			dw = this.originalPosition.left + this.originalSize.width,
			dh = this.originalPosition.top + this.originalSize.height,
			cw = /sw|nw|w/.test( a ), ch = /nw|ne|n/.test( a );
		if ( isminw ) {
			data.width = o.minWidth;
		}
		if ( isminh ) {
			data.height = o.minHeight;
		}
		if ( ismaxw ) {
			data.width = o.maxWidth;
		}
		if ( ismaxh ) {
			data.height = o.maxHeight;
		}

		if ( isminw && cw ) {
			data.left = dw - o.minWidth;
		}
		if ( ismaxw && cw ) {
			data.left = dw - o.maxWidth;
		}
		if ( isminh && ch ) {
			data.top = dh - o.minHeight;
		}
		if ( ismaxh && ch ) {
			data.top = dh - o.maxHeight;
		}

		// Fixing jump error on top/left - bug #2330
		if ( !data.width && !data.height && !data.left && data.top ) {
			data.top = null;
		} else if ( !data.width && !data.height && !data.top && data.left ) {
			data.left = null;
		}

		return data;
	},

	_getPaddingPlusBorderDimensions: function( element ) {
		var i = 0,
			widths = [],
			borders = [
				element.css( "borderTopWidth" ),
				element.css( "borderRightWidth" ),
				element.css( "borderBottomWidth" ),
				element.css( "borderLeftWidth" )
			],
			paddings = [
				element.css( "paddingTop" ),
				element.css( "paddingRight" ),
				element.css( "paddingBottom" ),
				element.css( "paddingLeft" )
			];

		for ( ; i < 4; i++ ) {
			widths[ i ] = ( parseFloat( borders[ i ] ) || 0 );
			widths[ i ] += ( parseFloat( paddings[ i ] ) || 0 );
		}

		return {
			height: widths[ 0 ] + widths[ 2 ],
			width: widths[ 1 ] + widths[ 3 ]
		};
	},

	_proportionallyResize: function() {

		if ( !this._proportionallyResizeElements.length ) {
			return;
		}

		var prel,
			i = 0,
			element = this.helper || this.element;

		for ( ; i < this._proportionallyResizeElements.length; i++ ) {

			prel = this._proportionallyResizeElements[ i ];

			// TODO: Seems like a bug to cache this.outerDimensions
			// considering that we are in a loop.
			if ( !this.outerDimensions ) {
				this.outerDimensions = this._getPaddingPlusBorderDimensions( prel );
			}

			prel.css( {
				height: ( element.height() - this.outerDimensions.height ) || 0,
				width: ( element.width() - this.outerDimensions.width ) || 0
			} );

		}

	},

	_renderProxy: function() {

		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if ( this._helper ) {

			this.helper = this.helper || $( "<div style='overflow:hidden;'></div>" );

			this._addClass( this.helper, this._helper );
			this.helper.css( {
				width: this.element.outerWidth(),
				height: this.element.outerHeight(),
				position: "absolute",
				left: this.elementOffset.left + "px",
				top: this.elementOffset.top + "px",
				zIndex: ++o.zIndex //TODO: Don't modify option
			} );

			this.helper
				.appendTo( "body" )
				.disableSelection();

		} else {
			this.helper = this.element;
		}

	},

	_change: {
		e: function( event, dx ) {
			return { width: this.originalSize.width + dx };
		},
		w: function( event, dx ) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function( event, dx, dy ) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function( event, dx, dy ) {
			return { height: this.originalSize.height + dy };
		},
		se: function( event, dx, dy ) {
			return $.extend( this._change.s.apply( this, arguments ),
				this._change.e.apply( this, [ event, dx, dy ] ) );
		},
		sw: function( event, dx, dy ) {
			return $.extend( this._change.s.apply( this, arguments ),
				this._change.w.apply( this, [ event, dx, dy ] ) );
		},
		ne: function( event, dx, dy ) {
			return $.extend( this._change.n.apply( this, arguments ),
				this._change.e.apply( this, [ event, dx, dy ] ) );
		},
		nw: function( event, dx, dy ) {
			return $.extend( this._change.n.apply( this, arguments ),
				this._change.w.apply( this, [ event, dx, dy ] ) );
		}
	},

	_propagate: function( n, event ) {
		$.ui.plugin.call( this, n, [ event, this.ui() ] );
		( n !== "resize" && this._trigger( n, event, this.ui() ) );
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

} );

/*
 * Resizable Extensions
 */

$.ui.plugin.add( "resizable", "animate", {

	stop: function( event ) {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			pr = that._proportionallyResizeElements,
			ista = pr.length && ( /textarea/i ).test( pr[ 0 ].nodeName ),
			soffseth = ista && that._hasScroll( pr[ 0 ], "left" ) ? 0 : that.sizeDiff.height,
			soffsetw = ista ? 0 : that.sizeDiff.width,
			style = {
				width: ( that.size.width - soffsetw ),
				height: ( that.size.height - soffseth )
			},
			left = ( parseFloat( that.element.css( "left" ) ) +
				( that.position.left - that.originalPosition.left ) ) || null,
			top = ( parseFloat( that.element.css( "top" ) ) +
				( that.position.top - that.originalPosition.top ) ) || null;

		that.element.animate(
			$.extend( style, top && left ? { top: top, left: left } : {} ), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseFloat( that.element.css( "width" ) ),
						height: parseFloat( that.element.css( "height" ) ),
						top: parseFloat( that.element.css( "top" ) ),
						left: parseFloat( that.element.css( "left" ) )
					};

					if ( pr && pr.length ) {
						$( pr[ 0 ] ).css( { width: data.width, height: data.height } );
					}

					// Propagating resize, and updating values for each animation step
					that._updateCache( data );
					that._propagate( "resize", event );

				}
			}
		);
	}

} );

$.ui.plugin.add( "resizable", "containment", {

	start: function() {
		var element, p, co, ch, cw, width, height,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			el = that.element,
			oc = o.containment,
			ce = ( oc instanceof $ ) ?
				oc.get( 0 ) :
				( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc;

		if ( !ce ) {
			return;
		}

		that.containerElement = $( ce );

		if ( /document/.test( oc ) || oc === document ) {
			that.containerOffset = {
				left: 0,
				top: 0
			};
			that.containerPosition = {
				left: 0,
				top: 0
			};

			that.parentData = {
				element: $( document ),
				left: 0,
				top: 0,
				width: $( document ).width(),
				height: $( document ).height() || document.body.parentNode.scrollHeight
			};
		} else {
			element = $( ce );
			p = [];
			$( [ "Top", "Right", "Left", "Bottom" ] ).each( function( i, name ) {
				p[ i ] = that._num( element.css( "padding" + name ) );
			} );

			that.containerOffset = element.offset();
			that.containerPosition = element.position();
			that.containerSize = {
				height: ( element.innerHeight() - p[ 3 ] ),
				width: ( element.innerWidth() - p[ 1 ] )
			};

			co = that.containerOffset;
			ch = that.containerSize.height;
			cw = that.containerSize.width;
			width = ( that._hasScroll ( ce, "left" ) ? ce.scrollWidth : cw );
			height = ( that._hasScroll ( ce ) ? ce.scrollHeight : ch ) ;

			that.parentData = {
				element: ce,
				left: co.left,
				top: co.top,
				width: width,
				height: height
			};
		}
	},

	resize: function( event ) {
		var woset, hoset, isParent, isOffsetRelative,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cp = that.position,
			pRatio = that._aspectRatio || event.shiftKey,
			cop = {
				top: 0,
				left: 0
			},
			ce = that.containerElement,
			continueResize = true;

		if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) {
			cop = co;
		}

		if ( cp.left < ( that._helper ? co.left : 0 ) ) {
			that.size.width = that.size.width +
				( that._helper ?
					( that.position.left - co.left ) :
					( that.position.left - cop.left ) );

			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
			that.position.left = o.helper ? co.left : 0;
		}

		if ( cp.top < ( that._helper ? co.top : 0 ) ) {
			that.size.height = that.size.height +
				( that._helper ?
					( that.position.top - co.top ) :
					that.position.top );

			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
			that.position.top = that._helper ? co.top : 0;
		}

		isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 );
		isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) );

		if ( isParent && isOffsetRelative ) {
			that.offset.left = that.parentData.left + that.position.left;
			that.offset.top = that.parentData.top + that.position.top;
		} else {
			that.offset.left = that.element.offset().left;
			that.offset.top = that.element.offset().top;
		}

		woset = Math.abs( that.sizeDiff.width +
			( that._helper ?
				that.offset.left - cop.left :
				( that.offset.left - co.left ) ) );

		hoset = Math.abs( that.sizeDiff.height +
			( that._helper ?
				that.offset.top - cop.top :
				( that.offset.top - co.top ) ) );

		if ( woset + that.size.width >= that.parentData.width ) {
			that.size.width = that.parentData.width - woset;
			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
		}

		if ( hoset + that.size.height >= that.parentData.height ) {
			that.size.height = that.parentData.height - hoset;
			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
		}

		if ( !continueResize ) {
			that.position.left = that.prevPosition.left;
			that.position.top = that.prevPosition.top;
			that.size.width = that.prevSize.width;
			that.size.height = that.prevSize.height;
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cop = that.containerPosition,
			ce = that.containerElement,
			helper = $( that.helper ),
			ho = helper.offset(),
			w = helper.outerWidth() - that.sizeDiff.width,
			h = helper.outerHeight() - that.sizeDiff.height;

		if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) {
			$( this ).css( {
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			} );
		}

		if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) {
			$( this ).css( {
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			} );
		}
	}
} );

$.ui.plugin.add( "resizable", "alsoResize", {

	start: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options;

		$( o.alsoResize ).each( function() {
			var el = $( this );
			el.data( "ui-resizable-alsoresize", {
				width: parseFloat( el.width() ), height: parseFloat( el.height() ),
				left: parseFloat( el.css( "left" ) ), top: parseFloat( el.css( "top" ) )
			} );
		} );
	},

	resize: function( event, ui ) {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			os = that.originalSize,
			op = that.originalPosition,
			delta = {
				height: ( that.size.height - os.height ) || 0,
				width: ( that.size.width - os.width ) || 0,
				top: ( that.position.top - op.top ) || 0,
				left: ( that.position.left - op.left ) || 0
			};

			$( o.alsoResize ).each( function() {
				var el = $( this ), start = $( this ).data( "ui-resizable-alsoresize" ), style = {},
					css = el.parents( ui.originalElement[ 0 ] ).length ?
							[ "width", "height" ] :
							[ "width", "height", "top", "left" ];

				$.each( css, function( i, prop ) {
					var sum = ( start[ prop ] || 0 ) + ( delta[ prop ] || 0 );
					if ( sum && sum >= 0 ) {
						style[ prop ] = sum || null;
					}
				} );

				el.css( style );
			} );
	},

	stop: function() {
		$( this ).removeData( "ui-resizable-alsoresize" );
	}
} );

$.ui.plugin.add( "resizable", "ghost", {

	start: function() {

		var that = $( this ).resizable( "instance" ), cs = that.size;

		that.ghost = that.originalElement.clone();
		that.ghost.css( {
			opacity: 0.25,
			display: "block",
			position: "relative",
			height: cs.height,
			width: cs.width,
			margin: 0,
			left: 0,
			top: 0
		} );

		that._addClass( that.ghost, "ui-resizable-ghost" );

		// DEPRECATED
		// TODO: remove after 1.12
		if ( $.uiBackCompat !== false && typeof that.options.ghost === "string" ) {

			// Ghost option
			that.ghost.addClass( this.options.ghost );
		}

		that.ghost.appendTo( that.helper );

	},

	resize: function() {
		var that = $( this ).resizable( "instance" );
		if ( that.ghost ) {
			that.ghost.css( {
				position: "relative",
				height: that.size.height,
				width: that.size.width
			} );
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" );
		if ( that.ghost && that.helper ) {
			that.helper.get( 0 ).removeChild( that.ghost.get( 0 ) );
		}
	}

} );

$.ui.plugin.add( "resizable", "grid", {

	resize: function() {
		var outerDimensions,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			cs = that.size,
			os = that.originalSize,
			op = that.originalPosition,
			a = that.axis,
			grid = typeof o.grid === "number" ? [ o.grid, o.grid ] : o.grid,
			gridX = ( grid[ 0 ] || 1 ),
			gridY = ( grid[ 1 ] || 1 ),
			ox = Math.round( ( cs.width - os.width ) / gridX ) * gridX,
			oy = Math.round( ( cs.height - os.height ) / gridY ) * gridY,
			newWidth = os.width + ox,
			newHeight = os.height + oy,
			isMaxWidth = o.maxWidth && ( o.maxWidth < newWidth ),
			isMaxHeight = o.maxHeight && ( o.maxHeight < newHeight ),
			isMinWidth = o.minWidth && ( o.minWidth > newWidth ),
			isMinHeight = o.minHeight && ( o.minHeight > newHeight );

		o.grid = grid;

		if ( isMinWidth ) {
			newWidth += gridX;
		}
		if ( isMinHeight ) {
			newHeight += gridY;
		}
		if ( isMaxWidth ) {
			newWidth -= gridX;
		}
		if ( isMaxHeight ) {
			newHeight -= gridY;
		}

		if ( /^(se|s|e)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
		} else if ( /^(ne)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.top = op.top - oy;
		} else if ( /^(sw)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.left = op.left - ox;
		} else {
			if ( newHeight - gridY <= 0 || newWidth - gridX <= 0 ) {
				outerDimensions = that._getPaddingPlusBorderDimensions( this );
			}

			if ( newHeight - gridY > 0 ) {
				that.size.height = newHeight;
				that.position.top = op.top - oy;
			} else {
				newHeight = gridY - outerDimensions.height;
				that.size.height = newHeight;
				that.position.top = op.top + os.height - newHeight;
			}
			if ( newWidth - gridX > 0 ) {
				that.size.width = newWidth;
				that.position.left = op.left - ox;
			} else {
				newWidth = gridX - outerDimensions.width;
				that.size.width = newWidth;
				that.position.left = op.left + os.width - newWidth;
			}
		}
	}

} );

var widgetsResizable = $.ui.resizable;


/*!
 * jQuery UI Sortable 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Sortable
//>>group: Interactions
//>>description: Enables items in a list to be sorted using the mouse.
//>>docs: http://api.jqueryui.com/sortable/
//>>demos: http://jqueryui.com/sortable/
//>>css.structure: ../../themes/base/sortable.css



var widgetsSortable = $.widget( "ui.sortable", $.ui.mouse, {
	version: "1.12.1",
	widgetEventPrefix: "sort",
	ready: false,
	options: {
		appendTo: "parent",
		axis: false,
		connectWith: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		dropOnEmpty: true,
		forcePlaceholderSize: false,
		forceHelperSize: false,
		grid: false,
		handle: false,
		helper: "original",
		items: "> *",
		opacity: false,
		placeholder: false,
		revert: false,
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		scope: "default",
		tolerance: "intersect",
		zIndex: 1000,

		// Callbacks
		activate: null,
		beforeStop: null,
		change: null,
		deactivate: null,
		out: null,
		over: null,
		receive: null,
		remove: null,
		sort: null,
		start: null,
		stop: null,
		update: null
	},

	_isOverAxis: function( x, reference, size ) {
		return ( x >= reference ) && ( x < ( reference + size ) );
	},

	_isFloating: function( item ) {
		return ( /left|right/ ).test( item.css( "float" ) ) ||
			( /inline|table-cell/ ).test( item.css( "display" ) );
	},

	_create: function() {
		this.containerCache = {};
		this._addClass( "ui-sortable" );

		//Get the items
		this.refresh();

		//Let's determine the parent's offset
		this.offset = this.element.offset();

		//Initialize mouse events for interaction
		this._mouseInit();

		this._setHandleClassName();

		//We're ready to go
		this.ready = true;

	},

	_setOption: function( key, value ) {
		this._super( key, value );

		if ( key === "handle" ) {
			this._setHandleClassName();
		}
	},

	_setHandleClassName: function() {
		var that = this;
		this._removeClass( this.element.find( ".ui-sortable-handle" ), "ui-sortable-handle" );
		$.each( this.items, function() {
			that._addClass(
				this.instance.options.handle ?
					this.item.find( this.instance.options.handle ) :
					this.item,
				"ui-sortable-handle"
			);
		} );
	},

	_destroy: function() {
		this._mouseDestroy();

		for ( var i = this.items.length - 1; i >= 0; i-- ) {
			this.items[ i ].item.removeData( this.widgetName + "-item" );
		}

		return this;
	},

	_mouseCapture: function( event, overrideHandle ) {
		var currentItem = null,
			validHandle = false,
			that = this;

		if ( this.reverting ) {
			return false;
		}

		if ( this.options.disabled || this.options.type === "static" ) {
			return false;
		}

		//We have to refresh the items data once first
		this._refreshItems( event );

		//Find out if the clicked node (or one of its parents) is a actual item in this.items
		$( event.target ).parents().each( function() {
			if ( $.data( this, that.widgetName + "-item" ) === that ) {
				currentItem = $( this );
				return false;
			}
		} );
		if ( $.data( event.target, that.widgetName + "-item" ) === that ) {
			currentItem = $( event.target );
		}

		if ( !currentItem ) {
			return false;
		}
		if ( this.options.handle && !overrideHandle ) {
			$( this.options.handle, currentItem ).find( "*" ).addBack().each( function() {
				if ( this === event.target ) {
					validHandle = true;
				}
			} );
			if ( !validHandle ) {
				return false;
			}
		}

		this.currentItem = currentItem;
		this._removeCurrentsFromItems();
		return true;

	},

	_mouseStart: function( event, overrideHandle, noActivation ) {

		var i, body,
			o = this.options;

		this.currentContainer = this;

		//We only need to call refreshPositions, because the refreshItems call has been moved to
		// mouseCapture
		this.refreshPositions();

		//Create and append the visible helper
		this.helper = this._createHelper( event );

		//Cache the helper size
		this._cacheHelperProportions();

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Get the next scrolling parent
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.currentItem.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend( this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),

			// This is a relative to absolute position minus the actual position calculation -
			// only used for relative positioned helper
			relative: this._getRelativeOffset()
		} );

		// Only after we got the offset, we can change the helper's position to absolute
		// TODO: Still need to figure out a way to make relative sorting possible
		this.helper.css( "position", "absolute" );
		this.cssPosition = this.helper.css( "position" );

		//Generate the original position
		this.originalPosition = this._generatePosition( event );
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		( o.cursorAt && this._adjustOffsetFromHelper( o.cursorAt ) );

		//Cache the former DOM position
		this.domPosition = {
			prev: this.currentItem.prev()[ 0 ],
			parent: this.currentItem.parent()[ 0 ]
		};

		// If the helper is not the original, hide the original so it's not playing any role during
		// the drag, won't cause anything bad this way
		if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
			this.currentItem.hide();
		}

		//Create the placeholder
		this._createPlaceholder();

		//Set a containment if given in the options
		if ( o.containment ) {
			this._setContainment();
		}

		if ( o.cursor && o.cursor !== "auto" ) { // cursor option
			body = this.document.find( "body" );

			// Support: IE
			this.storedCursor = body.css( "cursor" );
			body.css( "cursor", o.cursor );

			this.storedStylesheet =
				$( "<style>*{ cursor: " + o.cursor + " !important; }</style>" ).appendTo( body );
		}

		if ( o.opacity ) { // opacity option
			if ( this.helper.css( "opacity" ) ) {
				this._storedOpacity = this.helper.css( "opacity" );
			}
			this.helper.css( "opacity", o.opacity );
		}

		if ( o.zIndex ) { // zIndex option
			if ( this.helper.css( "zIndex" ) ) {
				this._storedZIndex = this.helper.css( "zIndex" );
			}
			this.helper.css( "zIndex", o.zIndex );
		}

		//Prepare scrolling
		if ( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				this.scrollParent[ 0 ].tagName !== "HTML" ) {
			this.overflowOffset = this.scrollParent.offset();
		}

		//Call callbacks
		this._trigger( "start", event, this._uiHash() );

		//Recache the helper size
		if ( !this._preserveHelperProportions ) {
			this._cacheHelperProportions();
		}

		//Post "activate" events to possible containers
		if ( !noActivation ) {
			for ( i = this.containers.length - 1; i >= 0; i-- ) {
				this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
			}
		}

		//Prepare possible droppables
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.current = this;
		}

		if ( $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( this, event );
		}

		this.dragging = true;

		this._addClass( this.helper, "ui-sortable-helper" );

		// Execute the drag once - this causes the helper not to be visiblebefore getting its
		// correct position
		this._mouseDrag( event );
		return true;

	},

	_mouseDrag: function( event ) {
		var i, item, itemElement, intersection,
			o = this.options,
			scrolled = false;

		//Compute the helpers position
		this.position = this._generatePosition( event );
		this.positionAbs = this._convertPositionTo( "absolute" );

		if ( !this.lastPositionAbs ) {
			this.lastPositionAbs = this.positionAbs;
		}

		//Do scrolling
		if ( this.options.scroll ) {
			if ( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
					this.scrollParent[ 0 ].tagName !== "HTML" ) {

				if ( ( this.overflowOffset.top + this.scrollParent[ 0 ].offsetHeight ) -
						event.pageY < o.scrollSensitivity ) {
					this.scrollParent[ 0 ].scrollTop =
						scrolled = this.scrollParent[ 0 ].scrollTop + o.scrollSpeed;
				} else if ( event.pageY - this.overflowOffset.top < o.scrollSensitivity ) {
					this.scrollParent[ 0 ].scrollTop =
						scrolled = this.scrollParent[ 0 ].scrollTop - o.scrollSpeed;
				}

				if ( ( this.overflowOffset.left + this.scrollParent[ 0 ].offsetWidth ) -
						event.pageX < o.scrollSensitivity ) {
					this.scrollParent[ 0 ].scrollLeft = scrolled =
						this.scrollParent[ 0 ].scrollLeft + o.scrollSpeed;
				} else if ( event.pageX - this.overflowOffset.left < o.scrollSensitivity ) {
					this.scrollParent[ 0 ].scrollLeft = scrolled =
						this.scrollParent[ 0 ].scrollLeft - o.scrollSpeed;
				}

			} else {

				if ( event.pageY - this.document.scrollTop() < o.scrollSensitivity ) {
					scrolled = this.document.scrollTop( this.document.scrollTop() - o.scrollSpeed );
				} else if ( this.window.height() - ( event.pageY - this.document.scrollTop() ) <
						o.scrollSensitivity ) {
					scrolled = this.document.scrollTop( this.document.scrollTop() + o.scrollSpeed );
				}

				if ( event.pageX - this.document.scrollLeft() < o.scrollSensitivity ) {
					scrolled = this.document.scrollLeft(
						this.document.scrollLeft() - o.scrollSpeed
					);
				} else if ( this.window.width() - ( event.pageX - this.document.scrollLeft() ) <
						o.scrollSensitivity ) {
					scrolled = this.document.scrollLeft(
						this.document.scrollLeft() + o.scrollSpeed
					);
				}

			}

			if ( scrolled !== false && $.ui.ddmanager && !o.dropBehaviour ) {
				$.ui.ddmanager.prepareOffsets( this, event );
			}
		}

		//Regenerate the absolute position used for position checks
		this.positionAbs = this._convertPositionTo( "absolute" );

		//Set the helper position
		if ( !this.options.axis || this.options.axis !== "y" ) {
			this.helper[ 0 ].style.left = this.position.left + "px";
		}
		if ( !this.options.axis || this.options.axis !== "x" ) {
			this.helper[ 0 ].style.top = this.position.top + "px";
		}

		//Rearrange
		for ( i = this.items.length - 1; i >= 0; i-- ) {

			//Cache variables and intersection, continue if no intersection
			item = this.items[ i ];
			itemElement = item.item[ 0 ];
			intersection = this._intersectsWithPointer( item );
			if ( !intersection ) {
				continue;
			}

			// Only put the placeholder inside the current Container, skip all
			// items from other containers. This works because when moving
			// an item from one container to another the
			// currentContainer is switched before the placeholder is moved.
			//
			// Without this, moving items in "sub-sortables" can cause
			// the placeholder to jitter between the outer and inner container.
			if ( item.instance !== this.currentContainer ) {
				continue;
			}

			// Cannot intersect with itself
			// no useless actions that have been done before
			// no action if the item moved is the parent of the item checked
			if ( itemElement !== this.currentItem[ 0 ] &&
				this.placeholder[ intersection === 1 ? "next" : "prev" ]()[ 0 ] !== itemElement &&
				!$.contains( this.placeholder[ 0 ], itemElement ) &&
				( this.options.type === "semi-dynamic" ?
					!$.contains( this.element[ 0 ], itemElement ) :
					true
				)
			) {

				this.direction = intersection === 1 ? "down" : "up";

				if ( this.options.tolerance === "pointer" || this._intersectsWithSides( item ) ) {
					this._rearrange( event, item );
				} else {
					break;
				}

				this._trigger( "change", event, this._uiHash() );
				break;
			}
		}

		//Post events to containers
		this._contactContainers( event );

		//Interconnect with droppables
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.drag( this, event );
		}

		//Call callbacks
		this._trigger( "sort", event, this._uiHash() );

		this.lastPositionAbs = this.positionAbs;
		return false;

	},

	_mouseStop: function( event, noPropagation ) {

		if ( !event ) {
			return;
		}

		//If we are using droppables, inform the manager about the drop
		if ( $.ui.ddmanager && !this.options.dropBehaviour ) {
			$.ui.ddmanager.drop( this, event );
		}

		if ( this.options.revert ) {
			var that = this,
				cur = this.placeholder.offset(),
				axis = this.options.axis,
				animation = {};

			if ( !axis || axis === "x" ) {
				animation.left = cur.left - this.offset.parent.left - this.margins.left +
					( this.offsetParent[ 0 ] === this.document[ 0 ].body ?
						0 :
						this.offsetParent[ 0 ].scrollLeft
					);
			}
			if ( !axis || axis === "y" ) {
				animation.top = cur.top - this.offset.parent.top - this.margins.top +
					( this.offsetParent[ 0 ] === this.document[ 0 ].body ?
						0 :
						this.offsetParent[ 0 ].scrollTop
					);
			}
			this.reverting = true;
			$( this.helper ).animate(
				animation,
				parseInt( this.options.revert, 10 ) || 500,
				function() {
					that._clear( event );
				}
			);
		} else {
			this._clear( event, noPropagation );
		}

		return false;

	},

	cancel: function() {

		if ( this.dragging ) {

			this._mouseUp( new $.Event( "mouseup", { target: null } ) );

			if ( this.options.helper === "original" ) {
				this.currentItem.css( this._storedCSS );
				this._removeClass( this.currentItem, "ui-sortable-helper" );
			} else {
				this.currentItem.show();
			}

			//Post deactivating events to containers
			for ( var i = this.containers.length - 1; i >= 0; i-- ) {
				this.containers[ i ]._trigger( "deactivate", null, this._uiHash( this ) );
				if ( this.containers[ i ].containerCache.over ) {
					this.containers[ i ]._trigger( "out", null, this._uiHash( this ) );
					this.containers[ i ].containerCache.over = 0;
				}
			}

		}

		if ( this.placeholder ) {

			//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
			// it unbinds ALL events from the original node!
			if ( this.placeholder[ 0 ].parentNode ) {
				this.placeholder[ 0 ].parentNode.removeChild( this.placeholder[ 0 ] );
			}
			if ( this.options.helper !== "original" && this.helper &&
					this.helper[ 0 ].parentNode ) {
				this.helper.remove();
			}

			$.extend( this, {
				helper: null,
				dragging: false,
				reverting: false,
				_noFinalSort: null
			} );

			if ( this.domPosition.prev ) {
				$( this.domPosition.prev ).after( this.currentItem );
			} else {
				$( this.domPosition.parent ).prepend( this.currentItem );
			}
		}

		return this;

	},

	serialize: function( o ) {

		var items = this._getItemsAsjQuery( o && o.connected ),
			str = [];
		o = o || {};

		$( items ).each( function() {
			var res = ( $( o.item || this ).attr( o.attribute || "id" ) || "" )
				.match( o.expression || ( /(.+)[\-=_](.+)/ ) );
			if ( res ) {
				str.push(
					( o.key || res[ 1 ] + "[]" ) +
					"=" + ( o.key && o.expression ? res[ 1 ] : res[ 2 ] ) );
			}
		} );

		if ( !str.length && o.key ) {
			str.push( o.key + "=" );
		}

		return str.join( "&" );

	},

	toArray: function( o ) {

		var items = this._getItemsAsjQuery( o && o.connected ),
			ret = [];

		o = o || {};

		items.each( function() {
			ret.push( $( o.item || this ).attr( o.attribute || "id" ) || "" );
		} );
		return ret;

	},

	/* Be careful with the following core functions */
	_intersectsWith: function( item ) {

		var x1 = this.positionAbs.left,
			x2 = x1 + this.helperProportions.width,
			y1 = this.positionAbs.top,
			y2 = y1 + this.helperProportions.height,
			l = item.left,
			r = l + item.width,
			t = item.top,
			b = t + item.height,
			dyClick = this.offset.click.top,
			dxClick = this.offset.click.left,
			isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t &&
				( y1 + dyClick ) < b ),
			isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l &&
				( x1 + dxClick ) < r ),
			isOverElement = isOverElementHeight && isOverElementWidth;

		if ( this.options.tolerance === "pointer" ||
			this.options.forcePointerForContainers ||
			( this.options.tolerance !== "pointer" &&
				this.helperProportions[ this.floating ? "width" : "height" ] >
				item[ this.floating ? "width" : "height" ] )
		) {
			return isOverElement;
		} else {

			return ( l < x1 + ( this.helperProportions.width / 2 ) && // Right Half
				x2 - ( this.helperProportions.width / 2 ) < r && // Left Half
				t < y1 + ( this.helperProportions.height / 2 ) && // Bottom Half
				y2 - ( this.helperProportions.height / 2 ) < b ); // Top Half

		}
	},

	_intersectsWithPointer: function( item ) {
		var verticalDirection, horizontalDirection,
			isOverElementHeight = ( this.options.axis === "x" ) ||
				this._isOverAxis(
					this.positionAbs.top + this.offset.click.top, item.top, item.height ),
			isOverElementWidth = ( this.options.axis === "y" ) ||
				this._isOverAxis(
					this.positionAbs.left + this.offset.click.left, item.left, item.width ),
			isOverElement = isOverElementHeight && isOverElementWidth;

		if ( !isOverElement ) {
			return false;
		}

		verticalDirection = this._getDragVerticalDirection();
		horizontalDirection = this._getDragHorizontalDirection();

		return this.floating ?
			( ( horizontalDirection === "right" || verticalDirection === "down" ) ? 2 : 1 )
			: ( verticalDirection && ( verticalDirection === "down" ? 2 : 1 ) );

	},

	_intersectsWithSides: function( item ) {

		var isOverBottomHalf = this._isOverAxis( this.positionAbs.top +
				this.offset.click.top, item.top + ( item.height / 2 ), item.height ),
			isOverRightHalf = this._isOverAxis( this.positionAbs.left +
				this.offset.click.left, item.left + ( item.width / 2 ), item.width ),
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if ( this.floating && horizontalDirection ) {
			return ( ( horizontalDirection === "right" && isOverRightHalf ) ||
				( horizontalDirection === "left" && !isOverRightHalf ) );
		} else {
			return verticalDirection && ( ( verticalDirection === "down" && isOverBottomHalf ) ||
				( verticalDirection === "up" && !isOverBottomHalf ) );
		}

	},

	_getDragVerticalDirection: function() {
		var delta = this.positionAbs.top - this.lastPositionAbs.top;
		return delta !== 0 && ( delta > 0 ? "down" : "up" );
	},

	_getDragHorizontalDirection: function() {
		var delta = this.positionAbs.left - this.lastPositionAbs.left;
		return delta !== 0 && ( delta > 0 ? "right" : "left" );
	},

	refresh: function( event ) {
		this._refreshItems( event );
		this._setHandleClassName();
		this.refreshPositions();
		return this;
	},

	_connectWith: function() {
		var options = this.options;
		return options.connectWith.constructor === String ?
			[ options.connectWith ] :
			options.connectWith;
	},

	_getItemsAsjQuery: function( connected ) {

		var i, j, cur, inst,
			items = [],
			queries = [],
			connectWith = this._connectWith();

		if ( connectWith && connected ) {
			for ( i = connectWith.length - 1; i >= 0; i-- ) {
				cur = $( connectWith[ i ], this.document[ 0 ] );
				for ( j = cur.length - 1; j >= 0; j-- ) {
					inst = $.data( cur[ j ], this.widgetFullName );
					if ( inst && inst !== this && !inst.options.disabled ) {
						queries.push( [ $.isFunction( inst.options.items ) ?
							inst.options.items.call( inst.element ) :
							$( inst.options.items, inst.element )
								.not( ".ui-sortable-helper" )
								.not( ".ui-sortable-placeholder" ), inst ] );
					}
				}
			}
		}

		queries.push( [ $.isFunction( this.options.items ) ?
			this.options.items
				.call( this.element, null, { options: this.options, item: this.currentItem } ) :
			$( this.options.items, this.element )
				.not( ".ui-sortable-helper" )
				.not( ".ui-sortable-placeholder" ), this ] );

		function addItems() {
			items.push( this );
		}
		for ( i = queries.length - 1; i >= 0; i-- ) {
			queries[ i ][ 0 ].each( addItems );
		}

		return $( items );

	},

	_removeCurrentsFromItems: function() {

		var list = this.currentItem.find( ":data(" + this.widgetName + "-item)" );

		this.items = $.grep( this.items, function( item ) {
			for ( var j = 0; j < list.length; j++ ) {
				if ( list[ j ] === item.item[ 0 ] ) {
					return false;
				}
			}
			return true;
		} );

	},

	_refreshItems: function( event ) {

		this.items = [];
		this.containers = [ this ];

		var i, j, cur, inst, targetData, _queries, item, queriesLength,
			items = this.items,
			queries = [ [ $.isFunction( this.options.items ) ?
				this.options.items.call( this.element[ 0 ], event, { item: this.currentItem } ) :
				$( this.options.items, this.element ), this ] ],
			connectWith = this._connectWith();

		//Shouldn't be run the first time through due to massive slow-down
		if ( connectWith && this.ready ) {
			for ( i = connectWith.length - 1; i >= 0; i-- ) {
				cur = $( connectWith[ i ], this.document[ 0 ] );
				for ( j = cur.length - 1; j >= 0; j-- ) {
					inst = $.data( cur[ j ], this.widgetFullName );
					if ( inst && inst !== this && !inst.options.disabled ) {
						queries.push( [ $.isFunction( inst.options.items ) ?
							inst.options.items
								.call( inst.element[ 0 ], event, { item: this.currentItem } ) :
							$( inst.options.items, inst.element ), inst ] );
						this.containers.push( inst );
					}
				}
			}
		}

		for ( i = queries.length - 1; i >= 0; i-- ) {
			targetData = queries[ i ][ 1 ];
			_queries = queries[ i ][ 0 ];

			for ( j = 0, queriesLength = _queries.length; j < queriesLength; j++ ) {
				item = $( _queries[ j ] );

				// Data for target checking (mouse manager)
				item.data( this.widgetName + "-item", targetData );

				items.push( {
					item: item,
					instance: targetData,
					width: 0, height: 0,
					left: 0, top: 0
				} );
			}
		}

	},

	refreshPositions: function( fast ) {

		// Determine whether items are being displayed horizontally
		this.floating = this.items.length ?
			this.options.axis === "x" || this._isFloating( this.items[ 0 ].item ) :
			false;

		//This has to be redone because due to the item being moved out/into the offsetParent,
		// the offsetParent's position will change
		if ( this.offsetParent && this.helper ) {
			this.offset.parent = this._getParentOffset();
		}

		var i, item, t, p;

		for ( i = this.items.length - 1; i >= 0; i-- ) {
			item = this.items[ i ];

			//We ignore calculating positions of all connected containers when we're not over them
			if ( item.instance !== this.currentContainer && this.currentContainer &&
					item.item[ 0 ] !== this.currentItem[ 0 ] ) {
				continue;
			}

			t = this.options.toleranceElement ?
				$( this.options.toleranceElement, item.item ) :
				item.item;

			if ( !fast ) {
				item.width = t.outerWidth();
				item.height = t.outerHeight();
			}

			p = t.offset();
			item.left = p.left;
			item.top = p.top;
		}

		if ( this.options.custom && this.options.custom.refreshContainers ) {
			this.options.custom.refreshContainers.call( this );
		} else {
			for ( i = this.containers.length - 1; i >= 0; i-- ) {
				p = this.containers[ i ].element.offset();
				this.containers[ i ].containerCache.left = p.left;
				this.containers[ i ].containerCache.top = p.top;
				this.containers[ i ].containerCache.width =
					this.containers[ i ].element.outerWidth();
				this.containers[ i ].containerCache.height =
					this.containers[ i ].element.outerHeight();
			}
		}

		return this;
	},

	_createPlaceholder: function( that ) {
		that = that || this;
		var className,
			o = that.options;

		if ( !o.placeholder || o.placeholder.constructor === String ) {
			className = o.placeholder;
			o.placeholder = {
				element: function() {

					var nodeName = that.currentItem[ 0 ].nodeName.toLowerCase(),
						element = $( "<" + nodeName + ">", that.document[ 0 ] );

						that._addClass( element, "ui-sortable-placeholder",
								className || that.currentItem[ 0 ].className )
							._removeClass( element, "ui-sortable-helper" );

					if ( nodeName === "tbody" ) {
						that._createTrPlaceholder(
							that.currentItem.find( "tr" ).eq( 0 ),
							$( "<tr>", that.document[ 0 ] ).appendTo( element )
						);
					} else if ( nodeName === "tr" ) {
						that._createTrPlaceholder( that.currentItem, element );
					} else if ( nodeName === "img" ) {
						element.attr( "src", that.currentItem.attr( "src" ) );
					}

					if ( !className ) {
						element.css( "visibility", "hidden" );
					}

					return element;
				},
				update: function( container, p ) {

					// 1. If a className is set as 'placeholder option, we don't force sizes -
					// the class is responsible for that
					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a
					// class name is specified
					if ( className && !o.forcePlaceholderSize ) {
						return;
					}

					//If the element doesn't have a actual height by itself (without styles coming
					// from a stylesheet), it receives the inline height from the dragged item
					if ( !p.height() ) {
						p.height(
							that.currentItem.innerHeight() -
							parseInt( that.currentItem.css( "paddingTop" ) || 0, 10 ) -
							parseInt( that.currentItem.css( "paddingBottom" ) || 0, 10 ) );
					}
					if ( !p.width() ) {
						p.width(
							that.currentItem.innerWidth() -
							parseInt( that.currentItem.css( "paddingLeft" ) || 0, 10 ) -
							parseInt( that.currentItem.css( "paddingRight" ) || 0, 10 ) );
					}
				}
			};
		}

		//Create the placeholder
		that.placeholder = $( o.placeholder.element.call( that.element, that.currentItem ) );

		//Append it after the actual current item
		that.currentItem.after( that.placeholder );

		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
		o.placeholder.update( that, that.placeholder );

	},

	_createTrPlaceholder: function( sourceTr, targetTr ) {
		var that = this;

		sourceTr.children().each( function() {
			$( "<td>&#160;</td>", that.document[ 0 ] )
				.attr( "colspan", $( this ).attr( "colspan" ) || 1 )
				.appendTo( targetTr );
		} );
	},

	_contactContainers: function( event ) {
		var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom,
			floating, axis,
			innermostContainer = null,
			innermostIndex = null;

		// Get innermost container that intersects with item
		for ( i = this.containers.length - 1; i >= 0; i-- ) {

			// Never consider a container that's located within the item itself
			if ( $.contains( this.currentItem[ 0 ], this.containers[ i ].element[ 0 ] ) ) {
				continue;
			}

			if ( this._intersectsWith( this.containers[ i ].containerCache ) ) {

				// If we've already found a container and it's more "inner" than this, then continue
				if ( innermostContainer &&
						$.contains(
							this.containers[ i ].element[ 0 ],
							innermostContainer.element[ 0 ] ) ) {
					continue;
				}

				innermostContainer = this.containers[ i ];
				innermostIndex = i;

			} else {

				// container doesn't intersect. trigger "out" event if necessary
				if ( this.containers[ i ].containerCache.over ) {
					this.containers[ i ]._trigger( "out", event, this._uiHash( this ) );
					this.containers[ i ].containerCache.over = 0;
				}
			}

		}

		// If no intersecting containers found, return
		if ( !innermostContainer ) {
			return;
		}

		// Move the item into the container if it's not there already
		if ( this.containers.length === 1 ) {
			if ( !this.containers[ innermostIndex ].containerCache.over ) {
				this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash( this ) );
				this.containers[ innermostIndex ].containerCache.over = 1;
			}
		} else {

			// When entering a new container, we will find the item with the least distance and
			// append our item near it
			dist = 10000;
			itemWithLeastDistance = null;
			floating = innermostContainer.floating || this._isFloating( this.currentItem );
			posProperty = floating ? "left" : "top";
			sizeProperty = floating ? "width" : "height";
			axis = floating ? "pageX" : "pageY";

			for ( j = this.items.length - 1; j >= 0; j-- ) {
				if ( !$.contains(
						this.containers[ innermostIndex ].element[ 0 ], this.items[ j ].item[ 0 ] )
				) {
					continue;
				}
				if ( this.items[ j ].item[ 0 ] === this.currentItem[ 0 ] ) {
					continue;
				}

				cur = this.items[ j ].item.offset()[ posProperty ];
				nearBottom = false;
				if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) {
					nearBottom = true;
				}

				if ( Math.abs( event[ axis ] - cur ) < dist ) {
					dist = Math.abs( event[ axis ] - cur );
					itemWithLeastDistance = this.items[ j ];
					this.direction = nearBottom ? "up" : "down";
				}
			}

			//Check if dropOnEmpty is enabled
			if ( !itemWithLeastDistance && !this.options.dropOnEmpty ) {
				return;
			}

			if ( this.currentContainer === this.containers[ innermostIndex ] ) {
				if ( !this.currentContainer.containerCache.over ) {
					this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash() );
					this.currentContainer.containerCache.over = 1;
				}
				return;
			}

			itemWithLeastDistance ?
				this._rearrange( event, itemWithLeastDistance, null, true ) :
				this._rearrange( event, null, this.containers[ innermostIndex ].element, true );
			this._trigger( "change", event, this._uiHash() );
			this.containers[ innermostIndex ]._trigger( "change", event, this._uiHash( this ) );
			this.currentContainer = this.containers[ innermostIndex ];

			//Update the placeholder
			this.options.placeholder.update( this.currentContainer, this.placeholder );

			this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash( this ) );
			this.containers[ innermostIndex ].containerCache.over = 1;
		}

	},

	_createHelper: function( event ) {

		var o = this.options,
			helper = $.isFunction( o.helper ) ?
				$( o.helper.apply( this.element[ 0 ], [ event, this.currentItem ] ) ) :
				( o.helper === "clone" ? this.currentItem.clone() : this.currentItem );

		//Add the helper to the DOM if that didn't happen already
		if ( !helper.parents( "body" ).length ) {
			$( o.appendTo !== "parent" ?
				o.appendTo :
				this.currentItem[ 0 ].parentNode )[ 0 ].appendChild( helper[ 0 ] );
		}

		if ( helper[ 0 ] === this.currentItem[ 0 ] ) {
			this._storedCSS = {
				width: this.currentItem[ 0 ].style.width,
				height: this.currentItem[ 0 ].style.height,
				position: this.currentItem.css( "position" ),
				top: this.currentItem.css( "top" ),
				left: this.currentItem.css( "left" )
			};
		}

		if ( !helper[ 0 ].style.width || o.forceHelperSize ) {
			helper.width( this.currentItem.width() );
		}
		if ( !helper[ 0 ].style.height || o.forceHelperSize ) {
			helper.height( this.currentItem.height() );
		}

		return helper;

	},

	_adjustOffsetFromHelper: function( obj ) {
		if ( typeof obj === "string" ) {
			obj = obj.split( " " );
		}
		if ( $.isArray( obj ) ) {
			obj = { left: +obj[ 0 ], top: +obj[ 1 ] || 0 };
		}
		if ( "left" in obj ) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ( "right" in obj ) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ( "top" in obj ) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ( "bottom" in obj ) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the
		// following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the
		// next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
		// the document, which means that the scroll is included in the initial calculation of the
		// offset of the parent, and never recalculated upon drag
		if ( this.cssPosition === "absolute" && this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		// This needs to be actually done for all browsers, since pageX/pageY includes this
		// information with an ugly IE fix
		if ( this.offsetParent[ 0 ] === this.document[ 0 ].body ||
				( this.offsetParent[ 0 ].tagName &&
				this.offsetParent[ 0 ].tagName.toLowerCase() === "html" && $.ui.ie ) ) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + ( parseInt( this.offsetParent.css( "borderTopWidth" ), 10 ) || 0 ),
			left: po.left + ( parseInt( this.offsetParent.css( "borderLeftWidth" ), 10 ) || 0 )
		};

	},

	_getRelativeOffset: function() {

		if ( this.cssPosition === "relative" ) {
			var p = this.currentItem.position();
			return {
				top: p.top - ( parseInt( this.helper.css( "top" ), 10 ) || 0 ) +
					this.scrollParent.scrollTop(),
				left: p.left - ( parseInt( this.helper.css( "left" ), 10 ) || 0 ) +
					this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: ( parseInt( this.currentItem.css( "marginLeft" ), 10 ) || 0 ),
			top: ( parseInt( this.currentItem.css( "marginTop" ), 10 ) || 0 )
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var ce, co, over,
			o = this.options;
		if ( o.containment === "parent" ) {
			o.containment = this.helper[ 0 ].parentNode;
		}
		if ( o.containment === "document" || o.containment === "window" ) {
			this.containment = [
				0 - this.offset.relative.left - this.offset.parent.left,
				0 - this.offset.relative.top - this.offset.parent.top,
				o.containment === "document" ?
					this.document.width() :
					this.window.width() - this.helperProportions.width - this.margins.left,
				( o.containment === "document" ?
					( this.document.height() || document.body.parentNode.scrollHeight ) :
					this.window.height() || this.document[ 0 ].body.parentNode.scrollHeight
				) - this.helperProportions.height - this.margins.top
			];
		}

		if ( !( /^(document|window|parent)$/ ).test( o.containment ) ) {
			ce = $( o.containment )[ 0 ];
			co = $( o.containment ).offset();
			over = ( $( ce ).css( "overflow" ) !== "hidden" );

			this.containment = [
				co.left + ( parseInt( $( ce ).css( "borderLeftWidth" ), 10 ) || 0 ) +
					( parseInt( $( ce ).css( "paddingLeft" ), 10 ) || 0 ) - this.margins.left,
				co.top + ( parseInt( $( ce ).css( "borderTopWidth" ), 10 ) || 0 ) +
					( parseInt( $( ce ).css( "paddingTop" ), 10 ) || 0 ) - this.margins.top,
				co.left + ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
					( parseInt( $( ce ).css( "borderLeftWidth" ), 10 ) || 0 ) -
					( parseInt( $( ce ).css( "paddingRight" ), 10 ) || 0 ) -
					this.helperProportions.width - this.margins.left,
				co.top + ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
					( parseInt( $( ce ).css( "borderTopWidth" ), 10 ) || 0 ) -
					( parseInt( $( ce ).css( "paddingBottom" ), 10 ) || 0 ) -
					this.helperProportions.height - this.margins.top
			];
		}

	},

	_convertPositionTo: function( d, pos ) {

		if ( !pos ) {
			pos = this.position;
		}
		var mod = d === "absolute" ? 1 : -1,
			scroll = this.cssPosition === "absolute" &&
				!( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ?
					this.offsetParent :
					this.scrollParent,
			scrollIsRootNode = ( /(html|body)/i ).test( scroll[ 0 ].tagName );

		return {
			top: (

				// The absolute mouse position
				pos.top	+

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top * mod -
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollTop() :
					( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod )
			),
			left: (

				// The absolute mouse position
				pos.left +

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left * mod	-
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 :
					scroll.scrollLeft() ) * mod )
			)
		};

	},

	_generatePosition: function( event ) {

		var top, left,
			o = this.options,
			pageX = event.pageX,
			pageY = event.pageY,
			scroll = this.cssPosition === "absolute" &&
				!( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ?
					this.offsetParent :
					this.scrollParent,
				scrollIsRootNode = ( /(html|body)/i ).test( scroll[ 0 ].tagName );

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if ( this.cssPosition === "relative" && !( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				this.scrollParent[ 0 ] !== this.offsetParent[ 0 ] ) ) {
			this.offset.relative = this._getRelativeOffset();
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if ( this.originalPosition ) { //If we are not dragging yet, we won't check for options

			if ( this.containment ) {
				if ( event.pageX - this.offset.click.left < this.containment[ 0 ] ) {
					pageX = this.containment[ 0 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top < this.containment[ 1 ] ) {
					pageY = this.containment[ 1 ] + this.offset.click.top;
				}
				if ( event.pageX - this.offset.click.left > this.containment[ 2 ] ) {
					pageX = this.containment[ 2 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top > this.containment[ 3 ] ) {
					pageY = this.containment[ 3 ] + this.offset.click.top;
				}
			}

			if ( o.grid ) {
				top = this.originalPageY + Math.round( ( pageY - this.originalPageY ) /
					o.grid[ 1 ] ) * o.grid[ 1 ];
				pageY = this.containment ?
					( ( top - this.offset.click.top >= this.containment[ 1 ] &&
						top - this.offset.click.top <= this.containment[ 3 ] ) ?
							top :
							( ( top - this.offset.click.top >= this.containment[ 1 ] ) ?
								top - o.grid[ 1 ] : top + o.grid[ 1 ] ) ) :
								top;

				left = this.originalPageX + Math.round( ( pageX - this.originalPageX ) /
					o.grid[ 0 ] ) * o.grid[ 0 ];
				pageX = this.containment ?
					( ( left - this.offset.click.left >= this.containment[ 0 ] &&
						left - this.offset.click.left <= this.containment[ 2 ] ) ?
							left :
							( ( left - this.offset.click.left >= this.containment[ 0 ] ) ?
								left - o.grid[ 0 ] : left + o.grid[ 0 ] ) ) :
								left;
			}

		}

		return {
			top: (

				// The absolute mouse position
				pageY -

				// Click offset (relative to the element)
				this.offset.click.top -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top +
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollTop() :
					( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) )
			),
			left: (

				// The absolute mouse position
				pageX -

				// Click offset (relative to the element)
				this.offset.click.left -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left +
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollLeft() :
					scrollIsRootNode ? 0 : scroll.scrollLeft() ) )
			)
		};

	},

	_rearrange: function( event, i, a, hardRefresh ) {

		a ? a[ 0 ].appendChild( this.placeholder[ 0 ] ) :
			i.item[ 0 ].parentNode.insertBefore( this.placeholder[ 0 ],
				( this.direction === "down" ? i.item[ 0 ] : i.item[ 0 ].nextSibling ) );

		//Various things done here to improve the performance:
		// 1. we create a setTimeout, that calls refreshPositions
		// 2. on the instance, we have a counter variable, that get's higher after every append
		// 3. on the local scope, we copy the counter variable, and check in the timeout,
		// if it's still the same
		// 4. this lets only the last addition to the timeout stack through
		this.counter = this.counter ? ++this.counter : 1;
		var counter = this.counter;

		this._delay( function() {
			if ( counter === this.counter ) {

				//Precompute after each DOM insertion, NOT on mousemove
				this.refreshPositions( !hardRefresh );
			}
		} );

	},

	_clear: function( event, noPropagation ) {

		this.reverting = false;

		// We delay all events that have to be triggered to after the point where the placeholder
		// has been removed and everything else normalized again
		var i,
			delayedTriggers = [];

		// We first have to update the dom position of the actual currentItem
		// Note: don't do it if the current item is already removed (by a user), or it gets
		// reappended (see #4088)
		if ( !this._noFinalSort && this.currentItem.parent().length ) {
			this.placeholder.before( this.currentItem );
		}
		this._noFinalSort = null;

		if ( this.helper[ 0 ] === this.currentItem[ 0 ] ) {
			for ( i in this._storedCSS ) {
				if ( this._storedCSS[ i ] === "auto" || this._storedCSS[ i ] === "static" ) {
					this._storedCSS[ i ] = "";
				}
			}
			this.currentItem.css( this._storedCSS );
			this._removeClass( this.currentItem, "ui-sortable-helper" );
		} else {
			this.currentItem.show();
		}

		if ( this.fromOutside && !noPropagation ) {
			delayedTriggers.push( function( event ) {
				this._trigger( "receive", event, this._uiHash( this.fromOutside ) );
			} );
		}
		if ( ( this.fromOutside ||
				this.domPosition.prev !==
				this.currentItem.prev().not( ".ui-sortable-helper" )[ 0 ] ||
				this.domPosition.parent !== this.currentItem.parent()[ 0 ] ) && !noPropagation ) {

			// Trigger update callback if the DOM position has changed
			delayedTriggers.push( function( event ) {
				this._trigger( "update", event, this._uiHash() );
			} );
		}

		// Check if the items Container has Changed and trigger appropriate
		// events.
		if ( this !== this.currentContainer ) {
			if ( !noPropagation ) {
				delayedTriggers.push( function( event ) {
					this._trigger( "remove", event, this._uiHash() );
				} );
				delayedTriggers.push( ( function( c ) {
					return function( event ) {
						c._trigger( "receive", event, this._uiHash( this ) );
					};
				} ).call( this, this.currentContainer ) );
				delayedTriggers.push( ( function( c ) {
					return function( event ) {
						c._trigger( "update", event, this._uiHash( this ) );
					};
				} ).call( this, this.currentContainer ) );
			}
		}

		//Post events to containers
		function delayEvent( type, instance, container ) {
			return function( event ) {
				container._trigger( type, event, instance._uiHash( instance ) );
			};
		}
		for ( i = this.containers.length - 1; i >= 0; i-- ) {
			if ( !noPropagation ) {
				delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) );
			}
			if ( this.containers[ i ].containerCache.over ) {
				delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) );
				this.containers[ i ].containerCache.over = 0;
			}
		}

		//Do what was originally in plugins
		if ( this.storedCursor ) {
			this.document.find( "body" ).css( "cursor", this.storedCursor );
			this.storedStylesheet.remove();
		}
		if ( this._storedOpacity ) {
			this.helper.css( "opacity", this._storedOpacity );
		}
		if ( this._storedZIndex ) {
			this.helper.css( "zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex );
		}

		this.dragging = false;

		if ( !noPropagation ) {
			this._trigger( "beforeStop", event, this._uiHash() );
		}

		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
		// it unbinds ALL events from the original node!
		this.placeholder[ 0 ].parentNode.removeChild( this.placeholder[ 0 ] );

		if ( !this.cancelHelperRemoval ) {
			if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
				this.helper.remove();
			}
			this.helper = null;
		}

		if ( !noPropagation ) {
			for ( i = 0; i < delayedTriggers.length; i++ ) {

				// Trigger all delayed events
				delayedTriggers[ i ].call( this, event );
			}
			this._trigger( "stop", event, this._uiHash() );
		}

		this.fromOutside = false;
		return !this.cancelHelperRemoval;

	},

	_trigger: function() {
		if ( $.Widget.prototype._trigger.apply( this, arguments ) === false ) {
			this.cancel();
		}
	},

	_uiHash: function( _inst ) {
		var inst = _inst || this;
		return {
			helper: inst.helper,
			placeholder: inst.placeholder || $( [] ),
			position: inst.position,
			originalPosition: inst.originalPosition,
			offset: inst.positionAbs,
			item: inst.currentItem,
			sender: _inst ? _inst.element : null
		};
	}

} );


/*!
 * jQuery UI Slider 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Slider
//>>group: Widgets
//>>description: Displays a flexible slider with ranges and accessibility via keyboard.
//>>docs: http://api.jqueryui.com/slider/
//>>demos: http://jqueryui.com/slider/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/slider.css
//>>css.theme: ../../themes/base/theme.css



var widgetsSlider = $.widget( "ui.slider", $.ui.mouse, {
	version: "1.12.1",
	widgetEventPrefix: "slide",

	options: {
		animate: false,
		classes: {
			"ui-slider": "ui-corner-all",
			"ui-slider-handle": "ui-corner-all",

			// Note: ui-widget-header isn't the most fittingly semantic framework class for this
			// element, but worked best visually with a variety of themes
			"ui-slider-range": "ui-corner-all ui-widget-header"
		},
		distance: 0,
		max: 100,
		min: 0,
		orientation: "horizontal",
		range: false,
		step: 1,
		value: 0,
		values: null,

		// Callbacks
		change: null,
		slide: null,
		start: null,
		stop: null
	},

	// Number of pages in a slider
	// (how many times can you page up/down to go through the whole range)
	numPages: 5,

	_create: function() {
		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();
		this._calculateNewMax();

		this._addClass( "ui-slider ui-slider-" + this.orientation,
			"ui-widget ui-widget-content" );

		this._refresh();

		this._animateOff = false;
	},

	_refresh: function() {
		this._createRange();
		this._createHandles();
		this._setupEvents();
		this._refreshValue();
	},

	_createHandles: function() {
		var i, handleCount,
			options = this.options,
			existingHandles = this.element.find( ".ui-slider-handle" ),
			handle = "<span tabindex='0'></span>",
			handles = [];

		handleCount = ( options.values && options.values.length ) || 1;

		if ( existingHandles.length > handleCount ) {
			existingHandles.slice( handleCount ).remove();
			existingHandles = existingHandles.slice( 0, handleCount );
		}

		for ( i = existingHandles.length; i < handleCount; i++ ) {
			handles.push( handle );
		}

		this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );

		this._addClass( this.handles, "ui-slider-handle", "ui-state-default" );

		this.handle = this.handles.eq( 0 );

		this.handles.each( function( i ) {
			$( this )
				.data( "ui-slider-handle-index", i )
				.attr( "tabIndex", 0 );
		} );
	},

	_createRange: function() {
		var options = this.options;

		if ( options.range ) {
			if ( options.range === true ) {
				if ( !options.values ) {
					options.values = [ this._valueMin(), this._valueMin() ];
				} else if ( options.values.length && options.values.length !== 2 ) {
					options.values = [ options.values[ 0 ], options.values[ 0 ] ];
				} else if ( $.isArray( options.values ) ) {
					options.values = options.values.slice( 0 );
				}
			}

			if ( !this.range || !this.range.length ) {
				this.range = $( "<div>" )
					.appendTo( this.element );

				this._addClass( this.range, "ui-slider-range" );
			} else {
				this._removeClass( this.range, "ui-slider-range-min ui-slider-range-max" );

				// Handle range switching from true to min/max
				this.range.css( {
					"left": "",
					"bottom": ""
				} );
			}
			if ( options.range === "min" || options.range === "max" ) {
				this._addClass( this.range, "ui-slider-range-" + options.range );
			}
		} else {
			if ( this.range ) {
				this.range.remove();
			}
			this.range = null;
		}
	},

	_setupEvents: function() {
		this._off( this.handles );
		this._on( this.handles, this._handleEvents );
		this._hoverable( this.handles );
		this._focusable( this.handles );
	},

	_destroy: function() {
		this.handles.remove();
		if ( this.range ) {
			this.range.remove();
		}

		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
			that = this,
			o = this.options;

		if ( o.disabled ) {
			return false;
		}

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		position = { x: event.pageX, y: event.pageY };
		normValue = this._normValueFromMouse( position );
		distance = this._valueMax() - this._valueMin() + 1;
		this.handles.each( function( i ) {
			var thisDistance = Math.abs( normValue - that.values( i ) );
			if ( ( distance > thisDistance ) ||
				( distance === thisDistance &&
					( i === that._lastChangedValue || that.values( i ) === o.min ) ) ) {
				distance = thisDistance;
				closestHandle = $( this );
				index = i;
			}
		} );

		allowed = this._start( event, index );
		if ( allowed === false ) {
			return false;
		}
		this._mouseSliding = true;

		this._handleIndex = index;

		this._addClass( closestHandle, null, "ui-state-active" );
		closestHandle.trigger( "focus" );

		offset = closestHandle.offset();
		mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
			top: event.pageY - offset.top -
				( closestHandle.height() / 2 ) -
				( parseInt( closestHandle.css( "borderTopWidth" ), 10 ) || 0 ) -
				( parseInt( closestHandle.css( "borderBottomWidth" ), 10 ) || 0 ) +
				( parseInt( closestHandle.css( "marginTop" ), 10 ) || 0 )
		};

		if ( !this.handles.hasClass( "ui-state-hover" ) ) {
			this._slide( event, index, normValue );
		}
		this._animateOff = true;
		return true;
	},

	_mouseStart: function() {
		return true;
	},

	_mouseDrag: function( event ) {
		var position = { x: event.pageX, y: event.pageY },
			normValue = this._normValueFromMouse( position );

		this._slide( event, this._handleIndex, normValue );

		return false;
	},

	_mouseStop: function( event ) {
		this._removeClass( this.handles, null, "ui-state-active" );
		this._mouseSliding = false;

		this._stop( event, this._handleIndex );
		this._change( event, this._handleIndex );

		this._handleIndex = null;
		this._clickOffset = null;
		this._animateOff = false;

		return false;
	},

	_detectOrientation: function() {
		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
	},

	_normValueFromMouse: function( position ) {
		var pixelTotal,
			pixelMouse,
			percentMouse,
			valueTotal,
			valueMouse;

		if ( this.orientation === "horizontal" ) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left -
				( this._clickOffset ? this._clickOffset.left : 0 );
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top -
				( this._clickOffset ? this._clickOffset.top : 0 );
		}

		percentMouse = ( pixelMouse / pixelTotal );
		if ( percentMouse > 1 ) {
			percentMouse = 1;
		}
		if ( percentMouse < 0 ) {
			percentMouse = 0;
		}
		if ( this.orientation === "vertical" ) {
			percentMouse = 1 - percentMouse;
		}

		valueTotal = this._valueMax() - this._valueMin();
		valueMouse = this._valueMin() + percentMouse * valueTotal;

		return this._trimAlignValue( valueMouse );
	},

	_uiHash: function( index, value, values ) {
		var uiHash = {
			handle: this.handles[ index ],
			handleIndex: index,
			value: value !== undefined ? value : this.value()
		};

		if ( this._hasMultipleValues() ) {
			uiHash.value = value !== undefined ? value : this.values( index );
			uiHash.values = values || this.values();
		}

		return uiHash;
	},

	_hasMultipleValues: function() {
		return this.options.values && this.options.values.length;
	},

	_start: function( event, index ) {
		return this._trigger( "start", event, this._uiHash( index ) );
	},

	_slide: function( event, index, newVal ) {
		var allowed, otherVal,
			currentValue = this.value(),
			newValues = this.values();

		if ( this._hasMultipleValues() ) {
			otherVal = this.values( index ? 0 : 1 );
			currentValue = this.values( index );

			if ( this.options.values.length === 2 && this.options.range === true ) {
				newVal =  index === 0 ? Math.min( otherVal, newVal ) : Math.max( otherVal, newVal );
			}

			newValues[ index ] = newVal;
		}

		if ( newVal === currentValue ) {
			return;
		}

		allowed = this._trigger( "slide", event, this._uiHash( index, newVal, newValues ) );

		// A slide can be canceled by returning false from the slide callback
		if ( allowed === false ) {
			return;
		}

		if ( this._hasMultipleValues() ) {
			this.values( index, newVal );
		} else {
			this.value( newVal );
		}
	},

	_stop: function( event, index ) {
		this._trigger( "stop", event, this._uiHash( index ) );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {

			//store the last changed value index for reference when handles overlap
			this._lastChangedValue = index;
			this._trigger( "change", event, this._uiHash( index ) );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( $.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this._hasMultipleValues() ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( key === "range" && this.options.range === true ) {
			if ( value === "min" ) {
				this.options.value = this._values( 0 );
				this.options.values = null;
			} else if ( value === "max" ) {
				this.options.value = this._values( this.options.values.length - 1 );
				this.options.values = null;
			}
		}

		if ( $.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		this._super( key, value );

		switch ( key ) {
			case "orientation":
				this._detectOrientation();
				this._removeClass( "ui-slider-horizontal ui-slider-vertical" )
					._addClass( "ui-slider-" + this.orientation );
				this._refreshValue();
				if ( this.options.range ) {
					this._refreshRange( value );
				}

				// Reset positioning from previous orientation
				this.handles.css( value === "horizontal" ? "bottom" : "left", "" );
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();

				// Start from the last handle to prevent unreachable handles (#9046)
				for ( i = valsLength - 1; i >= 0; i-- ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
			case "step":
			case "min":
			case "max":
				this._animateOff = true;
				this._calculateNewMax();
				this._refreshValue();
				this._animateOff = false;
				break;
			case "range":
				this._animateOff = true;
				this._refresh();
				this._animateOff = false;
				break;
		}
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	//internal value getter
	// _value() returns value trimmed by min and max, aligned by step
	_value: function() {
		var val = this.options.value;
		val = this._trimAlignValue( val );

		return val;
	},

	//internal values getter
	// _values() returns array of values trimmed by min and max, aligned by step
	// _values( index ) returns single value trimmed by min and max, aligned by step
	_values: function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else if ( this._hasMultipleValues() ) {

			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i += 1 ) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		} else {
			return [];
		}
	},

	// Returns the step-aligned value that val is closest to, between (inclusive) min and max
	_trimAlignValue: function( val ) {
		if ( val <= this._valueMin() ) {
			return this._valueMin();
		}
		if ( val >= this._valueMax() ) {
			return this._valueMax();
		}
		var step = ( this.options.step > 0 ) ? this.options.step : 1,
			valModStep = ( val - this._valueMin() ) % step,
			alignValue = val - valModStep;

		if ( Math.abs( valModStep ) * 2 >= step ) {
			alignValue += ( valModStep > 0 ) ? step : ( -step );
		}

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat( alignValue.toFixed( 5 ) );
	},

	_calculateNewMax: function() {
		var max = this.options.max,
			min = this._valueMin(),
			step = this.options.step,
			aboveMin = Math.round( ( max - min ) / step ) * step;
		max = aboveMin + min;
		if ( max > this.options.max ) {

			//If max is not divisible by step, rounding off may increase its value
			max -= step;
		}
		this.max = parseFloat( max.toFixed( this._precision() ) );
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.max;
	},

	_refreshRange: function( orientation ) {
		if ( orientation === "vertical" ) {
			this.range.css( { "width": "", "left": "" } );
		}
		if ( orientation === "horizontal" ) {
			this.range.css( { "height": "", "bottom": "" } );
		}
	},

	_refreshValue: function() {
		var lastValPercent, valPercent, value, valueMin, valueMax,
			oRange = this.options.range,
			o = this.options,
			that = this,
			animate = ( !this._animateOff ) ? o.animate : false,
			_set = {};

		if ( this._hasMultipleValues() ) {
			this.handles.each( function( i ) {
				valPercent = ( that.values( i ) - that._valueMin() ) / ( that._valueMax() -
					that._valueMin() ) * 100;
				_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
				if ( that.options.range === true ) {
					if ( that.orientation === "horizontal" ) {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								left: valPercent + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								width: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					} else {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								bottom: ( valPercent ) + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								height: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					}
				}
				lastValPercent = valPercent;
			} );
		} else {
			value = this.value();
			valueMin = this._valueMin();
			valueMax = this._valueMax();
			valPercent = ( valueMax !== valueMin ) ?
					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
					0;
			_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );

			if ( oRange === "min" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
			if ( oRange === "min" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
		}
	},

	_handleEvents: {
		keydown: function( event ) {
			var allowed, curVal, newVal, step,
				index = $( event.target ).data( "ui-slider-handle-index" );

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_UP:
				case $.ui.keyCode.PAGE_DOWN:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					event.preventDefault();
					if ( !this._keySliding ) {
						this._keySliding = true;
						this._addClass( $( event.target ), null, "ui-state-active" );
						allowed = this._start( event, index );
						if ( allowed === false ) {
							return;
						}
					}
					break;
			}

			step = this.options.step;
			if ( this._hasMultipleValues() ) {
				curVal = newVal = this.values( index );
			} else {
				curVal = newVal = this.value();
			}

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
					newVal = this._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = this._valueMax();
					break;
				case $.ui.keyCode.PAGE_UP:
					newVal = this._trimAlignValue(
						curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages )
					);
					break;
				case $.ui.keyCode.PAGE_DOWN:
					newVal = this._trimAlignValue(
						curVal - ( ( this._valueMax() - this._valueMin() ) / this.numPages ) );
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if ( curVal === this._valueMax() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal + step );
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if ( curVal === this._valueMin() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal - step );
					break;
			}

			this._slide( event, index, newVal );
		},
		keyup: function( event ) {
			var index = $( event.target ).data( "ui-slider-handle-index" );

			if ( this._keySliding ) {
				this._keySliding = false;
				this._stop( event, index );
				this._change( event, index );
				this._removeClass( $( event.target ), null, "ui-state-active" );
			}
		}
	}
} );




}));
﻿/*!
* jQuery UI Touch Punch 0.2.3
*
* Copyright 2011�2014, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
*  jquery.ui.widget.js
*  jquery.ui.mouse.js
*/
!function (a) { function f(a, b) { if (!(a.originalEvent.touches.length > 1)) { a.preventDefault(); var c = a.originalEvent.changedTouches[0], d = document.createEvent("MouseEvents"); d.initMouseEvent(b, !0, !0, window, 1, c.screenX, c.screenY, c.clientX, c.clientY, !1, !1, !1, !1, 0, null), a.target.dispatchEvent(d) } } if (a.support.touch = "ontouchend" in document, a.support.touch) { var e, b = a.ui.mouse.prototype, c = b._mouseInit, d = b._mouseDestroy; b._touchStart = function (a) { var b = this; !e && b._mouseCapture(a.originalEvent.changedTouches[0]) && (e = !0, b._touchMoved = !1, f(a, "mouseover"), f(a, "mousemove"), f(a, "mousedown")) }, b._touchMove = function (a) { e && (this._touchMoved = !0, f(a, "mousemove")) }, b._touchEnd = function (a) { e && (f(a, "mouseup"), f(a, "mouseout"), this._touchMoved || f(a, "click"), e = !1) }, b._mouseInit = function () { var b = this; b.element.bind({ touchstart: a.proxy(b, "_touchStart"), touchmove: a.proxy(b, "_touchMove"), touchend: a.proxy(b, "_touchEnd") }), c.call(b) }, b._mouseDestroy = function () { var b = this; b.element.unbind({ touchstart: a.proxy(b, "_touchStart"), touchmove: a.proxy(b, "_touchMove"), touchend: a.proxy(b, "_touchEnd") }), d.call(b) } } } (jQuery);
﻿/*!
 * Lazy Load - jQuery plugin for lazy loading images
 *
 * Copyright (c) 2007-2015 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://www.appelsiini.net/projects/lazyload
 *
 * Version:  1.9.7
 *
 */

(function($, window, document, undefined) {
    var $window = $(window);

    $.fn.lazyload = function(options) {
        var elements = this;
        var $container;
        var settings = {
            threshold       : 0,
            failure_limit   : 0,
            event           : "scroll",
            effect          : "show",
            container       : window,
            data_attribute  : "original",
            skip_invisible  : false,
            appear          : null,
            load            : null,
            placeholder     : _MTS_MEDIAURL + "images/busySpinner.gif",
            error           : _MTS_MEDIAURL + "images/noImage.png"
        };

        function update() {
            var counter = 0;

            elements.each(function() {
                var $this = $(this);
                if (settings.skip_invisible && !$this.is(":visible")) {
                    return;
                }
                if ($.abovethetop(this, settings) ||
                    $.leftofbegin(this, settings)) {
                        /* Nothing. */
                } else if (!$.belowthefold(this, settings) &&
                    !$.rightoffold(this, settings)) {
                        $this.trigger("appear");
                        /* if we found an image we'll load, reset the counter */
                        counter = 0;
                } else {
                    if (++counter > settings.failure_limit) {
                        return false;
                    }
                }
            });

        }

        if(options) {
            /* Maintain BC for a couple of versions. */
            if (undefined !== options.failurelimit) {
                options.failure_limit = options.failurelimit;
                delete options.failurelimit;
            }
            if (undefined !== options.effectspeed) {
                options.effect_speed = options.effectspeed;
                delete options.effectspeed;
            }

            $.extend(settings, options);
        }

        /* Cache container as jQuery as object. */
        $container = (settings.container === undefined ||
                      settings.container === window) ? $window : $(settings.container);

        /* Fire one scroll event per scroll. Not one scroll event per image. */
        if (0 === settings.event.indexOf("scroll")) {
            $container.bind(settings.event, function() {
                return update();
            });
        }

        this.each(function() {
            var self = this;
            var $self = $(self);

            self.loaded = false;

            /* If no src attribute given use data:uri. */
            if ($self.attr("src") === undefined || $self.attr("src") === false) {
                if ($self.is("img")) {
                    $self.attr("src", settings.placeholder);
                }
            }

            /* When appear is triggered load original image. */
            $self.one("appear", function() {
                if (!this.loaded) {
                    if (settings.appear) {
                        var elements_left = elements.length;
                        settings.appear.call(self, elements_left, settings);
                    }
                    $("<img />")
                        .bind("load", function() {
                            var original = $self.attr("data-" + settings.data_attribute);
                            $self.hide();
                            if ($self.is("img")) {
                                $self.attr("src", original);
                            } else {
                                $self.css("background-image", "url('" + original + "')");
                            }
                            $self[settings.effect](settings.effect_speed);

                            self.loaded = true;

                            /* Remove image from array so it is not looped next time. */
                            var temp = $.grep(elements, function(element) {
                                return !element.loaded;
                            });
                            elements = $(temp);

                            if (settings.load) {
                                var elements_left = elements.length;
                                settings.load.call(self, elements_left, settings);
                            }
                        })
                     .bind("error", function () { 
                           $self.attr("src", settings.error); 
                        })
                        .attr("src", $self.attr("data-" + settings.data_attribute));
                }
            });

            /* When wanted event is triggered load original image */
            /* by triggering appear.                              */
            if (0 !== settings.event.indexOf("scroll")) {
                $self.bind(settings.event, function() {
                    if (!self.loaded) {
                        $self.trigger("appear");
                    }
                });
            }
        });

        /* Check if something appears when window is resized. */
        $window.bind("resize", function(ev) {
            if (ev.target == window)
               update();
        });

        /* With IOS5 force loading images when navigating with back button. */
        /* Non optimal workaround. */
        if ((/(?:iphone|ipod|ipad).*os 5/gi).test(navigator.appVersion)) {
            $window.bind("pageshow", function(event) {
                if (event.originalEvent && event.originalEvent.persisted) {
                    elements.each(function() {
                        $(this).trigger("appear");
                    });
                }
            });
        }

        /* Force initial check if images should appear. */
        $(document).ready(function() {
            update();
        });

        return this;
    };

    /* Convenience methods in jQuery namespace.           */
    /* Use as  $.belowthefold(element, {threshold : 100, container : window}) */

    $.belowthefold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = (window.innerHeight ? window.innerHeight : $window.height()) + $window.scrollTop();
        } else {
            fold = $(settings.container).offset().top + $(settings.container).height();
        }

        return fold <= $(element).offset().top - settings.threshold;
    };

    $.rightoffold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.width() + $window.scrollLeft();
        } else {
            fold = $(settings.container).offset().left + $(settings.container).width();
        }

        return fold <= $(element).offset().left - settings.threshold;
    };

    $.abovethetop = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollTop();
        } else {
            fold = $(settings.container).offset().top;
        }

        return fold >= $(element).offset().top + settings.threshold  + $(element).height();
    };

    $.leftofbegin = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollLeft();
        } else {
            fold = $(settings.container).offset().left;
        }

        return fold >= $(element).offset().left + settings.threshold + $(element).width();
    };

    $.inviewport = function(element, settings) {
         return !$.rightoffold(element, settings) && !$.leftofbegin(element, settings) &&
                !$.belowthefold(element, settings) && !$.abovethetop(element, settings);
     };

    /* Custom selectors for your convenience.   */
    /* Use as $("img:below-the-fold").something() or */
    /* $("img").filter(":below-the-fold").something() which is faster */

    $.extend($.expr[":"], {
        "below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0}); },
        "above-the-top"  : function(a) { return !$.belowthefold(a, {threshold : 0}); },
        "right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0}); },
        "left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0}); },
        "in-viewport"    : function(a) { return $.inviewport(a, {threshold : 0}); },
        /* Maintain BC for couple of versions. */
        "above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
        "right-of-fold"  : function(a) { return $.rightoffold(a, {threshold : 0}); },
        "left-of-fold"   : function(a) { return !$.rightoffold(a, {threshold : 0}); }
    });

})(jQuery, window, document);

﻿/* Chosen v1.8.7 | (c) 2011-2018 by Harvest | MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md */

(function () { var t, e, s, i, n = function (t, e) { return function () { return t.apply(e, arguments) } }, r = function (t, e) { function s() { this.constructor = t } for (var i in e) o.call(e, i) && (t[i] = e[i]); return s.prototype = e.prototype, t.prototype = new s, t.__super__ = e.prototype, t }, o = {}.hasOwnProperty; (i = function () { function t() { this.options_index = 0, this.parsed = [] } return t.prototype.add_node = function (t) { return "OPTGROUP" === t.nodeName.toUpperCase() ? this.add_group(t) : this.add_option(t) }, t.prototype.add_group = function (t) { var e, s, i, n, r, o; for (e = this.parsed.length, this.parsed.push({ array_index: e, group: !0, label: t.label, title: t.title ? t.title : void 0, children: 0, disabled: t.disabled, classes: t.className }), o = [], s = 0, i = (r = t.childNodes).length; s < i; s++)n = r[s], o.push(this.add_option(n, e, t.disabled)); return o }, t.prototype.add_option = function (t, e, s) { if ("OPTION" === t.nodeName.toUpperCase()) return "" !== t.text ? (null != e && (this.parsed[e].children += 1), this.parsed.push({ array_index: this.parsed.length, options_index: this.options_index, value: t.value, text: t.text, html: t.innerHTML, title: t.title ? t.title : void 0, selected: t.selected, disabled: !0 === s ? s : t.disabled, group_array_index: e, group_label: null != e ? this.parsed[e].label : null, classes: t.className, style: t.style.cssText })) : this.parsed.push({ array_index: this.parsed.length, options_index: this.options_index, empty: !0 }), this.options_index += 1 }, t }()).select_to_array = function (t) { var e, s, n, r, o; for (r = new i, s = 0, n = (o = t.childNodes).length; s < n; s++)e = o[s], r.add_node(e); return r.parsed }, e = function () { function t(e, s) { this.form_field = e, this.options = null != s ? s : {}, this.label_click_handler = n(this.label_click_handler, this), t.browser_is_supported() && (this.is_multiple = this.form_field.multiple, this.set_default_text(), this.set_default_values(), this.setup(), this.set_up_html(), this.register_observers(), this.on_ready()) } return t.prototype.set_default_values = function () { return this.click_test_action = function (t) { return function (e) { return t.test_active_click(e) } }(this), this.activate_action = function (t) { return function (e) { return t.activate_field(e) } }(this), this.active_field = !1, this.mouse_on_container = !1, this.results_showing = !1, this.result_highlighted = null, this.is_rtl = this.options.rtl || /\bchosen-rtl\b/.test(this.form_field.className), this.allow_single_deselect = null != this.options.allow_single_deselect && null != this.form_field.options[0] && "" === this.form_field.options[0].text && this.options.allow_single_deselect, this.disable_search_threshold = this.options.disable_search_threshold || 0, this.disable_search = this.options.disable_search || !1, this.enable_split_word_search = null == this.options.enable_split_word_search || this.options.enable_split_word_search, this.group_search = null == this.options.group_search || this.options.group_search, this.search_contains = this.options.search_contains || !1, this.single_backstroke_delete = null == this.options.single_backstroke_delete || this.options.single_backstroke_delete, this.max_selected_options = this.options.max_selected_options || Infinity, this.inherit_select_classes = this.options.inherit_select_classes || !1, this.display_selected_options = null == this.options.display_selected_options || this.options.display_selected_options, this.display_disabled_options = null == this.options.display_disabled_options || this.options.display_disabled_options, this.include_group_label_in_selected = this.options.include_group_label_in_selected || !1, this.max_shown_results = this.options.max_shown_results || Number.POSITIVE_INFINITY, this.case_sensitive_search = this.options.case_sensitive_search || !1, this.hide_results_on_select = null == this.options.hide_results_on_select || this.options.hide_results_on_select }, t.prototype.set_default_text = function () { return this.form_field.getAttribute("data-placeholder") ? this.default_text = this.form_field.getAttribute("data-placeholder") : this.is_multiple ? this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || t.default_multiple_text : this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || t.default_single_text, this.default_text = this.escape_html(this.default_text), this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || t.default_no_result_text }, t.prototype.choice_label = function (t) { return this.include_group_label_in_selected && null != t.group_label ? "<b class='group-name'>" + this.escape_html(t.group_label) + "</b>" + t.html : t.html }, t.prototype.mouse_enter = function () { return this.mouse_on_container = !0 }, t.prototype.mouse_leave = function () { return this.mouse_on_container = !1 }, t.prototype.input_focus = function (t) { if (this.is_multiple) { if (!this.active_field) return setTimeout(function (t) { return function () { return t.container_mousedown() } }(this), 50) } else if (!this.active_field) return this.activate_field() }, t.prototype.input_blur = function (t) { if (!this.mouse_on_container) return this.active_field = !1, setTimeout(function (t) { return function () { return t.blur_test() } }(this), 100) }, t.prototype.label_click_handler = function (t) { return this.is_multiple ? this.container_mousedown(t) : this.activate_field() }, t.prototype.results_option_build = function (t) { var e, s, i, n, r, o, h; for (e = "", h = 0, n = 0, r = (o = this.results_data).length; n < r && (s = o[n], i = "", "" !== (i = s.group ? this.result_add_group(s) : this.result_add_option(s)) && (h++, e += i), (null != t ? t.first : void 0) && (s.selected && this.is_multiple ? this.choice_build(s) : s.selected && !this.is_multiple && this.single_set_selected_text(this.choice_label(s))), !(h >= this.max_shown_results)); n++); return e }, t.prototype.result_add_option = function (t) { var e, s; return t.search_match && this.include_option_in_results(t) ? (e = [], t.disabled || t.selected && this.is_multiple || e.push("active-result"), !t.disabled || t.selected && this.is_multiple || e.push("disabled-result"), t.selected && e.push("result-selected"), null != t.group_array_index && e.push("group-option"), "" !== t.classes && e.push(t.classes), s = document.createElement("li"), s.className = e.join(" "), t.style && (s.style.cssText = t.style), s.setAttribute("data-option-array-index", t.array_index), s.innerHTML = t.highlighted_html || t.html, t.title && (s.title = t.title), this.outerHTML(s)) : "" }, t.prototype.result_add_group = function (t) { var e, s; return (t.search_match || t.group_match) && t.active_options > 0 ? ((e = []).push("group-result"), t.classes && e.push(t.classes), s = document.createElement("li"), s.className = e.join(" "), s.innerHTML = t.highlighted_html || this.escape_html(t.label), t.title && (s.title = t.title), this.outerHTML(s)) : "" }, t.prototype.results_update_field = function () { if (this.set_default_text(), this.is_multiple || this.results_reset_cleanup(), this.result_clear_highlight(), this.results_build(), this.results_showing) return this.winnow_results() }, t.prototype.reset_single_select_options = function () { var t, e, s, i, n; for (n = [], t = 0, e = (s = this.results_data).length; t < e; t++)(i = s[t]).selected ? n.push(i.selected = !1) : n.push(void 0); return n }, t.prototype.results_toggle = function () { return this.results_showing ? this.results_hide() : this.results_show() }, t.prototype.results_search = function (t) { return this.results_showing ? this.winnow_results() : this.results_show() }, t.prototype.winnow_results = function (t) { var e, s, i, n, r, o, h, l, c, _, a, u, d, p, f; for (this.no_results_clear(), _ = 0, e = (h = this.get_search_text()).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), c = this.get_search_regex(e), i = 0, n = (l = this.results_data).length; i < n; i++)(r = l[i]).search_match = !1, a = null, u = null, r.highlighted_html = "", this.include_option_in_results(r) && (r.group && (r.group_match = !1, r.active_options = 0), null != r.group_array_index && this.results_data[r.group_array_index] && (0 === (a = this.results_data[r.group_array_index]).active_options && a.search_match && (_ += 1), a.active_options += 1), f = r.group ? r.label : r.text, r.group && !this.group_search || (u = this.search_string_match(f, c), r.search_match = null != u, r.search_match && !r.group && (_ += 1), r.search_match ? (h.length && (d = u.index, o = f.slice(0, d), s = f.slice(d, d + h.length), p = f.slice(d + h.length), r.highlighted_html = this.escape_html(o) + "<em>" + this.escape_html(s) + "</em>" + this.escape_html(p)), null != a && (a.group_match = !0)) : null != r.group_array_index && this.results_data[r.group_array_index].search_match && (r.search_match = !0))); return this.result_clear_highlight(), _ < 1 && h.length ? (this.update_results_content(""), this.no_results(h)) : (this.update_results_content(this.results_option_build()), (null != t ? t.skip_highlight : void 0) ? void 0 : this.winnow_results_set_highlight()) }, t.prototype.get_search_regex = function (t) { var e, s; return s = this.search_contains ? t : "(^|\\s|\\b)" + t + "[^\\s]*", this.enable_split_word_search || this.search_contains || (s = "^" + s), e = this.case_sensitive_search ? "" : "i", new RegExp(s, e) }, t.prototype.search_string_match = function (t, e) { var s; return s = e.exec(t), !this.search_contains && (null != s ? s[1] : void 0) && (s.index += 1), s }, t.prototype.choices_count = function () { var t, e, s; if (null != this.selected_option_count) return this.selected_option_count; for (this.selected_option_count = 0, t = 0, e = (s = this.form_field.options).length; t < e; t++)s[t].selected && (this.selected_option_count += 1); return this.selected_option_count }, t.prototype.choices_click = function (t) { if (t.preventDefault(), this.activate_field(), !this.results_showing && !this.is_disabled) return this.results_show() }, t.prototype.keydown_checker = function (t) { var e, s; switch (s = null != (e = t.which) ? e : t.keyCode, this.search_field_scale(), 8 !== s && this.pending_backstroke && this.clear_backstroke(), s) { case 8: this.backstroke_length = this.get_search_field_value().length; break; case 9: this.results_showing && !this.is_multiple && this.result_select(t), this.mouse_on_container = !1; break; case 13: case 27: this.results_showing && t.preventDefault(); break; case 32: this.disable_search && t.preventDefault(); break; case 38: t.preventDefault(), this.keyup_arrow(); break; case 40: t.preventDefault(), this.keydown_arrow() } }, t.prototype.keyup_checker = function (t) { var e, s; switch (s = null != (e = t.which) ? e : t.keyCode, this.search_field_scale(), s) { case 8: this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0 ? this.keydown_backstroke() : this.pending_backstroke || (this.result_clear_highlight(), this.results_search()); break; case 13: t.preventDefault(), this.results_showing && this.result_select(t); break; case 27: this.results_showing && this.results_hide(); break; case 9: case 16: case 17: case 18: case 38: case 40: case 91: break; default: this.results_search() } }, t.prototype.clipboard_event_checker = function (t) { if (!this.is_disabled) return setTimeout(function (t) { return function () { return t.results_search() } }(this), 50) }, t.prototype.container_width = function () { return null != this.options.width ? this.options.width : this.form_field.offsetWidth + "px" }, t.prototype.include_option_in_results = function (t) { return !(this.is_multiple && !this.display_selected_options && t.selected) && (!(!this.display_disabled_options && t.disabled) && !t.empty) }, t.prototype.search_results_touchstart = function (t) { return this.touch_started = !0, this.search_results_mouseover(t) }, t.prototype.search_results_touchmove = function (t) { return this.touch_started = !1, this.search_results_mouseout(t) }, t.prototype.search_results_touchend = function (t) { if (this.touch_started) return this.search_results_mouseup(t) }, t.prototype.outerHTML = function (t) { var e; return t.outerHTML ? t.outerHTML : ((e = document.createElement("div")).appendChild(t), e.innerHTML) }, t.prototype.get_single_html = function () { return '<a class="chosen-single chosen-default">\n  <span>' + this.default_text + '</span>\n  <div><b></b></div>\n</a>\n<div class="chosen-drop">\n  <div class="chosen-search">\n    <input class="chosen-search-input" type="text" autocomplete="off" />\n  </div>\n  <ul class="chosen-results"></ul>\n</div>' }, t.prototype.get_multi_html = function () { return '<ul class="chosen-choices">\n  <li class="search-field">\n    <input class="chosen-search-input" type="text" autocomplete="off" value="' + this.default_text + '" />\n  </li>\n</ul>\n<div class="chosen-drop">\n  <ul class="chosen-results"></ul>\n</div>' }, t.prototype.get_no_results_html = function (t) { return '<li class="no-results">\n  ' + this.results_none_found + " <span>" + this.escape_html(t) + "</span>\n</li>" }, t.browser_is_supported = function () { return "Microsoft Internet Explorer" === window.navigator.appName ? document.documentMode >= 8 : !(/iP(od|hone)/i.test(window.navigator.userAgent) || /IEMobile/i.test(window.navigator.userAgent) || /Windows Phone/i.test(window.navigator.userAgent) || /BlackBerry/i.test(window.navigator.userAgent) || /BB10/i.test(window.navigator.userAgent) || /Android.*Mobile/i.test(window.navigator.userAgent)) }, t.default_multiple_text = "Select Some Options", t.default_single_text = "Select an Option", t.default_no_result_text = "No results match", t }(), (t = jQuery).fn.extend({ chosen: function (i) { return e.browser_is_supported() ? this.each(function (e) { var n, r; r = (n = t(this)).data("chosen"), "destroy" !== i ? r instanceof s || n.data("chosen", new s(this, i)) : r instanceof s && r.destroy() }) : this } }), s = function (s) { function n() { return n.__super__.constructor.apply(this, arguments) } return r(n, e), n.prototype.setup = function () { return this.form_field_jq = t(this.form_field), this.current_selectedIndex = this.form_field.selectedIndex }, n.prototype.set_up_html = function () { var e, s; return (e = ["chosen-container"]).push("chosen-container-" + (this.is_multiple ? "multi" : "single")), this.inherit_select_classes && this.form_field.className && e.push(this.form_field.className), this.is_rtl && e.push("chosen-rtl"), s = { "class": e.join(" "), title: this.form_field.title }, this.form_field.id.length && (s.id = this.form_field.id.replace(/[^\w]/g, "_") + "_chosen"), this.container = t("<div />", s), this.container.width(this.container_width()), this.is_multiple ? this.container.html(this.get_multi_html()) : this.container.html(this.get_single_html()), this.form_field_jq.hide().after(this.container), this.dropdown = this.container.find("div.chosen-drop").first(), this.search_field = this.container.find("input").first(), this.search_results = this.container.find("ul.chosen-results").first(), this.search_field_scale(), this.search_no_results = this.container.find("li.no-results").first(), this.is_multiple ? (this.search_choices = this.container.find("ul.chosen-choices").first(), this.search_container = this.container.find("li.search-field").first()) : (this.search_container = this.container.find("div.chosen-search").first(), this.selected_item = this.container.find(".chosen-single").first()), this.results_build(), this.set_tab_index(), this.set_label_behavior() }, n.prototype.on_ready = function () { return this.form_field_jq.trigger("chosen:ready", { chosen: this }) }, n.prototype.register_observers = function () { return this.container.on("touchstart.chosen", function (t) { return function (e) { t.container_mousedown(e) } }(this)), this.container.on("touchend.chosen", function (t) { return function (e) { t.container_mouseup(e) } }(this)), this.container.on("mousedown.chosen", function (t) { return function (e) { t.container_mousedown(e) } }(this)), this.container.on("mouseup.chosen", function (t) { return function (e) { t.container_mouseup(e) } }(this)), this.container.on("mouseenter.chosen", function (t) { return function (e) { t.mouse_enter(e) } }(this)), this.container.on("mouseleave.chosen", function (t) { return function (e) { t.mouse_leave(e) } }(this)), this.search_results.on("mouseup.chosen", function (t) { return function (e) { t.search_results_mouseup(e) } }(this)), this.search_results.on("mouseover.chosen", function (t) { return function (e) { t.search_results_mouseover(e) } }(this)), this.search_results.on("mouseout.chosen", function (t) { return function (e) { t.search_results_mouseout(e) } }(this)), this.search_results.on("mousewheel.chosen DOMMouseScroll.chosen", function (t) { return function (e) { t.search_results_mousewheel(e) } }(this)), this.search_results.on("touchstart.chosen", function (t) { return function (e) { t.search_results_touchstart(e) } }(this)), this.search_results.on("touchmove.chosen", function (t) { return function (e) { t.search_results_touchmove(e) } }(this)), this.search_results.on("touchend.chosen", function (t) { return function (e) { t.search_results_touchend(e) } }(this)), this.form_field_jq.on("chosen:updated.chosen", function (t) { return function (e) { t.results_update_field(e) } }(this)), this.form_field_jq.on("chosen:activate.chosen", function (t) { return function (e) { t.activate_field(e) } }(this)), this.form_field_jq.on("chosen:open.chosen", function (t) { return function (e) { t.container_mousedown(e) } }(this)), this.form_field_jq.on("chosen:close.chosen", function (t) { return function (e) { t.close_field(e) } }(this)), this.search_field.on("blur.chosen", function (t) { return function (e) { t.input_blur(e) } }(this)), this.search_field.on("keyup.chosen", function (t) { return function (e) { t.keyup_checker(e) } }(this)), this.search_field.on("keydown.chosen", function (t) { return function (e) { t.keydown_checker(e) } }(this)), this.search_field.on("focus.chosen", function (t) { return function (e) { t.input_focus(e) } }(this)), this.search_field.on("cut.chosen", function (t) { return function (e) { t.clipboard_event_checker(e) } }(this)), this.search_field.on("paste.chosen", function (t) { return function (e) { t.clipboard_event_checker(e) } }(this)), this.is_multiple ? this.search_choices.on("click.chosen", function (t) { return function (e) { t.choices_click(e) } }(this)) : this.container.on("click.chosen", function (t) { t.preventDefault() }) }, n.prototype.destroy = function () { return t(this.container[0].ownerDocument).off("click.chosen", this.click_test_action), this.form_field_label.length > 0 && this.form_field_label.off("click.chosen"), this.search_field[0].tabIndex && (this.form_field_jq[0].tabIndex = this.search_field[0].tabIndex), this.container.remove(), this.form_field_jq.removeData("chosen"), this.form_field_jq.show() }, n.prototype.search_field_disabled = function () { return this.is_disabled = this.form_field.disabled || this.form_field_jq.parents("fieldset").is(":disabled"), this.container.toggleClass("chosen-disabled", this.is_disabled), this.search_field[0].disabled = this.is_disabled, this.is_multiple || this.selected_item.off("focus.chosen", this.activate_field), this.is_disabled ? this.close_field() : this.is_multiple ? void 0 : this.selected_item.on("focus.chosen", this.activate_field) }, n.prototype.container_mousedown = function (e) { var s; if (!this.is_disabled) return !e || "mousedown" !== (s = e.type) && "touchstart" !== s || this.results_showing || e.preventDefault(), null != e && t(e.target).hasClass("search-choice-close") ? void 0 : (this.active_field ? this.is_multiple || !e || t(e.target)[0] !== this.selected_item[0] && !t(e.target).parents("a.chosen-single").length || (e.preventDefault(), this.results_toggle()) : (this.is_multiple && this.search_field.val(""), t(this.container[0].ownerDocument).on("click.chosen", this.click_test_action), this.results_show()), this.activate_field()) }, n.prototype.container_mouseup = function (t) { if ("ABBR" === t.target.nodeName && !this.is_disabled) return this.results_reset(t) }, n.prototype.search_results_mousewheel = function (t) { var e; if (t.originalEvent && (e = t.originalEvent.deltaY || -t.originalEvent.wheelDelta || t.originalEvent.detail), null != e) return t.preventDefault(), "DOMMouseScroll" === t.type && (e *= 40), this.search_results.scrollTop(e + this.search_results.scrollTop()) }, n.prototype.blur_test = function (t) { if (!this.active_field && this.container.hasClass("chosen-container-active")) return this.close_field() }, n.prototype.close_field = function () { return t(this.container[0].ownerDocument).off("click.chosen", this.click_test_action), this.active_field = !1, this.results_hide(), this.container.removeClass("chosen-container-active"), this.clear_backstroke(), this.show_search_field_default(), this.search_field_scale(), this.search_field.blur() }, n.prototype.activate_field = function () { if (!this.is_disabled) return this.container.addClass("chosen-container-active"), this.active_field = !0, this.search_field.val(this.search_field.val()), this.search_field.focus() }, n.prototype.test_active_click = function (e) { var s; return (s = t(e.target).closest(".chosen-container")).length && this.container[0] === s[0] ? this.active_field = !0 : this.close_field() }, n.prototype.results_build = function () { return this.parsing = !0, this.selected_option_count = null, this.results_data = i.select_to_array(this.form_field), this.is_multiple ? this.search_choices.find("li.search-choice").remove() : (this.single_set_selected_text(), this.disable_search || this.form_field.options.length <= this.disable_search_threshold ? (this.search_field[0].readOnly = !0, this.container.addClass("chosen-container-single-nosearch")) : (this.search_field[0].readOnly = !1, this.container.removeClass("chosen-container-single-nosearch"))), this.update_results_content(this.results_option_build({ first: !0 })), this.search_field_disabled(), this.show_search_field_default(), this.search_field_scale(), this.parsing = !1 }, n.prototype.result_do_highlight = function (t) { var e, s, i, n, r; if (t.length) { if (this.result_clear_highlight(), this.result_highlight = t, this.result_highlight.addClass("highlighted"), i = parseInt(this.search_results.css("maxHeight"), 10), r = this.search_results.scrollTop(), n = i + r, s = this.result_highlight.position().top + this.search_results.scrollTop(), (e = s + this.result_highlight.outerHeight()) >= n) return this.search_results.scrollTop(e - i > 0 ? e - i : 0); if (s < r) return this.search_results.scrollTop(s) } }, n.prototype.result_clear_highlight = function () { return this.result_highlight && this.result_highlight.removeClass("highlighted"), this.result_highlight = null }, n.prototype.results_show = function () { return this.is_multiple && this.max_selected_options <= this.choices_count() ? (this.form_field_jq.trigger("chosen:maxselected", { chosen: this }), !1) : (this.container.addClass("chosen-with-drop"), this.results_showing = !0, this.search_field.focus(), this.search_field.val(this.get_search_field_value()), this.winnow_results(), this.form_field_jq.trigger("chosen:showing_dropdown", { chosen: this })) }, n.prototype.update_results_content = function (t) { return this.search_results.html(t) }, n.prototype.results_hide = function () { return this.results_showing && (this.result_clear_highlight(), this.container.removeClass("chosen-with-drop"), this.form_field_jq.trigger("chosen:hiding_dropdown", { chosen: this })), this.results_showing = !1 }, n.prototype.set_tab_index = function (t) { var e; if (this.form_field.tabIndex) return e = this.form_field.tabIndex, this.form_field.tabIndex = -1, this.search_field[0].tabIndex = e }, n.prototype.set_label_behavior = function () { if (this.form_field_label = this.form_field_jq.parents("label"), !this.form_field_label.length && this.form_field.id.length && (this.form_field_label = t("label[for='" + this.form_field.id + "']")), this.form_field_label.length > 0) return this.form_field_label.on("click.chosen", this.label_click_handler) }, n.prototype.show_search_field_default = function () { return this.is_multiple && this.choices_count() < 1 && !this.active_field ? (this.search_field.val(this.default_text), this.search_field.addClass("default")) : (this.search_field.val(""), this.search_field.removeClass("default")) }, n.prototype.search_results_mouseup = function (e) { var s; if ((s = t(e.target).hasClass("active-result") ? t(e.target) : t(e.target).parents(".active-result").first()).length) return this.result_highlight = s, this.result_select(e), this.search_field.focus() }, n.prototype.search_results_mouseover = function (e) { var s; if (s = t(e.target).hasClass("active-result") ? t(e.target) : t(e.target).parents(".active-result").first()) return this.result_do_highlight(s) }, n.prototype.search_results_mouseout = function (e) { if (t(e.target).hasClass("active-result") || t(e.target).parents(".active-result").first()) return this.result_clear_highlight() }, n.prototype.choice_build = function (e) { var s, i; return s = t("<li />", { "class": "search-choice" }).html("<span>" + this.choice_label(e) + "</span>"), e.disabled ? s.addClass("search-choice-disabled") : ((i = t("<a />", { "class": "search-choice-close", "data-option-array-index": e.array_index })).on("click.chosen", function (t) { return function (e) { return t.choice_destroy_link_click(e) } }(this)), s.append(i)), this.search_container.before(s) }, n.prototype.choice_destroy_link_click = function (e) { if (e.preventDefault(), e.stopPropagation(), !this.is_disabled) return this.choice_destroy(t(e.target)) }, n.prototype.choice_destroy = function (t) { if (this.result_deselect(t[0].getAttribute("data-option-array-index"))) return this.active_field ? this.search_field.focus() : this.show_search_field_default(), this.is_multiple && this.choices_count() > 0 && this.get_search_field_value().length < 1 && this.results_hide(), t.parents("li").first().remove(), this.search_field_scale() }, n.prototype.results_reset = function () { if (this.reset_single_select_options(), this.form_field.options[0].selected = !0, this.single_set_selected_text(), this.show_search_field_default(), this.results_reset_cleanup(), this.trigger_form_field_change(), this.active_field) return this.results_hide() }, n.prototype.results_reset_cleanup = function () { return this.current_selectedIndex = this.form_field.selectedIndex, this.selected_item.find("abbr").remove() }, n.prototype.result_select = function (t) { var e, s; if (this.result_highlight) return e = this.result_highlight, this.result_clear_highlight(), this.is_multiple && this.max_selected_options <= this.choices_count() ? (this.form_field_jq.trigger("chosen:maxselected", { chosen: this }), !1) : (this.is_multiple ? e.removeClass("active-result") : this.reset_single_select_options(), e.addClass("result-selected"), s = this.results_data[e[0].getAttribute("data-option-array-index")], s.selected = !0, this.form_field.options[s.options_index].selected = !0, this.selected_option_count = null, this.is_multiple ? this.choice_build(s) : this.single_set_selected_text(this.choice_label(s)), this.is_multiple && (!this.hide_results_on_select || t.metaKey || t.ctrlKey) ? t.metaKey || t.ctrlKey ? this.winnow_results({ skip_highlight: !0 }) : (this.search_field.val(""), this.winnow_results()) : (this.results_hide(), this.show_search_field_default()), (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex) && this.trigger_form_field_change({ selected: this.form_field.options[s.options_index].value }), this.current_selectedIndex = this.form_field.selectedIndex, t.preventDefault(), this.search_field_scale()) }, n.prototype.single_set_selected_text = function (t) { return null == t && (t = this.default_text), t === this.default_text ? this.selected_item.addClass("chosen-default") : (this.single_deselect_control_build(), this.selected_item.removeClass("chosen-default")), this.selected_item.find("span").html(t) }, n.prototype.result_deselect = function (t) { var e; return e = this.results_data[t], !this.form_field.options[e.options_index].disabled && (e.selected = !1, this.form_field.options[e.options_index].selected = !1, this.selected_option_count = null, this.result_clear_highlight(), this.results_showing && this.winnow_results(), this.trigger_form_field_change({ deselected: this.form_field.options[e.options_index].value }), this.search_field_scale(), !0) }, n.prototype.single_deselect_control_build = function () { if (this.allow_single_deselect) return this.selected_item.find("abbr").length || this.selected_item.find("span").first().after('<abbr class="search-choice-close"></abbr>'), this.selected_item.addClass("chosen-single-with-deselect") }, n.prototype.get_search_field_value = function () { return this.search_field.val() }, n.prototype.get_search_text = function () { return t.trim(this.get_search_field_value()) }, n.prototype.escape_html = function (e) { return t("<div/>").text(e).html() }, n.prototype.winnow_results_set_highlight = function () { var t, e; if (e = this.is_multiple ? [] : this.search_results.find(".result-selected.active-result"), null != (t = e.length ? e.first() : this.search_results.find(".active-result").first())) return this.result_do_highlight(t) }, n.prototype.no_results = function (t) { var e; return e = this.get_no_results_html(t), this.search_results.append(e), this.form_field_jq.trigger("chosen:no_results", { chosen: this }) }, n.prototype.no_results_clear = function () { return this.search_results.find(".no-results").remove() }, n.prototype.keydown_arrow = function () { var t; return this.results_showing && this.result_highlight ? (t = this.result_highlight.nextAll("li.active-result").first()) ? this.result_do_highlight(t) : void 0 : this.results_show() }, n.prototype.keyup_arrow = function () { var t; return this.results_showing || this.is_multiple ? this.result_highlight ? (t = this.result_highlight.prevAll("li.active-result")).length ? this.result_do_highlight(t.first()) : (this.choices_count() > 0 && this.results_hide(), this.result_clear_highlight()) : void 0 : this.results_show() }, n.prototype.keydown_backstroke = function () { var t; return this.pending_backstroke ? (this.choice_destroy(this.pending_backstroke.find("a").first()), this.clear_backstroke()) : (t = this.search_container.siblings("li.search-choice").last()).length && !t.hasClass("search-choice-disabled") ? (this.pending_backstroke = t, this.single_backstroke_delete ? this.keydown_backstroke() : this.pending_backstroke.addClass("search-choice-focus")) : void 0 }, n.prototype.clear_backstroke = function () { return this.pending_backstroke && this.pending_backstroke.removeClass("search-choice-focus"), this.pending_backstroke = null }, n.prototype.search_field_scale = function () { var e, s, i, n, r, o, h; if (this.is_multiple) { for (r = { position: "absolute", left: "-1000px", top: "-1000px", display: "none", whiteSpace: "pre" }, s = 0, i = (o = ["fontSize", "fontStyle", "fontWeight", "fontFamily", "lineHeight", "textTransform", "letterSpacing"]).length; s < i; s++)r[n = o[s]] = this.search_field.css(n); return (e = t("<div />").css(r)).text(this.get_search_field_value()), t("body").append(e), h = e.width() + 25, e.remove(), this.container.is(":visible") && (h = Math.min(this.container.outerWidth() - 10, h)), this.search_field.width(h) } }, n.prototype.trigger_form_field_change = function (t) { return this.form_field_jq.trigger("input", t), this.form_field_jq.trigger("change", t) }, n }() }).call(this);
﻿var mobileTab = "news";
var _autocompIdx = -1;
var _acTimer = -1;
var _ajaxSpinTimer = null;

$(document).on("click", "#twitterConnect", function ()
{
   window.open("https://twitter.com/" + (typeof (_twitterName) != 'undefined' && _twitterName.length > 0 ? _twitterName : "myteamscoop"), "_blank");
});

$(document).on("click", "#facebookConnect, #facebookClick", function ()
{
   window.open("https://www.facebook.com/" + (typeof (_facebookName) != 'undefined' && _facebookName.length > 0 ? _facebookName : "MyTeamScoop"), "_blank");
});

var _submenu = [],
   _iPad = navigator.userAgent.toLowerCase().search(/ipad/) >= 0 || navigator.userAgent.toLowerCase().search(/iphone/) >= 0,
   _event = "click",
   _event2 = "mouseenter",

   _curShareId = -1,
   _emailFrom = "From (Required)",
   _emailReq = "Recipients (Required)",
   _emailMsg = "Check out this story I found at " + ((typeof (_portalName) != 'undefined' && _portalName.length > 0) ? _portalName + "!" : "My Team Scoop!"),
   _emailMsgOpt = "Personal Message (Optional)",
   _reqColor = "#BBBBBB",
   _blkColor = "#1D1D1D",
   _errorTxt = "",
   _focusErr = "",

   _typeCon = null,
   _showMenu = false,
   _menuItem = [],
   _justSlided = false,

   _adClicks = [],
   _defaultPortalSport = 0,
   _doneLoading = false,
   _hitTimer = false,
   _filterPages = [],
   _filterKeys =
      [
         ["#msNews", "#newsInsert, #featuredContent, #news, #features, .fpvHeadHolder, .fPContainer, .videoWrap"],
         ["#msMyTeams", ".teamsFollowWrap"],
         ["#msTeams", "#teamList"],
         ["#msStats", "#filterMenu, #stats, .note1"],
         ["#msScores", "#scores, .note1, #scoreGridWidget"],
         ["#msSchedules", "#upcoming, #ucEvents, #upEvents, .note1"],
         ["#msStandings", "#filterMenu, #standings"],
         ["#msSchools", "#schoolList"]
      ],
   _keyException = [8, 37, 38, 39, 40],
   _sm = 0,
   _jsCachedSequence = [],
   _jsCacheBusy = false,
   _chosenSupported = "Microsoft Internet Explorer" === window.navigator.appName ? document.documentMode >= 8 : /iP(od|hone)/i.test(window.navigator.userAgent) ? !1 : /Android/i.test(window.navigator.userAgent) && /Mobile/i.test(window.navigator.userAgent) ? !1 : !0;

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
// usage : debounce(function() { }, 250);
function debounce(func, wait, immediate)
{
   var timeout;
   return function ()
   {
      var context = this, args = arguments;
      var later = function ()
      {
         timeout = null;
         if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
   };
};

function isMobileMedia()
{
   return window.matchMedia ? window.matchMedia("(min-width: 320px)").matches && window.matchMedia("(max-width: 767px)").matches : window.innerWidth >= 320 && window.innerWidth <= 767;
};

function isTabletMedia()
{
   return window.matchMedia ? window.matchMedia("(min-width: 768px)").matches && window.matchMedia("(max-width: 1024px)").matches : window.innerWidth >= 768 && window.innerWidth <= 1024;
};

function isDesktopMedia()
{
   return window.matchMedia ? window.matchMedia("(min-width: 1025px)").matches : window.innerWidth >= 1025;
};

// Center For jQuery - usage: $(element).center();
$.fn.center = function ()
{
   this.css("position", "absolute");
   var height = ($(window).height() - this.height()) / 2 + $(window).scrollTop(),
      width = ($(window).width() - this.width()) / 2 + $(window).scrollLeft();
   this.css("top", ((height > 0 ? height : 0) + "px"));
   this.css("left", ((width > 0 ? width : 0) + "px"));
   return this;
};

// Search for querystring parameters - usage: $.Query.parameter;
(function ($)
{
   $.Query = (function (parameter)
   {
      return GetQueryArrayFromUrl(parameter);
   })(window.location.search)
})(jQuery);

// Same url regex that is done on server side for seo purposes - usage: $.urlName(url)
(function ($)
{
   $.urlName = (function (url)
   {
      return url.replace(_MTS_urlRegex, "-").replace(/ /g, "-").replace(/\-+/g, "-");
   })
})(jQuery);

// Returns obj with query vals - usage: GetQueryArrayFromUrl(url)["parameter"]
function GetQueryArrayFromUrl(url)
{
   var qIdx = url.indexOf("?");
   if (url == "" || qIdx < 0) return {};
   url = url.substr(qIdx + 1).split('&');
   var b = {};
   for (var i = 0; i < url.length; ++i)
   {
      var p = url[i].split('=');
      if (p.length != 2)
      {
         continue;
      }
      b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
   }
   return b;
}

// Handle devices which falsely report support
var _isFileInputSupported = navigator.userAgent.match(/(Android (1.0|1.1|1.5|1.6|2.0|2.1))|(Windows Phone (OS 7|8.0)|(XBLWP)|(ZuneWP)|(w(eb)?OSBrowser)|(webOS)|Pre\/1.2|Kindle\/(1.0|2.0|2.5|3.0))/)
   ? false : true;

var _noFileReaderSupport = typeof (window.FileReader) == 'undefined' || typeof (window.File) == 'undefined' || typeof (window.FileList) == 'undefined' || typeof (window.Blob) == 'undefined';

function AlertCycle()
{
   this.parent = null;
   this.frames = 0;
   this.callback = function () { };
   this.last = new Date();
   this.index = 0;
   this.delay = 0;
   this.drop = 0;
}

AlertCycle.prototype = {

   init: function (count, delay)
   {
      this.index = 0;
      this.frames = $(".alertItem").length;
      this.delay = 5000;
      this.drop = 7500;
      this.last = new Date();

      var self = this;
      setInterval(function () { self.timer(); }, this.delay);
   },

   timer: function ()
   {
      var now = new Date();
      if (now - this.last > this.drop)
         return;

      this.last = now;
      var prev = this.index++;
      if (this.index >= this.frames)
         this.index = 0;

      if (this.index == prev)
         return;

      this.anim();
      this.last = now;
   },

   anim: function ()
   {
      var self = this;
      $("#alertsBody").animate({ "margin-top": "30px" }, 100, "swing", function ()
      {
         $("#alertsBody").html($("#alert_item_" + self.index).html());
         $("#alertsBody").animate({ "margin-top": "0px" }, 100, "swing", function () { });
      });
   }
};

if (window.name == "refresh")
{
   window.stop();
   window.location.replace(window.location.pathname + window.location.search + window.location.hash);
   window.name = "";
}

var BrowserDetect = {
   init: function ()
   {
      this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
      this.version = this.searchVersion(navigator.userAgent)
			   || this.searchVersion(navigator.appVersion)
			   || "an unknown version";
      this.OS = this.searchString(this.dataOS) || "an unknown OS";
   },
   searchString: function (data)
   {
      for (var i = 0; i < data.length; i++)
      {
         var dataString = data[i].string;
         var dataProp = data[i].prop;
         this.versionSearchString = data[i].versionSearch || data[i].identity;
         if (dataString)
         {
            if (dataString.indexOf(data[i].subString) != -1)
               return data[i].identity;
         }
         else if (dataProp)
            return data[i].identity;
      }
   },
   searchVersion: function (dataString)
   {
      var index = dataString.indexOf(this.versionSearchString);
      if (index == -1) return;
      return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
   },
   dataBrowser: [
		   {
		      string: navigator.userAgent,
		      subString: "Chrome",
		      identity: "Chrome"
		   },
		   {
		      string: navigator.userAgent,
		      subString: "OmniWeb",
		      versionSearch: "OmniWeb/",
		      identity: "OmniWeb"
		   },
		   {
		      string: navigator.vendor,
		      subString: "Apple",
		      identity: "Safari",
		      versionSearch: "Version"
		   },
		   {
		      prop: window.opera,
		      identity: "Opera",
		      versionSearch: "Version"
		   },
		   {
		      string: navigator.vendor,
		      subString: "iCab",
		      identity: "iCab"
		   },
		   {
		      string: navigator.vendor,
		      subString: "KDE",
		      identity: "Konqueror"
		   },
		   {
		      string: navigator.userAgent,
		      subString: "Firefox",
		      identity: "Firefox"
		   },
		   {
		      string: navigator.vendor,
		      subString: "Camino",
		      identity: "Camino"
		   },
		   {		// for newer Netscapes (6+)
		      string: navigator.userAgent,
		      subString: "Netscape",
		      identity: "Netscape"
		   },
		   {
		      string: navigator.userAgent,
		      subString: "MSIE",
		      identity: "Internet Explorer",
		      versionSearch: "MSIE"
		   },
		   {
		      string: navigator.userAgent,
		      subString: "Gecko",
		      identity: "Mozilla",
		      versionSearch: "rv"
		   },
		   { 		// for older Netscapes (4-)
		      string: navigator.userAgent,
		      subString: "Mozilla",
		      identity: "Netscape",
		      versionSearch: "Mozilla"
		   }
   ],
   dataOS: [
		   {
		      string: navigator.platform,
		      subString: "Win",
		      identity: "Windows"
		   },
		   {
		      string: navigator.platform,
		      subString: "Mac",
		      identity: "Mac"
		   },
		   {
		      string: navigator.userAgent,
		      subString: "iPhone",
		      identity: "iPhone/iPod"
		   },
         {
            string: navigator.userAgent,
            subString: "iPad",
            identity: "iPad"
         },
		   {
		      string: navigator.platform,
		      subString: "Linux",
		      identity: "Linux"
		   }
   ]

};
BrowserDetect.init();

// Facebook Login (called after sdk loaded)
if (typeof (_MTS_fireCommon) != "boolean" || _MTS_fireCommon)
{
   window.fbAsyncInit = function ()
   {
      FB.init({
         appId: _fbClientId, // App ID
         channelUrl: _baseUri + 'auth/facebook/channel.htm', // Channel File
         status: true, // check login status
         cookie: true, // enable cookies to allow the server to access the session
         xfbml: true  // parse XFBML
      });
   };

   // Load the facebook SDK Asynchronously
   (function (d)
   {
      var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
      if (d.getElementById(id)) { return; }
      js = d.createElement('script'); js.id = id; js.async = true;
      js.src = "//connect.facebook.net/en_US/all.js";
      ref.parentNode.insertBefore(js, ref);
   }(document));

   // Load the twitter SDK Asynchronously
   if (typeof _loadTwitterSDK === "boolean" && _loadTwitterSDK != null && _loadTwitterSDK === false)
   {
      if (typeof window.FileReader != 'undefined' && BrowserDetect.browser != "Opera" && !_iPad && BrowserDetect.browser != "Safari")
         _loadTwitterSDK = true;
   }

   if (typeof _loadTwitterSDK !== "boolean" || _loadTwitterSDK == null || _loadTwitterSDK)
   {
      !function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = "https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); } }(document, "script", "twitter-wjs");
   }
}


// Used to pass a function as a parameter with additional parameters for the function you are passing
// ex. var next = partial(nextFunction, nextFunctionParameter1, nextFunctionParameter2, ...)
// then ... someFunction(next)
function partial(func /*, 0..n args */)
{
   var args = Array.prototype.slice.call(arguments, 1);
   return function ()
   {
      var allArguments = args.concat(Array.prototype.slice.call(arguments));
      return func.apply(this, allArguments);
   };
}

//DOCUMENT IS LOADED
$(window).bind("load", function ()
{
   _doneLoading = true;
   if (_hitTimer)
      HideAd();

   AdjustAdHeight();
});

$(document).on("widgetsloaded", mts_lazyloading);

function mts_lazyloading()
{
   $("img.mts_lazy").lazyload({
      failure_limit: $("img.mts_lazy").length - 1,
      event: "mts_lazy"
   });

   $(".mts_lazy:in-viewport").removeClass("mts_lazy");
}
function set_MTS_SaveHistoryState(fun) {

    if (typeof _MTS_SaveHistoryState == 'undefined')
        _MTS_SaveHistoryState = [];

    _MTS_SaveHistoryState.push(fun);
}

$(window).on("unload", function ()
{

    if (typeof _MTS_SaveHistoryState !== 'undefined') {
        $(_MTS_SaveHistoryState).each(function (key, val) {
            val();
        });
    }

    
   if (history != null && typeof history === "object" && history.replaceState != null && typeof history.replaceState === "function")
   {
      var s = history.state;
      if (s == null)
         s = [];

      var hId = $.grep(s, function (e)
      {
         return e.name == "historyId";
      });

      if (hId.length == 0 && typeof(_MTS_pageId) !== "undefined")
         s.push({ "name": "historyId", "value": _MTS_pageId });

      var c = $.grep(s, function (e)
      {
         return e.name == "histCount";
      });

      if (c.length == 0 && typeof(_MTS_histcount) !== "undefined")
         s.push({ "name": "histCount", "value": _MTS_histCount });

      history.replaceState(s, "");
   }
});

// anything we only want to fire once
$(document).one("widgetsloaded", function ()
{
   SaveToHistory();
   $(window).resize(function ()
   {
      if (window.matchMedia("(min-width: 1024px)").matches)
      {
         $(".hpCtr, .navigationContainer").removeClass("mainNavO");

         if (typeof (_MTS_customDropdown) !== "boolean" || _MTS_customDropdown)
            ToggleCustomDropdowns();
      }
   });

   $(".betaIndicator").click(function ()
   {
      $(this).hide();
   });

   WireLockingNotice();

   if (typeof (_MTS_fireCommon) == "boolean" && !_MTS_fireCommon)
      return false;

   if (typeof (_warnAboutRejected) == "boolean" && _warnAboutRejected)
   {
      var er = $(".emailRejected");
      er.show();
      $(".rejectHide").click(function ()
      {
         er.hide();
      });
   }

   if (typeof (_MTS_customDropdown) !== "boolean" || _MTS_customDropdown)
      ToggleCustomDropdowns();

   if (typeof ($.smartbanner) == "function")
   {
      var appUrl = _webUri + "images/custom/" + _portalId + "/AppIcon40.png";
      $.smartbanner();
   }

   if ($(window).width() < 768 && $(window).width() > 319)
   {
      $(".note1").click(function ()
      {
         var opt = $("#options");
         if (opt.css('display') == "none")
         {
            opt.show();
         } else
         {
            opt.hide();
         }
      });
   }

   var fav = $(".fullAdView");

   var adLength = 5000;
   AdHeight(adLength);
   if (fav.length > 0)
   {
      var sa = $("#skipAd");

      sa.slideToggle();
      sa.click(function ()
      {
         HideAd();
      });

      setTimeout(function ()
      {
         _hitTimer = true;

         if (_doneLoading)
            HideAd();
      }, adLength);
   }

   var bbr = $("#backBtnRef");
   if (window.history == null || window.history.length <= 1)
      bbr.html("Close");
   bbr.click(function ()
   {
      BackAndRefresh();
   });

   if (_portalId != 21)
   {
      $(document).on(_event, ".grdImgBot", function ()
      {
         var myContainer = $(".sportsContainer");
         myContainer.animate({
            scrollTop: myContainer.scrollTop() + myContainer.height()
         });
      });
   }

   $(".closeSpinner, .busySpinnerBg").click(function ()
   {
      $(".busySpinnerBg").hide();
   });

   $(document).on(_event, "#linkToScores", function ()
   {
      var scores = $("#scoreLink"), sport = $("#sport"), sportVal = sport.length > 0 ? sport.val() : (typeof (_sm) != "undefined" ? _sm : -1);
      if (scores.length > 0 && sportVal <= 0)
         window.location = scores.attr("href");
      else
      {
         var date = (typeof (_date) == 'object' && _date != null) ? _date : new Date();
         var nxt = (typeof (_endDate) == 'object' && _endDate != null) ? _endDate : new Date(date.getFullYear(), date.getMonth(), date.getDate() - 6);

         var eDate = (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear();
         var sDate = (nxt.getMonth() + 1) + "-" + nxt.getDate() + "-" + nxt.getFullYear();

         var restOfUrl = "";
         var school = "";

         if (typeof (_filterType) != 'undefined' && typeof (_filterId) != 'undefined')
         {
            switch (_filterType.toLowerCase())
            {
               case "school":
                  school = _filterId;
                  break;
               default:
                  break;
            }
         }

         if (typeof (_curGender) != 'undefined')
         {
            var level = $("#level option").length > 0 ? $("#level").val() : 1;

            restOfUrl = getDescription(sportVal, level, school, _curGender, false) + "?start=" + sDate + "&end=" + eDate;
         }
         else if (_defaultPortalSport > 0)
            restOfUrl = getDescription(_defaultPortalSport, 1, school, 0, false) + "?start=" + sDate + "&end=" + eDate;
         else
            restOfUrl = getDescription(0, 1, school, 0, false) + "?start=" + eDate + "&end=" + eDate;

         window.location = _MTS_SITEURL + "scores" + restOfUrl;
      }
   });

   $("#fbLogin, #fbCont").click(function ()
   {
      FB.login(function (response)
      {
         if (response.authResponse)
         {
            FB.api('/me?fields=first_name,last_name,gender,email', function (ret)
            {
               window.location = "/auth/facebook/oauth2.aspx?fbId=" + response.authResponse.userID + "&email=" + ret.email +
               "&first=" + ret.first_name + "&last=" + ret.last_name + "&gender=" + ret.gender + "&ret=" + _fbTarget;
            });
         }
         else
         {
            // cancelled
         }
      }, { scope: 'email' });
   });

   var search = "#searchTxt";
   $(document).on("keypress", search, function (e)
   {
      var ac = $("#acomp");
      if ((ac.length == 0 || ac.attr("display") == "none" || ac.children(".highlight").length == 0) && e.keyCode == 13)
         SubmitSearch();

      return true;
   });

   var goSearch = "#goSearch";
   $(document).on("click", goSearch, function (e) {
      var ac = $("#acomp");
      if ((ac.length == 0 || ac.attr("display") == "none" || ac.children(".highlight").length == 0))
         SubmitSearch();

      return true;
   });


   $(document).on("keyup", search, function (e)
   {
      var a = $("#acomp");
      if (a.length == 0)
      {
         a = $("<div id='acomp' />");
         $(document.body).append(a);
      }

      var childrenCount = a.children().length;
      hasChildren = childrenCount > 0,
         altKeyCodes = [38, 40, 13],
         isUsingAltCode = false;

      for (var i = altKeyCodes.length - 1; i >= 0; i--)
      {
         if (altKeyCodes[i] == e.keyCode)
         {
            isUsingAltCode = true;
            break;
         }
      }

      if (isUsingAltCode && hasChildren && a.css("display") != "none")
      {
         // arr up
         if (e.keyCode == 38)
         {
            if (_autocompIdx == 0)
               _autocompIdx = childrenCount - 1;
            else
               _autocompIdx--;

            HighlightAutoComplete(childrenCount, a);
         }
            // arr dn
         else if (e.keyCode == 40)
         {
            if (_autocompIdx == childrenCount - 1)
               _autocompIdx = 0;
            else
               _autocompIdx++;

            HighlightAutoComplete(childrenCount, a);
         }
            // enter
         else if (e.keyCode == 13)
         {
            $(a.children()[_autocompIdx])[0].click();
         }
      }
      else if (!isUsingAltCode)
      {
         var me = this;
         if (_acTimer != -1)
         {
            clearTimeout(_acTimer);
            _acTimer = -1;
         }

         var func = partial(StartAutoComplete, me, a);
         MTS_searchHelper(func);
      }
   });

   $(document).click(function (e)
   {
      var ac = $("#acomp");
      if (ac.css("display") != "none" && e.target.id != ac.attr("id"))
      {
         ac.hide();
      }
   });

   $(document).on(_event, "#searchBarBtn", function ()
   {
      SubmitSearch();
   });

   $(".subNav").hide();

   $("#alertsArrow").click(function ()
   {
      if ($("#alertDD").css('height') != "0px")
         $("#alertDD").css('height', '0px');
      else
         $("#alertDD").css('height', 'auto');
   });
   (new AlertCycle()).init();

   $(document).on(_event, ".shareIcons", function ()
   {
      var id = this.id;
      var shareType = id.split('_')[0];

      id = id.split('_')[1];
      switch (shareType)
      {
         default:
            break;
         case "eShare":
            emailShare(id);
            break;
      }
   });

   $(document).on(_event, ".shareIconsEmail, .emShare", function ()
   {
      var id = this.id.split('_')[1];
      emailShare(id);
   });

   $(document).on(_event, "#emailCancel", function ()
   {
      $(".emailBg").remove();
      $(".emailTemplate").remove();
   });

   $(document).on(_event, "#emailSend", function ()
   {
      var sendTo = $.trim($("#emailList").val());
      var msg = $.trim($("#emailMsg").val());
      var from = _userId > 0 ? "" : $.trim($("#emailFrom").val());
      var mode = $(this).parent().find("#shareMode").val();

      emailSend(sendTo, msg, from, mode);
   });

   $(document).on("focusin", ".emailTxt", function ()
   {
      if (this.value == _emailReq || this.value == _emailMsg || this.value == _emailMsgOpt || this.value == _emailFrom)
      {
         this.value = "";
         this.style.color = _blkColor;
      }
   });

   $(document).on("focusout", ".emailTxt", function ()
   {
      if (this.value == "")
      {
         this.value = this.id == "emailList" ? _emailReq : this.id == "emailFrom" ? _emailFrom : _emailMsgOpt;
         this.style.color = _reqColor;
      }
   });

   $(document).on("mouseenter", ".itemAdd", function ()
   {
      clearTimeout(timerRemove);
      $(".moreListCtr").show();
   });

   //MENU LIST DROP FOR HOVERS
   var dlc = $(".menuDropBg"),
      timerRemove = null,
      showClass = "menuDropBgShow";

	$(document).on("mouseleave", ".mainNavContainer .item, .menuDropBg, .moreListCtr", function ()
   {
      if ($(this).parent(".moreList").length > 0)
         return;

      clearTimeout(timerRemove);
      timerRemove = setTimeout(function() {
         if (window.matchMedia("(min-width: 1024px)").matches) {
            dlc.removeClass(showClass);
            $(".moreListCtr").hide();
         }
      }, 250);
	});

   $(document).on("mouseenter", ".menuDropBg, .moreListCtr", function ()
   {
      clearTimeout(timerRemove);
   });

   $(document).on(_event, ".navCaret", function (e)
   {
      e.preventDefault();
   });

   //NEW MENU DROP
   $(document).on(
   {
      click: function ()
      {
         if (!isDesktopMedia())
            _MTS_handleMouseNav(this);
      }, mouseenter: function ()
      {
         if (isDesktopMedia())
            _MTS_handleMouseNav(this);
      }
   }, ".item");

   function _MTS_handleMouseNav(me)
   {
      if ($.trim(me.innerHTML) != "" && ((me.parentNode.attributes["id"] &&
            me.parentNode.attributes["id"].value == "navbar") || $(me).parent().hasClass("moreList")) &&
            ($(me).hasClass("categoryItem") || $(me).hasClass("headerItem")))
      {
         clearTimeout(timerRemove);
         var mnco = $(".mainNavContainerO");
         var type = $.trim($(me).find(".navType").html().replace(/<div>|<\/div>/ig, ""));
         var parentId = me.id.split('_')[1];

         var fc = $(".featuredStoryContainer, .recentHeadlinesContainer");
         if (type == "Sports" || type == "Schools" || type == "Leagues" || type == "District")
         {
            fc.show();
         }
         else
         {
            fc.hide();
         }

			$(".mt").hide();
			
         _typeCon = $(".list_" + parentId);
			if (_typeCon.length > 0)
         {
            _typeCon.show();
            mnco.css({ "height": "0px" });
            _showMenu = true;
				var menu = $(".menuDropBg");
				if (menu.attr("class").indexOf("menuDropBgShow") == -1)
            {
               menu.toggleClass("menuDropBgShow");
               menu.css({ "left": $(me).offset().left + "px" });
            }

            $("#menuText").html(type.toUpperCase());
            var mdbg = $(".menuDropBgShow");

            if (window.matchMedia("(min-width: 1024px)").matches)
            {
					var tps = $(me).position().left;
					if ($(me).parent(".moreList").length > 0) {
						tps += $(".moreListCtr").outerWidth();
					}

					var sct = $(".menuDropBgShow");
					if ($(me).parent().hasClass("moreList")) {
						sct.css({ "right": "200px", "left": "auto" });
					} else {
						sct.css({ "left": tps + "px" });
               }

               var listItem = $(".mt:visible a");
               var mtCount = listItem.length;
               var mtHeight = listItem.outerHeight();
               var product = mtCount * mtHeight + 1;
               sct.css({ "height": product + "px" });

            }
            else
            {
					mdbg.removeAttr("style");
					mdbg.css({ "height": "100%" });
               $(".masterMcwrap").toggleClass("menuDropBgShow");
            }

            if (_portalId != 21) //EXCLUDE PORTAL 21
            {
               var mtv = $(".mt:visible").children(".mdItem").length;
               var gib = $(".grdImgBot");
               gib.removeClass('grdImgBotHide');

               if (mtv < 9)
               {
                  gib.addClass("grdImgBotHide");
               } else
               {
                  gib.removeClass('grdImgBotHide');
               }
            }
         }
      }
   }

   $(document).on("mouseleave", ".item", function ()
   {
      HidePopupMenu();
   });

   $(".menuDropBg").hover(function ()
   {
      _showMenu = true;
   }, function ()
   {
      HidePopupMenu();
   });

   $(".scrollerContainer").slider(
   {
      create: slideMenu,
      orientation: "vertical",
      slide: slideMenu,
      stop: holdMenu,
      min: 0, max: 100,
      value: 100
   });

   $(document).on({
      mouseenter: function ()
      {
         HoverMenu(this.id.split('_')[2], this.id.split('_')[1]);
      }, mouseleave: function ()
      {
         UnhoverMenu(this.id.split('_')[2], this.id.split('_')[1]);
      }
   }, ".dropDownElement, .dropDownArr");

   $(document).on(_event, "#menuHeader", function (ev)
   {
      ev.stopPropagation();

      HidePopupMenu(true);

      var mnco = $(".mainNavContainerO");
      mnco.css({ "height": "auto" });
   });

   //MY PROFILE BUBBLE
   var myProfile = $(".myProfile");
   if (myProfile.length > 0)
   {
      var phl = $(".myProfile").position().left;
      $(".profileHover").css({ "left": phl });
      $(".myProfile").hover(
      function ()
      {
         $(".profileHover").fadeTo("fast", 1);
      },
      function ()
      {
         $(".profileHover").fadeTo("fast", 0);
      });
   }

   $(".shareTopIcon").click(
   function ()
   {
      if ($(".sharingIcons").width() == 0)
      {
         $(".sharingIcons").animate({ "width": "192px" });
      } else
      {
         $(".sharingIcons").animate({ "width": "0px" });
      }
   });

   $(document).on(_event, ".iA", function (ev)
   {
      ev.stopPropagation();

      var me = $(this),
         link = $(me.parent().find("iframe")[0].contentWindow.document.body).find("a").attr("href"),
         adName = me.width() + "x" + me.height();

      if (CheckAdClick(adName))
      {
         try
         {
            TrackClick("DFP-" + adName);
         } catch (err) { }
      }

      setTimeout(function ()
      {
         if (link.length > 0)
            window.open(link);
      }, 100);
   });

   $("#OASFlashPeel").mousedown(function (ev)
   {
      if (CheckAdClick("peel"))
      {
         try
         {
            TrackClick("DFP-Peel");
         } catch (err) { }
      }
   });

   // PEEL AD BROWSER RESIZING & DEFAULT LOAD SIZE AT 1024 OR <
   if ($("#dfp-pagepeel-oop_ad_container").length > 0)
   {
      if ($(window).width() <= 1024 || _iPad)
         $("#dfp-pagepeel-oop_ad_container").hide();
      $(window).resize(function ()
      {
         if ($(window).width() <= 1024)
            $("#dfp-pagepeel-oop_ad_container").hide();
         else
            $("#dfp-pagepeel-oop_ad_container").show();
      });
   }

   //MOBILE MENU BUTTON FUNCTION
   $(document).on(_event, ".mobileMenuBtn", function ()
   {
      $(".navigationContainer, .hpCtr").toggleClass('mainNavO').removeAttr('style');
      $(".navigationContainer").show();

      var mcont = $("#mainContainer");
      if (mcont.css('display') !== "none")
      {
         mcont.hide();
      } else
      {
         mcont.show();
      }

      var cont = $("#content");
      if (cont.css('display') !== "none")
      {
         cont.hide();
      } else
      {
         cont.show();
      }
   });

   //MOBILE SELECTOR BUTTON FUNCTIONS
   $(".msBtn").click(function ()
   {
      $("#features").hide();
   });

   for (var i = _filterKeys.length - 1; i >= 0; i--)
      CreateMenuClick(_filterKeys[i][0], _filterKeys[i][1]);

   $(".mOptBtn").click(function ()
   {
      $(".optionsContainer").toggleClass('optionsContainerO');
   });

   var masterBackBtn = $(".masterBackButton");
   if (window.history != null && window.history.length > 1)
   {
      masterBackBtn.click(function ()
      {
         if (window.history != null && window.history.length > 2)
         {
            if (document.referrer != null && document.referrer.indexOf("user/login") >= 0)
               window.history.go(-2);
            else
               window.history.go(-1);
         }
      });
   }
   else
   {
      masterBackBtn.hide();
   }

   //Mobile Coverage Tools Menu Button Function
   $("#mctMnuBtn").click(function ()
   {
      var tt = $(".topTabs");
      tt.toggleClass("tto");
   });

   $("#showMoreScoresMobile").click(function ()
   {
      _MTS_ajaxPending = true;
      $.ajax("/api/getPortalScoresMobile", [], function (ret)
      {
         alert(ret);
      });
   });

   $(document).on(_event, "#portalPost, #mPortalPost", function ()
   {
      window.location = "/news/editor/?mode=portal&sTag=" + _sm;
   });

   $(document).on(_event, "#portalAdmin, #mPortalAdmin", function ()
   {
      window.location = "/admin/";
   });

   // fixes bug with google places autocomplete while using fastclick.js
   // http://stackoverflow.com/questions/9972080/cant-tap-on-item-in-google-autocomplete-list-on-mobile
   $(document).on('DOMNodeInserted', '.pac-container', function ()
   {
      $('.pac-item, .pac-item span', this).addClass('needsclick');
   });

   $(".layoutPreviewOverlay").click(function ()
   {
      var p = confirm("Do you want to push this preview live?")
      {
         if (p)
         {
            var p = [];
            p.param("id", $("#previewVal").val());

            ajax("/api/portalAdmin/saveCustomLayout.aspx", p, function (ret)
            {
               var o;
               eval("o = " + ret);

               if (o.ok)
                  window.close();
               else
                  alert("Error : " + o.error);
            });
         }
         else
            window.close();
      }
   });

   if (_portalId < 1)
   {
      if ($(window).width() > 1024)
      {
         var lg = $("#logo_image");
         var hhpc = $(".hpCtr");
         var hc = $("#headContainer, #headContainerL");

         hhpc.css({ "top": "4px" });
         hhpc.css({ "transform": "none", "-webkit-transform": "none", "-moz-transform": "none", "-ms-transform": "none" });
         //hhpc.css({ "left": 440 + "px" });
      }
   }

   resizeOnLoad();

   $(".sportsContainer").scroll(function ()
   {
      if ($(this).scrollTop() > 0)
      {
         var gib = $(".grdImgBot");
         gib.addClass('grdImgBotHide');
      } else
      {
         var gib = $(".grdImgBot");
         gib.removeClass('grdImgBotHide');
      }
   });

   noPortalVertNav();

   setNav();
   targetFirefoxHeader();
   $(window).resize(setNav);

   pushFooter();

});

// Event fired from widget main.js when all widgets are finished loading
if (_MTS_widgetsReady)
   _MTS_commonWidgetInit();
else
   $(document).bind(_MTS_widgetsReady, _MTS_commonWidgetInit);

function _MTS_commonWidgetInit()
{
   var ms = $(".mobileSelectors");
   if (ms.length > 0 && ms.css("display") != "none")
   {
      switch (mobileTab)
      {
         case "schedules":
            $("#msSchedules").click();
            break;
         case "scores":
            $("#msScores").click();
            break;
         default:
            $("#msNews").click();
            break;
      }

      if ($(".scores_list_widget:visible").length > 0)
         $(".scores_grid_widget").hide();
   }
}

function resizeNav()
{
   if (isDesktopMedia())
   {
      $("#mainContainer").show();
      $("#content").show();
   }
}

function resizeOnLoad()
{
   if (typeof (_registrationPop) == "boolean" && _registrationPop)
      GetRegistrationPop();

   resizeNav();

   var tmpImg = new Image();
   tmpImg.src = $('#logo').attr('src');
   tmpImg.onload = function ()
   {
      var hc = $("#headContainer");
      var h = $("#logo").outerHeight();
      var nc = $(".navigationContainer");
      var mw = $(".masterMcWrap");
      var sc = $(".sportsContainer");
      var ca = $(".centeredAd");
      var hhpc = $(".hpCtr");
      var pg = $("#page");
      var lg = $("#logo");
      var sb = $(".searchBar");
      var cc = $(".searchBar .chosen-container, .searchBar select");
      var hsl = $(".hSignLog");
      var sbp = sb.position().left;
      var hd = $("#header");
      var hcp = parseInt(hd.css("padding-left")) * 2;

      $(".mts_widget:empty").hide();

      var tfw = $(".teamsFollowWrap");
      if (tfw.children().length == 0)
      {
         tfw.hide();
         $(".myTeamsHeader").hide();
      }
   };
}

function GetRegistrationPop()
{
   if (readCookie("popupTimeout") == null)
   {
      ajax("/Content/regPromo.aspx", [], function (ret)
      {
         $("body").append(ret);
         $("#regPromoContentCtr, .rpBg").click(function ()
         {
            HideRegistrationPop(7);
         });
         $("#regPromoContentCtr #signUpNow").click(function (e)
         {
            e.stopPropagation();
            GotoRegistration();
         })
         $("#regPromoContentCtr #signInNow").click(function (e)
         {
            e.stopPropagation();
            GotoLogin();
         });
         $("#regPromoContentCtr #never").click(function (e)
         {
            e.stopPropagation();
            HideRegistrationPop(365);
         });
      });
   }
}

function createCookie(name, value, days)
{
   if (days)
   {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      var expires = "; expires=" + date.toGMTString();
   }
   else var expires = "";
   document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name)
{
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for (var i = 0; i < ca.length; i++)
   {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
   }
   return null;
}

function HideRegistrationPop(days)
{
   createCookie("popupTimeout", "", days);
   $(".rpBg, #regPromoContentCtr").fadeTo(1000, 0, function ()
   {
      $(this).hide();
   });
}

function GotoRegistration()
{
   window.location = "/user/register/";
}

function GotoLogin()
{
   window.location = $("#loginBottom").attr("href");
}

function HighlightAutoComplete(childrenCount, a)
{
   for (var i = childrenCount - 1; i >= 0; i--)
   {
      var target = $(a.children()[i]);
      if (i == _autocompIdx)
         target.addClass("highlight");
      else
         target.removeClass("highlight");
   }
}

function SubmitSearch()
{
   var sf = $("#searchFrm"), searchType = $("#searchType"), st = searchType.length > 0 ? searchType[0].options : "";
   if (st.length > 0)
      sf.attr("action", ReplaceQueryParameter(sf.attr("action"), "type", st[st.selectedIndex].value));
   sf.submit();
}

function StartAutoComplete(me, a, action, attach)
{
   if (me.value.length > 0)
   {
      var p = [];
      p.push({ name: "phrase", value: me.value });
      p.push({ name: "ac", value: 1 });
      p.push({ name: "gz", value: "t" });
      p.push({ name: "s", value: "0" });
      p.push({ name: "rt", value: -1 });
      p.push({ name: "n", value: 5 });
      p.push({ name: "sport", value: -1 });
      p.push({ name: "incHid", value: "f" });

      var filters = $("#searchType");
      if (filters.length > 0)
      {
         var types = [],
               options = filters[0].options;
         if (filters.val() == "All")
         {
            // prevent all from getting into type list
            for (var i = options.length - 1; i >= 1; i--)
            {
               types.push(options[i].value);
            }
         }
         else
         {
            types.push(options[options.selectedIndex].value);
         }

         if (types.length > 0)
            p.push({ name: "types", value: types });

         ajax("/api/search.aspx", p, function (r)
         {
            var o; eval("o = " + r + ";");
            if (o.items.length != 0)
            {
               a.html("");
               var attachTarget = typeof (attach) !== "undefined" ? attach : $("#searchTxt");
               var sbh = attachTarget.height();
               var sbt = attachTarget.offset().top;
               var sbl = attachTarget.offset().left;
               a.css({ "top": (sbt + sbh) + 10 + "px" });
               a.css({ "left": sbl + "px" });
               a.show();
               var e = null;
               for (var i = 0; i < o.items.length; i++)
               {
                  e = document.createElement("a");
                  e.className = "itm";
                  e.innerHTML = o.items[i].title;
                  e.id = o.items[i].id;
                  e.href = o.items[i].link;
                  a.append(e);
               }
            }
            else
            {
               $("#acomp").css({ display: "none" });
            }
         });
      }
   }
}

function /*void*/GetSportFromId(id)
{
   if (typeof (_sports) == undefined)
      return id;

   for (var i = _sports.length - 1; i >= 0; i--)
   {
      if (_sports[i].Id == id)
      {
         return _sports[i].UrlName;
         break;
      }
   }

   return id;
}

function /*void*/GetLevelFromId(id)
{
   if (typeof (_levels) == undefined)
      return id;

   for (var i = _levels.length - 1; i >= 0; i--)
   {
      if (_levels[i].Id == id)
      {
         return _levels[i].UrlName;
         break;
      }
   }

   return id;
}

function /*void*/GetGenderFromId(id)
{
   if (typeof (_genders) == undefined)
      return id;

   if (_genders.length < id)
      return id;

   return _genders[id];
}

function /*void*/CreateMenuClick(click, action)
{
   var sections = action.split(',');
   for (var i in sections)
   {
      if (sections[i].length <= 0)
         continue;

      var found = false;
      for (var j in _filterPages)
      {
         if ($.trim(sections[i]) == _filterPages[j])
         {
            found = true;
            break;
         }
      }

      if (!found)
         _filterPages.push($.trim(sections[i]));
   }

   $(click).click(function ()
   {
      FilterContent(action);
   });
}

function /*void*/ToggleMobileMenu()
{
   $(".topTabs").toggleClass('topTabsO');
}

function /*void*/FilterContent(show)
{
   for (var i = _filterPages.length - 1; i >= 0; i--)
      $(_filterPages[i]).hide();

   $(show).show();
}

function /*void*/TrackImpression(eventName, eventType)
{
   TrackingEvent("impression", "DFP Impression", eventName, 1);
}

function /*void*/TrackClick(eventName)
{
   TrackingEvent("click", "DFP Click", eventName, 1);
}

function /*void*/TrackPhoto(imgId)
{
   TrackingEvent("click", "Photo Click", "IMG " + imgId, 1);
}

function /*void*/TrackingEvent(type, category, name, count)
{
   if (typeof (ga) !== "undefined")
   {
      ga("send", "event", name, type, category, count, true);
   }

   if (typeof (_gaq) !== "undefined")
   {
      _gaq.push(["_trackEvent", category, name]);
   }
}

function /*void*/HideAd()
{
   var fav = $(".fullAdView"),
      fpa = $(".fullPageAd");

   fav.fadeTo(600, 0, function ()
   {
      fav.hide();
   });

   fpa.fadeTo(600, 0, function ()
   {
      fpa.hide();
   });
}

function /*void*/AdHeight(/*int*/timer)
{
   var newTimer = timer - 100;

   if (newTimer > 0)
   {
      setTimeout(function ()
      {
         //AdjustAdHeight();
         AdHeight(timer);
      }, newTimer);
   }
}

function /*void*/AdjustAdHeight()
{
   var fav = $(".fullAdView");

   if (fav.length > 0)
      fav.css({ "height": window.innerHeight + window.outerHeight || document.height || $(document).height() });
}

// Position a custom dropdown below the selector
function /*void*/PositionDropdown(me, dropdown)
{
   var sgSelect = $(me),
      position = dropdown.offset(),
      mainCon = $("#mainContainer").offset();

   dropdown.css(
   {
      "top": (sgSelect.offset().top + sgSelect.outerHeight() - mainCon.top) + "px",
      "left": (sgSelect.offset().left - mainCon.left) + "px"
   });
}

function /*void*/CreateSearchButton(/*dom*/searchField, /*dom*/searchButton, /*str*/redirectLocation)
{
   searchField.focus(function ()
   {
      var me = $(this);

      me.select();

      window.setTimeout(function ()
      {
         me.select();
      }, 1);

      // Work around WebKit
      function mouseUpHandler()
      {
         me.off("mouseup", mouseUpHandler);
         return false;
      }

      me.mouseup(mouseUpHandler);
   });

   searchButton.click(function ()
   {
      PerformSearch(searchField, redirectLocation);
   });

   searchField.keyup(function (e)
   {
      if (e.keyCode == 13)
         PerformSearch(searchField, redirectLocation);
   });
}

function /*void*/PerformSearch(/*dom*/searchField, /*str*/redirectLocation)
{
   var searchTerm = $.trim(searchField.val());

   if (searchTerm.length > 0)
      window.location = redirectLocation + encodeURIComponent(escape(searchTerm));
}

function /*void*/CheckAdClick(/*string*/ad)
{
   for (var i = _adClicks.length - 1; i >= 0; i--)
   {
      if (ad == _adClicks[i])
         return false;
   }

   _adClicks.push(ad);

   return true;
}

function SaveToHistory()
{
   try
   {
      // dont save to history if iframe
      if (window.self !== window.top)
         return;
   }
   catch (ex)
   {
      // cross origin may throw error
      return;
   }

   var hist = JSON.parse(sessionStorage.getItem("history"));
   if (hist == null)
      hist = [];

   var prevPage = parseInt(sessionStorage.getItem("lastPg"));
   var back = (sessionStorage.getItem("back") == 'true');
   var histLength = parseInt(sessionStorage.getItem("histLength"));

   if (window.performance.navigation.type == 0 && prevPage != null && !back)
   {
      var idx = -1;
      for (var i = hist.length - 1; i >= 0; i--)
      {
         if (hist[i].id == prevPage)
         {
            idx = i;
            break;
         }
      }

      if (i >= 0)
         hist = hist.splice(0, i + 1);
   }

   if (history != null && typeof history === "object" && history.state !== null)
   {
      var hId = [];
      var count = [];
      hId = $.grep(history.state, function (e)
      {
         return e.name == "historyId";
      });

      count = $.grep(history.state, function (e)
      {
         return e.name == "histCount";
      });

      if (hId.length > 0)
         _MTS_pageId = hId[0].value;

      var idx = -1;
      for (var i = hist.length - 1; i >= 0; i--)
      {
         if (hist[i].id == _MTS_pageId && hist[i].pg == _MTS_pageVP)
         {
            idx = i;
            break;
         }
      }

      if (count.length > 0 && idx >= 0)
      {
         _MTS_histCount = count[0].value;
         hist[idx].count = count[0].value;
      }
   }
   else if (window.performance.navigation.type == 0)
   {
      if (hist.length > 0 && hist[hist.length - 1].pg == _MTS_pageVP)
      {
         _MTS_pageId = hist[hist.length - 1].id;
         if (history.length !== histLength)
            hist[hist.length - 1].count++;
         _MTS_histCount = hist[hist.length - 1].count;
      }
      else
      {
         if (hist.length > 0)
            _MTS_pageId = hist[hist.length - 1].id + 1;

         _MTS_histCount = 1;
         hist.push({ "id": _MTS_pageId, "pg": _MTS_pageVP, "count": _MTS_histCount });
      }
   }

   sessionStorage.setItem("history", JSON.stringify(hist));
   sessionStorage.setItem("lastPg", _MTS_pageId);
   sessionStorage.setItem("back", false);
   sessionStorage.setItem("histLength", history.length);
}

/* extern void *mts_androidApp; */
function /*void*/BackAndRefresh()
{
   if (typeof (mts_androidApp) != "undefined")
   {  // NOW WITH PERSONALITY+1
      mts_androidApp.BackAndRefresh();
      return;
   }

   if (window.history == null || window.history.length <= 1)
      window.close();

   var hist = JSON.parse(sessionStorage.getItem("history"));
   var count = -1;

   if (hist != null)
   {
      var idx = 0;
      for (var i = hist.length - 1; i >= 0; i--)
      {
         if (hist[i].id == _MTS_pageId || hist[i].pg == _MTS_pageVP || hist[i].pg.indexOf("~/Login.aspx") >= 0 || hist[i].pg.indexOf("~/Register.aspx") >= 0)
            idx--;
         else
            break;
      }
      count = idx;
   }

   window.name = "refresh";
   sessionStorage.setItem("back", true);
   window.history.go(count);
}

function /*void*/HoverMenu(/*string*/id, /*string*/type, /*int*/gender)
{
   var width = $(window).width();
   if (width <= 768)
   {
      return false;
   }
   else
   {
      var index = -1;
      for (var i = _menuItem.length - 1; i >= 0; i--)
      {
         if (_menuItem[i].id == id && _menuItem[i].type == type && _menuItem[i].gender == gender)
         {
            index = i
            break;
         }
      }

      if (index == -1)
      {
         _menuItem.push({ "id": id, "type": type, "show": false, "loaded": false, "loading": false, "gender": gender });
         index = _menuItem.length - 1;
      }

      LoadMenu(index, type, gender);
   }
}

function /*void*/UnhoverMenu(/*string*/id, /*string*/type, /*string*/gender)
{
   for (var i = _menuItem.length - 1; i >= 0; i--)
   {
      if (_menuItem[i].id == id && _menuItem[i].type == type && (gender == undefined || _menuItem[i].gender == gender))
      {
         _menuItem[i].show = false;
         return false;
      }
   }
}

function /*void*/holdMenu()
{
   _showMenu = true;
   _justSlided = true;
   setTimeout(function ()
   {
      _justSlided = false;
   }, 400);
}

function /*void*/slideMenu(event, ui)
{
   if (_typeCon != null)
   {
      var height = _typeCon[0].scrollHeight - _typeCon[0].clientHeight;
      _typeCon.scrollTop(height - (height * (ui.value / 100)));
   }
}

function /*void*/LoadMenu(/*string*/id, /*string*/type, /*string*/gender)
{
   if (_menuItem[id].show == true)
      return false;

   _menuItem[id].show = true;

   if (_menuItem[id].loading)
      return false;

   _menuItem[id].loading = true;

   setTimeout(function ()
   {
      if (_menuItem[id].show == true)
      {
         var menu = $(".menuDrop");
         menu.find(".featuredStoryContainer").remove();
         menu.find(".recentHeadlinesContainer").remove();
         menu.find(".noHeadlines").remove();

         if (_menuItem[id].loaded == true)
         {
            menu.append($("#" + type + "_" + _menuItem[id].id + (gender != undefined ? "_" + gender : "")).html());
            _menuItem[id].loading = false;
         }
         else
         {
            var prms = [];

            prms.push({ name: "mode", value: type });
            prms.push({ name: "menuId", value: _menuItem[id].id });

            if (_menuItem[id].gender != null)
               prms.push({ name: "gender", value: _menuItem[id].gender });

            //            ajax("/api/getPortalMenuItems.aspx", prms, function (ret)
            //            {
            //               if (ret.length > 0)
            //               {
            //                  var hiddenMenus = $("#hiddenMenus");
            //                  var hiddenDiv = "<div id='" + type + "_" + _menuItem[id].id + (gender != undefined ? "_" + gender : "") + "'>" + ret + "</div>";

            //                  if (hiddenMenus.length > 0)
            //                     $(hiddenDiv).appendTo(hiddenMenus);
            //                  else
            //                     $("<div id='hiddenMenus' style='display: none'>" + hiddenDiv + "</div>").appendTo($("body"));

            //                  menu.append($(ret));

            //                  _menuItem[id].loaded = true;
            //                  _menuItem[id].loading = false;
            //               }
            //            });
         }
      }
      else
         _menuItem[id].loading = false;
   }, 400);
}

function /*void*/HidePopupMenu(/*bool*/instant)
{
   if (_justSlided)
      return false;

   _showMenu = false;

   if (instant)
   {
      $(".menuDropBg").removeClass('menuDropBgShow').css({ "height": "0px" });
      return false;
   }

   setTimeout(function ()
   {
      if (_showMenu)
         return;
      $(".menuDropBg").removeClass('menuDropBgShow').css({ "height": "0px" });
      $("#div-gpt-ad-728x90_ad_container").show();
   }, 125);
}

function CheckEmailAddress(url)
{
   var regEx = new RegExp(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i);
   if (url.match(regEx))
   {
      return true;
   }

   return false;
}

function CheckForm(/*string*/sendTo, /*string*/emailFrom)
{
   var temp, commaTemp;

   if (sendTo == _emailReq)
   {
      _errorTxt = "You have entered an invalid email address.";
      _focusErr = $("#emailList");
      return false;
   }
   else if (_userId == -1 && emailFrom == _emailFrom)
   {
      _errorTxt = "The from field is required when not logged in.";
      _focusErr = $("#emailFrom");
      return false;
   }

   var array = sendTo.split(';');
   for (var i = 0; i < array.length; i++)
   {
      commaTemp = array[i].split(',');
      for (var j = 0; j < commaTemp.length; j++)
      {
         temp = commaTemp[j].trim();
         if (!CheckEmailAddress(temp))
         {
            _errorTxt = "You have entered an invalid email address.";
            _focusErr = $("#emailList");
            return false;
         }
      }
   }
   return true;
}

var _recaptchaLoaded = false;
function requireCaptcha(callback, action)
{
   if (_recaptchaLoaded)
   {
      sendRecaptcha(key, action, callback, 0);
      return false;
   }

   _recaptchaLoaded = true;
   var jsScript = {
      load: function (src, callback)
      {
         var script = document.createElement('script'),
            loaded;
         script.setAttribute('src', src);
         if (callback)
         {
            script.onreadystatechange = script.onload = function ()
            {
               if (!loaded)
               {
                  callback();
               }
               loaded = true;
            };
         }
         document.getElementsByTagName('head')[0].appendChild(script);
      }
   };

   var key = "6LfGm-cUAAAAADpBRiNHbpTrOzZMn9JcB2UPwhW2";
   jsScript.load("https://www.recaptcha.net/recaptcha/api.js?render=" + key, function ()
   {
      sendRecaptcha(key, action, callback, 0);
   });
}

function sendRecaptcha(key, action, callback, count)
{
   if (count === undefined)
      count = 0;
   else if (count > 20)
      return;

   if (typeof(grecaptcha.execute) === "function")
   {
      grecaptcha.execute(key, { action: action }).then(function (token)
      {
         callback(token);
      });
   }
   else
   {
      count++;
      setTimeout(function ()
      {
         sendRecaptcha(key, action, callback, count);
      }, 250);
   }
}

function emailSend(/*string*/sendTo, /*string*/emailMsg, /*string*/emailFrom, mode)
{
   if (CheckForm(sendTo, emailFrom))
   {
      var isTeam = typeof _teamId === "number" && _teamId > 0;
      var modeCheck = mode ? mode : (isTeam ? "newsItem" : "portalNews");
      requireCaptcha(function (token)
      {
         if (emailMsg == _emailMsgOpt)
            emailMsg = "";

         var prms = [];
         prms.push({ name: "shareId", value: _curShareId });
         prms.push({ name: "emailList", value: sendTo });
         prms.push({ name: "emailMsg", value: emailMsg });
         prms.push({ name: "from", value: emailFrom });
         prms.push({ name: "recaptcha", value: token });
         prms.push({ name: "action", value: modeCheck });
         prms.push({ name: "mode", value: modeCheck });

         if (mode == "video")
            prms.push({ name: "playlistId", value: _playlistId });

         _MTS_JQUERY.post("/api/sendShareEmail.aspx", prms, function (o)
         {
            if (o.ok)
            {
               $(".emailBg").remove();
               $(".emailTemplate").remove();
            }
            else
            {
               // Failure
            }
         }, "json");
      }, modeCheck);
   }
   else
   {
      alert(_errorTxt);
      _focusErr.focus();
      _focusErr.select();
   }
}

function emailShare(/*string*/id)
{
   _curShareId = id;

   var emailHtml =
      "<div class='emailBg'>" +
         "<div class='emailTemplate' id='sendEmail'>" +
            "<div class='emailTempHead'>Share This Story</div>" +
            (_userId > 0 ? "" : "<input title='E-mail From' type='text' class='emailTxt' id='emailFrom' value='" + _emailFrom + "' />") +
            "<input title='E-mail List' type='text' class='emailTxt' id='emailList' value='" + _emailReq + "' />" +
            "<textarea title='Email Message' class='emailTxtArea' id='emailMsg'>" + _emailMsg + "</textarea>" +
            "<div class='tempButtons'>" +
               "<div class='mts_cc_button tempButton' id='emailSend'>Send</div>" +
               "<div class='mts_cc_button tempButton' id='emailCancel'>Cancel</div>" +
            "</div>" +
         "</div > " +
      "</div";

   $("body").append(emailHtml);
   //   CenterElement($(".emailTemplate"));
   $(".emailBg").show();
}

// Formats the information stored in the database for display as html
function /*string*/DbToHtml(/*string*/input)
{
   var keyValues = [];
   keyValues.push({ "oldValue": "\n", "newValue": "<br />" });

   return replace(input, keyValues);
}

// Formats the information displayed as html for database storage
function /*string*/HtmlToDb(/*string*/input)
{
   var keyValues = [];
   keyValues.push({ "oldValue": "<br />", "newValue": "\n" });
   keyValues.push({ "oldValue": "<br>", "newValue": "\n" });
   keyValues.push({ "oldValue": "<BR />", "newValue": "\n" });
   keyValues.push({ "oldValue": "<BR>", "newValue": "\n" });

   return replace(input, keyValues);
}

function /*string*/htmlEncode(/*string*/value)
{
   if (value)
      return jQuery('<div />').text(value).html();
   else
      return '';
}

function /*string*/htmlDecode(/*string*/value)
{
   if (value)
      return $('<div />').html(value).text();
   else
      return '';
}

function /*string*/replace(/*string*/string, /*array*/keyValuePairs)
{
   var regex = null;
   for (var i = 0; i < keyValuePairs.length; i++)
   {
      regex = new RegExp(keyValuePairs[i].oldValue, "g");
      string = string.replace(regex, keyValuePairs[i].newValue);
   }

   return string;
}

function /*void*/CenterElement(/*selector*/element)
{
   var dialog = $(element);
   if (dialog.length === 0)
      return;

   if (dialog[0].parentNode !== document.body)
   {
      dialog[0].parentNode.removeChild(dialog[0]);
      document.body.appendChild(dialog[0]);
   }

   var wWidth = $(window).width();
   var wHeight = $(window).height();

   var dWidth = dialog.outerWidth();
   var dHeight = dialog.outerHeight();

   var top = (wHeight / 2) - (dHeight / 2);
   var left = (wWidth / 2) - (dWidth / 2);

   var sTop = $(document).scrollTop();
   var sLeft = $(document).scrollLeft();

   top += sTop;
   left += sLeft;

   dialog.css(
	{
	   left: left.toString() + "px",
	   top: top.toString() + "px"
	});
}

Array.prototype.param = function (key, value)
{
   this.push({ "name": key, "value": value });
};

Array.prototype.contains = function (value)
{
   for (var i = (this.length - 1) ; i >= 0; --i)
   {
      if (this[i] === value)
         return true;
   }

   return false;
};

/* Removed due to conflict when using for
Array.prototype.remove = function(from, to) {
   var rest = this.slice((to || from) + 1 || this.length);
   this.length = from < 0 ? this.length + from : from;
   return this.push.apply(this, rest);
};*/

function /*string*/getDescription(/*int*/sport, /*string*/level, /*int*/school, /*int*/gender, /*bool*/useDefault)
{
   var description = "/";

   if (level != 0)
   {
      if (useDefault)
         description += "Varsity"
      else
      {
         if ($("#level").length > 0 && $("#level option").length > 0)
            description += $.trim($("#level option:selected").text()).replace(/ /g, "-");
         else if (level == "1")
            description += "Varsity"
      }
   }
   else
      description += "All";

   if (gender != 0 || school != 0)
   {
      description += "/";

      switch (gender)
      {
         default:
            description += "All";
            break;
         case 1:
            description += "Boys";
            break;
         case 2:
            description += "Girls";
            break;
         case 3:
            description += "Coed";
            break;
      }
   }

   if (sport != 0)
   {
      var sportName = "";
      description += "/";

      if (useDefault)
         sportName = _defaultPortalSportName;
      else
      {
         if ($(".sportBanner").length > 0)
            sportName = $(".sportBanner").text();
         else if ($("#sport").length > 0)
         {
            sportName = $("#sport option:selected").text();
            if (sportName.indexOf("Boys") >= 0 || sportName.indexOf("Coed") >= 0)
               sportName = sportName.substring(5);
            else if (sportName.indexOf("Girls") >= 0)
               sportName = sportName.substring(6);
         }
         else
            sportName = _defaultPortalSportName;
      }

      description += $.trim(sportName).replace(/ /g, "-");
   }
   else
      description += "/All";

   if (school != 0)
   {
      var schoolName = "";

      if ($(".schoolName").length > 0)
         schoolName = $.trim($(".schoolName").text());
      else if ($("#school").length > 0)
         schoolName = $("#school option:selected").text();
      else
         schoolName = $("#schoolDrop option:selected").text();

      description += "/" + $.trim(schoolName).replace(/ /g, "-");
   }

   description = description.replace(/ /g, "-");

   if (description == "")
      description = "undefined";

   return description.toLowerCase();
}

function mainLogClick()
{
   var popper = new PopupDialog();
   popper.NewYesNoPrompt("Are you sure you want to log out?", "Log Out", null, function (value, me, passThrough)
   {
      if (value)
      {
         window.location = "/SignOut.aspx";
      }
   });
}

//------------------------------------------- Start Resizing Functions -------------------------------------------\\
var _resizeSelectors = [];
var _readySpool = [];
var _spoolTimer = null;

function SpoolTimeout()
{
   if (_readySpool.length === 0)
   {
      clearInterval(_spoolTimer);
      _spoolTimer = null;
      return;
   }

   var item = _readySpool.pop();
   HeightResizer(item.selector, item.size, item.callback);
}

function PushToSpool(selector, size, callback)
{
   var exists = false;
   for (var i = 0; i < _readySpool.length; i++)
   {
      if (_readySpool[i].selector === selector && _readySpool[i].size === size)
      {
         exists = true;
         break;
      }
   }

   if (!exists)
      _readySpool.push({ "selector": selector, "size": size, "callback": callback });

   if (_spoolTimer == null)
      _spoolTimer = setInterval(SpoolTimeout, 10);
}

$(window).resize(function ()
{
   if ($("#customHeightcss").length > 0)
      $("#customHeightcss").remove();

   $.each(_resizeSelectors, function (i, selector)
   {
      HeightResizer(selector.selector, selector.size);
   });
});

function AddResizeSelector(selector, size, callback)
{
   var exists = false;
   for (var i = 0; i < _resizeSelectors.length; i++)
   {
      if (_resizeSelectors[i].selector === selector && _resizeSelectors[i].size === size)
      {
         exists = true;
         break;
      }
   }

   if (!exists)
   {
      _resizeSelectors.push({ "selector": selector, "size": size, "callback": callback });
      HeightResizer(selector, size, callback);
   }
}

function SetThumbnailHeightFromWidth(selector, callback)
{
   AddResizeSelector(selector, 0, callback);
}

function SetSlideHeightFromWidth(selector)
{
   AddResizeSelector(selector, 1);
}

function SetTeamLogoHeightFromWidth(selector)
{
   AddResizeSelector(selector, 3);
}

function HeightResizer(selector, size, callback)
{
   var me = $(selector + ":visible")
   if (me.length === 0 || (me[0].nodeName == "IMG" && (!me[0].complete || typeof me[0].naturalWidth == 'undefined' || me[0].naturalWidth == 0))
      || (me[0].nodeName != "IMG" && (me.find("img").length == 0 || !me.find("img")[0].complete || typeof me.find("img")[0].naturalWidth == 'undefined' || me.find("img")[0].naturalWidth == 0)))
   {
      PushToSpool(selector, size, callback);
      return;
   }

   $(selector).ready(function ()
   {
      var width;
      var height;

      if (size === 0)
      {
         width = _imageSizes.ThumbnailMxW;
         height = _imageSizes.ThumbnailMxH;
      }
      else if (size === 1)
      {
         width = _imageSizes.SlideShowMxW;
         height = _imageSizes.SlideShowMxH;
      }
      else if (size === 3)
      {
         width = _imageSizes.TeamLogoMxW;
         height = _imageSizes.TeamLogoMxH;
      }
      else
      {
         return;
      }

      var css = document.createElement("style");
      css.setAttribute("type", "text/css");
      css.setAttribute("id", "customHeightcss");
      document.getElementsByTagName('head')[0].appendChild(css);

      me.contents().filter(function () { return this.nodeType === 3; }).remove();
      me.children().contents().filter(function () { return this.nodeType === 3; }).remove(); // clean second level
      me.children().children().contents().filter(function () { return this.nodeType === 3; }).remove(); // clean third

      //console.log($($(selector)[0]).width());
      var node = document.createTextNode(selector + " { height: " + Math.floor(($($(selector + ":visible")[0]).width() / (width / height))) + "px; }");
      $("#customHeightcss").append(node);

      if (typeof (callback) == "function")
         callback();
   });
}
//-------------------------------------------- End Resizing Functions --------------------------------------------\\

function /*void*/AdjustWrap(/*obj*/wrap, /*obj*/around)
{
   var pb = $(wrap), adWrapper = $(around);
   if (pb.length > 0 && adWrapper.length > 0)
   {
      var maxElement = GetElementWithMaxHeight(pb),
         maxHeight = maxElement.outerHeight(true);

      adWrapper.height("auto");
      pb.outerHeight(maxElement.outerHeight());
   }
}

function GetElementWithMaxHeight(obj)
{
   var tallest = null, howTall = null;
   for (var i = obj.length - 1; i >= 0; i--)
   {
      var target = $(obj[i]), tall = target.outerHeight();
      if (howTall == null || howTall < tall)
      {
         tallest = i;
         howTall = tall;
      }
   }

   return $(obj[tallest]);
}

function /*void*/GrabMarginHeight(/*obj*/obj)
{
   var top = parseInt(obj.css("margin-top")),
      bot = parseInt(obj.css("margin-bottom"));

   return (isNaN(top) ? 0 : top) + (isNaN(bot) ? 0 : bot);
}

function /*void*/ValidateNumber(ev)
{
   var theEvent = ev || window.event,
   key = theEvent.keyCode || theEvent.which;

   for (var i = _keyException.length - 1; i >= 0; i--)
   {
      if (_keyException[i] == key)
         return false;
   }

   key = String.fromCharCode(key);
   var regex = /[0-9]|\./;
   if (!regex.test(key))
   {
      theEvent.returnValue = false;
      if (theEvent.preventDefault) theEvent.preventDefault();
   }
}

function loadJSCached(url)
{
   var scripts = $("script"), lowerUrl = url.toLowerCase();
   for (var i = scripts.length - 1; i >= 0; i--)
   {
      if (scripts[i].src.toLowerCase().indexOf(lowerUrl) >= 0)
         return false;
   }

   _jsCachedSequence.push(url);
   startJSGrab();
}

function startJSGrab()
{
   if (!_jsCacheBusy && _jsCachedSequence.length > 0)
      loadJSCachedSequenced(_jsCachedSequence.shift());
}

function loadJSCachedSequenced(url)
{
   _jsCacheBusy = true;
   var script = document.createElement("script");
   script.type = "text/javascript";
   script.src = url;
   script.async = false;
   document.getElementsByTagName("head")[0].appendChild(script);
   _jsCacheBusy = false;
   startJSGrab();
}

function CreateAlertsCookie()
{
   var alerts = $(".alertItem");
   var alertIds = "";

   for (var i = 0; i < alerts.length; i++)
   {
      var id = alerts[i].id.split('_')[2];
      alertIds += id + (i != (alerts.length - 1) ? "," : "");
   }

   var date = new Date();
   // set to expire in 30 days
   date.setTime(date.getTime() + 2592000000);
   var expires = "; expires=" + date.toGMTString();
   document.cookie = "alerts=" + alertIds + expires + "; path=/";
}

function /*void*/ToggleCustomDropdowns(size, selector, disableSearch)
{
   if ($().chosen)
      $(selector == null ? "select:visible" : selector).chosen({ width: typeof (size) === "number" ? size + "px" : "240px", disable_search: disableSearch == null || disableSearch });
}

function ReplaceQueryParameter(uri, key, value)
{
   var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
      separator = uri.indexOf('?') !== -1 ? "&" : "?";
   return uri.match(re) ? uri.replace(re, '$1' + key + "=" + value + '$2') : uri + separator + key + "=" + value;
}

function noPortalVertNav()
{
   //if (_portalId < 1 && $(window).outerWidth() > 1024)
   //{
   //   var nc = $(".navigationContainer");
   //   var hc = $("#headContainer").outerHeight();
   //   nc.css({ "height": ($(window).outerHeight() - hc) + "px" });
   //   var mnc = $(".navigation_menu_widget");
   //   mnc.hide();
   //}
}

function fireEmailRejected()
{
   ajax("/api/changeEmailRejected.aspx", {}, function ()
   {
      alert("Your notifications have been turned off.");
      $(".emailRejected").hide();
   });
}

function WireLockingNotice()
{
   var lockingNotice = $("#mts_unlockstory");
   if (lockingNotice.length > 0)
   {
      lockingNotice.click(function ()
      {
         unlockStory();
      });
   }
}

function unlockStory(callback, id, type)
{
   var lockingNotice = $("#mts_unlockstory");
   var parameters = [];
   parameters.push({ name: "itemId", value: id });
   parameters.push({ name: "tagType", value: type });
   $.post("/api/portalAdmin/unlockPortalNews.aspx", parameters, function (o)
   {
      if (o.ok)
      {
         lockingNotice.slideToggle();
         if (typeof (callback) === "function")
            callback();
      }
   }, "json");
}

function setNav()
{
   if(!$("body").hasClass("vertical") && !$("body").hasClass("mVertical")) {
      //ADJUST NAVIGATION ITEMS IF TOO MANY ITEMS EXIST
      var nct = $(".navigationContainer");
      var nb = $("#navbar.mainNavContainer");
      var namw = $(".navigation_admin_menu_widget");
   
      if (window.matchMedia("(min-width: 1024px)").matches)
      {
         $(".mobileNavItem, .mobileNavSection").hide();
         $(".desktopNavItem").css("display", "inline-block");
         $(".desktopNavSection").css("display", "block");

         var sumi = getHNavItemWidth();
         var sumw = sumi + (_MTS_PORTALID == 25 ? 0 : namw.outerWidth());

         while (sumw > nct.outerWidth())
         {
            if (nb.children(".item:visible:not('.mobileNavItem')").length == 1)
               break;

            var itemc = $("#navbar.mainNavContainer").children(".mnuHeading").last();
            var item = $("#navbar.mainNavContainer a.item:visible:not('.mobileNavItem, .moreList .item')").last();
            $(item).data("itemWidth", item.outerWidth());
            if (!itemc.prev().hasClass("itemAdd"))
            {
               itemc.before(
                  "<div class='itemAdd'><span class='navType'>More</span><i class='fas fa-chevron-down moreItems'></i>" +
                  "<div class='moreListCtr'><div class='moreList'></div></div>" +
                  "</div>"
               );
            }

            var ml = $(".moreList");
            item.detach();
            item.prependTo(ml);
            $(".itemAdd").show();
            sumi = getHNavItemWidth();
            sumw = sumi;
         }

         var ml = $(".moreList");
         var item = ml.children(".item:not('.mobileNavItem')").first();
         while ((sumw + $(item).data("itemWidth")) < nct.outerWidth())
         {
            item.detach();
            $(".itemAdd").before(item);
            if (ml.children(".item").length == 0)
            {
               $(".itemAdd").hide();
               break;
            }
            sumi = getHNavItemWidth();
            sumw = sumi;
            item = ml.children(".item:not('.mobileNavItem')").first();
         }
      } else
      {
         $(".mobileNavItem, .mobileNavSection").show();
         $(".desktopNavItem, .desktopNavSection").hide();

         var ml = $(".moreList");
         item = ml.children(".item");
         item.detach();
         $(".itemAdd").before(item);
         $(".itemAdd").hide();
      }
   }
}

function getHNavItemWidth()
{
   var itema = $("#navbar.mainNavContainer a.item:visible:not('.mobileNavItem, .moreList .item')");
   var width = 0;
   itema.each(function ()
   {
      width += $(this).outerWidth();
   });
   
   if ($(".itemAdd:visible").length > 0)
      width += $(".itemAdd:visible").outerWidth();

   return width;
}

//This function simply checks to see if firefox is the browser, and removes a css white-space property.
function targetFirefoxHeader()
{
   var browser = navigator.userAgent.toLowerCase();
   if (browser.indexOf('firefox') > -1)
   {
      var navc = $(".horizontal .navigationContainer");
      navc.css({"white-space": "normal"});
   }
}

function MTS_startAjax()
{
   MTS_clearAjaxTimer();
   _ajaxSpinTimer = setTimeout(function ()
   {
      $(".busySpinnerBg").show();
   }, 600);
}

function MTS_endAjax()
{
   MTS_clearAjaxTimer();
   $(".busySpinnerBg").hide();
}

function MTS_clearAjaxTimer()
{
   if (_ajaxSpinTimer != null)
   {
      clearTimeout(_ajaxSpinTimer);
      _ajaxSpinTimer = null;
   }
}

function MTS_routeApiCall(map, path, callback, sync, post)
{
   var p = [];
   p.push({ name: "path", value: path });
   p.push({ name: "map", value: map + "&portal_id=" + _MTS_PORTALID });
   
   if (sync) {
      $.ajaxSetup({
         async: false
      });
   }

   if (post)
      $.post("/api/portalAdmin/sendApiRequest.aspx?", p, callback, "json");
   else
      $.getJSON("/api/portalAdmin/sendApiRequest.aspx?", p, callback);

   if (sync) {
      $.ajaxSetup({
         async: true
      });
   }
}

function MTS_validateEmail(email)
{
   return /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/gi.test(email);
}

function getImageLink(image, size)
{
    var cloudUrl = GetCloudUrl(image);
    
   var id = image.id;

   var imageLink = _MTS_PHOTO_TEMPLATE.replace("%%IMG_ID%%", id).replace("%%SIZE%%", size).replace("%%TEAM_ID%%", image.teamId).replace("%%USER_ID%%", image.uploaderId).replace("%%TYPE%%", 0);

    if (image.inCloud && cloudUrl!=null && cloudUrl.length > 0)
   {
      imageLink = cloudUrl + "/" + getBigInt(image.id) + id + (size >= 2 ? "" : "_" + size);
      if (image.webActiveVersion > 1)
         imageLink = imageLink + "_v" + image.webActiveVersion;
   }

   
   return imageLink;
}

function getBigInt(i)
{
   var parts = [0, 0, 0, 0, 0, 0];
   var c = parts.length - 1;

   do
   {
      parts[c] = c == 0 ? Math.floor(i) : Math.floor(i % 1000);
      i /= 1000;
   } while (--c >= 0);

   var builder = "";
   for (var p in parts)
   {
      if (!isNaN(parseInt(p)))
         builder += parseInt(parts[p]) + "/";
   }

   return builder;
}

function GetCloudUrl(image)
{
   var cloudUrl = "";
   if (typeof (_activeContainer) != "undefined")
   {
      for (var i = _activeContainer.portals.length - 1; i >= 0; i--)
      {
         if (_activeContainer.portals[i].id == image.container)
         {
            cloudUrl = _activeContainer.portals[i].url;
            break;
         }
      }
   }

   return cloudUrl;
}

Date.prototype.formatDate = function ()
{
   return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
}

Date.prototype.formatTime = function ()
{
   var hour = this.getHours();
   var isPM = hour > 11;
   if (hour > 12)
      hour -= 12;
   if (hour == 0)
      hour = 12;
   var minute = this.getMinutes();
   return  hour + ":" + (minute < 10 ? "0" : "") + minute + " " + (isPM ? "PM" : "AM");
}

Array.prototype.removeIf = function (callback)
{
   var i = this.length;
   while (i--)
   {
      if (callback(this[i], i))
      {
         this.splice(i, 1);
      }
   }
}

//This function sets the minimum height of the main content to ensure the footer always rests towards bottom of page
function pushFooter()
{
   let customHeader = $(".custom_header_widget");
   let defaultLogo = $(".navigation_logo_widget");
   let defaultNav = $(".navigationContainer");
   let defaultFooter = $(".site_links_widget");
   let footerHeight = defaultFooter.length > 0 ? defaultFooter.outerHeight() : 0;
   let defaultHeaderSum = window.innerHeight - (defaultLogo.outerHeight() + defaultNav.outerHeight() + footerHeight);
   let customHeaderSum = window.innerHeight - (customHeader.outerHeight() + 100); //100 is an arbitrary value to pull footer into view
   let headerHeight = customHeader.length > 0 ? customHeaderSum : defaultHeaderSum;
   let mainContent = document.querySelector(".masterMcWrap");

   if (mainContent != null)
      mainContent.style.setProperty("--pres-mmc-min-height", headerHeight + "px");
}
﻿/*!
 * jQuery Smart Banner
 * Copyright (c) 2012 Arnold Daniels <arnold@jasny.net>
 * Based on 'jQuery Smart Web App Banner' by Kurt Zenisek @ kzeni.com
 */
!function ($) {
    var SmartBanner = function (options) {
//        this.origHtmlMargin = parseFloat($('html').css('margin-top')) // Get the original margin-top of the HTML element so we can take that into account
        this.options = $.extend({}, $.smartbanner.defaults, options)

        var standalone = navigator.standalone // Check if it's already a standalone web app or running within a webui view of an app (not mobile safari)
          , UA = navigator.userAgent

        // Detect banner type (iOS or Android)
        if (this.options.force) {
            this.type = this.options.force
        } else if (UA.match(/iPhone|iPod/i) != null || (UA.match(/iPad/) && this.options.iOSUniversalApp)) {
            if (UA.match(/Safari/i) != null &&
               (UA.match(/CriOS/i) != null ||
               window.Number(UA.substr(UA.indexOf('OS ') + 3, 3).replace('_', '.')) < 6)) this.type = 'ios' // Check webview and native smart banner support (iOS 6+)
        } else if (UA.match(/\bSilk\/(.*\bMobile Safari\b)?/) || UA.match(/\bKF\w/) || UA.match('Kindle Fire')) {
            this.type = 'kindle'
        } else if (UA.match(/Android/i) != null) {
            this.type = 'android'
        } else if (UA.match(/Windows NT 6.2/i) != null && UA.match(/Touch/i) !== null) {
            this.type = 'windows'
        }

        // Don't show banner if device isn't iOS or Android, website is loaded in app or user dismissed banner
        if (!this.type || standalone || this.getCookie('sb-closed') || this.getCookie('sb-installed')) {
            return
        }

        // Calculate scale
        this.scale = this.options.scale == 'auto' ? $(window).width() / window.screen.width : this.options.scale
        if (this.scale < 1) this.scale = 1

        // Get info from meta data
        var meta = $(this.type == 'android' ? 'meta[name="google-play-app"]' :
            this.type == 'ios' ? 'meta[name="apple-itunes-app"]' :
            this.type == 'kindle' ? 'meta[name="kindle-fire-app"]' : 'meta[name="msApplication-ID"]');
        if (meta.length == 0) return

        // For Windows Store apps, get the PackageFamilyName for protocol launch
        if (this.type == 'windows') {
            this.pfn = $('meta[name="msApplication-PackageFamilyName"]').attr('content');
            this.appId = meta.attr('content')[1]
        } else {
            this.appId = /app-id=([^\s,]+)/.exec(meta.attr('content'))[1]
        }

        this.title = this.options.title ? this.options.title : meta.data('title') || $('title').text().replace(/\s*[|\-·].*$/, '')
        this.author = this.options.author ? this.options.author : meta.data('author') || ($('meta[name="author"]').length ? $('meta[name="author"]').attr('content') : window.location.hostname)
        this.iconUrl = meta.data('icon-url');
        this.price = meta.data('price');

        // Create banner
        this.create()
        this.show()
        this.listen()
    }

    SmartBanner.prototype = {

        constructor: SmartBanner

      , create: function() {
            var iconURL
              , link=(this.options.url ? this.options.url : (this.type == 'windows' ? 'ms-windows-store:PDP?PFN=' + this.pfn : (this.type == 'android' ? 'market://details?id=' : (this.type == 'kindle' ? 'amzn://apps/android?asin=' : 'https://itunes.apple.com/' + this.options.appStoreLanguage + '/app/id'))) + this.appId)
              , price = this.price || this.options.price
              , inStore=price ? price + ' - ' + (this.type == 'android' ? this.options.inGooglePlay : this.type == 'kindle' ? this.options.inAmazonAppStore : this.type == 'ios' ? this.options.inAppStore : this.options.inWindowsStore) : ''
              , gloss=this.options.iconGloss === null ? (this.type=='ios') : this.options.iconGloss
            if(this.options.url)
              link = this.options.url
            else {
              if(this.type=='android') {
                link = 'market://details?id=' + this.appId
                if(this.options.GooglePlayParams)
                  link = link + '&referrer=' + this.options.GooglePlayParams
              }
              else
              link = 'https://itunes.apple.com/' + this.options.appStoreLanguage + '/app/id' + this.appId
            }

            var banner = '<div id="smartbanner" class="'+this.type+'"><div class="sb-container"><a title="" href="#" class="sb-close">&times;</a><span class="sb-icon"></span><div class="sb-info"><strong>'+this.title+'</strong><span>'+this.author+'</span><span>'+inStore+'</span></div><a href="'+link+'" class="sb-button"><span>'+this.options.button+'</span></a></div></div>';
            (this.options.layer) ? $(this.options.appendToSelector).append(banner) : $(this.options.appendToSelector).prepend(banner);

            if (this.options.icon) {
                iconURL = this.options.icon
            } else if(this.iconUrl) {
                iconURL = this.iconUrl;
            } else if ($('link[rel="apple-touch-icon-precomposed"]').length > 0) {
                iconURL = $('link[rel="apple-touch-icon-precomposed"]').attr('href')
                if (this.options.iconGloss === null) gloss = false
            } else if ($('link[rel="apple-touch-icon"]').length > 0) {
                iconURL = $('link[rel="apple-touch-icon"]').attr('href')
            } else if ($('meta[name="msApplication-TileImage"]').length > 0) {
              iconURL = $('meta[name="msApplication-TileImage"]').attr('content')
            } else if ($('meta[name="msapplication-TileImage"]').length > 0) { /* redundant because ms docs show two case usages */
              iconURL = $('meta[name="msapplication-TileImage"]').attr('content')
            }

            if (iconURL) {
                $('#smartbanner .sb-icon').css('background-image','url('+iconURL+')')
                if (gloss) $('#smartbanner .sb-icon').addClass('gloss')
            } else{
                $('#smartbanner').addClass('no-icon')
            }

            this.bannerHeight = $('#smartbanner').outerHeight() + 2

            if (this.scale > 1) {
                $('#smartbanner')
                    .css('top', parseFloat($('#smartbanner').css('top')) * this.scale)
                    .css('height', parseFloat($('#smartbanner').css('height')) * this.scale)
                    .hide()
                $('#smartbanner .sb-container')
                    .css('-webkit-transform', 'scale('+this.scale+')')
                    .css('-msie-transform', 'scale('+this.scale+')')
                    .css('-moz-transform', 'scale('+this.scale+')')
                    .css('width', $(window).width() / this.scale)
            }
//            $('#smartbanner').css('position', (this.options.layer) ? 'absolute' : 'static')
        }

      , listen: function () {
            $('#smartbanner .sb-close').on('click',$.proxy(this.close, this))
            $('#smartbanner .sb-button').on('click',$.proxy(this.install, this))
        }

      , show: function(callback) {
            var banner = $('#smartbanner');
            banner.stop();

            if (this.options.layer) {
                banner.animate({top: 0, display: 'block'}, this.options.speedIn).addClass('shown').show();
                $('html').animate({marginTop: this.origHtmlMargin + (this.bannerHeight * this.scale)}, this.options.speedIn, 'swing', callback);
            } else {
                if ($.support.transition) {
                    banner.animate({top:0},this.options.speedIn).addClass('shown');
                    var transitionCallback = function() {
                        $('html').removeClass('sb-animation');
                        if (callback) {
                            callback();
                        }
                    };
                    $('html').addClass('sb-animation').one($.support.transition.end, transitionCallback).emulateTransitionEnd(this.options.speedIn).css('margin-top', this.origHtmlMargin+(this.bannerHeight*this.scale));
                } else {
                    banner.slideDown(this.options.speedIn).addClass('shown');
                }
            }
        }

      , hide: function(callback) {
            var banner = $('#smartbanner');
            banner.stop();

            if (this.options.layer) {
                banner.animate({top: -1 * this.bannerHeight * this.scale, display: 'block'}, this.options.speedIn).removeClass('shown');
                $('html').animate({marginTop: this.origHtmlMargin}, this.options.speedIn, 'swing', callback);
            } else {
               banner.slideUp(this.options.speedOut).removeClass('shown');
            }
        }

      , close: function(e) {
            e.preventDefault()
            this.hide()
            this.setCookie('sb-closed','true',this.options.daysHidden);
        }

      , install: function(e) {
			if (this.options.hideOnInstall) {
				this.hide()
			}
            this.setCookie('sb-installed','true',this.options.daysReminder)
        }

      , setCookie: function(name, value, exdays) {
            var exdate = new Date()
            exdate.setDate(exdate.getDate()+exdays)
            value=encodeURI(value)+((exdays==null)?'':'; expires='+exdate.toUTCString())
            document.cookie=name+'='+value+'; path=/;'
        }

      , getCookie: function(name) {
            var i,x,y,ARRcookies = document.cookie.split(";")
            for(i=0;i<ARRcookies.length;i++) {
                x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("="))
                y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1)
                x = x.replace(/^\s+|\s+$/g,"")
                if (x==name) {
                    return decodeURI(y)
                }
            }
            return null
        }

      // Demo only
      , switchType: function() {
          var that = this

          this.hide(function () {
              that.type = that.type == 'android' ? 'ios' : 'android'
              var meta = $(that.type == 'android' ? 'meta[name="google-play-app"]' : 'meta[name="apple-itunes-app"]').attr('content')
              that.appId = /app-id=([^\s,]+)/.exec(meta)[1]

              $('#smartbanner').detach()
              that.create()
              that.show()
          })
      }
    }

    $.smartbanner = function (option) {
        var $window = $(window)
        , data = $window.data('smartbanner')
        , options = typeof option == 'object' && option
        if (!data) $window.data('smartbanner', (data = new SmartBanner(options)))
        if (typeof option == 'string') data[option]()
    }

    // override these globally if you like (they are all optional)
    $.smartbanner.defaults = {
        title: null, // What the title of the app should be in the banner (defaults to <title>)
        author: null, // What the author of the app should be in the banner (defaults to <meta name="author"> or hostname)
        price: 'FREE', // Price of the app
        appStoreLanguage: 'us', // Language code for App Store
        inAppStore: 'On the App Store', // Text of price for iOS
        inGooglePlay: 'In Google Play', // Text of price for Android
        inAmazonAppStore: 'In the Amazon Appstore',
        inWindowsStore: 'In the Windows Store', //Text of price for Windows
        GooglePlayParams: null, // Aditional parameters for the market
        icon: null, // The URL of the icon (defaults to <meta name="apple-touch-icon">)
        iconGloss: null, // Force gloss effect for iOS even for precomposed
        button: 'VIEW', // Text for the install button
        url: null, // The URL for the button. Keep null if you want the button to link to the app store.
        scale: 'auto', // Scale based on viewport size (set to 1 to disable)
        speedIn: 300, // Show animation speed of the banner
        speedOut: 400, // Close animation speed of the banner
        daysHidden: 15, // Duration to hide the banner after being closed (0 = always show banner)
        daysReminder: 90, // Duration to hide the banner after "VIEW" is clicked *separate from when the close button is clicked* (0 = always show banner)
        force: null, // Choose 'ios', 'android' or 'windows'. Don't do a browser check, just always show this banner
        hideOnInstall: true, // Hide the banner after "VIEW" is clicked.
        layer: false, // Display as overlay layer or slide down the page
        iOSUniversalApp: true, // If the iOS App is a universal app for both iPad and iPhone, display Smart Banner to iPad users, too.
        appendToSelector: 'body' //Append the banner to a specific selector
    }

    $.smartbanner.Constructor = SmartBanner;


    // ============================================================
    // Bootstrap transition
    // Copyright 2011-2014 Twitter, Inc.
    // Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)

    function transitionEnd() {
        var el = document.createElement('smartbanner')

        var transEndEventNames = {
            WebkitTransition: 'webkitTransitionEnd',
            MozTransition: 'transitionend',
            OTransition: 'oTransitionEnd otransitionend',
            transition: 'transitionend'
        }

        for (var name in transEndEventNames) {
            if (el.style[name] !== undefined) {
                return {end: transEndEventNames[name]}
            }
        }

        return false // explicit for ie8 (  ._.)
    }

    if ($.support.transition !== undefined)
        return  // Prevent conflict with Twitter Bootstrap

    // http://blog.alexmaccaw.com/css-transitions
    $.fn.emulateTransitionEnd = function(duration) {
        var called = false, $el = this
        $(this).one($.support.transition.end, function() {
            called = true
        })
        var callback = function() {
            if (!called) $($el).trigger($.support.transition.end)
        }
        setTimeout(callback, duration)
        return this
    }

    $(function() {
        $.support.transition = transitionEnd()
    })
    // ============================================================

}(window.jQuery);

﻿/******************************************************************************************************************************************************
   Return value in findXMPinJPEG function was edited that is not present in the version on the site.
   Function now returns { doc: $.parseXML(xmpString), obj: xml2Object(domDocument) }.
   If replacing this file with updated version from site, these changes will need to be added again along with using xmpdata.obj where xmpdata is used.
******************************************************************************************************************************************************/

(function ()
{

   var debug = false;

   var root = this;

   var EXIF = function (obj)
   {
      if (obj instanceof EXIF) return obj;
      if (!(this instanceof EXIF)) return new EXIF(obj);
      this.EXIFwrapped = obj;
   };

   if (typeof exports !== 'undefined')
   {
      if (typeof module !== 'undefined' && module.exports)
      {
         exports = module.exports = EXIF;
      }
      exports.EXIF = EXIF;
   } else
   {
      root.EXIF = EXIF;
   }

   var ExifTags = EXIF.Tags = {

      // version tags
      0x9000: "ExifVersion",             // EXIF version
      0xA000: "FlashpixVersion",         // Flashpix format version

      // colorspace tags
      0xA001: "ColorSpace",              // Color space information tag

      // image configuration
      0xA002: "PixelXDimension",         // Valid width of meaningful image
      0xA003: "PixelYDimension",         // Valid height of meaningful image
      0x9101: "ComponentsConfiguration", // Information about channels
      0x9102: "CompressedBitsPerPixel",  // Compressed bits per pixel

      // user information
      0x927C: "MakerNote",               // Any desired information written by the manufacturer
      0x9286: "UserComment",             // Comments by user

      // related file
      0xA004: "RelatedSoundFile",        // Name of related sound file

      // date and time
      0x9003: "DateTimeOriginal",        // Date and time when the original image was generated
      0x9004: "DateTimeDigitized",       // Date and time when the image was stored digitally
      0x9290: "SubsecTime",              // Fractions of seconds for DateTime
      0x9291: "SubsecTimeOriginal",      // Fractions of seconds for DateTimeOriginal
      0x9292: "SubsecTimeDigitized",     // Fractions of seconds for DateTimeDigitized

      // picture-taking conditions
      0x829A: "ExposureTime",            // Exposure time (in seconds)
      0x829D: "FNumber",                 // F number
      0x8822: "ExposureProgram",         // Exposure program
      0x8824: "SpectralSensitivity",     // Spectral sensitivity
      0x8827: "ISOSpeedRatings",         // ISO speed rating
      0x8828: "OECF",                    // Optoelectric conversion factor
      0x9201: "ShutterSpeedValue",       // Shutter speed
      0x9202: "ApertureValue",           // Lens aperture
      0x9203: "BrightnessValue",         // Value of brightness
      0x9204: "ExposureBias",            // Exposure bias
      0x9205: "MaxApertureValue",        // Smallest F number of lens
      0x9206: "SubjectDistance",         // Distance to subject in meters
      0x9207: "MeteringMode",            // Metering mode
      0x9208: "LightSource",             // Kind of light source
      0x9209: "Flash",                   // Flash status
      0x9214: "SubjectArea",             // Location and area of main subject
      0x920A: "FocalLength",             // Focal length of the lens in mm
      0xA20B: "FlashEnergy",             // Strobe energy in BCPS
      0xA20C: "SpatialFrequencyResponse",    //
      0xA20E: "FocalPlaneXResolution",   // Number of pixels in width direction per FocalPlaneResolutionUnit
      0xA20F: "FocalPlaneYResolution",   // Number of pixels in height direction per FocalPlaneResolutionUnit
      0xA210: "FocalPlaneResolutionUnit",    // Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution
      0xA214: "SubjectLocation",         // Location of subject in image
      0xA215: "ExposureIndex",           // Exposure index selected on camera
      0xA217: "SensingMethod",           // Image sensor type
      0xA300: "FileSource",              // Image source (3 == DSC)
      0xA301: "SceneType",               // Scene type (1 == directly photographed)
      0xA302: "CFAPattern",              // Color filter array geometric pattern
      0xA401: "CustomRendered",          // Special processing
      0xA402: "ExposureMode",            // Exposure mode
      0xA403: "WhiteBalance",            // 1 = auto white balance, 2 = manual
      0xA404: "DigitalZoomRation",       // Digital zoom ratio
      0xA405: "FocalLengthIn35mmFilm",   // Equivalent foacl length assuming 35mm film camera (in mm)
      0xA406: "SceneCaptureType",        // Type of scene
      0xA407: "GainControl",             // Degree of overall image gain adjustment
      0xA408: "Contrast",                // Direction of contrast processing applied by camera
      0xA409: "Saturation",              // Direction of saturation processing applied by camera
      0xA40A: "Sharpness",               // Direction of sharpness processing applied by camera
      0xA40B: "DeviceSettingDescription",    //
      0xA40C: "SubjectDistanceRange",    // Distance to subject

      // other tags
      0xA005: "InteroperabilityIFDPointer",
      0xA420: "ImageUniqueID"            // Identifier assigned uniquely to each image
   };

   var TiffTags = EXIF.TiffTags = {
      0x0100: "ImageWidth",
      0x0101: "ImageHeight",
      0x8769: "ExifIFDPointer",
      0x8825: "GPSInfoIFDPointer",
      0xA005: "InteroperabilityIFDPointer",
      0x0102: "BitsPerSample",
      0x0103: "Compression",
      0x0106: "PhotometricInterpretation",
      0x0112: "Orientation",
      0x0115: "SamplesPerPixel",
      0x011C: "PlanarConfiguration",
      0x0212: "YCbCrSubSampling",
      0x0213: "YCbCrPositioning",
      0x011A: "XResolution",
      0x011B: "YResolution",
      0x0128: "ResolutionUnit",
      0x0111: "StripOffsets",
      0x0116: "RowsPerStrip",
      0x0117: "StripByteCounts",
      0x0201: "JPEGInterchangeFormat",
      0x0202: "JPEGInterchangeFormatLength",
      0x012D: "TransferFunction",
      0x013E: "WhitePoint",
      0x013F: "PrimaryChromaticities",
      0x0211: "YCbCrCoefficients",
      0x0214: "ReferenceBlackWhite",
      0x0132: "DateTime",
      0x010E: "ImageDescription",
      0x010F: "Make",
      0x0110: "Model",
      0x0131: "Software",
      0x013B: "Artist",
      0x8298: "Copyright"
   };

   var GPSTags = EXIF.GPSTags = {
      0x0000: "GPSVersionID",
      0x0001: "GPSLatitudeRef",
      0x0002: "GPSLatitude",
      0x0003: "GPSLongitudeRef",
      0x0004: "GPSLongitude",
      0x0005: "GPSAltitudeRef",
      0x0006: "GPSAltitude",
      0x0007: "GPSTimeStamp",
      0x0008: "GPSSatellites",
      0x0009: "GPSStatus",
      0x000A: "GPSMeasureMode",
      0x000B: "GPSDOP",
      0x000C: "GPSSpeedRef",
      0x000D: "GPSSpeed",
      0x000E: "GPSTrackRef",
      0x000F: "GPSTrack",
      0x0010: "GPSImgDirectionRef",
      0x0011: "GPSImgDirection",
      0x0012: "GPSMapDatum",
      0x0013: "GPSDestLatitudeRef",
      0x0014: "GPSDestLatitude",
      0x0015: "GPSDestLongitudeRef",
      0x0016: "GPSDestLongitude",
      0x0017: "GPSDestBearingRef",
      0x0018: "GPSDestBearing",
      0x0019: "GPSDestDistanceRef",
      0x001A: "GPSDestDistance",
      0x001B: "GPSProcessingMethod",
      0x001C: "GPSAreaInformation",
      0x001D: "GPSDateStamp",
      0x001E: "GPSDifferential"
   };

   // EXIF 2.3 Spec
   var IFD1Tags = EXIF.IFD1Tags = {
      0x0100: "ImageWidth",
      0x0101: "ImageHeight",
      0x0102: "BitsPerSample",
      0x0103: "Compression",
      0x0106: "PhotometricInterpretation",
      0x0111: "StripOffsets",
      0x0112: "Orientation",
      0x0115: "SamplesPerPixel",
      0x0116: "RowsPerStrip",
      0x0117: "StripByteCounts",
      0x011A: "XResolution",
      0x011B: "YResolution",
      0x011C: "PlanarConfiguration",
      0x0128: "ResolutionUnit",
      0x0201: "JpegIFOffset",    // When image format is JPEG, this value show offset to JPEG data stored.(aka "ThumbnailOffset" or "JPEGInterchangeFormat")
      0x0202: "JpegIFByteCount", // When image format is JPEG, this value shows data size of JPEG image (aka "ThumbnailLength" or "JPEGInterchangeFormatLength")
      0x0211: "YCbCrCoefficients",
      0x0212: "YCbCrSubSampling",
      0x0213: "YCbCrPositioning",
      0x0214: "ReferenceBlackWhite"
   };

   var StringValues = EXIF.StringValues = {
      ExposureProgram: {
         0: "Not defined",
         1: "Manual",
         2: "Normal program",
         3: "Aperture priority",
         4: "Shutter priority",
         5: "Creative program",
         6: "Action program",
         7: "Portrait mode",
         8: "Landscape mode"
      },
      MeteringMode: {
         0: "Unknown",
         1: "Average",
         2: "CenterWeightedAverage",
         3: "Spot",
         4: "MultiSpot",
         5: "Pattern",
         6: "Partial",
         255: "Other"
      },
      LightSource: {
         0: "Unknown",
         1: "Daylight",
         2: "Fluorescent",
         3: "Tungsten (incandescent light)",
         4: "Flash",
         9: "Fine weather",
         10: "Cloudy weather",
         11: "Shade",
         12: "Daylight fluorescent (D 5700 - 7100K)",
         13: "Day white fluorescent (N 4600 - 5400K)",
         14: "Cool white fluorescent (W 3900 - 4500K)",
         15: "White fluorescent (WW 3200 - 3700K)",
         17: "Standard light A",
         18: "Standard light B",
         19: "Standard light C",
         20: "D55",
         21: "D65",
         22: "D75",
         23: "D50",
         24: "ISO studio tungsten",
         255: "Other"
      },
      Flash: {
         0x0000: "Flash did not fire",
         0x0001: "Flash fired",
         0x0005: "Strobe return light not detected",
         0x0007: "Strobe return light detected",
         0x0009: "Flash fired, compulsory flash mode",
         0x000D: "Flash fired, compulsory flash mode, return light not detected",
         0x000F: "Flash fired, compulsory flash mode, return light detected",
         0x0010: "Flash did not fire, compulsory flash mode",
         0x0018: "Flash did not fire, auto mode",
         0x0019: "Flash fired, auto mode",
         0x001D: "Flash fired, auto mode, return light not detected",
         0x001F: "Flash fired, auto mode, return light detected",
         0x0020: "No flash function",
         0x0041: "Flash fired, red-eye reduction mode",
         0x0045: "Flash fired, red-eye reduction mode, return light not detected",
         0x0047: "Flash fired, red-eye reduction mode, return light detected",
         0x0049: "Flash fired, compulsory flash mode, red-eye reduction mode",
         0x004D: "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",
         0x004F: "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",
         0x0059: "Flash fired, auto mode, red-eye reduction mode",
         0x005D: "Flash fired, auto mode, return light not detected, red-eye reduction mode",
         0x005F: "Flash fired, auto mode, return light detected, red-eye reduction mode"
      },
      SensingMethod: {
         1: "Not defined",
         2: "One-chip color area sensor",
         3: "Two-chip color area sensor",
         4: "Three-chip color area sensor",
         5: "Color sequential area sensor",
         7: "Trilinear sensor",
         8: "Color sequential linear sensor"
      },
      SceneCaptureType: {
         0: "Standard",
         1: "Landscape",
         2: "Portrait",
         3: "Night scene"
      },
      SceneType: {
         1: "Directly photographed"
      },
      CustomRendered: {
         0: "Normal process",
         1: "Custom process"
      },
      WhiteBalance: {
         0: "Auto white balance",
         1: "Manual white balance"
      },
      GainControl: {
         0: "None",
         1: "Low gain up",
         2: "High gain up",
         3: "Low gain down",
         4: "High gain down"
      },
      Contrast: {
         0: "Normal",
         1: "Soft",
         2: "Hard"
      },
      Saturation: {
         0: "Normal",
         1: "Low saturation",
         2: "High saturation"
      },
      Sharpness: {
         0: "Normal",
         1: "Soft",
         2: "Hard"
      },
      SubjectDistanceRange: {
         0: "Unknown",
         1: "Macro",
         2: "Close view",
         3: "Distant view"
      },
      FileSource: {
         3: "DSC"
      },

      Components: {
         0: "",
         1: "Y",
         2: "Cb",
         3: "Cr",
         4: "R",
         5: "G",
         6: "B"
      }
   };

   function addEvent(element, event, handler)
   {
      if (element.addEventListener)
      {
         element.addEventListener(event, handler, false);
      } else if (element.attachEvent)
      {
         element.attachEvent("on" + event, handler);
      }
   }

   function imageHasData(img)
   {
      return !!(img.exifdata);
   }


   function base64ToArrayBuffer(base64, contentType)
   {
      contentType = contentType || base64.match(/^data\:([^\;]+)\;base64,/mi)[1] || ''; // e.g. 'data:image/jpeg;base64,...' => 'image/jpeg'
      base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
      var binary = atob(base64);
      var len = binary.length;
      var buffer = new ArrayBuffer(len);
      var view = new Uint8Array(buffer);
      for (var i = 0; i < len; i++)
      {
         view[i] = binary.charCodeAt(i);
      }
      return buffer;
   }

   function objectURLToBlob(url, callback)
   {
      var http = new XMLHttpRequest();
      http.open("GET", url, true);
      http.responseType = "blob";
      http.onload = function (e)
      {
         if (this.status == 200 || this.status === 0)
         {
            callback(this.response);
         }
      };
      http.send();
   }

   function getImageData(img, callback)
   {
      function handleBinaryFile(binFile)
      {
         var data = findEXIFinJPEG(binFile);
         img.exifdata = data || {};
         var iptcdata = findIPTCinJPEG(binFile);
         img.iptcdata = iptcdata || {};
         if (EXIF.isXmpEnabled)
         {
            var xmpdata = {};
            try
            {
               xmpdata = findXMPinJPEG(binFile);
            }
            catch (ex)
            {

            }
            img.xmpdata = xmpdata || {};
         }
         if (callback)
         {
            callback.call(img);
         }
      }

      if (img.src)
      {
         if (/^data\:/i.test(img.src))
         { // Data URI
            var arrayBuffer = base64ToArrayBuffer(img.src);
            handleBinaryFile(arrayBuffer);

         } else if (/^blob\:/i.test(img.src))
         { // Object URL
            var fileReader = new FileReader();
            fileReader.onload = function (e)
            {
               handleBinaryFile(e.target.result);
            };
            objectURLToBlob(img.src, function (blob)
            {
               fileReader.readAsArrayBuffer(blob);
            });
         } else
         {
            var http = new XMLHttpRequest();
            http.onload = function ()
            {
               if (this.status == 200 || this.status === 0)
               {
                  handleBinaryFile(http.response);
               } else
               {
                  throw "Could not load image";
               }
               http = null;
            };
            http.open("GET", img.src, true);
            http.responseType = "arraybuffer";
            http.send(null);
         }
      } else if (self.FileReader && (img instanceof self.Blob || img instanceof self.File))
      {
         var fileReader = new FileReader();
         fileReader.onload = function (e)
         {
            if (debug) console.log("Got file of length " + e.target.result.byteLength);
            handleBinaryFile(e.target.result);
         };

         fileReader.readAsArrayBuffer(img);
      }
   }

   function findEXIFinJPEG(file)
   {
      var dataView = new DataView(file);

      if (debug) console.log("Got file of length " + file.byteLength);
      if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8))
      {
         if (debug) console.log("Not a valid JPEG");
         return false; // not a valid jpeg
      }

      var offset = 2,
          length = file.byteLength,
          marker;

      while (offset < length)
      {
         if (dataView.getUint8(offset) != 0xFF)
         {
            if (debug) console.log("Not a valid marker at offset " + offset + ", found: " + dataView.getUint8(offset));
            return false; // not a valid marker, something is wrong
         }

         marker = dataView.getUint8(offset + 1);
         if (debug) console.log(marker);

         // we could implement handling for other markers here,
         // but we're only looking for 0xFFE1 for EXIF data

         if (marker == 225)
         {
            if (debug) console.log("Found 0xFFE1 marker");

            return readEXIFData(dataView, offset + 4, dataView.getUint16(offset + 2) - 2);

            // offset += 2 + file.getShortAt(offset+2, true);

         } else
         {
            offset += 2 + dataView.getUint16(offset + 2);
         }

      }

   }

   function findIPTCinJPEG(file)
   {
      var dataView = new DataView(file);

      if (debug) console.log("Got file of length " + file.byteLength);
      if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8))
      {
         if (debug) console.log("Not a valid JPEG");
         return false; // not a valid jpeg
      }

      var offset = 2,
          length = file.byteLength;


      var isFieldSegmentStart = function (dataView, offset)
      {
         return (
             dataView.getUint8(offset) === 0x38 &&
             dataView.getUint8(offset + 1) === 0x42 &&
             dataView.getUint8(offset + 2) === 0x49 &&
             dataView.getUint8(offset + 3) === 0x4D &&
             dataView.getUint8(offset + 4) === 0x04 &&
             dataView.getUint8(offset + 5) === 0x04
         );
      };

      while (offset < length)
      {

         if (isFieldSegmentStart(dataView, offset))
         {

            // Get the length of the name header (which is padded to an even number of bytes)
            var nameHeaderLength = dataView.getUint8(offset + 7);
            if (nameHeaderLength % 2 !== 0) nameHeaderLength += 1;
            // Check for pre photoshop 6 format
            if (nameHeaderLength === 0)
            {
               // Always 4
               nameHeaderLength = 4;
            }

            var startOffset = offset + 8 + nameHeaderLength;
            var sectionLength = dataView.getUint16(offset + 6 + nameHeaderLength);

            return readIPTCData(file, startOffset, sectionLength);

            break;

         }


         // Not the marker, continue searching
         offset++;

      }

   }
   var IptcFieldMap = {
      0x78: 'caption',
      0x6E: 'credit',
      0x19: 'keywords',
      0x37: 'dateCreated',
      0x50: 'byline',
      0x55: 'bylineTitle',
      0x7A: 'captionWriter',
      0x69: 'headline',
      0x74: 'copyright',
      0x0F: 'category'
   };
   function readIPTCData(file, startOffset, sectionLength)
   {
      var dataView = new DataView(file);
      var data = {};
      var fieldValue, fieldName, dataSize, segmentType, segmentSize;
      var segmentStartPos = startOffset;
      while (segmentStartPos < startOffset + sectionLength)
      {
         if (dataView.getUint8(segmentStartPos) === 0x1C && dataView.getUint8(segmentStartPos + 1) === 0x02)
         {
            segmentType = dataView.getUint8(segmentStartPos + 2);
            if (segmentType in IptcFieldMap)
            {
               dataSize = dataView.getInt16(segmentStartPos + 3);
               segmentSize = dataSize + 5;
               fieldName = IptcFieldMap[segmentType];
               fieldValue = getStringFromDB(dataView, segmentStartPos + 5, dataSize);
               // Check if we already stored a value with this name
               if (data.hasOwnProperty(fieldName))
               {
                  // Value already stored with this name, create multivalue field
                  if (data[fieldName] instanceof Array)
                  {
                     data[fieldName].push(fieldValue);
                  }
                  else
                  {
                     data[fieldName] = [data[fieldName], fieldValue];
                  }
               }
               else
               {
                  data[fieldName] = fieldValue;
               }
            }

         }
         segmentStartPos++;
      }
      return data;
   }



   function readTags(file, tiffStart, dirStart, strings, bigEnd)
   {
      var entries = file.getUint16(dirStart, !bigEnd),
          tags = {},
          entryOffset, tag,
          i;

      for (i = 0; i < entries; i++)
      {
         entryOffset = dirStart + i * 12 + 2;
         tag = strings[file.getUint16(entryOffset, !bigEnd)];
         if (!tag && debug) console.log("Unknown tag: " + file.getUint16(entryOffset, !bigEnd));
         try
         {
            tags[tag] = readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd);
         }
         catch (ex)
         {

         }
      }
      return tags;
   }


   function readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd)
   {
      var type = file.getUint16(entryOffset + 2, !bigEnd),
          numValues = file.getUint32(entryOffset + 4, !bigEnd),
          valueOffset = file.getUint32(entryOffset + 8, !bigEnd) + tiffStart,
          offset,
          vals, val, n,
          numerator, denominator;

      switch (type)
      {
         case 1: // byte, 8-bit unsigned int
         case 7: // undefined, 8-bit byte, value depending on field
            if (numValues == 1)
            {
               return file.getUint8(entryOffset + 8, !bigEnd);
            } else
            {
               offset = numValues > 4 ? valueOffset : (entryOffset + 8);
               vals = [];
               for (n = 0; n < numValues; n++)
               {
                  vals[n] = file.getUint8(offset + n);
               }
               return vals;
            }

         case 2: // ascii, 8-bit byte
            offset = numValues > 4 ? valueOffset : (entryOffset + 8);
            return getStringFromDB(file, offset, numValues - 1);

         case 3: // short, 16 bit int
            if (numValues == 1)
            {
               return file.getUint16(entryOffset + 8, !bigEnd);
            } else
            {
               offset = numValues > 2 ? valueOffset : (entryOffset + 8);
               vals = [];
               for (n = 0; n < numValues; n++)
               {
                  vals[n] = file.getUint16(offset + 2 * n, !bigEnd);
               }
               return vals;
            }

         case 4: // long, 32 bit int
            if (numValues == 1)
            {
               return file.getUint32(entryOffset + 8, !bigEnd);
            } else
            {
               vals = [];
               for (n = 0; n < numValues; n++)
               {
                  vals[n] = file.getUint32(valueOffset + 4 * n, !bigEnd);
               }
               return vals;
            }

         case 5:    // rational = two long values, first is numerator, second is denominator
            if (numValues == 1)
            {
               numerator = file.getUint32(valueOffset, !bigEnd);
               denominator = file.getUint32(valueOffset + 4, !bigEnd);
               val = new Number(numerator / denominator);
               val.numerator = numerator;
               val.denominator = denominator;
               return val;
            } else
            {
               vals = [];
               for (n = 0; n < numValues; n++)
               {
                  numerator = file.getUint32(valueOffset + 8 * n, !bigEnd);
                  denominator = file.getUint32(valueOffset + 4 + 8 * n, !bigEnd);
                  vals[n] = new Number(numerator / denominator);
                  vals[n].numerator = numerator;
                  vals[n].denominator = denominator;
               }
               return vals;
            }

         case 9: // slong, 32 bit signed int
            if (numValues == 1)
            {
               return file.getInt32(entryOffset + 8, !bigEnd);
            } else
            {
               vals = [];
               for (n = 0; n < numValues; n++)
               {
                  vals[n] = file.getInt32(valueOffset + 4 * n, !bigEnd);
               }
               return vals;
            }

         case 10: // signed rational, two slongs, first is numerator, second is denominator
            if (numValues == 1)
            {
               return file.getInt32(valueOffset, !bigEnd) / file.getInt32(valueOffset + 4, !bigEnd);
            } else
            {
               vals = [];
               for (n = 0; n < numValues; n++)
               {
                  vals[n] = file.getInt32(valueOffset + 8 * n, !bigEnd) / file.getInt32(valueOffset + 4 + 8 * n, !bigEnd);
               }
               return vals;
            }
      }
   }

   /**
   * Given an IFD (Image File Directory) start offset
   * returns an offset to next IFD or 0 if it's the last IFD.
   */
   function getNextIFDOffset(dataView, dirStart, bigEnd)
   {
      //the first 2bytes means the number of directory entries contains in this IFD
      var entries = dataView.getUint16(dirStart, !bigEnd);

      // After last directory entry, there is a 4bytes of data,
      // it means an offset to next IFD.
      // If its value is '0x00000000', it means this is the last IFD and there is no linked IFD.

      return dataView.getUint32(dirStart + 2 + entries * 12, !bigEnd); // each entry is 12 bytes long
   }

   function readThumbnailImage(dataView, tiffStart, firstIFDOffset, bigEnd)
   {
      // get the IFD1 offset
      var IFD1OffsetPointer = getNextIFDOffset(dataView, tiffStart + firstIFDOffset, bigEnd);

      if (!IFD1OffsetPointer)
      {
         // console.log('******** IFD1Offset is empty, image thumb not found ********');
         return {};
      }
      else if (IFD1OffsetPointer > dataView.byteLength)
      { // this should not happen
         // console.log('******** IFD1Offset is outside the bounds of the DataView ********');
         return {};
      }
      // console.log('*******  thumbnail IFD offset (IFD1) is: %s', IFD1OffsetPointer);

      var thumbTags = readTags(dataView, tiffStart, tiffStart + IFD1OffsetPointer, IFD1Tags, bigEnd)

      // EXIF 2.3 specification for JPEG format thumbnail

      // If the value of Compression(0x0103) Tag in IFD1 is '6', thumbnail image format is JPEG.
      // Most of Exif image uses JPEG format for thumbnail. In that case, you can get offset of thumbnail
      // by JpegIFOffset(0x0201) Tag in IFD1, size of thumbnail by JpegIFByteCount(0x0202) Tag.
      // Data format is ordinary JPEG format, starts from 0xFFD8 and ends by 0xFFD9. It seems that
      // JPEG format and 160x120pixels of size are recommended thumbnail format for Exif2.1 or later.

      if (thumbTags['Compression'])
      {
         // console.log('Thumbnail image found!');

         switch (thumbTags['Compression'])
         {
            case 6:
               // console.log('Thumbnail image format is JPEG');
               if (thumbTags.JpegIFOffset && thumbTags.JpegIFByteCount)
               {
                  // extract the thumbnail
                  var tOffset = tiffStart + thumbTags.JpegIFOffset;
                  var tLength = thumbTags.JpegIFByteCount;
                  thumbTags['blob'] = new Blob([new Uint8Array(dataView.buffer, tOffset, tLength)], {
                     type: 'image/jpeg'
                  });
               }
               break;

            case 1:
               console.log("Thumbnail image format is TIFF, which is not implemented.");
               break;
            default:
               console.log("Unknown thumbnail image format '%s'", thumbTags['Compression']);
         }
      }
      else if (thumbTags['PhotometricInterpretation'] == 2)
      {
         console.log("Thumbnail image format is RGB, which is not implemented.");
      }
      return thumbTags;
   }

   function getStringFromDB(buffer, start, length)
   {
      var outstr = "";
      for (var n = start; n < start + length; n++)
      {
         outstr += String.fromCharCode(buffer.getUint8(n));
      }
      return outstr;
   }

   function readEXIFData(file, start)
   {
      if (getStringFromDB(file, start, 4) != "Exif")
      {
         if (debug) console.log("Not valid EXIF data! " + getStringFromDB(file, start, 4));
         return false;
      }

      var bigEnd,
          tags, tag,
          exifData, gpsData,
          tiffOffset = start + 6;

      // test for TIFF validity and endianness
      if (file.getUint16(tiffOffset) == 0x4949)
      {
         bigEnd = false;
      } else if (file.getUint16(tiffOffset) == 0x4D4D)
      {
         bigEnd = true;
      } else
      {
         if (debug) console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
         return false;
      }

      if (file.getUint16(tiffOffset + 2, !bigEnd) != 0x002A)
      {
         if (debug) console.log("Not valid TIFF data! (no 0x002A)");
         return false;
      }

      var firstIFDOffset = file.getUint32(tiffOffset + 4, !bigEnd);

      if (firstIFDOffset < 0x00000008)
      {
         if (debug) console.log("Not valid TIFF data! (First offset less than 8)", file.getUint32(tiffOffset + 4, !bigEnd));
         return false;
      }

      tags = readTags(file, tiffOffset, tiffOffset + firstIFDOffset, TiffTags, bigEnd);

      if (tags.ExifIFDPointer)
      {
         exifData = readTags(file, tiffOffset, tiffOffset + tags.ExifIFDPointer, ExifTags, bigEnd);
         for (tag in exifData)
         {
            switch (tag)
            {
               case "LightSource":
               case "Flash":
               case "MeteringMode":
               case "ExposureProgram":
               case "SensingMethod":
               case "SceneCaptureType":
               case "SceneType":
               case "CustomRendered":
               case "WhiteBalance":
               case "GainControl":
               case "Contrast":
               case "Saturation":
               case "Sharpness":
               case "SubjectDistanceRange":
               case "FileSource":
                  exifData[tag] = StringValues[tag][exifData[tag]];
                  break;

               case "ExifVersion":
               case "FlashpixVersion":
                  exifData[tag] = String.fromCharCode(exifData[tag][0], exifData[tag][1], exifData[tag][2], exifData[tag][3]);
                  break;

               case "ComponentsConfiguration":
                  exifData[tag] =
                      StringValues.Components[exifData[tag][0]] +
                      StringValues.Components[exifData[tag][1]] +
                      StringValues.Components[exifData[tag][2]] +
                      StringValues.Components[exifData[tag][3]];
                  break;
            }
            tags[tag] = exifData[tag];
         }
      }

      if (tags.GPSInfoIFDPointer)
      {
         gpsData = readTags(file, tiffOffset, tiffOffset + tags.GPSInfoIFDPointer, GPSTags, bigEnd);
         for (tag in gpsData)
         {
            switch (tag)
            {
               case "GPSVersionID":
                  gpsData[tag] = gpsData[tag][0] +
                      "." + gpsData[tag][1] +
                      "." + gpsData[tag][2] +
                      "." + gpsData[tag][3];
                  break;
            }
            tags[tag] = gpsData[tag];
         }
      }

      // extract thumbnail
      tags['thumbnail'] = readThumbnailImage(file, tiffOffset, firstIFDOffset, bigEnd);

      return tags;
   }

   function findXMPinJPEG(file)
   {

      if (!('DOMParser' in self))
      {
         // console.warn('XML parsing not supported without DOMParser');
         return;
      }
      var dataView = new DataView(file);

      if (debug) console.log("Got file of length " + file.byteLength);
      if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8))
      {
         if (debug) console.log("Not a valid JPEG");
         return false; // not a valid jpeg
      }

      var offset = 2,
          length = file.byteLength,
          dom = new DOMParser();

      while (offset < (length - 4))
      {
         if (getStringFromDB(dataView, offset, 4) == "http")
         {
            var startOffset = offset - 1;
            var sectionLength = dataView.getUint16(offset - 2) - 1;
            var xmpString = getStringFromDB(dataView, startOffset, sectionLength)
            var xmpEndIndex = xmpString.indexOf('xmpmeta>') + 8;
            xmpString = xmpString.substring(xmpString.indexOf('<x:xmpmeta'), xmpEndIndex);

            var indexOfXmp = xmpString.indexOf('x:xmpmeta') + 10
            //Many custom written programs embed xmp/xml without any namespace. Following are some of them.
            //Without these namespaces, XML is thought to be invalid by parsers
            xmpString = xmpString.slice(0, indexOfXmp)
                        + 'xmlns:Iptc4xmpCore="http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/" '
                        + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
                        + 'xmlns:tiff="http://ns.adobe.com/tiff/1.0/" '
                        + 'xmlns:plus="http://schemas.android.com/apk/lib/com.google.android.gms.plus" '
                        + 'xmlns:ext="http://www.gettyimages.com/xsltExtension/1.0" '
                        + 'xmlns:exif="http://ns.adobe.com/exif/1.0/" '
                        + 'xmlns:stEvt="http://ns.adobe.com/xap/1.0/sType/ResourceEvent#" '
                        + 'xmlns:stRef="http://ns.adobe.com/xap/1.0/sType/ResourceRef#" '
                        + 'xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" '
                        + 'xmlns:xapGImg="http://ns.adobe.com/xap/1.0/g/img/" '
                        + 'xmlns:Iptc4xmpExt="http://iptc.org/std/Iptc4xmpExt/2008-02-29/" '
                        + xmpString.slice(indexOfXmp)

            var domDocument = dom.parseFromString(xmpString, 'text/xml');
            return { doc: $.parseXML(xmpString), obj: xml2Object(domDocument) };
         } else
         {
            offset++;
         }
      }
   }

   function xml2json(xml)
   {
      var json = {};

      if (xml.nodeType == 1)
      { // element node
         if (xml.attributes.length > 0)
         {
            json['@attributes'] = {};
            for (var j = 0; j < xml.attributes.length; j++)
            {
               var attribute = xml.attributes.item(j);
               json['@attributes'][attribute.nodeName] = attribute.nodeValue;
            }
         }
      } else if (xml.nodeType == 3)
      { // text node
         return xml.nodeValue;
      }

      // deal with children
      if (xml.hasChildNodes())
      {
         for (var i = 0; i < xml.childNodes.length; i++)
         {
            var child = xml.childNodes.item(i);
            var nodeName = child.nodeName;
            if (json[nodeName] == null)
            {
               json[nodeName] = xml2json(child);
            } else
            {
               if (json[nodeName].push == null)
               {
                  var old = json[nodeName];
                  json[nodeName] = [];
                  json[nodeName].push(old);
               }
               json[nodeName].push(xml2json(child));
            }
         }
      }

      return json;
   }

   function xml2Object(xml)
   {
      try
      {
         var obj = {};
         if (xml.children.length > 0)
         {
            for (var i = 0; i < xml.children.length; i++)
            {
               var item = xml.children.item(i);
               var attributes = item.attributes;
               for (var idx in attributes)
               {
                  var itemAtt = attributes[idx];
                  var dataKey = itemAtt.nodeName;
                  var dataValue = itemAtt.nodeValue;

                  if (dataKey !== undefined)
                  {
                     obj[dataKey] = dataValue;
                  }
               }
               var nodeName = item.nodeName;

               if (typeof (obj[nodeName]) == "undefined")
               {
                  obj[nodeName] = xml2json(item);
               } else
               {
                  if (typeof (obj[nodeName].push) == "undefined")
                  {
                     var old = obj[nodeName];

                     obj[nodeName] = [];
                     obj[nodeName].push(old);
                  }
                  obj[nodeName].push(xml2json(item));
               }
            }
         } else
         {
            obj = xml.textContent;
         }
         return obj;
      } catch (e)
      {
         console.log(e.message);
      }
   }

   EXIF.enableXmp = function ()
   {
      EXIF.isXmpEnabled = true;
   }

   EXIF.disableXmp = function ()
   {
      EXIF.isXmpEnabled = false;
   }

   EXIF.getData = function (img, callback)
   {
      if (((self.Image && img instanceof self.Image)
          || (self.HTMLImageElement && img instanceof self.HTMLImageElement))
          && !img.complete)
         return false;

      if (!imageHasData(img))
      {
         getImageData(img, callback);
      } else
      {
         if (callback)
         {
            callback.call(img);
         }
      }
      return true;
   }

   EXIF.getTag = function (img, tag)
   {
      if (!imageHasData(img)) return;
      return img.exifdata[tag];
   }

   EXIF.getIptcTag = function (img, tag)
   {
      if (!imageHasData(img)) return;
      return img.iptcdata[tag];
   }

   EXIF.getAllTags = function (img)
   {
      if (!imageHasData(img)) return {};
      var a,
          data = img.exifdata,
          tags = {};
      for (a in data)
      {
         if (data.hasOwnProperty(a))
         {
            tags[a] = data[a];
         }
      }
      return tags;
   }

   EXIF.getAllIptcTags = function (img)
   {
      if (!imageHasData(img)) return {};
      var a,
          data = img.iptcdata,
          tags = {};
      for (a in data)
      {
         if (data.hasOwnProperty(a))
         {
            tags[a] = data[a];
         }
      }
      return tags;
   }

   EXIF.pretty = function (img)
   {
      if (!imageHasData(img)) return "";
      var a,
          data = img.exifdata,
          strPretty = "";
      for (a in data)
      {
         if (data.hasOwnProperty(a))
         {
            if (typeof data[a] == "object")
            {
               if (data[a] instanceof Number)
               {
                  strPretty += a + " : " + data[a] + " [" + data[a].numerator + "/" + data[a].denominator + "]\r\n";
               } else
               {
                  strPretty += a + " : [" + data[a].length + " values]\r\n";
               }
            } else
            {
               strPretty += a + " : " + data[a] + "\r\n";
            }
         }
      }
      return strPretty;
   }

   EXIF.readFromBinaryFile = function (file)
   {
      return findEXIFinJPEG(file);
   }

   if (typeof define === 'function' && define.amd)
   {
      define('exif-js', [], function ()
      {
         return EXIF;
      });
   }
}.call(this));
﻿var _photoList = [];
var _pubList = [];
var _tagItemId = -1; // -1 = tag selected, 0+ = item id
var _uploading = false;
var _badExt = ['exe', 'vbs', 'bat', 'com', 'js', 'sh', 'ini', 'bin', 'swf', 'flv'];
var _imageExtensions = ['jpeg', 'jpg', 'png', 'bmp', 'gif', 'tif', 'eps', 'ai', 'pdf', 'psd'];
var _uploadedCount = 0;
var _defaultTags = [];
var _uploaderChangesMade = false;
var _MTS_previewImg = null;
var _MTS_previewObj = null;
var _MTS_selectionScale = 1;
var _MTS_focusImg = null;
var _MTS_focusObjs = [];
var _MTS_focusImgs = [];
var _MTS_focusDims = [];
var _pendingData = [];
var _profiles = [];
var _selectedRunDate = null;
var _selectedAd = null;
var _selectedIdx = -1;
var _imageVersionChange = false;
var _changedCount = 0;
var _updateRank = false;
var _MTS_published = false;

if (typeof (_uploadType) == "undefined")
   _uploadType = "image";

if (_MTS_widgetsReady)
   WireUpload();
else
   _MTS_JQUERY(document).one("widgetsloaded", WireUpload);

function WireUpload()
{
   _MTS_stopSearchOnce = true;
   _cal.initialize();
   _MTS_selectTagOverride = handleTagClick;
   _MTS_JQUERY(".photo_upload_widget").remove().appendTo("body");

   if (typeof _chosenSupported == "undefined")
      _chosenSupported = "Microsoft Internet Explorer" === window.navigator.appName ? document.documentMode >= 8 : /iP(od|hone)/i.test(window.navigator.userAgent) ? !1 : /Android/i.test(window.navigator.userAgent) && /Mobile/i.test(window.navigator.userAgent) ? !1 : !0;

   if (typeof (_MTS_JQUERY().chosen) === "function" && _chosenSupported)
      _MTS_JQUERY("#albumSelect").chosen({ width: "240px", disable_search: true });
   else
      _MTS_JQUERY("#albumSelect").show();

   var ph = _MTS_JQUERY(".photoHolder");
   var pt = _MTS_JQUERY(".photoToolsCtr");
   var ib = _MTS_JQUERY(".interfaceBarCtr");
   var ub = _MTS_JQUERY(".updateButton");

   pt.css({ "height": ((_MTS_JQUERY(window).outerHeight() - ub.outerHeight()) - (ib.outerHeight())) + "px" });
   ph.css({ "height": (_MTS_JQUERY(window).outerHeight() - ib.outerHeight()) + "px" });

   var txc = _MTS_JQUERY(".mts_cc_text").css('color');
   var cnah = _MTS_JQUERY(".bordered:hover, .indTag:hover, .viewTags:hover");
   cnah.css({ "border-bottom-color": txc });

   var phb = _MTS_JQUERY(".phBlock");
   var phc = _MTS_JQUERY(".phBlockCtr");
   var pht = _MTS_JQUERY(".phBlockTools");
   var phi = _MTS_JQUERY(".phImgCtr");
   var cp = _MTS_JQUERY(".closePreview");
   var vp = _MTS_JQUERY(".previewCtr");
   var dd = _MTS_JQUERY(".dragDrop, .browseUnderlay");
   var nm = _MTS_JQUERY(".noMedia, .phToolTip");
   var pc = _MTS_JQUERY(".photoCtr");
   var pi = _MTS_JQUERY(".prevImg");
   var cropping = false;

   
   if (typeof(_pubs) != "undefined" && _pubs) {
      
       for (var i = 0; i < _pubs.length ; i++) {
           _pubList.push(new publicationInfo(_pubs[i].Id, _pubs[i].Name, _pubs[i].PageRequired))
       }
   }

   _MTS_JQUERY("#pageStar").hide();

   _MTS_JQUERY(document).on("click", ".mts_focus", function ()
   {
      var elements = getAllElementsAt(this);
      if (elements.length == 1)
         elements[0].find("img").click();
   });

   _MTS_JQUERY(".photoHolder").on("scroll", function ()
   {
      for (var i = _MTS_focusObjs.length - 1; i >= 0; i--)
         _MTS_focusObjs[i].update();
   });

   _MTS_JQUERY(document).on("focus", "input[name='link']", function ()
   {
      if (this.value == "")
         this.value = "http://";
   });

   _MTS_JQUERY(document).on("blur", "input[name='link']", function ()
   {
      if (this.value == "http://")
         this.value = "";
   });

   _MTS_JQUERY(document).on("click", ".closeUpload", function (event)
   {
      var close = CloseUpload();
      if (typeof close !== 'undefined' && !close)
         event.preventDefault();
   });

   _MTS_JQUERY(".photo_upload_widget").on("drag dragstart dragend dragover dragenter dragleave", function (event)
   {
      event.preventDefault();
   });

   if (_MTS_JQUERY(".dragDrop").length > 0)
   {
      _MTS_JQUERY(".photoUploadContainer").on("drop", function (event)
      {
         event.preventDefault();
         event.stopPropagation();
         var items = event.target.files;
         if (!items || items.length === 0 || event.dataTransfer)
            items = (event.dataTransfer ? event.dataTransfer.items : event.originalEvent.dataTransfer.files);

         if (items[0] && typeof (items[0].webkitGetAsEntry) === "function")
         {
            var item = items[0].webkitGetAsEntry();
            if (item)
            {
               traverseFileUploadTree(item.filesystem.root, undefined, undefined, startPhotoUpload);
            }
            else
            {
               loopPhotoFiles(items);
               startPhotoUpload();
            }
         }
         else
         {
            loopPhotoFiles(items);
            startPhotoUpload();
         }
      });
   }

   _MTS_JQUERY(document).on("click", ".phBrowse, #fPhotoHere", function ()
   {
      _MTS_JQUERY("#fPhotoBrowse").click();
   });

   _MTS_JQUERY("#fPhotoBrowse").change(function ()
   {
      loopPhotoFiles(_MTS_JQUERY(this)[0]);
      startPhotoUpload();
   });

   phi.css({ "height": ((phi.outerWidth() * 2.5) / 4) + "px" });
   _MTS_JQUERY(".photoHolder").on("click", ".phImgCtr", function ()
   {
      if (_uploadType === "Advertisement")
         return false;

      cropping = false;
      displayPhoto(this);
      _MTS_JQUERY("#phuDragDrop").addClass("hideIt");

      if (_uploadType == "Image")
      {
         _MTS_JQUERY(".tab").removeClass("selected");
         _MTS_JQUERY(".tab.tags").addClass("selected");
         _MTS_JQUERY(".tool").removeClass("showTool");
         _MTS_JQUERY(".phutags").addClass("showTool");
      }
   });

   _MTS_JQUERY(".photoHolder").on("click", ".phCrop", function ()
   {
      cropping = true;
      displayPhoto(this);
      wireImgArea();
      checkForPhotos();
   });

   _MTS_JQUERY(".photoHolder").on("click", "#saveCrop", function ()
   {
      applyImgArea();
      hidePreview();
      checkForPhotos();
   });

   _MTS_JQUERY(".photoHolder").on("click", ".phVersion", function ()
   {
      _MTS_JQUERY(this).parents(".phBlockMain").siblings(".versionCtr").toggleClass("togglePanel");
   });

   _MTS_JQUERY(".photoHolder").on("click", ".closeVersionCtr", function ()
   {
      _MTS_JQUERY(this).parents(".versionCtr").removeClass("togglePanel");
   });

   _MTS_JQUERY(".photoHolder").on("click", "input[name='photoStart'], input[name='photoEnd']", function ()
   {
      var me = _MTS_JQUERY(this);
      var date = new Date($.trim(this.innerHTML));
      if (isNaN(date))
         date = new Date();

      _cal.GetMiniCalendar("select", "Date", date, function (m, d, y)
      {
         me.val(m.toString() + "/" + d.toString() + "/" + y.toString());
      });
   });

   if (typeof _rankImgs !== 'undefined' && _rankImgs)
   {
      if (_MTS_JQUERY(window).outerWidth() > 1024)
      {
         _MTS_JQUERY(".photoCtr").sortable({
            update: function (event, ui)
            {
               RankPhotos(ui.item[0]);
            }
         });
      }

      _MTS_JQUERY(".photoHolder").on("click", ".phUp, .phDown", function ()
      {
         var con = _MTS_JQUERY(this).parents("li");

         var isNext = _MTS_JQUERY(this).hasClass("phDown");
         var sib = isNext ? con.next("li") : con.prev("li");
         if (sib.length > 0)
         {
            con.remove();
            isNext ? sib.after(con) : sib.before(con);
            RankPhotos(con[0]);
         }
      });

      _MTS_JQUERY("#wipeRank").click(function ()
      {
         var allItems = true;
         var photoIds = _MTS_JQUERY.map(_photoList, function (e, i)
         {
            return i;
         });

         if (_MTS_JQUERY(".photoHolder").find("input[type='checkbox'].phCheck:checked").length > 0)
         {
            allItems = false;
            photoIds = _MTS_JQUERY.map(_photoList, function (e, i)
            {
               if (_MTS_JQUERY("#block_" + i).find("input[type='checkbox'].phCheck:checked").length > 0)
                  return i;

               return null;
            });
         }

         if (confirm("Are you sure you want to reset the display order for all " + (allItems ? "" : "selected ") + "items?"))
         {
             for (var i = 0; i < photoIds.length; i++) {
                 _photoList[photoIds[i]].rank = 0;
                 _photoList[photoIds[i]].changesmade = true;
             }
            SortPhotosByRank();
         }
      });
   }

   function RankPhotos(item)
   {
      var found = false;
      _MTS_JQUERY(".photoCtr").children().each(function (idx)
      {
         var id = this.id.split('_')[1];

          if (_photoList[id].rank > 0 || !found) {
              _photoList[id].rank = idx + 1;
              _photoList[id].changesmade = true;
          }

         found = found || this.id == item.id;
      });
       
      CheckPhotosForRank();
   }

   function displayPhoto(me)
   {
      var cropGroup = _MTS_JQUERY("#cropGroup");
      vp.show();
      if (pi.outerHeight() > pi.outerWidth())
         pi.addClass("portrait");

      vp.css({ "height": ((_MTS_JQUERY(window).outerHeight() / 2) - 60) + "px" });
      _MTS_focusImg = _MTS_JQUERY(me).parents(".phBlockCtr").find(".phImg");
      var vps = _MTS_focusImg.attr('src'),
         viewImg = _MTS_JQUERY(".prevImg");

      viewImg.attr('src', vps);
      
      vp.css({ "height": ph.outerHeight() + "px" });
      _MTS_previewImg = viewImg;
      ph.addClass("overflow");

      for (var i = 0, j = _MTS_focusObjs.length - 1; i <= j; i++)
         _MTS_focusObjs[i].setOptions({ hide: true });

      if (cropping)
         cropGroup.show();
      else
         cropGroup.hide();

      if (_uploadType == "Image")
      {
         var caption = _MTS_JQUERY(me).parents(".phBlockCtr").find("textarea[name='caption']").val();
         var credit = _MTS_JQUERY(me).parents(".phBlockCtr").find("input[name='credit']").val();
         _MTS_JQUERY("#uniCap").val(caption);
         _MTS_JQUERY("#uniCred").val(credit);
      }

      _MTS_JQUERY(me).parents(".phBlockCtr").find("input[type=checkbox].phCheck").prop("checked", true).change();
      _MTS_JQUERY(".closePreview").data("photoId", _MTS_JQUERY(me).parents(".phBlockCtr").attr("id").split('_')[1]);
   }

   function hidePreview()
   {
      vp.hide();
      pt.removeClass("overflow");
      ph.removeClass("overflow");
      if (cropping)
      {
         hideImgArea();
         cropping = false;
      }
      showThumbnailCrop();
      $("#phuDragDrop").removeClass("hideIt");
   }

   _MTS_JQUERY("#prevX1, #prevX2, #prevY1, #prevY2").change(function ()
   {
      setImgArea();
   });

   cp.on("click", function ()
   {
      hidePreview();
      _MTS_JQUERY("")
      _MTS_JQUERY(".uploadTagWrapper").removeClass("showTagWrapper");
      _MTS_JQUERY("#phuDragDrop").removeClass("hideIt");
      _MTS_JQUERY("#uniCap, #uniCred").val("");
      _MTS_JQUERY("#block_" + _MTS_JQUERY(this).data("photoId")).find(".phCheck").prop("checked", false).change();
      checkForPhotos(); 
   });

   var vt = _MTS_JQUERY(".viewTags");
   var tv = _MTS_JQUERY(".tagViewerCtr");
   //var ct = _MTS_JQUERY(".closeTagViewer");
   _MTS_JQUERY(".photoHolder").on("click", ".viewTags", function ()
   {
      _tagItemId = _MTS_JQUERY(this).parents(".phBlockCtr").attr("id").split('_')[1];
      var tgi = _MTS_JQUERY(".tgImgCtr");
      tgi.css({ "height": ((_MTS_JQUERY(".tagViewerCtr").outerWidth() * 2.5) / 4) + "px" });
      //tv.addClass("tagViewerOpen");
      var phsrc = _MTS_JQUERY(this).parent(".phBlockInfo").siblings(".phImgCtr").children(".phImg").attr('src');
 
      var tgsrc = _MTS_JQUERY(".tgImgCtr").children(".phImg");
      tgsrc.attr('src', phsrc);

      updateTagList();
   });

   //ct.on("click", function ()
   //{
   //   tv.removeClass("tagViewerOpen");
   //});

   var cna = _MTS_JQUERY("#cnaBtn, #cancelCna");
   var cnc = _MTS_JQUERY(".createNewAlbumCtr");
   cna.on("click", function ()
   {
      cnc.toggleClass("cnaOpen");
   });

   _MTS_JQUERY("#saveCna").click(function ()
   {
      var title = _MTS_JQUERY.trim(_MTS_JQUERY("#albumName").val());
      var desc = _MTS_JQUERY.trim(_MTS_JQUERY("#albumDesc").val());
      var slugline = _MTS_JQUERY.trim(_MTS_JQUERY("#albumSlugline").val());

      if (title.length == 0)
      {
         alert("Album needs a title.");
         return;
      }

      var album = [{
         id: -1,
         name: title,
         desc: desc,
         slugline: slugline,
         created: true
      }];

      var p = [];
      p.push({ name: "albums", value: JSON.stringify(album) });
      _MTS_JQUERY.post("/api/portalAdmin/updateAlbumManager.aspx", p, function (o)
      {
         if (o.ok)
         {
            _MTS_JQUERY("#albumSelect").append(_MTS_JQUERY("<option></option>").attr("value", o.newAlbumId).text(title).prop("selected", true));
            _MTS_JQUERY("#albumSelect").trigger("chosen:updated");
            _uploaderChangesMade = true;
            cnc.toggleClass("cnaOpen");
         }
         else
            alert(o.error);
      }, "json");
   });

   ub.on("click", function ()
   {
      if (_uploading)
         return;

      if (_pendingData.length > 0)
      {
         _MTS_JQUERY(document).off("metadataLoaded");
         _MTS_JQUERY(document).on("metadataLoaded", savePhotos);
      }
      else if (!ub.hasClass("updateButtonActive"))
      {
         alert("There are no items to save");
      }
      else
      {
         _uploadedCount = 0;
         _MTS_JQUERY(".imgCheck, .imgErr").remove();
         savePhotos();
      }
   });

   _MTS_JQUERY("#selAll").change(function ()
   {
      _MTS_JQUERY(".photoHolder").find("input[type='checkbox'].phCheck").prop("checked", _MTS_JQUERY(this).prop("checked"));
      checkForSelected();
      updateTagList();
   });

   _MTS_JQUERY("#remSel").click(function ()
   {
      if (_MTS_JQUERY(this).hasClass("noSelect"))
         return;

      var photos = _MTS_JQUERY(".photoHolder").find("input[type='checkbox'].phCheck:checked").parents(".phBlockCtr").map(function ()
      {
         return this.id.split('_')[1];
      });

      removeMultiPhotoUpload(photos, true);
   });

   _MTS_JQUERY("#remAll").click(function ()
   {
      if (_MTS_JQUERY(this).hasClass("noSelect"))
         return;

      var photos = _MTS_JQUERY(".photoHolder").find(".phBlockCtr").map(function ()
      {
         return this.id.split('_')[1];
      });

      removeMultiPhotoUpload(photos, false);
   });

   if (_uploadType === "Advertisement")
   {
    
      _MTS_JQUERY(".photoHolder").on("click", ".phImgCtr", function ()
      {
         _MTS_JQUERY(this).parents(".phBlockCtr").find("input[type='checkbox'].phCheck").click();
      });
   }

   _MTS_JQUERY(".photoHolder").on("change", "input[type='checkbox'].phCheck", function ()
   {
      if (_uploadType == "Image")
      {
         checkForSelected();
         updateTagList();
      }
      else if (_uploadType == "Advertisement")
      {
         _MTS_JQUERY(".phCheck:checked").not(this).prop("checked", false);
         
         if (_MTS_JQUERY(this).is(":checked"))
         {
            enableAdForm();

            var parent = _MTS_JQUERY(this).parents(".phBlockCtr")[0];
            var id = parent.id.split('_')[1];
            _selectedAd = _photoList[id];
            _selectedIdx = id;

            _MTS_JQUERY(".adInfoForm").find("input[name='accountNumber']").val(_selectedAd.accountNumber);
            _MTS_JQUERY(".adInfoForm").find("input[name='title']").val(_selectedAd.title);
            _MTS_JQUERY(".adInfoForm").find("input[name='adNumber']").val(_selectedAd.adNumber);
            _MTS_JQUERY(".adInfoForm").find("input[name='width']").val(_selectedAd.width);
            _MTS_JQUERY(".adInfoForm").find("input[name='height']").val(_selectedAd.height);
            _MTS_JQUERY(".adInfoForm").find("textarea[name='notes']").val(_selectedAd.notes);
            _MTS_JQUERY(".adInfoForm").find("input[name='url']").val(_selectedAd.url);
            _MTS_JQUERY(".adInfoForm").find("input[name='colorSetting'][value='" + _selectedAd.colorSetting + "']").prop("checked", true);
            _MTS_JQUERY(".adInfoForm").find("input[name='requestedPageLocation']").val(_selectedAd.requestedPageLocation);

            _MTS_JQUERY("#dateWrapper").find(".runDate").remove();
            _MTS_JQUERY("#insertionWrapper").hide();

            if (_selectedAd.runDates)
            {
               _selectedAd.runDates.forEach(function (date, index)
               {
                  var template = "<div id='date_" + index + "' class='runDate'>" + _MTS_JQUERY("#dateTemplate").html() + "</div>";
                  _MTS_JQUERY("#dateWrapper").append(template);

                  var parsed = new Date(date.RunDate);
                  if (!isNaN(parsed))
                  {
                     parsed = (parsed.getMonth() + 1) + "/" + parsed.getDate() + "/" + parsed.getFullYear();
                  }

                  _MTS_JQUERY("#date_" + index).find(".dateContent").html(parsed);
               });
            }

            _MTS_JQUERY(".result").removeClass("selectedTag");
                }
         else
         {
            _selectedAd = null;
            disableAdForm();
         }

         _MTS_JQUERY(".uploadTagWrapper").removeClass("showTagWrapper");
      }
   });

   _MTS_JQUERY(".photoHolder").on("click", ".phRemove", function ()
   {
      var container = _MTS_JQUERY(this).parents(".phBlockCtr")[0];
      removePhotoUpload(container.id.split('_')[1]);
   });

   _MTS_JQUERY(".tagList").on("click", ".removeTag", function ()
   {
      var id = _MTS_JQUERY(this).siblings("input[name='id']").val();
      var type = _MTS_JQUERY(this).siblings("input[name='type']").val();
      removeTag([_photoList[_tagItemId]], id, type);
   });

   _MTS_JQUERY("#selectedTags").on("click", ".removeTag", function ()
   {
      var id = _MTS_JQUERY(this).siblings("input[name='id']").val();
      var type = _MTS_JQUERY(this).siblings("input[name='type']").val();
      var files = _MTS_JQUERY(".photoHolder").find("input[type='checkbox'].phCheck:checked").parents(".phBlockCtr").map(function ()
      {
         var id = this.id.split('_')[1];
         return typeof _photoList[id] != 'undefined' && !_photoList[id].removed ? _photoList[id] : null;
      });

      removeTag(files, id, type);
   });

   _MTS_JQUERY("#allTags").on("click", ".removeTag", function ()
   {
      var id = _MTS_JQUERY(this).siblings("input[name='id']").val();
      var type = _MTS_JQUERY(this).siblings("input[name='type']").val();
      var files = _MTS_JQUERY.map(_photoList, function (file)
      {
         return file.removed ? null : file;
      });

      removeTag(files, id, type);
   });

   _MTS_JQUERY(".searchResults").on("click", ".selectedTag", function (e)
   {
      e.preventDefault();
      e.stopPropagation();
   
      var params = this.href.match(/([\w]+)/g);
      var type = params.pop();
      var id = params.pop();
      _MTS_JQUERY(this).removeClass("selectedTag");

      if (_uploadType == "Image")
      {
          _MTS_JQUERY(".uploadTagContainer:visible .tagAll").each(function ()
         {

             var tag = _MTS_JQUERY(this);
            if (tag.find("input[name='id']").val() == id && tag.find("input[name='type']").val() == type)
               tag.find(".removeTag").click();
         });
      }
      else
      {
         removeAdTag(id, type);
      }
   });

   _MTS_JQUERY(".photo_upload_widget").find("#tagSelected").click(function ()
   {
      if (_MTS_JQUERY(this).hasClass("noSelect"))
         return;
     
      _tagItemId = -1;
      ToggleNewUploadTag();
   });

   _MTS_JQUERY(".photoHolder").on("click", ".tagIcon", function ()
   {
      _tagItemId = parseInt(_MTS_JQUERY(this).parents(".phBlockCtr").attr("id").split('_')[1]);
      _MTS_JQUERY("#block_" + _tagItemId).find(".viewTags").click();
      
      ToggleNewUploadTag();

      _MTS_JQUERY(".tab").removeClass("selected");
      _MTS_JQUERY(".tab.tags").addClass("selected");
      _MTS_JQUERY(".tool").removeClass("showTool");
      _MTS_JQUERY(".phutags").addClass("showTool");
      _MTS_JQUERY("#phuDragDrop").addClass("hideIt");

      _MTS_JQUERY(".photoHolder input[type=checkbox].phCheck").prop("checked", false).change();
      _MTS_JQUERY(this).parents(".phBlockCtr").find("input[type=checkbox].phCheck").prop("checked", true).change();
   });

   _MTS_JQUERY(".photoHolder").on("change", "input[type='text']", function ()
   {
      _uploaderChangesMade = true;
   });

   _MTS_JQUERY("#update_Cap, #update_Cred").click(function ()
   {
      var sect = this.id.split('_')[1];
      var txt = _MTS_JQUERY("#uni" + sect).val();
      var photos = _MTS_JQUERY(".photoHolder").find("input[type='checkbox'].phCheck:checked").parents(".phBlockCtr");
      if (photos.length == 0)
         photos = _MTS_JQUERY(".photoHolder .phBlockCtr");

      photos.find("[name='" + (sect == "Cap" ? "caption" : "credit") + "']").val(txt);
      _uploaderChangesMade = true;
   });

   _MTS_JQUERY("#mts_unlockstory").click(function ()
   {
      _MTS_JQUERY(".photo_upload_widget").css("height", "100%");
      _MTS_JQUERY(".updateButtonCtr").css("bottom", "0px");
      _MTS_JQUERY(".progress").css("bottom", "50px");
   });

   _MTS_JQUERY(window).on("orientationchange", function ()
   {
      if (_MTS_JQUERY(window).width() > 767)
         return;

      if (_MTS_JQUERY(window).width() > _MTS_JQUERY(window).height())
      {
         var pl = _MTS_JQUERY(".previewLbl");
         setTimeout(function ()
         {
            pl.addClass("hideLbl");
         }, 2000);

         var pct = _MTS_JQUERY(".previewCtr");
         pct.on("click", function ()
         {
            pl.toggleClass("hideLbl");
         });
      } else
      {
         var pl = _MTS_JQUERY(".previewLbl");
         pl.removeClass("hideLbl");
      }

      var rem = _MTS_JQUERY("#remSel, #remAll").detach();
      if (typeof window.orientation == 'undefined' || window.orientation == 0)
         rem.appendTo(".mtType");
      else
         rem.appendTo(".selOptions");
   });

   _MTS_JQUERY(window).resize(function ()
   {
      resizePhotoUpload();
   });

   checkForPhotos();
   checkForSelected();

   if (_uploadType == "Image")
      updateTagList();

   var tab = _MTS_JQUERY(".tab");
   tab.on("click", function ()
   {
      if (_MTS_JQUERY(this).hasClass("selected"))
         return;

      var cl = _MTS_JQUERY(this).attr("class").substring(4);
      var name = ".phu" + cl;
      _MTS_JQUERY(".tool").removeClass("showTool");
      tab.removeClass("selected");
      _MTS_JQUERY(this).addClass("selected");
      _MTS_JQUERY(name).addClass("showTool");
   });

   _MTS_JQUERY(".photo_upload_widget #searchPhrase").on('keydown', function (e)
   {
      if (e.which === 13)
      {
         e.preventDefault();
         MTS_handleEz(0, null, this);
      }
   });

   /*_MTS_JQUERY(document).on("focus", "input[name='publication']", function ()
   {
       ToggleNewUploadTag();
   });
   */

   _MTS_JQUERY(document).on("click", "input[name='publication']", function ()
  {
      ToggleNewUploadTag();
  });
  
   _MTS_JQUERY(document).on("change", "input[name='colorSetting']", function ()
   {
      _selectedAd.colorSetting = _MTS_JQUERY(this).val();
      _uploaderChangesMade = true;
   });

   _MTS_JQUERY("#pickRunDates").on("click", function ()
   {
      showRunDateCalendar();
   });

   _MTS_JQUERY(document).on("change", "input[name='publication'], input[name='edition'], input[name='section'], " +
      "input[name='page'], input[name='zone'], input[name='horizontalPosition'], input[name='verticalPosition']", function ()
      {
         var key = this.name;
         key = key[0].toUpperCase() + key.substr(1);
         _selectedRunDate[key] = this.value;
      });

   _MTS_JQUERY(document).on("click", ".dateContent", function ()
   {
      _MTS_JQUERY(".selectedRunDate").removeClass("selectedRunDate");
      _MTS_JQUERY(this).addClass("selectedRunDate");
      _MTS_JQUERY("#insertionWrapper").show();
      var index = _MTS_JQUERY(this).parents(".runDate")[0].id.split('_')[1];
      _selectedRunDate = _selectedAd.runDates[index];
      var pub = findPublicationByPubCode(_selectedRunDate.Publication, _selectedRunDate.PublicationId);
      setRunDateValue(pub == null ? "" : pub.Name, _selectedRunDate.Edition, _selectedRunDate.Section, _selectedRunDate.Page,
         _selectedRunDate.Zone, _selectedRunDate.HorizontalPosition, _selectedRunDate.VerticalPosition);
   });

   _MTS_JQUERY(document).on("click", ".delete", function ()
   {
      var index = _MTS_JQUERY(this).parents(".runDate")[0].id.split('_')[1];

      _MTS_JQUERY(this).parents(".runDate").remove();
      _MTS_JQUERY("#insertionWrapper").hide();

      _selectedAd.runDates.splice(index, 1);
      _selectedRunDate = null;

      _MTS_JQUERY(".runDate").each(function (index, element)
      {
         element.id = "date_" + index;
      });

      _uploaderChangesMade = true;
   });

   _MTS_JQUERY(document).on("change", ".adInfoInput", function ()
   {
      if (this.name === "title")
         _MTS_JQUERY("#block_" + _selectedIdx).find(".phInfoName").html(this.value);

      _selectedAd[this.name] = this.value;
      _uploaderChangesMade = true;
   });

   _MTS_JQUERY(window).trigger("orientationchange");

   disableAdForm();
}

function findPublicationByPubCode(pubCode, pubId)
{
   var hasPubId = typeof(pubId) !== "undefined" && pubId > 0;
   for (var j = _pubs.length - 1; j >= 0; j--)
   {
      if (hasPubId ? _pubs[j].Id == pubId : _pubs[j].PubCode === pubCode)
      {
         return _pubs[j];
      }
   }

   return null;
}

function setRunDateValue(pub, ed, sec, pg, zone, hp, vp)
{
   _MTS_JQUERY("input[name='publication']").val(pub);
   _MTS_JQUERY("input[name='edition']").val(ed);
   _MTS_JQUERY("input[name='section']").val(sec);
   _MTS_JQUERY("input[name='page']").val(pg);
   _MTS_JQUERY("input[name='zone']").val(zone);
   _MTS_JQUERY("input[name='horizontalPosition']").val(hp);
   _MTS_JQUERY("input[name='verticalPosition']").val(vp);
}

function resizePhotoUpload()
{
   var ph = _MTS_JQUERY(".photoHolder");
   var pt = _MTS_JQUERY(".photoToolsCtr");
   var ib = _MTS_JQUERY(".interfaceBarCtr");
   var ub = _MTS_JQUERY(".updateButton");
   var phi = _MTS_JQUERY(".phImgCtr");
   var cp = _MTS_JQUERY(".closePreview");
   var vp = _MTS_JQUERY(".previewCtr");

   pt.css({ "height": ((_MTS_JQUERY(window).outerHeight() - ub.outerHeight()) - (ib.outerHeight() + 20)) + "px" });
   ph.css({ "height": (_MTS_JQUERY(window).outerHeight() - ib.outerHeight()) + "px" });
   phi.css({ "height": ((phi.outerWidth() * 2.5) / 4) + "px" });
   _MTS_JQUERY(".photo_upload_widget").css("height", _MTS_JQUERY(window).height() - _MTS_JQUERY("#mts_unlockstory:visible").height() + "px");

   vp.css({ "height": (_MTS_JQUERY(window).outerHeight() - 40) + "px" });
   wireImgArea();
}

function checkForPhotos()
{
   var nmw = _MTS_JQUERY(".noMediaWrapper");
   var ub = _MTS_JQUERY(".updateButton");
   var tags = _MTS_JQUERY(".photo_upload_widget").find("#remAll, #tagSelected");
   if (_uploading)
   {
      nmw.hide();
      ub.removeClass("updateButtonActive");
      ub.html("Sending...");
      tags.removeClass("noSelect");
   }
   else if (_MTS_JQUERY("#cropGroup #saveCrop:visible").length > 0)
   {
      nmw.show();
      ub.removeClass("updateButtonActive");
      ub.html("Cropping...");
      tags.addClass("noSelect");
   }
   else if (_MTS_JQUERY(".photoHolder .phBlockCtr").length == 0)
   {
      nmw.show();
      ub.removeClass("updateButtonActive");

      switch (_uploadType)
      {
         default:
         case "Image":
         case "Author":
            ub.html("Waiting for photos");
            break;
         case "Advertisement":
            ub.html("Waiting for ads");
            break;
      }

      tags.addClass("noSelect");
   }
   else
   {
      nmw.hide();
      ub.addClass("updateButtonActive");
      ub.html("Save and update");
      tags.removeClass("noSelect");
   }
}

function checkForSelected()
{
   if (_MTS_JQUERY(".photoHolder .phBlockCtr").length > 0 && _MTS_JQUERY(".photoHolder").find("input[type='checkbox'].phCheck:not(:checked)").length == 0)
      _MTS_JQUERY("#selAll").prop("checked", true);
   else
      _MTS_JQUERY("#selAll").prop("checked", false);

   if (_MTS_JQUERY(".photoHolder").find("input[type='checkbox'].phCheck:checked").length > 0)
   {
      _MTS_JQUERY("#remSel").removeClass("noSelect");
      _MTS_JQUERY("#allTags").hide();
      _MTS_JQUERY("#selectedTags").show();
   }
   else
   {
      _MTS_JQUERY("#remSel").addClass("noSelect");
      _MTS_JQUERY("#allTags").show();
      _MTS_JQUERY("#selectedTags").hide();
   }

   _MTS_JQUERY(".selectCount").html(_MTS_JQUERY(".photoHolder").find("input[type='checkbox'].phCheck:checked").length);
}

function enableAdForm()
{
   _MTS_JQUERY(".adInfoInput, input[name='colorSetting']").prop("disabled", false);
   _MTS_JQUERY("#pickRunDates").addClass("pickRunDatesActive").on("click", function ()
   {
      showRunDateCalendar();
   });
}

function disableAdForm()
{
   _MTS_JQUERY(".adInfoInput").prop("disabled", true).val("");
   _MTS_JQUERY(".result").removeClass("selectedTag");
   _MTS_JQUERY("input[name='colorSetting']").prop("disabled", true).first().prop("checked", true);
   _MTS_JQUERY("#pickRunDates").removeClass("pickRunDatesActive").off("click");
   _MTS_JQUERY(".runDate").remove();
}

function showRunDateCalendar()
{
   var date = new Date();

   _cal.GetMiniCalendar("multi", "Select Run Dates", date, function (m, d, y)
   {
      for (var i = 0; i < m.length; i++)
      {
         var id = $(".runDate").length;
         var template = "<div id='date_" + id + "' class='runDate'>" + _MTS_JQUERY("#dateTemplate").html() + "</div>";
         $("#dateWrapper").append(template);

         var dateText = m[i].toString() + "/" + d[i].toString() + "/" + y[i].toString();
         var date = $("#date_" + id).find(".dateContent");
         date.html(dateText);

         var newRunDate = {};
         newRunDate.RunDate = dateText;
         _selectedAd.runDates.push(newRunDate);

         if (i == 0)
         {
            date.click();
         }
      }

      if (m.length > 0)
         _uploaderChangesMade = true;
   }, false, null);
}

function getCommonTagHtml(commonTags, files)
{
   var html = "";
   for (var i = commonTags.length - 1; i >= 0; i--)
   {
      if (commonTags[i].removed)
         continue;

      var allHaveTag = true;
      for (var j = 0; j < files.length; j++)
      {
         var exists = false;
         for (var k = 0; k < files[j].tags.length; k++)
         {
            var tag = files[j].tags[k];
            if (tag.id == commonTags[i].id && tag.type == commonTags[i].type && !tag.removed)
            {
               exists = true;
               break;
            }
         }
         if (!exists)
         {
            allHaveTag = false;
            break;
         }
      }
      if (allHaveTag)
         html += getTagHtml(commonTags[i]);
   }

   if (html.length == 0)
      html = "No tags selected";

   return html;
}

function getTagHtml(tag)
{
   return "<div class='tagAll' title=\"" + tag.title.replace(/"/g, "&quot;") + "\">" + tag.title +
      "<img alt='Remove Tag' class='removeTag' src='" + _mediaUrl + "images/gratsClose.png'>" +
      "<input type='hidden' name='id' value='" + tag.id + "' />" +
      "<input type='hidden' name='type' value='" + tag.type + "' />" +
      "</div>";
}

function removeTag(files, tagId, tagType)
{
   for (var i = 0; i < files.length; i++)
   {
      for (var j = files[i].tags.length - 1; j >= 0; j--)
      {
         var tag = files[i].tags[j];
         if (tag.id == tagId && tag.type == tagType)
         {
            tag.removed = true;
            _uploaderChangesMade = true;
            files[i].changesmade = true;
         }
      }
   }

   updateTagList();
}

function removeAdTag(tagId, tagType)
{
   for (var i = _selectedAd.tags.length - 1; i >= 0; i--)
   {
      var tag = _selectedAd.tags[i];

      if (tag.id == tagId && tag.type == tagType)
      {
         tag.removed = true;
         _uploaderChangesMade = true;
      }
   }

   updateAdTagList();
}

function loopPhotoFiles(me)
{
   var target = typeof(me.files) === "undefined" ? me : me.files;
   for (var i = 0; i < target.length; i++)
   {
      var filesize = target[i].size;
      var file = null;

      if (_uploadType == "Image")
      {
         file = new mtsPhotoInfo(target[i],
            isImageType(target[i].name),
            filesize > _MTS_uploadLimit,
            true, true);

         if (typeof _tagsLinkName != "undefined" && typeof _tagsLinkType != "undefined")
         {
            for (var j = 0; j < _tags.length; j++)
               file.tags.push(new mtsTag(_tags[j], _tagsLinkType[j], _tagsLinkName[j]));
         }
      }
      else
      {
         file = new adInfo(target[i],
            isImageType(target[i].name),
            filesize > _MTS_uploadLimit,
            true, true);
      }

      _photoList.push(file);

      _uploaderChangesMade = true;
   }
}

function startPhotoUpload()
{
   drawPhotoUploadList();
   loadPhotoThumbnails();
   checkForPhotos();

   if (_uploadType == "Image")
   {
      updateTagList();
   }
   else if (_uploadType === "Advertisement")
   {
      setTimeout(function ()
      {
         _MTS_JQUERY(".phBlockCtr input[type='checkbox'].phCheck:visible:last").click();
      }, 0);
   }
}

function traverseFileUploadTree(item, path, folder, callback)
{
   if (!callback.pending)
      callback.pending = 0;

   callback.pending++;
   path = path || "";
   if (item.isFile)
   {
      // Get file
      item.file(function (file)
      {
         _photoList.push(new mtsPhotoInfo(file,
            isImageType(target[i].name),
            file.size > _MTS_uploadLimit,
            true, true, folder));
         _uploaderChangesMade = true;
         callback.pending--;
         if (callback.pending == 0)
            callback();
      });
   } else if (item.isDirectory)
   {
      // Get folder contents
      var dirReader = item.createReader();
      dirReader.readEntries(function (entries)
      {
         callback.pending--;
         for (var i = 0; i < entries.length; i++)
            traverseFileUploadTree(entries[i], path + item.name + "/", entries[i].isDirectory ? entries[i].name : folder, callback);
      });
   }
}

function drawPhotoUploadList()
{
   for (var i = 0; i < _photoList.length; i++)
   {
      if (_photoList[i].drawn || _photoList[i].removed)
         continue;

      _photoList[i].drawn = true;

      var html = _MTS_JQUERY(".photoBlockTemplate").html();

      if (!_photoList[i].isImage && _uploadType !== "Advertisement")
      {
         html = "";
         alert("Invalid File: " + _photoList[i].file.name + "\nFile must be an image.");
      }
      else if (_photoList[i].isTooBig)
      {
         html = "";
         alert(`File too large: ${_photoList[i].file.name}\nMust be smaller than ${_MTS_uploadLimit / 1024 / 1024}MB.`);
      }
      else
      {
         html = html.replace(/%%PHOTO_ID%%/g, i);
      }

      _MTS_JQUERY(".photoCtr").append(html);
      if (_photoList[i].toningId > 0)
         _MTS_JQUERY(".photoCtr .phBlockCtr:last").find("select[name=toningProfile]").val(_photoList[i].toningId).trigger("chosen:updated");

      _MTS_JQUERY(".phImgCtr").css({ "height": ((_MTS_JQUERY(".phImgCtr").outerWidth() * 2.5) / 4) + "px" });
      _MTS_JQUERY(".photoCtr .phBlockCtr:last").addClass('fill');

      if (_uploadType == "Image")
      {
         var parent = _MTS_JQUERY("#block_" + i);
         if (_photoList[i].file !== null)
         {
            loadMetadata(i);
            parent.find("input[id='hiddenImage']").prop("checked", _photoList[i].hide);
         }
         else
         {
            parent.find(".phInfoName").html(_photoList[i].filename);
            parent.find(".phInfoName").attr('title', _photoList[i].filename);
            parent.find("textarea[name='caption']").val(_photoList[i].caption);
            parent.find("input[name='fileName']").val(_photoList[i].filename);
            parent.find("input[name='slugline']").val(_photoList[i].slugline);
            parent.find("input[name='credit']").val(_photoList[i].credit);
            parent.find("input[name='link']").val(_photoList[i].link);
            parent.find("textarea[name='desc']").val(_photoList[i].desc);
            parent.find("input[name='photoStart']").val(_photoList[i].start);
            parent.find("input[name='photoEnd']").val(_photoList[i].end);
            parent.find("select[name='toningProfile']").val(_photoList[i].toningId);
            parent.find("select[name='presentation']").val(_photoList[i].presentation);
            parent.find("input[id='hiddenImage']").prop("checked", _photoList[i].hide);

            if (_photoList[i].pendingTone != undefined)
            {
               parent.find(".pendingTone").html("Toning Pending: " + _photoList[i].pendingTone.profile).css({ color: "#" + _photoList[i].pendingTone.hex }).show();
            }

            if (_photoList[i].webActiveVersion > 1)
            {
               parent.find(".versionInfo").html("ver. " + _photoList[i].webActiveVersion);
               parent.find(".phVersion").show();
               for (var k = _photoList[i].webActiveVersion; k >= 1; k--)
               {
                  var tprof = "&nbsp;", hex = "#444";
                  for (var l = _photoList[i].prevVersions.length - 1; l >= 0; l--)
                  {
                     if (_photoList[i].prevVersions[l].ver == k)
                     {
                        tprof = _photoList[i].prevVersions[l].profile;
                        break;
                     }
                  }

                  var act = "";
                  if (_photoList[i].webActiveVersion == k)
                     act = "<div class=\"activeState\">Active Web Image</div>";
                  else
                     act = "<a title='Set Active' class=\"setActive mts_cc_text\">Set Active</a>";

                  var vh = _MTS_JQUERY("#verItemTemplate").html();
                  vh = vh.replace(/%%VER_PROF%%/g, tprof);
                  vh = vh.replace(/%%VER_NUM%%/g, k > 1 ? ("ver. " + k) : "original");
                  vh = vh.replace(/%%VER_ACTION%%/g, act);
                  vh = vh.replace(/%%IMAGE_ID%%/g, _photoList[i].id);

                  var obj = _MTS_JQUERY(vh);
                  parent.find(".versionCtr").append(obj);
                  obj.on("click", ".setActive", function (ev)
                  {
                     var par = $(ev.target).parent(), api = "/api/v1/cms/images/set/",
                        str = par.find(".versionNumber").html().split(' '), ver = str.length > 1 ? parseInt(str[1]) : 1,
                        sti = par.find("input[name='imageId']").val(), img = parseInt(sti);

                     var map = [];
                     map.push("image_id=" + img);
                     map.push("portal_id=" + _portalId);
                     map.push("ver=" + ver);

                     var qs = [];
                     qs.push("path=" + encodeURIComponent(api));
                     qs.push("map=" + encodeURIComponent(map.join("&")));

                     _MTS_JQUERY.getJSON("/api/portalAdmin/sendApiRequest.aspx?" + qs.join("&"), function (ret)
                     {
                        if (ret.Success)
                        {
                           par.parents(".versionCtr").find(".activeState").replaceWith("<a title='Set Active' class='setActive mts_cc_text'>Set Active</a>");
                           par.find(".setActive").replaceWith(("<div class='activeState'>Active Web Image</div>"));

                           var img = par.parents(".phBlockCtr").find(".phImg");
                           img.attr("src", par.siblings(".versionThumb").attr("src"));
                        }
                        else
                        {
                           alert("Failed to set active: " + ret.Error);
                        }
                     });
                  });
               }
            }
            else
            {
               parent.find(".phVersion").hide();
            }
         }

         if (_profiles.length == 0)
            parent.find("select[name='toningProfile']").hide();

         addDefaultTags(i);
      }
      else
      {
         var parent = _MTS_JQUERY("#block_" + i);
         parent.find("input[name='slugline']").hide();
         parent.find(".phInfoName").removeClass("hidden");

         parent.find(".hfgCtr").hide();
         parent.find("input[name='fileName']").hide();
         parent.find("select[name='presentation']").hide();
         parent.find(".phCrop").hide();
         parent.find(".tagIcon").hide();
         parent.find("textarea[name='caption']").hide();
         parent.find("input[name='credit']").hide();
         parent.find("input[name='link']").hide();
         parent.find("textarea[name='desc']").hide();
         parent.find("input[name='photoStart']").hide();
         parent.find("input[name='photoEnd']").hide();
         parent.find("select[name='toningProfile']").hide();
      }
   }
}

function loadPhotoThumbnails()
{
   for (var i = 0; i < _photoList.length; i++)
   {
      if (_photoList[i].isImage && !_photoList[i].isTooBig && _photoList[i].isPendingThumb)
      {
         if (_photoList[i].file !== null)
            loadPhotoThumb(i, _photoList[i].file);
         else
         {
            _MTS_JQUERY("#block_" + i).find(".phImg").attr("src", _photoList[i].src).removeClass("loading");
            var histList = _MTS_JQUERY("#block_" + i).find(".versionItem");
            for (var k = histList.length - 1, l = 1; k >= 0; k--, l++)
            {
               var str = _MTS_JQUERY(histList[k]).find(".versionNumber").html().split(' '), ver = str.length > 1 ? parseInt(str[1]) : 0;
               _MTS_JQUERY(histList[k]).find(".versionThumb").attr("src", _photoList[i].src.replace(/([0-9]*)_v([0-9]+)/g, "$1") + (l > 1 ? "_v" + l : "")).removeClass("loading");
            }
            _photoList[i].isPendingThumb = false;
         }
      }
      else if (_uploadType === "Advertisement")
      {
         if (_photoList[i].file)
         {
            loadPdfThumb(i, _photoList[i].file)
            var parent = _MTS_JQUERY("#block_" + i);
            parent.find(".phInfoName").html(_photoList[i].title);
            _photoList[i].isPendingThumb = false;
            parent.find(".loading").attr("src", _MTS_MEDIAURL + "images/blockNoImg.png").removeClass("loading");
         }
      }
   }
}

function loadPdfThumb(id, file)
{
   var reader = new FileReader();
   reader.onload = function (e)
   {
      var loadedImg = _MTS_JQUERY("#block_" + id).find(".phImgCtr");

      if (typeof (_MTS_placePdf) === "function")
         _MTS_placePdf(loadedImg, _photoList[id].title, e.target.result);

      _photoList[id].isPendingThumb = false;
   };
   reader.readAsDataURL(file);
}

function loadPhotoThumb(id, file)
{
   var reader = new FileReader();
   reader.onload = function (e)
   {
      var loadedImg = _MTS_JQUERY("#block_" + id).find(".phImg");
   
      loadedImg.removeClass("loading").attr("src", e.target.result);
      orientPhoto(id);
      _photoList[id].isPendingThumb = false;
   };
   reader.readAsDataURL(file);
}

function getInitCords()
{
   var x = 0, y = 0, x2 = _MTS_previewImg.width(), y2 = _MTS_previewImg.height();

   var divFactor = calculateGCD(_imageSizes.SiteWideMxH, _imageSizes.SiteWideMxW);
   var setWidth = false;
   if (divFactor > 1)
   {
      var widthFactor = _imageSizes.SiteWideMxW / divFactor;
      var heightFactor = _imageSizes.SiteWideMxH / divFactor;
      var afterRatio = calculateAspectRatioFit(widthFactor, heightFactor, x2, y2);
      if (afterRatio.width > 50 && afterRatio.height > 50)
      {
         x2 = Math.floor(afterRatio.width);
         y2 = Math.floor(afterRatio.height);
         setWidth = true;
      }
   }

   if (!setWidth)
   {
      x2 = 50;
      y2 = 50;
   }

   return { "x": x, "y": y, "x2": x2, "y2": y2 };
}

function calculateGCD(a, b)
{
   if (!b)
   {
      return a;
   }

   return calculateGCD(b, a % b);
}

function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight)
{
   var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

   return { width: srcWidth * ratio, height: srcHeight * ratio };
}

function wireImgArea()
{
   
    if (_MTS_previewImg == null)
      return;

   var coords = getInitCords();
   var x = coords.x;
   var y = coords.y;
   var x2 = coords.x2;
   var y2 = coords.y2;
   for (var i = 0, j = _MTS_focusObjs.length - 1; i <= j; i++)
   {
      _MTS_focusObjs[i].setOptions({ hide: true });
      if (_MTS_focusImgs[i][0] == _MTS_focusImg[0])
      {
        
          x = _MTS_focusDims[i].x1 / _MTS_focusDims[i].previewScale;
         y = _MTS_focusDims[i].y1 / _MTS_focusDims[i].previewScale;
         x2 = _MTS_focusDims[i].x2 / _MTS_focusDims[i].previewScale;
         y2 = _MTS_focusDims[i].y2 / _MTS_focusDims[i].previewScale;
      }
   }

   _MTS_previewImg[0].style.width = _MTS_previewImg.width();
   _MTS_previewImg[0].style.height = _MTS_previewImg.height();

   if (_MTS_previewObj == null)
   {
       
       _MTS_previewObj = _MTS_previewImg.imgAreaSelect({
         x1: coords.x, y1: coords.y, x2: coords.x2, y2: coords.y2,
         instance: true,
         minWidth: 50, minHeight: 50,
         onSelectEnd: handleForm,
         persistent: true,
         handles: true
      });
   }

   else
   {
       
       _MTS_previewObj.setOptions({
         x1: x, y1:y, x2: x2, y2: y2,
         hide: false
      });
   }
  
   updateCoords(x, x2, y, y2);

   _MTS_selectionScale = _MTS_previewImg.width();
}

function setImgArea()
{
   var x1 = parseInt(_MTS_JQUERY("#prevX1").val()),
      x2 = parseInt(_MTS_JQUERY("#prevX2").val()) + x1,
      y1 = parseInt(_MTS_JQUERY("#prevY1").val()),
      y2 = parseInt(_MTS_JQUERY("#prevY2").val()) + y1;
   _MTS_previewObj.setSelection(x1, y1, x2, y2);
   _MTS_previewObj.update();
}

function hideImgArea()
{
   if (typeof _MTS_previewObj !== 'undefined' && _MTS_previewObj != null)
      _MTS_previewObj.setOptions({ hide: true });
  
}

function handleForm(img, selection)
{
    
    updateCoords(selection.x1, selection.x2, selection.y1, selection.y2);
}

function updateCoords(x1, x2, y1, y2)
{
    
    _MTS_JQUERY('input[id="prevX1"]').val(x1);
   _MTS_JQUERY('input[id="prevY1"]').val(y1);
   _MTS_JQUERY('input[id="prevX2"]').val(x2);
   _MTS_JQUERY('input[id="prevY2"]').val(y2);
}

function applyImgArea()
{
   var x1 = parseInt(_MTS_JQUERY("#prevX1").val()),
      x2 = parseInt(_MTS_JQUERY("#prevX2").val()),
      y1 = parseInt(_MTS_JQUERY("#prevY1").val()),
      y2 = parseInt(_MTS_JQUERY("#prevY2").val()),
      focusScale = _MTS_focusImg.width() / _MTS_selectionScale;
   
   var imgIdx = -1;
   for (var i = _MTS_focusImgs.length - 1; i >= 0; i--)
   {
      if (_MTS_focusImgs[i][0] == _MTS_focusImg[0])
      {
         imgIdx = i;
         break;
      }
   }
  
   x1 *= focusScale;
  
   x2 *= focusScale;
   y1 *= focusScale;
   y2 *= focusScale;

   if (x1 < 0)
       x1 = 0;
       
   if (x2 < 0)
       x2 = 0;
      
   if (y1 < 0)
       y1 = 0;
   
   if (y2 < 0)
       y2 = 0;
   
   if (imgIdx >= 0)
   {
       _MTS_focusDims[i] = {
         "x1": x1,
         "x2": x2,
         "y1": y1,
         "y2": y2,
         "previewScale": focusScale,
         "scale": _MTS_selectionScale / _MTS_previewImg[0].naturalWidth
      };

      _MTS_focusObjs[imgIdx].setOptions({
         x1: Math.floor(x1), y1: Math.floor(y1), x2: Math.floor(x2), y2: Math.floor(y2)
      });
   }
   else
   {
     
       _MTS_focusDims.push({
         "x1": x1,
         "x2": x2,
         "y1": y1,
         "y2": y2,
         "previewScale": focusScale,
         "scale": _MTS_selectionScale / _MTS_previewImg[0].naturalWidth
      });
       
      _MTS_focusObjs.push(_MTS_focusImg.imgAreaSelect({
         x1: Math.floor(x1), y1: Math.floor(y1), x2: Math.floor(x2), y2: Math.floor(y2),
         persistent: true,
         disable: true,
         instance: true
      }));

      _MTS_focusImgs.push(_MTS_focusImg);
   }
}

function showThumbnailCrop()
{
   for (var i = 0, j = _MTS_focusObjs.length - 1; i <= j; i++)
   {
      var dims = _MTS_focusDims[i];
      _MTS_focusObjs[i].setOptions({
         x1: dims.x1, y1: dims.y1, x2: dims.x2, y2: dims.y2,
         hide: false,
         classPrefix: "mts_focus imgareaselect"
      });

      var photos = _MTS_JQUERY(".phImgCtr img");
      for (var k = photos.length - 1; k >= 0; k--)
      {
         if (photos[k] == _MTS_focusImgs[i][0])
         {
             _photoList[k].dims = _MTS_focusDims[i];
             _photoList[k].changesmade = true;
            break;
         }
      }
   }
}

function disableThumbnailCrop()
{
   for (var i = _MTS_focusObjs.length - 1; i >= 0; i--)
   {
      var dims = _MTS_focusDims[i];
      _MTS_focusObjs[i].setOptions({
         hide: true
      });

      var photos = _MTS_JQUERY(".phImgCtr img");
      for (var k = photos.length - 1; k >= 0; k--)
      {
         if (photos[k] == _MTS_focusImgs[i][0])
         {
            _photoList[k].dims = [];
            break;
         }
      }

      _MTS_focusImgs.pop();
      _MTS_focusDims.pop();
      _MTS_focusObjs.pop();
   }
}

function getAllElementsAt(element)
{
   var elementPos = getElementPosition(element);
   if (elementPos == null)
      return [];

   var $elements = _MTS_JQUERY(".phImgCtr").map(function ()
   {
      var pos = getElementPosition(this);
      return (elementPos.y <= pos.y && elementPos.y >= pos.t) && (elementPos.x <= pos.x && elementPos.x >= pos.l) ? _MTS_JQUERY(this) : null;
   });

   return $elements;
}

function getElementPosition(me)
{
   var $this = _MTS_JQUERY(me);
   var offset = $this.offset();
   if (!offset)
      return null;

   var l = offset.left;
   var t = offset.top;
   var h = $this.height();
   var w = $this.width();

   var maxx = l + w;
   var maxy = t + h;

   return { "x": maxx, "y": maxy, "t": t, "l": l };
}

function addDefaultTags(id)
{
   for (var i = 0; i < _defaultTags.length; i++)
      addTag(_photoList[id].tags, _defaultTags[i].id, _defaultTags[i].type, _defaultTags[i].title);
}

function loadMetadata(id)
{
   _pendingData.push(id);
   var image = _photoList[id];
   var parent = _MTS_JQUERY("#block_" + id);
   EXIF.enableXmp();

   EXIF.getData(image.file, function ()
   {
      var credit = EXIF.getTag(this, "Artist") || EXIF.getIptcTag(this, "credit") || $(this.xmpdata.doc).find("dc\\:creator").text().replace(/\s+/g, ' ').trim();
      var caption = EXIF.getTag(this, "ImageDescription") || EXIF.getIptcTag(this, "caption") || $(this.xmpdata.doc).find("dc\\:description").text().replace(/\s+/g, ' ').trim();

      parent.find(".phInfoName").html(image.file.name);
      parent.find(".phInfoName").attr('title', image.file.name);
      parent.find("input[name='fileName']").val(image.file.name);
      parent.find("input[name='credit']").val(credit);
      parent.find("textarea[name='caption']").val(caption);

      _pendingData.splice(_pendingData.indexOf(id), 1);
      if (_pendingData.length == 0)
      {
         _MTS_JQUERY(document).trigger("metadataLoaded");
         _MTS_JQUERY(document).off("metadataLoaded");
      }
   });
}

function orientPhoto(id)
{
   _pendingData.push(id);
   var image = _photoList[id];
   var phImg = _MTS_JQUERY("#block_" + id).find(".phImg");
   phImg.removeClass("flip rotate90 rotate180 rotate270 rotate90flip rotate180flip rotate270flip");

   EXIF.getData(image.file, function ()
   {
      var orientationNumber = EXIF.getTag(this, "Orientation");
      switch(orientationNumber)
      {
         case 8:
            // up is pointing to the right
            phImg.addClass("rotate270");
            break;
         case 7:
            // up is pointing to the right and mirrored
            phImg.addClass("rotate90flip");
            break;
         case 6:
            // up is pointing to the left
            phImg.addClass("rotate90");
            break;
         case 5:
            // up is pointing to the left and mirrored
            phImg.addClass("rotate270flip");
            break;
         case 4:
            // up is pointing to the bottom and mirrored
            phImg.addClass("rotate180flip");
            break;
         case 3:
            // up is pointing to the bottom
            phImg.addClass("rotate180");
            break;
         case 2:
            // mirrored
            phImg.addClass("flip");
         default:
            break;
      }

      _pendingData.splice(_pendingData.indexOf(id), 1);
      _MTS_JQUERY(document).trigger("orientationLoaded");
      _MTS_JQUERY(document).off("orientationLoaded");
   });
}

function checkFormDataChanges(parent, i)
{
   var fileContainer = parent.find("input[name='fileName']");
   var fileName = _MTS_JQUERY.trim(fileContainer.length > 0 ? fileContainer.val() : "");
   var slugline = _MTS_JQUERY.trim(parent.find("input[name='slugline']").val());
   var caption = _MTS_JQUERY.trim(parent.find("textarea[name='caption']").val());
   var credit = _MTS_JQUERY.trim(parent.find("input[name='credit']").val());
   var link = _MTS_JQUERY.trim(parent.find("input[name='link']").val());
   var desc = _MTS_JQUERY.trim(parent.find("textarea[name='desc']").val());
   var start = _MTS_JQUERY.trim(parent.find("input[name='photoStart']").val().replace(/\//g, '-'));
   var end = _MTS_JQUERY.trim(parent.find("input[name='photoEnd']").val().replace(/\//g, '-'));
   var toning = _MTS_JQUERY.trim(parent.find("select[name='toningProfile']").val());
   var presentation = _MTS_JQUERY.trim(parent.find("select[name='presentation']").val());
   var hide = parent.find("input[id='hiddenImage']").is(":checked");

   if (_photoList[i].slugline != slugline ||
      _photoList[i].caption != caption ||
      _photoList[i].credit != credit ||
      _photoList[i].desc != desc ||
      _photoList[i].start.replace(/\//g, '-') != start ||
      _photoList[i].end.replace(/\//g, '-') != end ||
      _photoList[i].toningId != toning ||
      _photoList[i].presentation != presentation ||
      _photoList[i].hide != hide ||
      _photoList[i].link != link ||
      (fileContainer.length > 0 && fileName != _photoList[i].filename))
   {
      _photoList[i].changesmade = true;
   }

   // update object with form values.
   _photoList[i].slugline = slugline;
   _photoList[i].caption = caption;
   _photoList[i].credit = credit;
   _photoList[i].desc = desc;
   _photoList[i].start = start;
   _photoList[i].end = end;
   _photoList[i].toningId = toning;
   _photoList[i].presentation = presentation;
   _photoList[i].hide = hide;
   _photoList[i].link = link;
   _photoList[i].filename = fileName;
}

function checkImageChanges()
{
   for (var i = 0; i < _photoList.length; i++)
   {

      if (!_photoList[i].removed && (_photoList[i].id > -1 || (!_photoList[i].isTooBig && (!_photoList[i].file || isAllowedType(_photoList[i].file.name))
         && (_photoList[i].file && isImageType(_photoList[i].file.name)))))
      {
         var parent = _MTS_JQUERY("#block_" + i);
         var image = _photoList[i];

         // if the dims or tag changed or image was replaced.. it will already be marked with changesmade
         // check now for form changes
         checkFormDataChanges(parent, i);

         if (_photoList[i].changesmade)
            _changedCount++;
      }
   }
}

function checkOkSave(item)
{
   if (item.id == -1 // new item
      || _uploadType != "Image" // not image
      || item.changesmade) // if update and changes to this item were made
   {
      return true;
   }

   return false;
}

function savePhotos(callback) 
{
   // first call to this should figure out how many changes are being made for the progress updater
   if (_changedCount == 0)
   {
      if (_uploadType === "Image")
      {
         checkImageChanges();
      }
      else
      {
         _changedCount = _photoList.length;
      }
   }

   for (var i = 0; i < _photoList.length; i++)
   {

      if (!_photoList[i].removed && ((_photoList[i].id > -1) || (!_photoList[i].isTooBig && (!_photoList[i].file || isAllowedType(_photoList[i].file.name))
         && (_photoList[i].file && isImageType(_photoList[i].file.name)) || _uploadType === "Advertisement")))
      {

         if (_photoList[i].isPendingUpload && checkOkSave(_photoList[i]))//function to check if new return true, if changes made return true 
         {
            sendPhoto(i);
            return;
         }
      }
   }

   _uploading = false;
   _uploaderChangesMade = false;
   _photoList = _MTS_JQUERY.map(_photoList, function (file)
   {
      file.isPendingUpload = true;
      file.alreadyUploaded = true;
      file.changesmade = false;
      return file;
   });
   _changedCount = 0;
   checkForPhotos();
   disableThumbnailCrop();
}

function sendPhoto(id)
{
   if (_photoList[id] == null)
   {

      _uploading = false;
      checkForPhotos();
      return false;
   }

   var image = _photoList[id];
    var mode = image.id > -1 ? "update" : "upload";
   
   var parent = _MTS_JQUERY("#block_" + id);

   var params = new FormData();
   params.append("uploadType", _uploadType);
   params.append("imgId", image.id);
   params.append("mode", mode);

   var uploadUrl = "/api/uploadImage.aspx";
   _imageVersionChange = false;

   switch (_uploadType)
   {
      case "Image":
         {
            params.append("dims", JSON.stringify(image.dims));
            params.append("cap", htmlEncode(image.caption));
            params.append("cre", image.credit);
            params.append("start", image.start);
            params.append("end", image.end);
            params.append("toning", image.toningId);
            params.append("hide", image.hide);
            params.append("presentation", image.presentation);
            params.append("desc", htmlEncode(image.desc));
            params.append("link", image.link);
            params.append("fileName", image.filename);
            params.append("slugline", image.slugline);

            if (mode === 'update')
               _imageVersionChange = true;
         }
         break;
      case "Advertisement":
         {
            var runDates = JSON.stringify(image.runDates);

            params.append("accountNumber", image.accountNumber);
            params.append("title", image.title);
            params.append("adNumber", image.adNumber);
            params.append("width", image.width);
            params.append("height", image.height);
            params.append("notes", image.notes);
            params.append("url", image.url);
            params.append("colorSetting", image.colorSetting);
            params.append("rpl", image.requestedPageLocation);
            params.append("runDates", runDates);
            params.append("hasPlaceholder", image.HasPlaceholder);

         }
         break;
      case "Author":
         {
            params.append("authorId", _authorId);
         }
         break;
   }


   var tags = _MTS_JQUERY.map(image.tags, function (tag)
   {
      if (!tag.removed)
         return tag.id + "_" + tag.type;
   });
   var tagStr = JSON.stringify(tags);

   params.append("tags", tagStr);

   //check required 
   if (_uploadType == "Advertisement")
   {

      var error = "";
      if ($.trim(image.title).length == 0)
      {
         error = "a title";
      }
      else if ($.trim(image.width.toString()).length == 0)
      {
         error = "a width";
      }
      else if ($.trim(image.height.toString()).length == 0)
      {
         error = "a height";
      }
      else if (image.runDates.length == 0)
      {
         error = "at least one run date";
      }

      if (error.length == 0)
      {
         var validPubs = false;
         var havePublications = image.runDates.map(function (me)
         {
            return (me.Publication != undefined && me.Publication.length > 0) || (me.PublicationId != undefined && me.PublicationId > 0);
         });

         for (var i = havePublications.length - 1; i >= 0; i--)
         {
            validPubs = havePublications[i];
            if (validPubs == false)
               break;
         }

         if (!validPubs)
         {
            error = "a publication for each run date";
         }
      }

      if (error.length > 0)
      {
         alert("Please provide " + error);
         uploadUrl = "";
         return;
      }

      //check if publication tags require pagenumber
      //var reqPage = false;

      //if (image.page.toString().trim().length == 0 && image.tags.length > 0)
      //{
      //   for (var t = 0; t < image.tags.length; t++)
      //   {
      //      if (image.tags[t].removed)
      //         continue;

      //      for (var v = 0; v < _pubList.length; v++)
      //      {
      //         //if (_pubList[v].pubName === image.tags[t].title)
      //         if (_pubList[v].pubId == image.tags[t].id)
      //         {

      //            if (_pubList[v].pageReq)
      //               reqPage = true;

      //            break;
      //         }
      //      }

      //      if (reqPage)
      //         break;
      //   }
      //}

      //if (reqPage)
      //{
      //   alert("One of the tagged publications requires page number.");
      //   uploadUrl = "";
      //   return;
      //}
   }

   image.isPendingUpload = false;
   _uploading = true;

   checkForPhotos();
   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function (event) { stateChange_PhotoUpload(xhr, event, id); };

   if (_uploadType == "Image")
   {
      var albumId = _MTS_JQUERY("#albumSelect").val();
      var sites = "";
      $.each($(".phusites input:checked"), function (i, val) { sites += (sites.length === 0 ? "" : ",") + val.id.split('_')[1] });

      params.append("aId", albumId);
      params.append("sites", sites);
      params.append("alb", typeof image.album !== 'undefined' && image.album.length > 0 ? image.album : "");

      if (_rankImgs)
      {
         params.append("rank", image.rank);
          params.append("lId", _currentAlbumId);
          params.append("manager", $("#manager").val());
          
      }
   }

   xhr.open("POST", uploadUrl, true);
   if (!image.alreadyUploaded && (mode == "upload" || image.file))
   {
      xhr.setRequestHeader("X-FILE-NAME", image.file ? encodeURIComponent(image.file.name) : "");
      params.append("image", image.file);
      xhr.send(params);
   }
   else
   {
      xhr.send(params);
   }
}

function stateChange_PhotoUpload(xhr, event, id)
{
   if (event.target.readyState == 4)
   {
      _uploadedCount++;
      var act = _MTS_JQUERY("#block_" + id + " .phImgCtr");

      if ((event.target.status == 200 || event.target.status == 304))
      {
         var o = JSON.parse(xhr.response);
         if (o.ok === "true")
         {
            var aim = "<div class='imgCheck'></div>";
            act.prepend(aim);
            _MTS_JQUERY(".imgCheck").addClass("imgCheckShow");
            _photoList[id].id = o.imgId;
            if (_uploadType == "Advertisement")
            {
               _photoList[id].runDates = o.runDates;
               if (_photoList[id] == _selectedAd)
               {
                  _selectedRunDate = null;
                  _MTS_JQUERY("#insertionWrapper").hide();
                  _MTS_JQUERY("#dateWrapper").empty();
                  _selectedAd.runDates.forEach(function (date, index)
                  {
                     var template = "<div id='date_" + index + "' class='runDate'>" + _MTS_JQUERY("#dateTemplate").html() + "</div>";
                     _MTS_JQUERY("#dateWrapper").append(template);

                     var parsed = new Date(date.RunDate);
                     if (!isNaN(parsed))
                     {
                        parsed = (parsed.getMonth() + 1) + "/" + parsed.getDate() + "/" + parsed.getFullYear();
                     }

                     _MTS_JQUERY("#date_" + index).find(".dateContent").html(parsed);
                  });
               }
            }
            if (typeof (_MTS_UPLOAD_CALLBACK) === "function")
            {
               _MTS_UPLOAD_CALLBACK(_photoList[id].id, _photoList[id].alreadyUploaded);
               _photoList[id].alreadyUploaded = true;
            }
         }
         else
         {
            var aim = "<div class='imgErr'></div>";
            act.prepend(aim);
            _MTS_JQUERY(".imgErr").addClass("imgCheckShow");
            alert((_photoList[id].id > -1 ? "Update" : "Upload") + " Failed!");
         }
      }
      else
      {
         var aim = "<div class='imgErr'></div>";
         act.prepend(aim);
         _MTS_JQUERY(".imgErr").addClass("imgCheckShow");
          alert((_photoList[id].id > -1 ? "Update" : "Upload") + " Failed!\nError " + event.target.status + ": " + event.target.statusText);
      }

      var prog = getUploadProgress();
      _MTS_JQUERY(".progressBar").animate({ "width": prog + "%" }, "linear", function ()
      {
         if (prog == 100)
         {
            var images = _MTS_JQUERY(".photoHolder .phImg");
            images.removeClass("flip rotate90 rotate180 rotate270 rotate90flip rotate180flip rotate270flip");
            var newpreviewsrc = "";
           
            for (var i = images.length - 1; i >= 0; i--)
            {
               var id = _MTS_JQUERY(images[i]).parents(".phBlockCtr")[0].id.split('_')[1];
               if (_uploadType !== "Advertisement")
               {
                  //images[i].src = _MTS_PHOTO_TEMPLATE.replace("%%IMG_ID%%", _photoList[id].id)
                  //   .replace("%%SIZE%%", 2).replace("%%TEAM_ID%%", _photoList[i].teamId).replace("%%USER_ID%%", _photoList[id].uploaderId).replace("%%TYPE%%", 0) + "?cacheBuster=" + Math.random();
                  images[i].src = getImageLink(_photoList[id], 2);
               }
            }
            
            alert("Save & Update Complete" + (_MTS_JQUERY(".imgErr").length > 0 ? "d with errors" : ""));
         
             _MTS_JQUERY(".progressBar").width(0);
             
         }
          
         if (_uploading)
            savePhotos();
      });
   }
}

function /*void*/ToggleNewUploadTag()
{
  
    _beforeUpload = false;
   _MTS_JQUERY(".uploadTagWrapper:first").addClass("showTagWrapper");
   _MTS_JQUERY(".uploadTagWrapper .search_widget .filterRow").removeClass("filterRowOpen");
   var ftfc = _MTS_JQUERY(".findTeamFormContainer:visible").height();
   var ffc = _MTS_JQUERY(".formFilterContainer:visible").height();
   var mpc = _MTS_JQUERY(".morePagesContainer:visible").outerHeight();
   var sum = ftfc + ffc + mpc;
   _MTS_JQUERY(".searchResults").css({ "height": (_MTS_JQUERY(".uploadTagWrapper").outerHeight() - sum) - 40 + "px" });
  
   if (_uploadType == "Image")
   {
      if (!_MTS_sportsEnabled)
         _MTS_JQUERY(".filterColumn:not('#CategoryFilter,#SubcategoryFilter')").addClass("filterDisabled");
   }
   else
   {
      _MTS_JQUERY(".filterColumn:not('#PublicationFilter')").addClass("filterDisabled");
   }

   MTS_handleEz(0, highlightTags, _MTS_JQUERY(".showTagWrapper").find("#searchPhrase"));
}

function handleTagClick(link, title, id, type)
{
   if (_uploadType == "Image")
   {
      if (_MTS_JQUERY(".search_widget:visible").parents(".uploadTagWrapper.showTagWrapper").length > 0)
         selectUploadTag(link, title, id, type);
      else
         selectTag(link, title, id, type);
   }
   else
   {
      selectAdTag(link, title, id, type);
   }

   _MTS_JQUERY(".result[href$='" + id + ",\\'" + type + "\\')']").addClass("selectedTag");
}

function selectUploadTag(link, title, tagId, type)
{
    if (_tagItemId > -1 && _photoList[_tagItemId] != null) {
        addTag(_photoList[_tagItemId].tags, tagId, type, title);
        _photoList[_tagItemId].changesmade = true;
    }
   else if (_tagItemId < 0)
   {
      var selected = _MTS_JQUERY(".photoHolder").find("input[type='checkbox'].phCheck:checked").parents(".phBlockCtr");
      if (selected.length > 0)
      {
         for (i = 0; i < selected.length; i++)
         {
            var id = selected[i].id.split('_')[1];
             addTag(_photoList[id].tags, tagId, type, title);
             _photoList[id].changesmade = true;
         }
      }
      else
      {
         for (i = 0; i < _photoList.length; i++)
         {
            addTag(_photoList[i].tags, tagId, type, title);
            _photoList[i].changesmade = true;
         }
      }
   }

   updateTagList();
}

function addTag(list, tagId, linkType, title)
{
   var exists = false;
   for (var i = 0; i < list.length; i++)
   {
       var tag = list[i];
     
      if (tag.id == tagId && tag.type == linkType)
      {
         exists = true;
         if (tag.removed)
            _uploaderChangesMade = true;
         tag.removed = false;
         break;
      }
   }
   if (!exists)
   {
      list.push(new mtsTag(tagId, linkType, title));
      _uploaderChangesMade = true;
   }
}

function highlightTags()
{
   if (_uploadType === "Advertisement")
   {
      if (_selectedRunDate)
      {
         var pub = findPublicationByPubCode(_selectedRunDate.Publication, _selectedRunDate.PublicationId);
         if (pub != null)
         {
            _MTS_JQUERY(".result[href$='" + pub.Id + ",\\'Publication\\')']").addClass("selectedTag");
         }
      }
   }
   else
   {
      _MTS_JQUERY(".uploadTagContainer:visible .tagAll").each(function ()
      {
         var id = _MTS_JQUERY(this).find("input[name='id']").val();

         var type = _MTS_JQUERY(this).find("input[name='type']").val();

         _MTS_JQUERY(".result[href$='" + id + ",\\'" + type + "\\')']").addClass("selectedTag");
      });
   }
}

function selectAdTag(link, title, tagId, type)
{
   _MTS_JQUERY(".selectedTag").removeClass("selectedTag");
   
   var pub = "";
   for (var i = _pubs.length - 1; i >= 0; i--)
   {
      if (_pubs[i].Name == title)
      {
         pub = _pubs[i].PubCode;
         break;
      }
   }

   _selectedRunDate.Publication = pub;
   _selectedRunDate.PublicationId = tagId;
   _MTS_JQUERY("input[name='publication']").val(title);
}

function updateTagList()
{

   var html = "";
   if (_tagItemId > -1 && _photoList[_tagItemId] != null)
   {
      for (var i = 0; i < _photoList[_tagItemId].tags.length; i++)
      {
         if (!_photoList[_tagItemId].tags[i].removed)
            html += getTagHtml(_photoList[_tagItemId].tags[i]);
      }

      if (html.length == 0)
         html = "No tags selected";

      _MTS_JQUERY(".tagList").html(html);
   }

   var commonTags = [];
   var files = [];

   files = _MTS_JQUERY.map(_photoList, function (file)
   {
      return file.removed ? null : file;
   });

   if (files.length > 0)
      commonTags = files[0].tags;

   _MTS_JQUERY(".photo_upload_widget").find("#allTags").html(getCommonTagHtml(commonTags, files));

   files = _MTS_JQUERY(".photoHolder").find("input[type='checkbox'].phCheck:checked").parents(".phBlockCtr").map(function ()
   {
      var id = this.id.split('_')[1];
      return typeof _photoList[id] != 'undefined' && !_photoList[id].removed ? _photoList[id] : null;
   });

   if (files.length > 0)
      commonTags = files[0].tags;

   _MTS_JQUERY(".photo_upload_widget").find("#selectedTags").html(getCommonTagHtml(commonTags, files));
}

function isAllowedType(file)
{
   var type = file.substring(file.lastIndexOf(".") + 1);

   for (var i = 0; i < _badExt.length; i++)
   {
      if (_badExt[i] == type.toLowerCase())
         return false;
   }

   return true;
}

function isImageType(file)
{
   return isFileType(file, _imageExtensions);
}

function isFileType(file, extensions)
{
   var type = file.substring(file.lastIndexOf(".") + 1);

   for (var i = 0; i < extensions.length; i++)
   {
      if (extensions[i] == type.toLowerCase())
         return true;
   }

   return false;
}

function getUploadProgress()
{
   var files = _MTS_JQUERY.map(_photoList, function (file)
   {
      if (!file.removed && (file.id > -1 || (!file.isTooBig && (!file.file || (isAllowedType(file.file.name) && (isImageType(file.file.name) || _uploadType === "Advertisement"))))))
      {
         return file;
      }
   });

   return (_uploadedCount / /*files.length*/_changedCount) * 100;
}

function mtsPhotoInfo(f, img, big, thumb, up, alb)
{
   this.file = f;
   this.isImage = img;
   this.isTooBig = big;
   this.isPendingThumb = thumb;
   this.isPendingUpload = up;
   this.album = alb;

   var dims = "";
   var photos = _MTS_JQUERY(".phImgCtr img");
   for (var i = _MTS_focusImgs.length - 1; i >= 0; i--)
   {
      for (var j = photos.length - 1; j >= 0; j--)
      {
         if (_MTS_focusImgs[i][0] == photos[j])
         {
            dims = _MTS_focusDims[i];
            break;
         }
      }
   }
   this.dims = dims;

   this.drawn = false;
   this.removed = false;

   this.alreadyUploaded = false;
   this.id = -1;
   this.container = -1;
   this.inCloud = false;
   this.src = "";
   this.slugline = "";
   this.caption = "";
   this.credit = "";
   this.filename = "";
   this.link = "";
   this.desc = "";
   this.start = "";
   this.end = "";
   this.rank = 0;
   this.date = new Date();
   this.uploaderId = _MTS_userId;
   this.teamId = 0;
   this.portalId = _MTS_PORTALID;
   this.sites = [];
   this.toningId = typeof (_toningId) == "number" ? _toningId : 0;
   this.presentation = 0;
   this.changesmade = false;
   this.hide = !_MTS_published;
   this.tags = [];
}

function adInfo(f, img, big, thumb, up)
{
   this.file = f;
   this.isImage = img;
   this.isTooBig = big;
   this.isPendingThumb = thumb;
   this.isPendingUpload = up;

   this.drawn = false;
   this.removed = false;

   this.alreadyUploaded = false;
   this.id = -1;
   this.src = "";
   this.accountNumber = "";

   if (f)
   {
      var idx = f.name.lastIndexOf(".");
      this.title = idx > 0 ? f.name.substring(0, idx) : f.name;
   }
   else
   {
      this.title = "";
   }

   this.title = f ? f.name.substring(0, f.name.lastIndexOf(".")) : "";
   this.adNumber = "";
   this.edition = "";
   this.section = "";
   this.page = "";
   this.zone = "";
   this.width = "";
   this.height = "";
   this.horizontalPosition = "";
   this.verticalPosition = "";
   this.notes = "";
   this.url = "";
   this.colorSetting = _MTS_JQUERY("input[name='colorSetting']:checked").val();
   this.requestedPageLocation = "";
   this.runDates = [];
   this.tags = [];
}
function publicationInfo(id, name, pagerequired)
{
    this.pubId = id;
    this.pubName = name;
    this.pageReq = pagerequired;
}

function mtsTag(id, type, title)
{
   this.id = id;
   this.type = type;
   this.title = title;
   this.removed = false;
}

function OpenUpload(id, type, loadExisting, tagIds, tagTypes, tagTitles, stock, imageIds, published = false)
{
   _MTS_published = published;
   if (!isNaN(id) && id > 0 && typeof type === 'string' && type.length > 0)
   {
      switch (type)
      {
         case "PhotoAlbum":
            _MTS_JQUERY("#albumSelect").find("option[value='" + id + "']").prop("selected", true);
            break;
         default:
            _MTS_JQUERY("#albumSelect").find("option:first").prop("selected", true);
            break;
      }

      if (loadExisting)
         getExistingPhotos(id, type, stock);
   }
   else if (typeof imageIds !== 'undefined' && loadExisting)
   {
      getExistingPhotos(null, null, null, imageIds);
   }

   if (tagIds != null && tagTypes != null && tagTitles != null)
   {
      for (var i = 0; i < tagIds.length; i++)
      {
         if (tagIds[i] > 0)
            addTag(_defaultTags, tagIds[i], tagTypes[i], tagTitles[i]);
      }
   }

   _uploaderChangesMade = false;
   _MTS_JQUERY("#albumSelect").trigger("chosen:updated");
   _MTS_JQUERY(".photo_upload_widget").addClass("animateLeft");
   _MTS_JQUERY("body").addClass("overflow");


   _MTS_JQUERY(".photo_upload_widget").css("height", _MTS_JQUERY(window).height() - _MTS_JQUERY("#mts_unlockstory:visible").height() + "px");
   var updateCtr = _MTS_JQUERY(".photo_upload_widget .updateButtonCtr");
   updateCtr.css({ bottom: _MTS_JQUERY("#mts_unlockstory:visible").height() + "px" });
   resizePhotoUpload();
}

function CloseUpload()
{
   if (_uploaderChangesMade && !confirm("You have unsaved changes - would you like to continue anyways?"))
      return false;
   if (typeof _MTS_CloseUploadFunc === 'function')
      _MTS_CloseUploadFunc();

   _MTS_JQUERY(".photo_upload_widget").removeClass("animateLeft");
   _MTS_JQUERY("body").removeClass("overflow");
   _MTS_JQUERY(".imgCheck, .imgErr").remove();
   _MTS_JQUERY(".progressBar").width("0");
   _MTS_JQUERY(".updateButtonCtr, .progress").css("position", "absolute");
   _MTS_JQUERY(".previewCtr").hide();
   _MTS_JQUERY(".tagViewerCtr").removeClass("tagViewerOpen");
   _MTS_JQUERY("#selectedTags").hide();
   _MTS_JQUERY("#allTags").show();
   _MTS_JQUERY(".showTagWrapper").removeClass("showTagWrapper");
   hideImgArea();
   disableThumbnailCrop();

   _uploderChangesMade = false;
   _MTS_previewImg = null;

   var photos = _MTS_JQUERY(".photoHolder").find(".phBlockCtr").map(function ()
   {
      return this.id.split('_')[1];
   });

   for (var i = 0; i < photos.length; i++)
      removePhotoUpload(photos[i], false);

   _photoList.length = 0;
}

function removeMultiPhotoUpload(list, selected)
{
   if (typeof _MTS_RemoveMultiPhotoPrompt === 'function' && !_MTS_RemoveMultiPhotoPrompt(selected))
      return;
   
   for (var i = 0; i < list.length; i++)
      removePhotoUpload(list[i], false);
}

function removePhotoUpload(idx, showPrompt)
   {
   if (typeof showPrompt === 'undefined')
      showPrompt = true;

   var id = _photoList[idx].id;
   if (showPrompt && typeof _MTS_RemovePhotoPrompt === 'function' && !_MTS_RemovePhotoPrompt())
      return;

   if (typeof _MTS_RemovePhotoFunc !== 'function' || id <= 0)
      removePhotoUploadCallback(idx);
   else
      _MTS_RemovePhotoFunc(id + (typeof(_currentAlbumId) !== "undefined" ? "_" + _currentAlbumId : ""), idx, removePhotoUploadCallback);
}

function removePhotoUploadCallback(idx)
{
   _photoList[idx].removed = true;
   _MTS_JQUERY("#block_" + idx).remove();
   checkForPhotos();

   if (_uploadType == "Image")
   {
      checkForSelected();
      updateTagList();
   }
}

function decodeURISafe(uri, mod)
{
   var out = new String(), arr, i = 0, l, x;
   typeof mod === "undefined" ? mod = 0 : 0;
   arr = uri.split(/(%(?:d0|d1)%.{2})/);
   for (l = arr.length; i < l; i++)
   {
      try
      {
         x = decodeURI(arr[i]);
      } catch (e)
      {
         x = mod ? arr[i].replace(/%(?!\d+)/g, '%25') : arr[i];
      }
      out += x;
   }
   return out;
}

function getExistingPhotos(id, type, stock, imageIds)
{
   var p = [];
   p.push({ name: "id", value: id });
   p.push({ name: "type", value: type });
   p.push({ name: "stock", value: stock });
   p.push({ name: "imageIds", value: imageIds });
   _MTS_ajaxPending = true;

   _MTS_JQUERY.getJSON("/api/widget/getExistingPhotosForUploader.aspx", p, function (o)
   {
      o = _MTS_JQUERY.decodeJSONObj(o);

      for (var i = 0; i < o.images.length; i++)
      {
         var file = new mtsPhotoInfo(null, true, false, true, true);
         file.id = o.images[i].id;
         file.container = o.images[i].container;
         file.inCloud = o.images[i].inCloud;
         file.src = o.images[i].src;
         file.caption = o.images[i].caption;

         file.credit = o.images[i].credit;
         file.filename = o.images[i].filename;

         file.slugline = o.images[i].slug;
         file.link = o.images[i].link;
         file.desc = o.images[i].desc;
         file.start = o.images[i].start;
         file.end = o.images[i].end;
         file.rank = o.images[i].rank;
         file.date = new Date(o.images[i].date);
         file.uploaderId = o.images[i].uploaderId;
         file.teamId = o.images[i].teamId;
         file.portalId = o.images[i].parentPortalId;
         file.sites = o.images[i].sites;
         file.toningId = o.images[i].toningId;
         file.presentation = o.images[i].presentation;
         file.pendingTone = o.images[i].pendingTone;
         file.webActiveVersion = o.images[i].webActiveVersion;
         file.prevVersions = o.images[i].prevVersions;
         file.hide = o.images[i].hide;

         var input = _MTS_JQUERY(".chkCtr input");
         for (var j = input.length - 1; j >= 0; j--)
         {
            var target = _MTS_JQUERY(input[j]);
            var id = target.attr("id").split('_')[1];
            var found = false;

            if (id == file.portalId)
            {
               found = true;
            }
            else
            {
               for (var k = file.sites.length - 1; k >= 0; k--)
               {
                  if (id == file.sites[k].id)
                  {
                     found = true;
                     break;
                  }
               }
            }

            if (found)
            {
               target.attr("disabled", "disabled");
               target.attr("checked", "checked");
            }
            else
            {
               target.removeAttr("disabled");
               target.removeAttr("checked");
            }
         }

         for (var j = 0; j < o.images[i].tags.length; j++)
            file.tags.push(new mtsTag(o.images[i].tags[j].linkId, o.images[i].tags[j].linkType, o.images[i].tags[j].title));

         _photoList.push(file);
      }

      startPhotoUpload();
      CheckPhotosForRank();

      var parent = $($(".phImg")[0]).parent();
      if (parent.length > 0)
      {
         var info = $(".photoCtr > .phBlockCtr");
         if (info.length > 0)
         {
            info.each(function (index)
            {
               var input = $("<div class='imageReplace mts_cc_button'>Replace<input title='File Upload' class='replace' type='file' /></div>");
               _MTS_JQUERY(this).find(".phBlockInfo").prepend(input);
            });

            $(document).on("change", ".replace", function ()
            {
               var idx = $(".replace").index(this);
               _photoList[idx].file = this.files[0];
               _photoList[idx].changesmade = true;
               _photoList[idx].alreadyUploaded = false;

               let parent = _MTS_JQUERY(this).parents(".phBlockCtr");
               parent.find(".phInfoName").html(_photoList[idx].file.name).attr("title", _photoList[idx].file.name);
               parent.find("input[name='fileName']").val(_photoList[idx].file.name);
               parent.find("input[type=checkbox].phCheck").prop("checked", true).change();
            });
         }
      }
   });
}

function CheckPhotosForRank()
{
   var ranked = _MTS_JQUERY.map(_photoList, function (e, i)
   {
      return e.rank > 0 ? e : null;
   });

    if (ranked.length == 0) {
        _MTS_JQUERY("#wipeRank").addClass("noSelect");
        
    }
    else {
        _MTS_JQUERY("#wipeRank").removeClass("noSelect");
        
    }
}

function SortPhotosByRank()
{
   var photos = _MTS_JQUERY(".photoCtr li").sort(function (a, b)
   {
      var aId = a.id.split('_')[1];
      var bId = b.id.split('_')[1];

      var aP = _photoList[aId];
      var bP = _photoList[bId];

      if (aP.rank > 0 && bP.rank > 0)
         return aP.rank > bP.rank ? 1 : aP.rank < bP.rank ? -1 : 0;
      if (aP.rank == 0 && bP.rank == 0)
         return aP.date.getTime() < bP.date.getTime() ? 1 : aP.date.getTime() > bP.date.getTime() ? -1 : 0
      return aP.rank > 0 && bP.rank <= 0 ? -1 : aP.rank <= 0 && bP.rank > 0 ? 1 : 0;
   });

   _MTS_JQUERY(".photoCtr").append(photos);
   CheckPhotosForRank();
}
﻿//Copyright(c) 2008- 2013 Michal Wojciechowski, http://odyniec.net/

//Permission is hereby granted, free of charge, to any person obtaining
//a copy of this software and associated documentation files (the
//"Software"), to deal in the Software without restriction, including
//without limitation the rights to use, copy, modify, merge, publish,
//   distribute, sublicense, and / or sell copies of the Software, and to
//permit persons to whom the Software is furnished to do so, subject to
//the following conditions:

//The above copyright notice and this permission notice shall be
//included in all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
//LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

eval(function (p, a, c, k, e, d) { e = function (c) { return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]); return p }('(m($){18 W=2v.4T,D=2v.4S,F=2v.4R,u=2v.4Q;m V(){C $("<4P/>")};$.N=m(T,c){18 O=$(T),1F,A=V(),1k=V(),I=V().r(V()).r(V()).r(V()),B=V().r(V()).r(V()).r(V()),E=$([]),1K,G,l,17={v:0,l:0},Q,M,1l,1g={v:0,l:0},12=0,1J="1H",2k,2j,1t,1s,S,1B,1A,2o,2n,14,1Q,a,b,j,g,f={a:0,b:0,j:0,g:0,H:0,L:0},2u=R.4O,1M=4N.4M,$p,d,i,o,w,h,2p;m 1n(x){C x+17.v-1g.v};m 1m(y){C y+17.l-1g.l};m 1b(x){C x-17.v+1g.v};m 1a(y){C y-17.l+1g.l};m 1z(3J){C 3J.4L-1g.v};m 1y(3I){C 3I.4K-1g.l};m 13(32){18 1i=32||1t,1h=32||1s;C{a:u(f.a*1i),b:u(f.b*1h),j:u(f.j*1i),g:u(f.g*1h),H:u(f.j*1i)-u(f.a*1i),L:u(f.g*1h)-u(f.b*1h)}};m 23(a,b,j,g,31){18 1i=31||1t,1h=31||1s;f={a:u(a/1i||0),b:u(b/1h||0),j:u(j/1i||0),g:u(g/1h||0)};f.H=f.j-f.a;f.L=f.g-f.b};m 1f(){9(!1F||!O.H()){C}17={v:u(O.2t().v),l:u(O.2t().l)};Q=O.2Y();M=O.3H();17.l+=(O.30()-M)>>1;17.v+=(O.2q()-Q)>>1;1B=u(c.4J/1t)||0;1A=u(c.4I/1s)||0;2o=u(F(c.4H/1t||1<<24,Q));2n=u(F(c.4G/1s||1<<24,M));9($().4F=="1.3.2"&&1J=="21"&&!2u["4E"]){17.l+=D(R.1q.2r,2u.2r);17.v+=D(R.1q.2s,2u.2s)}1g=/1H|4D/.1c(1l.q("1p"))?{v:u(1l.2t().v)-1l.2s(),l:u(1l.2t().l)-1l.2r()}:1J=="21"?{v:$(R).2s(),l:$(R).2r()}:{v:0,l:0};G=1n(0);l=1m(0);9(f.j>Q||f.g>M){1U()}};m 1V(3F){9(!1Q){C}A.q({v:1n(f.a),l:1m(f.b)}).r(1k).H(w=f.H).L(h=f.L);1k.r(I).r(E).q({v:0,l:0});I.H(D(w-I.2q()+I.2Y(),0)).L(D(h-I.30()+I.3H(),0));$(B[0]).q({v:G,l:l,H:f.a,L:M});$(B[1]).q({v:G+f.a,l:l,H:w,L:f.b});$(B[2]).q({v:G+f.j,l:l,H:Q-f.j,L:M});$(B[3]).q({v:G+f.a,l:l+f.g,H:w,L:M-f.g});w-=E.2q();h-=E.30();2O(E.3f){15 8:$(E[4]).q({v:w>>1});$(E[5]).q({v:w,l:h>>1});$(E[6]).q({v:w>>1,l:h});$(E[7]).q({l:h>>1});15 4:E.3G(1,3).q({v:w});E.3G(2,4).q({l:h})}9(3F!==Y){9($.N.2Z!=2R){$(R).U($.N.2z,$.N.2Z)}9(c.1T){$(R)[$.N.2z]($.N.2Z=2R)}}9(1j&&I.2q()-I.2Y()==2){I.q("3E",0);3x(m(){I.q("3E","4C")},0)}};m 22(3D){1f();1V(3D);a=1n(f.a);b=1m(f.b);j=1n(f.j);g=1m(f.g)};m 27(2X,2w){c.1P?2X.4B(c.1P,2w):2X.1r()};m 1d(2W){18 x=1b(1z(2W))-f.a,y=1a(1y(2W))-f.b;9(!2p){1f();2p=11;A.1G("4A",m(){2p=Y})}S="";9(c.2D){9(y<=c.1W){S="n"}X{9(y>=f.L-c.1W){S="s"}}9(x<=c.1W){S+="w"}X{9(x>=f.H-c.1W){S+="e"}}}A.q("2V",S?S+"-19":c.26?"4z":"");9(1K){1K.4y()}};m 2S(4x){$("1q").q("2V","");9(c.4w||f.H*f.L==0){27(A.r(B),m(){$(J).1r()})}$(R).U("P",2l);A.P(1d);c.2f(T,13())};m 2C(1X){9(1X.3z!=1){C Y}1f();9(S){$("1q").q("2V",S+"-19");a=1n(f[/w/.1c(S)?"j":"a"]);b=1m(f[/n/.1c(S)?"g":"b"]);$(R).P(2l).1G("1x",2S);A.U("P",1d)}X{9(c.26){2k=G+f.a-1z(1X);2j=l+f.b-1y(1X);A.U("P",1d);$(R).P(2T).1G("1x",m(){c.2f(T,13());$(R).U("P",2T);A.P(1d)})}X{O.1O(1X)}}C Y};m 1w(3C){9(14){9(3C){j=D(G,F(G+Q,a+W(g-b)*14*(j>a||-1)));g=u(D(l,F(l+M,b+W(j-a)/14*(g>b||-1))));j=u(j)}X{g=D(l,F(l+M,b+W(j-a)/14*(g>b||-1)));j=u(D(G,F(G+Q,a+W(g-b)*14*(j>a||-1))));g=u(g)}}};m 1U(){a=F(a,G+Q);b=F(b,l+M);9(W(j-a)<1B){j=a-1B*(j<a||-1);9(j<G){a=G+1B}X{9(j>G+Q){a=G+Q-1B}}}9(W(g-b)<1A){g=b-1A*(g<b||-1);9(g<l){b=l+1A}X{9(g>l+M){b=l+M-1A}}}j=D(G,F(j,G+Q));g=D(l,F(g,l+M));1w(W(j-a)<W(g-b)*14);9(W(j-a)>2o){j=a-2o*(j<a||-1);1w()}9(W(g-b)>2n){g=b-2n*(g<b||-1);1w(11)}f={a:1b(F(a,j)),j:1b(D(a,j)),b:1a(F(b,g)),g:1a(D(b,g)),H:W(j-a),L:W(g-b)};1V();c.2g(T,13())};m 2l(2U){j=/w|e|^$/.1c(S)||14?1z(2U):1n(f.j);g=/n|s|^$/.1c(S)||14?1y(2U):1m(f.g);1U();C Y};m 1v(3B,3A){j=(a=3B)+f.H;g=(b=3A)+f.L;$.2c(f,{a:1b(a),b:1a(b),j:1b(j),g:1a(g)});1V();c.2g(T,13())};m 2T(2m){a=D(G,F(2k+1z(2m),G+Q-f.H));b=D(l,F(2j+1y(2m),l+M-f.L));1v(a,b);2m.4v();C Y};m 2h(){$(R).U("P",2h);1f();j=a;g=b;1U();S="";9(!B.2y(":4u")){A.r(B).1r().2E(c.1P||0)}1Q=11;$(R).U("1x",1N).P(2l).1G("1x",2S);A.U("P",1d);c.3y(T,13())};m 1N(){$(R).U("P",2h).U("1x",1N);27(A.r(B));23(1b(a),1a(b),1b(a),1a(b));9(!(J 4t $.N)){c.2g(T,13());c.2f(T,13())}};m 2A(2i){9(2i.3z!=1||B.2y(":4s")){C Y}1f();2k=a=1z(2i);2j=b=1y(2i);$(R).P(2h).1x(1N);C Y};m 2B(){22(Y)};m 2x(){1F=11;25(c=$.2c({1S:"4r",26:11,20:"1q",2D:11,1W:10,3w:m(){},3y:m(){},2g:m(){},2f:m(){}},c));A.r(B).q({3b:""});9(c.2F){1Q=11;1f();1V();A.r(B).1r().2E(c.1P||0)}3x(m(){c.3w(T,13())},0)};18 2R=m(16){18 k=c.1T,d,t,2N=16.4q;d=!1L(k.2P)&&(16.2e||16.3t.2e)?k.2P:!1L(k.2a)&&16.3u?k.2a:!1L(k.2b)&&16.3v?k.2b:!1L(k.2Q)?k.2Q:10;9(k.2Q=="19"||(k.2b=="19"&&16.3v)||(k.2a=="19"&&16.3u)||(k.2P=="19"&&(16.2e||16.3t.2e))){2O(2N){15 37:d=-d;15 39:t=D(a,j);a=F(a,j);j=D(t+d,a);1w();1u;15 38:d=-d;15 40:t=D(b,g);b=F(b,g);g=D(t+d,b);1w(11);1u;3s:C}1U()}X{a=F(a,j);b=F(b,g);2O(2N){15 37:1v(D(a-d,G),b);1u;15 38:1v(a,D(b-d,l));1u;15 39:1v(a+F(d,Q-1b(j)),b);1u;15 40:1v(a,b+F(d,M-1a(g)));1u;3s:C}}C Y};m 1R(3r,2M){3p(18 2d 4p 2M){9(c[2d]!==1Y){3r.q(2M[2d],c[2d])}}};m 25(K){9(K.20){(1l=$(K.20)).2G(A.r(B))}$.2c(c,K);1f();9(K.2L!=3q){E.1o();E=$([]);i=K.2L?K.2L=="4o"?4:8:0;3g(i--){E=E.r(V())}E.29(c.1S+"-4n").q({1p:"1H",36:0,1I:12+1||1});9(!4m(E.q("H"))>=0){E.H(5).L(5)}9(o=c.2K){E.q({2K:o,2H:"3m"})}1R(E,{3n:"2J-28",3l:"2I-28",3o:"1e"})}1t=c.4l/Q||1;1s=c.4k/M||1;9(K.a!=3q){23(K.a,K.b,K.j,K.g);K.2F=!K.1r}9(K.1T){c.1T=$.2c({2b:1,2a:"19"},K.1T)}B.29(c.1S+"-4j");1k.29(c.1S+"-4i");3p(i=0;i++<4;){$(I[i-1]).29(c.1S+"-2J"+i)}1R(1k,{4h:"2I-28",4g:"1e"});1R(I,{3o:"1e",2K:"2J-H"});1R(B,{4f:"2I-28",4e:"1e"});9(o=c.3n){$(I[0]).q({2H:"3m",3k:o})}9(o=c.3l){$(I[1]).q({2H:"4d",3k:o})}A.2G(1k.r(I).r(1K)).2G(E);9(1j){9(o=(B.q("3j")||"").3i(/1e=(\\d+)/)){B.q("1e",o[1]/1Z)}9(o=(I.q("3j")||"").3i(/1e=(\\d+)/)){I.q("1e",o[1]/1Z)}}9(K.1r){27(A.r(B))}X{9(K.2F&&1F){1Q=11;A.r(B).2E(c.1P||0);22()}}14=(d=(c.4c||"").4b(/:/))[0]/d[1];O.r(B).U("1O",2A);9(c.1E||c.1D===Y){A.U("P",1d).U("1O",2C);$(3h).U("19",2B)}X{9(c.1D||c.1E===Y){9(c.2D||c.26){A.P(1d).1O(2C)}$(3h).19(2B)}9(!c.4a){O.r(B).1O(2A)}}c.1D=c.1E=1Y};J.1o=m(){25({1E:11});A.r(B).1o()};J.49=m(){C c};J.33=25;J.48=13;J.47=23;J.46=1N;J.45=22;18 1j=(/44 ([\\w.]+)/i.43(1M)||[])[1],3c=/42/i.1c(1M),3d=/41/i.1c(1M)&&!/3Z/i.1c(1M);$p=O;3g($p.3f){12=D(12,!1L($p.q("z-3e"))?$p.q("z-3e"):12);9($p.q("1p")=="21"){1J="21"}$p=$p.20(":3Y(1q)")}12=c.1I||12;9(1j){O.3X("3W","3V")}$.N.2z=1j||3d?"3U":"3T";9(3c){1K=V().q({H:"1Z%",L:"1Z%",1p:"1H",1I:12+2||2})}A.r(B).q({3b:"3a",1p:1J,3S:"3a",1I:12||"0"});A.q({1I:12+2||2});1k.r(I).q({1p:"1H",36:0});T.35||T.3R=="35"||!O.2y("3Q")?2x():O.1G("3P",2x);9(!1F&&1j&&1j>=7){T.34=T.34}};$.2w.N=m(Z){Z=Z||{};J.3O(m(){9($(J).1C("N")){9(Z.1o){$(J).1C("N").1o();$(J).3N("N")}X{$(J).1C("N").33(Z)}}X{9(!Z.1o){9(Z.1D===1Y&&Z.1E===1Y){Z.1D=11}$(J).1C("N",3M $.N(J,Z))}}});9(Z.3L){C $(J).1C("N")}C J}})(3K);', 62, 304, '|||||||||if|x1|y1|_7|||_23|y2|||x2||top|function||||css|add|||_4|left|||||_a|_d|return|_2|_e|_3|_10|width|_c|this|_55|height|_13|imgAreaSelect|_8|mousemove|_12|document|_1c|_6|unbind|_5|_1|else|false|_58||true|_16|_2c|_21|case|_50|_11|var|resize|_29|_28|test|_3a|opacity|_30|_15|sy|sx|_35|_b|_14|_27|_26|remove|position|body|hide|_1b|_1a|break|_45|_42|mouseup|evY|evX|_1e|_1d|data|enable|disable|_9|one|absolute|zIndex|_17|_f|isNaN|ua|_4a|mousedown|fadeSpeed|_22|_51|classPrefix|keys|_31|_32|resizeMargin|_40|undefined|100|parent|fixed|_36|_2e||_4f|movable|_38|color|addClass|ctrl|shift|extend|_54|altKey|onSelectEnd|onSelectChange|_49|_4c|_19|_18|_3e|_48|_20|_1f|_25|outerWidth|scrollTop|scrollLeft|offset|_24|Math|fn|_4e|is|keyPress|_4b|_4d|_3f|resizable|fadeIn|show|append|borderStyle|background|border|borderWidth|handles|_53|key|switch|alt|arrows|_34|_3c|_41|_44|cursor|_3b|_39|innerWidth|onKeyPress|outerHeight|_2f|_2d|setOptions|src|complete|fontSize||||hidden|visibility|_56|_57|index|length|while|window|match|filter|borderColor|borderColor2|solid|borderColor1|borderOpacity|for|null|_52|default|originalEvent|ctrlKey|shiftKey|onInit|setTimeout|onSelectStart|which|_47|_46|_43|_37|margin|_33|slice|innerHeight|_2b|_2a|jQuery|instance|new|removeData|each|load|img|readyState|overflow|keypress|keydown|on|unselectable|attr|not|chrome||webkit|opera|exec|msie|update|cancelSelection|setSelection|getSelection|getOptions|persistent|split|aspectRatio|dashed|outerOpacity|outerColor|selectionOpacity|selectionColor|selection|outer|imageHeight|imageWidth|parseInt|handle|corners|in|keyCode|imgareaselect|animated|instanceof|visible|preventDefault|autoHide|_3d|toggle|move|mouseout|fadeOut|auto|relative|getBoundingClientRect|jquery|maxHeight|maxWidth|minHeight|minWidth|pageY|pageX|userAgent|navigator|documentElement|div|round|min|max|abs'.split('|')));

﻿// AI Research Tool
// Calendar
//
// JDBunnell, 2010



/* extern var */_cal = {
   obj: null,
   bg: null,

   monthNames: ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
   doom_codes: [0, 6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4],
   monthCount: [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],

   startContractYear: 2008,
   startContractMonth: 1,
   startContractDay: 1,

   viewMonth: 1,
   viewYear: 2010,

   month: 1,
   day: 1,
   year: 2010,
   wndTitle: "",

   monthRecycle: [],
   dayRecycle: [],
   yearRecycle: [],

   minYear: 2008,
   maxYear: 2011,

   posTop: 0,
   posLeft: 0,
   mode: "select",

   rangeStartDate: null,
   rangeEndDate: null,
   rangeStartDateSet: false,
   rangeEndDateSet: false,

   callbackFunc: function () { },
   closeCallbackFunc: function () { },

   initialize: function ()
   {
      _cal.obj = document.getElementById("calBox");
      if (_cal.obj == null)
      {
         var domElement = document.createElement("div");
         domElement.id = "calBox";
         domElement.className = "mini_calendar_widget mts_widget"
         document.body.appendChild(domElement);

         _cal.obj = document.getElementById("calBox");
         if (_cal.obj == null)
            return;
      }

      _MTS_JQUERY(window).resize(function ()
      {
         _cal.centerMiniCal();
      });

      if (_MTS_widgetsReady)
         _MTS_miniCalenderWidgetInit();
      else
         _MTS_JQUERY(document).one("widgetsloaded", _MTS_miniCalenderWidgetInit);
   },

   clearRecycle: function ()
   {
      _cal.monthRecycle = [];
      _cal.dayRecycle = [];
      _cal.yearRecycle = [];
   },

   setContract: function (yyyy, mm, dd)
   {
      var curYear = (new Date()).getFullYear();

      if (yyyy > curYear)
      {
         _cal.startContractYear = curYear;
         _cal.startContractDay = 0;
         _cal.startContractMonth = 0;
      }
      else
      {
         _cal.startContractDay = dd;
         _cal.startContractMonth = mm;
         _cal.startContractYear = yyyy;
      }
   },

   setSelection: function (mm, dd, yyyy)
   {
      _cal.month = parseInt(mm, 10);
      _cal.day = parseInt(dd, 10);
      _cal.year = parseInt(yyyy, 10);

      _cal.viewMonth = parseInt(mm, 10);
      _cal.viewYear = parseInt(yyyy, 10);
   },

   setRange: function (startDate, endDate)
   {
      _cal.rangeStartDate = startDate;
      _cal.rangeEndDate = endDate;

      _cal.rangeStartDateSet = true;
      _cal.rangeEndDateSet = true;

      for (var d = new Date(_cal.rangeStartDate); d <= _cal.rangeEndDate; d.setDate(d.getDate() + 1))
      {
         _cal.addDate(d);
      }
   },

   setCallback: function (fnc)
   {
      _cal.callbackFunc = fnc;
   },

   setCloseCallback: function (fnc)
   {
      _cal.closeCallbackFunc = fnc;
   },

   isLeap: function (yy)
   {
      if (yy % 4 == 0)
      {
         if (yy % 100 == 0)
            return (yy % 400 == 0);

         return true;
      }


      return false;
   },

   fireCallback: function ()
   {
      _cal.callbackFunc(_cal.month, _cal.day, _cal.year);
   },

   fireCallbackRecycle: function ()
   {
      _cal.callbackFunc(_cal.monthRecycle, _cal.dayRecycle, _cal.yearRecycle);
      _cal.hide();
      _cal.clearRecycle();
   },

   fireCallbackRange: function ()
   {
      if (!_cal.rangeStartDateSet && !_cal.rangeEndDateSet)
      {
         _MTS_JQUERY(".noSelection").html("Select a date or range first");

         return;
      }

      _cal.callbackFunc(_cal.rangeStartDate, _cal.rangeEndDate);
      _cal.hide();
   },

   fireCloseCallback: function ()
   {
      if (typeof(_cal.closeCallbackFunc) === "function")
         _cal.closeCallbackFunc();
   },

   selDay: function (dd)
   {
      _cal.month = _cal.viewMonth;
      _cal.day = parseInt(dd, 10);
      _cal.year = _cal.viewYear;
      _cal.fireCallback();
      _cal.hide();
   },

   selWeek: function (/*bool*/firstCall, /*int*/dd)
   {
      _cal.clearRecycle();
      var date = new Date(_cal.viewYear, _cal.viewMonth - 1, dd);
      _cal.addDay(date.getDate());
      var firstDayOfWeek = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      var lastDayOfWeek = new Date(date.getFullYear(), date.getMonth(), date.getDate());

      while (firstDayOfWeek.getDay() != 0)
      {
         firstDayOfWeek.setDate(firstDayOfWeek.getDate() - 1);
         if (_cal.viewMonth != firstDayOfWeek.getMonth() + 1)
            _cal.viewMonth = firstDayOfWeek.getMonth() + 1;

         if (_cal.viewYear != firstDayOfWeek.getFullYear())
            _cal.viewYear = firstDayOfWeek.getFullYear();

         _cal.addDay(firstDayOfWeek.getDate());
      }
      _cal.viewMonth = date.getMonth() + 1;
      _cal.viewYear = date.getFullYear();
      while (lastDayOfWeek.getDay() != 6)
      {
         lastDayOfWeek.setDate(lastDayOfWeek.getDate() + 1);
         if (_cal.viewMonth != lastDayOfWeek.getMonth() + 1)
            _cal.viewMonth = lastDayOfWeek.getMonth() + 1;

         if (_cal.viewYear != lastDayOfWeek.getFullYear())
            _cal.viewYear = lastDayOfWeek.getFullYear();

         _cal.addDay(lastDayOfWeek.getDate());
      }
      _cal.viewMonth = date.getMonth() + 1;
      _cal.viewYear = date.getFullYear();

      if (!firstCall)
      {
         _cal.fireCallbackRecycle();
         _cal.hide();
      }
   },

   selRange: function (dd)
   {
      var len = _cal.dayRecycle.length;
      while (len--)
      {
         _cal.addDate(new Date(_cal.yearRecycle[len], _cal.monthRecycle[len] - 1, _cal.dayRecycle[len]));
      }

      var date = new Date(_cal.viewYear, _cal.viewMonth - 1, dd);

      if ((!_cal.rangeStartDateSet && !_cal.rangeEndDateSet) || (_cal.rangeStartDateSet && _cal.rangeEndDateSet) || date < _cal.rangeStartDate)
      {
         _cal.rangeStartDate = date;
         _cal.rangeEndDate = date;

         _cal.rangeStartDateSet = true;
         _cal.rangeEndDateSet = false;
      }
      else if (_cal.rangeStartDateSet && !_cal.rangeEndDateSet)
      {
         _cal.rangeEndDate = date;

         _cal.rangeEndDateSet = true;
      }

      if (_cal.rangeStartDate != null && _cal.rangeEndDate != null)
      {
         for (var d = new Date(_cal.rangeStartDate); d <= _cal.rangeEndDate; d.setDate(d.getDate() + 1))
         {
            _cal.addDate(d);
         }
      }
   },

   selRangeEnd: function (dd)
   {
      var len = _cal.dayRecycle.length;
      while (len--)
      {
         _cal.addDate(new Date(_cal.yearRecycle[len], _cal.monthRecycle[len] - 1, _cal.dayRecycle[len]));
      }

      var date = new Date(_cal.viewYear, _cal.viewMonth - 1, dd);

      _cal.rangeEndDate = date;
      _cal.rangeEndDateSet = true;

      if (_cal.rangeStartDate != null && _cal.rangeEndDate != null)
      {
         for (var d = new Date(_cal.rangeStartDate); d <= _cal.rangeEndDate; d.setDate(d.getDate() + 1))
         {
            _cal.addDate(d);
         }
      }
   },

   addDay: function (dd)
   {
      var day = parseInt(dd, 10);
      var dayIndex = _cal.inDayArray(day.toString());

      if (dayIndex < 0)
      {
         _cal.monthRecycle.push(_cal.viewMonth.toString());
         _cal.dayRecycle.push(day.toString());
         _cal.yearRecycle.push(_cal.viewYear.toString());
         _MTS_JQUERY("#" + _cal.viewMonth + "_" + _cal.viewYear + "_" + day).parent().removeClass("off").addClass("on");
      } else
      {
         _cal.monthRecycle.splice(dayIndex, 1);
         _cal.yearRecycle.splice(dayIndex, 1);
         _cal.dayRecycle.splice(dayIndex, 1);
         _MTS_JQUERY("#" + _cal.viewMonth + "_" + _cal.viewYear + "_" + day).parent().removeClass("on").addClass("off");
      }
   },

   addDate: function (date)
   {
      var dayIndex = _cal.dateInArrays(date);

      if (dayIndex < 0)
      {
         _cal.monthRecycle.push((date.getMonth() + 1).toString());
         _cal.dayRecycle.push(date.getDate().toString());
         _cal.yearRecycle.push(date.getFullYear().toString());
         _MTS_JQUERY("#" + (date.getMonth() + 1) + "_" + date.getFullYear() + "_" + date.getDate()).parent().removeClass("off").addClass("on");
      } else
      {
         _cal.monthRecycle.splice(dayIndex, 1);
         _cal.yearRecycle.splice(dayIndex, 1);
         _cal.dayRecycle.splice(dayIndex, 1);
         _MTS_JQUERY("#" + (date.getMonth() + 1) + "_" + date.getFullYear() + "_" + date.getDate()).parent().removeClass("on").addClass("off");
      }
   },

   fillDays: function (day)
   {
      if (day != "")
      {
         for (var i = 0; i < day.split(',').length; i++)
         {
            _cal.dayRecycle.push(_MTS_JQUERY.trim(day.split(',')[i].split('/')[1]));
            _cal.monthRecycle.push(_MTS_JQUERY.trim(day.split(',')[i].split('/')[0]));
            _cal.yearRecycle.push(_MTS_JQUERY.trim(day.split(',')[i].split('/')[2]));
         }
      }
   },

   inDayArray: function (day)
   {
      for (var i = 0; i < _cal.dayRecycle.length; i++)
      {
         if (_cal.dayRecycle[i] == day && _cal.monthRecycle[i] == _cal.viewMonth && _cal.yearRecycle[i] == _cal.viewYear)
            return i;
      }

      return -1;
   },

   dateInArrays: function (date)
   {
      for (var i = 0; i < _cal.dayRecycle.length; i++)
      {
         if (_cal.dayRecycle[i] == date.getDate() && _cal.monthRecycle[i] == (date.getMonth() + 1) && _cal.yearRecycle[i] == date.getFullYear())
            return i;
      }

      return -1;
   },

   adjYear: function (d)
   {
      _cal.viewYear += parseInt(d, 10);
      if (_cal.viewYear < _cal.startContractYear)
         _cal.viewYear = _cal.startContractYear;
      else if (_cal.viewYear > _cal.maxYear)
         _cal.viewYear = _cal.maxYear;

      _cal.render();
   },

   setYear: function (e)
   {
      _cal.viewYear = parseInt(e.value, 10);
      if (_cal.viewYear < _cal.startContractYear)
         _cal.viewYear = _cal.startContractYear;
      else if (_cal.viewYear > _cal.maxYear)
         _cal.viewYear = _cal.maxYear;

      _cal.render();
   },

   adjMonth: function (d)
   {
      var m = _cal.viewMonth + parseInt(d, 10);
      var y = _cal.viewYear;
      if (m > 12)
      {
         m = 1;
         y++;
      } else if (m < 1)
      {
         m = 12;
         y--;
      }

      _cal.viewMonth = m;
      _cal.viewYear = y;
      _cal.render();
   },

   setMonth: function (e)
   {
      _cal.viewMonth = parseInt(e.value, 10);
      _cal.render();
   },

   getMonthName: function (m)
   {
      return this.monthNames[m];
   },

   getDayOfWeekName: function (nrDayOfWeek)
   {
      var dayOfWeek = "";

      switch (nrDayOfWeek)
      {
         case 0:
            dayOfWeek = "Sunday";
            break;
         case 1:
            dayOfWeek = "Monday";
            break;
         case 2:
            dayOfWeek = "Tuesday";
            break;
         case 3:
            dayOfWeek = "Wednesday";
            break;
         case 4:
            dayOfWeek = "Thursday";
            break;
         case 5:
            dayOfWeek = "Friday";
            break;
         case 6:
            dayOfWeek = "Saturday";
            break;
         default:
            break;
      }

      return dayOfWeek;
   },

   calculateDayOfWeek: function (m, d, y)
   {
      var Yx = Math.floor(y / 100);
      var xY = y - (Yx * 100);

      var C = 0;
      switch ((Yx - 15) % 4)
      {
         case 0:
            C = 3; break;
         case 1:
            C = 2; break;
         case 2:
            C = 0; break;
         case 3:
            C = 5; break;
         default: break;
      };

      var P = Math.floor((y - 2000) / 12);
      var Q = (y - 2000) % 12;
      var R = Math.floor(Q / 4);
      var D = (P + Q + R + C) % 7;

      if (_cal.isLeap(y))
         _cal.doom_codes = new Array(0, 4, 1, 0, 4, 9, 6, 11, 8, 5, 10, 7, 12);
      else
         _cal.doom_codes = new Array(0, 3, 0, 0, 4, 9, 6, 11, 8, 5, 10, 7, 12);

      return ((d - _cal.doom_codes[m] + D + 14) % 7);
   },

   render: function ()
   {
      if (_cal.viewYear < _cal.startContractYear)
         _cal.viewYear = _cal.startContractYear;
      else if (_cal.viewYear > _cal.maxYear)
         _cal.viewYear = _cal.maxYear;

      if (_cal.viewYear == _cal.startContractYear && _cal.viewMonth < _cal.startContractMonth)
         _cal.viewMonth = _cal.startContractMonth;

      var ds = 1;
      var de = _cal.monthCount[_cal.viewMonth];
      if (_cal.isLeap(_cal.viewYear) && _cal.viewMonth == 2)
         de = 29;

      var cc = 0;
      var rc = 0;

      //var sy = _cal.minYear;
      var sy = _cal.startContractYear;
      var ey = _cal.maxYear;

      var dw = _cal.calculateDayOfWeek(_cal.viewMonth, 1, _cal.viewYear);

      var html = "<div class='listing group rounded'>";
      html += "<div class='miniCalHeading'><a title='Close Mini-Cal' class='closeMiniCal' class='closeMiniCal' href='javascript:_cal.close();'></a>" + _cal.wndTitle + "</div>";
      html += "<a title='Previous' class='prevArrows' href='javascript:_cal.adjYear(-1);'></a>";
      html += "<div class='selectDate'><select id='calyear' onchange='_cal.setYear(this);'>";
      for (var i = sy; i <= ey; i++)
      {
         html += "<option value='" + i + "'";
         if (i == _cal.viewYear)
            html += " selected";
         html += ">" + i + "</option>";
      }

      html += "</select></div></td><td colspan='1'><a title='Next' class='NxtArrows' href='javascript:_cal.adjYear(1);'></a></td></tr>";
      html += "<a title='Previous' class='prevArrows' href='javascript:_cal.adjMonth(-1);'></a>";
      html += "<div class='selectMonth'><select id='calmonth' onchange='_cal.setMonth(this);'>";
      for (var i = 1; i < 13; i++)
      {
         html += "<option value='" + i + "'";
         if (i == _cal.viewMonth)
            html += " selected";
         html += ">" + _cal.monthNames[i] + "</option>";
      }

      html += "</select></div><a title='Next' class='NxtArrows' href='javascript:_cal.adjMonth(1);'></a>";
      html += "<div class='calDays'><div class='dayTxt'>S</div><div class='dayTxt'>M</div><div class='dayTxt'>T</div><div class='dayTxt'>W</div><div class='dayTxt'>T</div><div class='dayTxt'>F</div><div class='dayTxt'>S</div>";
      do
      {
         if (ds == 1)
         {
            html += "<div class='cent'>";
            while (cc < dw)
            {
               html += "<div class='off'><div class='dateLink'>&nbsp;</div></div>";
               cc++;
            }
         }

         if (this.startContractMonth == _cal.viewMonth && this.startContractYear == _cal.viewYear && ds <= this.startContractDay)
         {
            html += "<div class='" + (ds == _cal.day && this.mode == "select" ? "on" : "off") + "'>" + ds + "</div>";
         }
         else if (this.mode == "select")
         {
            html += "<a title='Date Link' href='javascript:_cal.selDay(" + ds + ");' class='" + (((_cal.viewMonth == this.month && _cal.viewYear == this.year && ds == _cal.day) || _cal.inDayArray(ds) > -1) ? "on" : "off") + "'><div class='dateLink'>" + ds + "</div></a>";
         }
         else if (this.mode == "range")
         {
            html += "<a title='Cal Date Range Start' href='javascript:_cal.selRange(" + ds + ");' class='" + ((_cal.inDayArray(ds) > -1) ? "on" : "off") + "'><div class='dateLink' id='" + _cal.viewMonth + "_" + _cal.viewYear + "_" + ds + "'>" + ds + "</div></a>";
         }
         else if (this.mode == "rangeEnd")
         {
            html += "<a title='Cal Date Range End' href='javascript:_cal.selRangeEnd(" + ds + ");' class='" + ((_cal.inDayArray(ds) > -1) ? "on" : "off") + "'><div class='dateLink' id='" + _cal.viewMonth + "_" + _cal.viewYear + "_" + ds + "'>" + ds + "</div></a>";
         }
         else
         {
            html += "<a title='Date Link' href='" + (_cal.mode == "week" ? "javascript:_cal.selWeek(false, " : "javascript:_cal.addDay(") + ds + ");' class='" + (_cal.inDayArray(ds) > -1 ? "on" : "off") + "'><div class='dateLink' id='" + _cal.viewMonth + "_" + _cal.viewYear + "_" + ds + "'>" + ds + "</div></a>";
         }

         ds++;
         cc++;
         if (cc > 6)
         {
            html += "</div><div class='cent'>";
            cc = 0;
            rc++;
         }

      } while (ds <= de);

      while (cc < 7 && rc <= 5)
      {
         html += "<div class='off'><div class='dateLink'>&nbsp;</div></div>";
         cc++;

         if (cc == 7 && rc < 5)
         {
            cc = 0;
            rc++;
            html += "</div><div class='cent'>";
         }
      }

      html += _cal.mode == "select" ? "" : _cal.mode == "week" ? "" : "<div class='miniCalBtnRow'><div onclick='javascript:" + (_cal.mode == "range" || _cal.mode == "rangeEnd" ? "_cal.fireCallbackRange();" : "_cal.fireCallbackRecycle();") + "' class='buttonMiniCal'>" + (_cal.mode == "range" || _cal.mode == "rangeEnd" ? "Select" : "Create") + "</div>";
      html += _cal.mode == "range" ? "<div class='noSelection'></div>" : "";
      html += "</div>";
      html += "</div>";
      _cal.obj.innerHTML = html;

      if (typeof (ToggleCustomDropDowns) == "function")
      {
         ToggleCustomDropdowns();
         $("#calBox select").chosen({ disable_search: true });
         $("#calBox .chosen-container").css({ "width": "100%" });
      }

      $("#calBox .dateLink").css({ "height": $(".dateLink").outerWidth() + "px" });
      $("#calBox .dateLink").css({ "line-height": $("#calBox .dateLink").outerHeight() + "px" });
      _cal.centerMiniCal();
      _cal.setDateCookie(_cal.viewMonth + "/1/" + _cal.viewYear);
   },

   setDateCookie: function (value)
   {
      if (typeof (createCookie) === "function")
         createCookie("MTS_caldate", value);
   },

   show: function (x, y)
   {
      this.posTop = 0;
      this.posLeft = 0;

      var cookieDate = typeof (readCookie) === "function" ? readCookie("MTS_caldate") : null;
      if (cookieDate != null)
      {
         var datSel = new Date(cookieDate);
         if (!isNaN(datSel))
            _cal.setSelection(datSel.getMonth() + 1, datSel.getDate(), datSel.getFullYear());
      }

      _MTS_JQUERY("#calBox").fadeTo(0, 0);
      _MTS_JQUERY("#calBox").show();
      _cal.render();
      _MTS_JQUERY("#calBox").fadeTo(0, 1);

      if (typeof (ToggleCustomDropDowns) == "function")
      {
         ToggleCustomDropdowns();
         $("#calBox select").chosen({ disable_search: true });
         $("#calBox .chosen-container").css({ "width": "100%" });
      }

      var on = $(".on");
      $("#calBox .dateLink").css({ "height": $(".dateLink").outerWidth() + "px" });
      $("#calBox .dateLink").css({ "line-height": $("#calBox .dateLink").outerHeight() + "px" });
      $(".off").css({ "height": $(".off").outerWidth() + "px" });
      on.css({ "height": on.outerWidth() + "px" });
      $("#calBox .dateLink").css({ "line-height": $("#calBox .dateLink").outerHeight() + "px" });

      $("body").addClass("overflow");
   },

   hide: function ()
   {
      if (_cal.mode == "range")
      {
         _cal.rangeStartDate = null
         _cal.rangeEndDate = null;
         _cal.rangeStartDateSet = false;
         _cal.rangeEndDateSet = false;

         _cal.clearRecycle();
      }

      _cal.obj.style.display = "none";
      _MTS_JQUERY("#calBox").hide();
      //_MTS_JQUERY(".listingBg").hide();
      $("body").removeClass("overflow");
   },

   close: function ()
   {
      _cal.hide();
      _cal.fireCloseCallback();
   },

   centerMiniCal: function ()
   {
      var wh = _MTS_JQUERY(window);
      var ch = _MTS_JQUERY(".listing");

      if (wh.height() > ch.height())
      {
         ch.removeAttr("style");
         ch.css({
            "top": (wh.height() - ch.height()) / 2 + "px",
            "left": (wh.width() - ch.outerWidth()) / 2 + "px"
         });
      } else
      {
         ch.removeAttr("style");
         ch.css({
            "left": (wh.width() - ch.outerWidth()) / 2 + "px"
         });
      }
   },

   GetMiniCalendar: function (/*string*/mode, /*string*/title, /*date*/datSel, /*function*/callback, /*bool*/pastDates, closeCallback)
   {
      var dte = new Date();
      if (isNaN(datSel))
         datSel = dte;

      _cal.clearRecycle();
      _cal.mode = mode;
      _cal.wndTitle = title;
      _cal.setContract(dte.getFullYear() - 50, dte.getMonth() + 1, dte.getDate() - 1);
      _cal.maxYear = _cal.startContractYear + 100;
      _cal.setCallback(callback);
      _cal.setCloseCallback(closeCallback);

      _cal.setSelection(datSel.getMonth() + 1, datSel.getDate(), datSel.getFullYear());
      _cal.show(100, 100);

      var bg = _MTS_JQUERY(_cal.bg);
      bg.css({ "height": _MTS_JQUERY(document).height(), "zIndex": 113 });
      bg.show();
   }
};

function _MTS_miniCalenderWidgetInit()
{
   if (typeof (MTS_CAL_INIT) != "undefined")
   {
      MTS_CAL_INIT();
   }
}
﻿var _MTS_restrictSport = false;
var _MTS_adv = false;
var _MTS_stopSearchOnce = false;
var _MTS_currentSearch = [];
var _MTS_lastSearchType = null;
var _searchContainers = [];

if (typeof (_MTS_SEARCH_TYPE) == "undefined")
   _MTS_SEARCH_TYPE = "tag";

_MTS_JQUERY(document).one("widgetsloaded", function ()
{
   _searchContainers = _MTS_JQUERY(".findTeamFormContainer, .search_widget, #searchPhrase");
});

(function ()
{
   var _teamTab = "news";
   var _once = true;
   var _searching = false;

   _MTS_JQUERY(document).ready(function ()
   {
      _searchContainers = _MTS_JQUERY(".findTeamFormContainer, .search_widget, #searchPhrase");
      _MTS_JQUERY(document).on("click", "#ezAdv", tglAdv);
      _MTS_JQUERY("#ezGo").click(ezTimer);
      _MTS_JQUERY("#selRange").change(function () { MTS_handleEz(0); });
      _MTS_JQUERY("#zip").focus(function () { if (_MTS_JQUERY(this).val() === "Zip Code") { _MTS_JQUERY(this).val(""); } })
            .blur(function () { if (_MTS_JQUERY(this).val() === "") { _MTS_JQUERY(this).val("Zip Code"); } })
      setInterval(ezTimer, 1000);
   });

   function tglAdv()
   {
      _MTS_adv = !_MTS_adv;
      _MTS_JQUERY(".advCol").toggleClass("advOpen");
      if (typeof (_MTS_toggleMobileFilters) === "function")
         _MTS_toggleMobileFilters();
      var rotate = _MTS_JQUERY(".toggleOptions");
      rotate.toggleClass("toggleOptionsRotate");
   }

   function ezTimer()
   {
      var a = ["input[class='mts_search_form']:visible", "input[id='searchPhrase']:visible", "#zip", ".filterColumn:visible", "#start", "#end"];

      for (var i = 0; i < a.length; i++)
      {
         var e = _MTS_JQUERY(a[i]);

         for (var j = 0; j < e.length; j++)
         {
            if (hasChange(_MTS_JQUERY(e[j])))
            {
               var par = _MTS_JQUERY(e[j]).parents(".findTeamFormContainer, .search_widget");
               var target = e[j];
               if (i > 1)
                  target = par.find(a[1]);

               MTS_searchHelper(function ()
               {
                  MTS_handleEz(0, null, target);
               });
            }
         }
      }
   }

   function hasChange(e)
   {
      var v = _MTS_JQUERY.trim(e.val());
      if (e.hasClass("filterColumn"))
      {
         var par = e.parents(".filterRow");
         if (par.data("prev-val") != par.find(".filterDisabled:visible").length)
         {
            par.data("prev-val", par.find(".filterDisabled:visible").length);
            return true;
         }
      }
      else
      {
         if (e.data("prev-val") == null)
            e.data("prev-val", "no search provided");

         if (e.data("prev-val") != v)
         {
            e.data("prev-val", v);
            return true;
         }
      }

      return false;
   }

   function obtainLocation()
   {
      var lat = 0, lng = 0;
      if (navigator.geolocation)
      {
         navigator.geolocation.getCurrentPosition(function (pos)
         {
            lat = pos.coords.latitude;
            lng = pos.coords.longitude;

            var url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&sensor=false';
            _MTS_JQUERY.getJSON(url, function (r)
            {
               var st = false, zp = false;
               if (r.status === "OK")
               {
                  found:
                  for (var j = 0; j < r.results.length; j++)
                  {
                     var res = r.results[j];
                     for (var i = 0; i < res.address_components.length; i++)
                     {
                        var com = res.address_components[i];
                        if (!zp && com.types[0] === "postal_code")
                        {
                           _MTS_JQUERY("#zip").val(com.long_name);
                           break found;
                        }
                     }
                  }
               }
            });
         },
      function (err)
      {
         lat = 0;
         lng = 0;
      });
      }
   }
})();

function MTS_handleEz(start, callback, target)
{
    if (!_searchContainers.index || (target && target.length > 0 && !_MTS_JQUERY(target).is(":visible")))
      return false;

   var reqTeam = typeof (_restrictTeam) != 'undefined' && _restrictTeam && typeof (_teamId) != 'undefined',
      reqSport = _MTS_restrictSport && typeof (_sportId) != 'undefined';

   var showDel = typeof (_showDel) != 'undefined' && _showDel;
   var showFut = typeof (_showFut) != 'undefined' && _showFut;

   var phr = _MTS_JQUERY(target ? target : "input[id='searchPhrase']:visible").val() + ((typeof (_defSearchParam) != 'undefined') ? " " + _defSearchParam : "");
   if (phr === "undefined" || (phr.length === 0 && window.location.pathname === "/"))
      return;

   var p = [];
   p.push({ name: "phrase", value: phr });
   p.push({ name: "ac", value: 0 });
   p.push({ name: "gz", value: "t" });
   p.push({ name: "s", value: "" + start });
   p.push({ name: "rt", value: reqTeam ? _teamId : -1 });
   p.push({ name: "sport", value: reqSport ? _sportId : -1 });
   p.push({ name: "incHid", value: showDel ? "t" : "f" });
   p.push({ name: "incFut", value: showFut ? "t" : "f" });
   p.push({ name: "responseType", value: typeof (_responseType) != "undefined" ? _responseType : "default" });
   if (typeof (_portalId) === "string")
      p.push({ name: "portalId", value: _portalId });

   var search = _MTS_JQUERY(".itemLoader:visible");
   if (search.length > 0)
      search.show();

   var par = target ? _MTS_JQUERY(target).parents(".findTeamFormContainer, .search_widget") : _MTS_JQUERY(".search_widget");
   var parIdx = _searchContainers.index(par[0]);
   var filters = par ? par.find(".filterColumn") : _MTS_JQUERY(".filterColumn:visible");
   if (filters.length > 0)
   {
      var types = [];
      for (var i = filters.length - 1; i >= 0; i--)
      {
         if (_MTS_JQUERY(filters[i]).attr("class").indexOf("filterDisabled") == -1 && _MTS_JQUERY(filters[i]).css("display") !== "none")
         {
            var type = filters[i].id.split("Filter")[0];
            if (type == "recentData")
               p.push({ name: "recentData", value: true });
            else if (type == "frequent")
               p.push({ name: "frequent", value: true });
            else
               types.push(type);
         }
      }

      if (types.length > 0)
         p.push({ name: "types", value: types });
   }
   p.push({ name: "parIdx", value: parIdx });

   var direction = _MTS_JQUERY(".direction");
   if (_MTS_adv)
   {
      p.push({ name: "adv", value: "1" });
      p.push({ name: "zip", value: _MTS_JQUERY("#zip").val() });
      p.push({ name: "dst", value: _MTS_JQUERY("#selRange").val() });
      p.push({ name: "start", value: _MTS_JQUERY("#start").val() });
      p.push({ name: "end", value: _MTS_JQUERY("#end").val() });
      p.push({ name: "sort", value: _MTS_JQUERY("#sort").val() });
		p.push({ name: "dir", value: _MTS_JQUERY(".direction").hasClass("rotateDir") });
   }

   if (typeof(_MTS_SORT_TYPE) !== "undefined")
   {
      p.push({ name: "sort", value: _MTS_SORT_TYPE });
   }

   var dirSet = typeof (_MTS_SORT_DIR) !== "undefined";
   if (!_MTS_adv)
   {
      if (dirSet)
      {
         p.push({ name: "dir", value: dirSet ? _MTS_SORT_DIR : "false" });
      }
      else if (direction.length > 0)
      {
         p.push({ name: "sort", value: _MTS_JQUERY("#sort").val() });
         p.push({ name: "dir", value: _MTS_JQUERY(".direction").hasClass("rotateDir") });
      }
   }

   if (_MTS_stopSearchOnce)
   {
      _MTS_stopSearchOnce = false; // used for scheduleAdministrator.js
      return false;
   }

   if (typeof (_selectedTeamId) != 'undefined')
      _selectedTeamId = -1;

   // Used to track while api call is inputting data to prevent data submission on team organizer
   _searching = true;
   _MTS_ajaxPending = true;

   // prevent multiple json calls from being created
   if (_MTS_currentSearch[parIdx])
      _MTS_currentSearch[parIdx].abort();

   var parent = null;
   for (var i = 0; i < p.length; i++)
   {
      if (p[i].name != "parIdx")
         continue;
      parent = _searchContainers.eq(p[i].value);
   }

   var results = parent && parent.length > 0 ? parent.find("div[id='results']") : _MTS_JQUERY("div[id='results']:visible");
   if (results.length === 0)
      results = _MTS_JQUERY("div[id='results']:visible");

   results.children().remove();

   _MTS_currentSearch[parIdx] = _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/search.aspx", p, function (o)
   {
      if (o.ok)
      {
         var pStr = "div[id='paging_top']:visible, div[id='paging_btm']:visible";
         var pg = parent && parent.length > 0 ? parent.find(pStr) : _MTS_JQUERY(pStr);
         pg.children().remove();

         var hasSearchTags = o.searchTagResults.length > 0, a = hasSearchTags ? o.searchTagResults : o.results, l = a.length, t = {}, logo = "";
         if (l == 0)
         {
            results.append(_MTS_JQUERY("<div class='noMatch'>No matching results were found." +
               (reqTeam ? " Click <span id='addTeam' class='link mts_cc_text'>here</span> to add it." : "") + "</div>"));
         }
         else
         {
            var exactMatchFound = false, searching = _MTS_JQUERY.trim(_MTS_JQUERY(target ? target : "input[id='searchPhrase']:visible").val());
            for (var i = 0; i < l; i++)
            {
               t = a[i];
               if (!hasSearchTags)
               {
                  var x = _MTS_JQUERY(MTS_composeTeamItem(t, o, parent))
                  var leagueVal = x.find(".leagueValue"), schoolVal = x.find(".schoolValue"), genderVal = x.find(".genderValue");
                  var league = leagueVal.length > 0 ? leagueVal.find("option[value=" + t.leagueId + "]") : "",
                     school = schoolVal.length > 0 ? schoolVal.find("option[value=" + t.schoolId + "]") : "",
                     gender = genderVal.length > 0 ? genderVal.find("input[value=" + t.gender.replace("'", "\\'") + "]") : "",
                     deleted = x.find(".delete"),
                     hidden = x.find(".deactivate");

                  if (league.length > 0)
                     league.prop("selected", true);
                  if (school.length > 0)
                     school.prop("selected", true);
                  if (gender.length > 0)
                     gender.prop("checked", true);
                  if (deleted.length > 0)
                     deleted.html(t.deleted == "True" ? "Undelete" : "Delete");
                  if (hidden.length > 0)
                     hidden.html(t.hidden == "True" ? "Activate" : "Deactivate");

                  results.append(x);
               }
               else
               {
                  switch (t.type)
                  {
                     default:
                     case "Roster":
                     case "PortalVideo":
                     case "PortalEvent":
                     case "Image":
                     case "User":
                     case "NewsItem":
                     case "Audio":
                        results.append(_MTS_JQUERY(MTS_composeSearchTagItem(t, o, results, parent)));
                        break;
                     case "Team":
                        for (var j = o.results.length - 1; j >= 0; j--)
                        {
                           if (o.results[j].id == t.id)
                           {
                              results.append(_MTS_JQUERY(MTS_composeTeamItem(o.results[j], o, parent)));
                              break;
                           }
                        }
                        break;
                  }
               }

               var searchType = parent && parent.length > 0 && parent.find("input[name='searchType']").length > 0 ? parent.find("input[name='searchType']").val() : _MTS_SEARCH_TYPE;
               if (searching.length == 0 || decodeURIComponent(t.name).toLowerCase() == searching.toLowerCase() || typeof (searchType) != "undefined")
               {
                  exactMatchFound = true;
               }
            }

            if (!exactMatchFound)
            {
               results.append(_MTS_JQUERY("<div class='noMatch'>No exact match found." +
                  (reqTeam ? " Click <span id='addTeam' class='link mts_cc_text'>here</span> to add it." : "") + "</div>"));
            }

            var sp = ((o.start / o.count) | 0);
            var ep = ((o.total / o.count) | 0);
            if (ep > 0 && o.total % 25 == 0)
               ep--;

            var si = Math.max(sp - 2, 0);
            var ei = Math.min(sp + (5 - (sp - si)), ep);

            pg.append(new MTS_pageItem("First", sp > 0, 0, false, parent));
            pg.append(new MTS_pageItem("Prev", sp > 0, sp - 1, false, parent));
            for (var i = si; i <= ei; i++)
            {
               var _MTS_JQUERY1 = i;
               pg.append(new MTS_pageItem("" + (i + 1), true, _MTS_JQUERY1, _MTS_JQUERY1 == start, parent));
            }
            pg.append(new MTS_pageItem("Next", sp < ep, sp + 1, false, parent));
            pg.append(new MTS_pageItem("Last", sp < ep, ep, false, parent));
         }

         if (typeof (_searchEventFired) == 'function')
            _searchEventFired();

         if (typeof callback === 'function')
            callback();

         if (typeof (_MTS_JQUERY().dotdotdot) == "function")
            _MTS_JQUERY(".name:visible").dotdotdot();
      }

      if (parent)
         parent.find("#elaps").html(o.elapsed)
      else
         _MTS_JQUERY("#elaps").html(o.elapsed);

      if (typeof (SetTeamLogoHeightFromWidth) == "function")
         SetTeamLogoHeightFromWidth("div[id='results']:visible .logoContainer");

      _searching = false;
      if (search.length > 0)
         search.hide();

      var searchCallback = parent && parent.length > 0 && parent.find("input[name='searchCallback']").length > 0 ? parent.find("input[name='searchCallback']").val() : "";
      if (typeof eval(searchCallback) !== 'undefined')
         eval(searchCallback)();
      else if (typeof (_MTS_searchCallback) == "function")
         _MTS_searchCallback();
   });
}

function MTS_composeTeamItem(t, o, p)
{
   var s = MTS_getTemplate(p);
   s = s.replace(/%%TEAM_NAME%%/g, decodeURIComponent(t.name));
   if (t.logo)
   {
      var teamLogo = o.mediaUrl.replace("%%TEAM_ID%%", t.id), lastSlash = teamLogo.lastIndexOf("/");
      teamLogo = teamLogo.substring(0, lastSlash) + "/fTeam" + teamLogo.substring(lastSlash);
      logo = "<img alt='Team Logo' class='logo' src='" + teamLogo + "' />";
   }
   else
   {
      logo = "<img alt='Team Logo' class='logo' src='" + _MTS_MEDIAURL + "images/sports/" + t.sportThumb + "L.jpg' />";
   }

   var link = "team/" + o.teamDefaultTab + "/" + t.id + "/" + t.urlName + "/";
   var searchType = p && p.length > 0 && p.find("input[name='searchType']").length > 0 ? p.find("input[name='searchType']").val() : _MTS_SEARCH_TYPE;

   s = s.replace(/%%TEAM_LOGO%%/g, logo);
   s = s.replace(/%%TEAM_LOCALE%%/g, t.city.length > 0 ? t.city : "");
   s = s.replace(/%%TEAM_GENDER%%/g, t.gender + ' ' + t.level + ' ' + t.sport);
   s = s.replace(/%%TEAM_LINK%%/g, MTS_getLinkFromSearchType(link, t.name + " " + t.gender + " " + t.sport, t.id, "Team"));
   s = s.replace(/%%TEAM_ID%%/g, t.id);
   s = s.replace(/%%FAN_BTN%%/g, typeof (searchType) === "undefined" || searchType.toLowerCase() === "tag" ? "" : (t.isFan == "true" ? "<img class='iamFan' src='" + _MTS_MEDIAURL + "images/iAmFan.png' alt='Fan Of Team' />" : "<div id='fan_" + t.id + "' class='mts_cc_button becomeFanBox'> Be A Fan </div>"));
   s = s.replace(/%%TEAM_URLNAME%%/g, t.urlName);
   s = s.replace(/%%SEARCH_TYPE%%/g, "TeamIcon");
   s = s.replace(/%%SEARCH_DATE%%/g, "");
   s = s.replace(/%%TEAM_CODE%%/g, t.scoreKeeperCode);
   s = MTS_getFormatByType(s, "Team", true);
   return s;
}

function MTS_composeSearchTagItem(t, o, r, p)
{
   var s = MTS_getTemplate(p), hasLogo = t.logo.length > 0;
   var link = t.link;
   if (typeof _MTS_ReplaceImgLink !== 'undefined' && _MTS_ReplaceImgLink && t.type == "Image")
      link = t.logo;
   var titleWithParent = t.title;
   if (t.parenttitle != "")
      titleWithParent = "(" + t.parenttitle + ") " + t.title;

   s = s.replace(/%%TEAM_NAME%%/g, titleWithParent.replace(/"/g, "&quot;"));
   s = s.replace(/%%TEAM_LOGO%%/g, hasLogo ? "<img alt='Team Logo' class='logo' src='" + t.logo + "' />" : "");
   s = s.replace(/%%TEAM_LOCALE%%/g, "");
   s = s.replace(/%%TEAM_GENDER%%/g, "");
   s = s.replace(/%%TEAM_LINK%%/g, MTS_getLinkFromSearchType(link, t.parenttitle != "" && t.type == "Image" ? t.parenttitle : titleWithParent, t.id, t.type, r));
   s = s.replace(/%%TEAM_ID%%/g, t.id);
   s = s.replace(/%%FAN_BTN%%/g, "");
   s = s.replace(/%%TEAM_URLNAME%%/g, "");
   s = s.replace(/%%SEARCH_TYPE%%/g, t.type + "Icon");
   s = s.replace(/%%SEARCH_DATE%%/g, t.date);
   s = MTS_getFormatByType(s, t.type, hasLogo);
   return s;
}

function MTS_getTemplate(p)
{
   if (p && p.length > 0 && p.find(".rTemplate").length > 0)
      return p.find(".rTemplate").html();
   if (_MTS_JQUERY("#rTemplate").length > 0)
      return _MTS_JQUERY("#rTemplate").html();

   return "";
}

function MTS_getLinkFromSearchType(link, title, id, type, r)
{
   var parent = typeof r !== 'undefined' && r.parents(".search_widget").length > 0 ? r.parents(".search_widget") : null;
   var searchType = parent && parent.length > 0 && parent.find("input[name='searchType']").length > 0 ? parent.find("input[name='searchType']").val() : _MTS_SEARCH_TYPE;

   if (typeof (searchType) != "undefined")
   {
      var selTagFnc = null;
      var selCallStr = parent && parent.length > 0 && parent.find("input[name='selectCallback']").length > 0 ? parent.find("input[name='selectCallback']").val(): "";
      if (typeof eval(selCallStr) !== 'undefined')
         selTagFnc = eval(selCallStr);
      else if (typeof _MTS_selectTagOverride == "function")
         selTagFnc = _MTS_selectTagOverride
      else if (typeof selectTag == "function")
         selTagFnc = selectTag;

      var selTagFncName = selTagFnc == null ? "void" : (typeof selTagFnc.name !== "undefined" ? selTagFnc.name : selTagFnc.toString().replace(/(\/\*.*?\*\/)/g, "").match(/^function\s*([^\s(]+)/)[1]);
      switch (searchType.toLowerCase())
      {
         default:
         case "search":
            return _MTS_SITEURL +link;
         case "layout":
            var newTitle;
            switch (type.toLowerCase())
            {
               default:
                  newTitle = id;
                  break;
               case "sport":
               case "video":
               case "user":
                  newTitle = id;
                  break;
            }

            return "javascript:" + selTagFncName + "('" + escape(newTitle.replace(/'/g, "\\'")) + "')";
         case "tag":
            return "javascript:" + selTagFncName + "('" + (link.indexOf("://") < 0 ? "/" : "") + link + "','" + escape(title.replace(/'/g, "\\'").replace(/(?!^<(\/|)(\w+)>)(?:\r\n|\r|\n)(?!<(\/|)(\w+)>)/g, '')) + "'," + id + ",'" + type + "')";
      }
   }
   else
      return _MTS_SITEURL +link;
}

function MTS_getFormatByType(s, type, hasLogo)
{
   switch (type)
   {
      default:
      case "Team":
         s = s.replace(/%%LINK_CLASS%%/g, "fullLink");
         s = s.replace(/%%LOGO_CLASS%%/g, "logoContainer");
         s = s.replace(/%%INFO_CLASS%%/g, "info");
         break;
      case "Roster":
      case "Audio":
      case "Image":
      case "PortalVideo":
      case "User":
      case "NewsItem":
      case "PortalEvent":
         if (!hasLogo)
         {
            s = s.replace(/%%INFO_CLASS%%/g, "fullInfo info");
            s = s.replace(/%%LOGO_CLASS%%/g, "noLogo logoContainer");
         }
         else
         {
            s = s.replace(/%%INFO_CLASS%%/g, "info");
            s = s.replace(/%%LOGO_CLASS%%/g, "logoContainer");
      }

         s = s.replace(/%%LINK_CLASS%%/g, "fullLink");
         break;
   }

   return s;
}

function MTS_pageItem(txt, cond, fnc, sel, parent)
{
   var pi = _MTS_JQUERY("<div>" + txt + "</div>");
   pi.attr("class", "page" + (sel ? "Active" : (cond ? "Click" : "Disabled")))
   .click(function () { if (cond) { MTS_handleEz(fnc, null, parent.length > 0 ? parent.find(".mts_search_form, #searchPhrase") : _MTS_JQUERY("#searchPhrase:visible")); } });
   return pi;
}

﻿/*
 *	jQuery dotdotdot 1.7.4
 *
 *	Copyright (c) Fred Heusschen
 *	www.frebsite.nl
 *
 *	Plugin website:
 *	dotdotdot.frebsite.nl
 *
 *	Licensed under the MIT license.
 *	http://en.wikipedia.org/wiki/MIT_License
 */
!function (t, e) { function n(t, e, n) { var r = t.children(), o = !1; t.empty(); for (var i = 0, d = r.length; d > i; i++) { var l = r.eq(i); if (t.append(l), n && t.append(n), a(t, e)) { l.remove(), o = !0; break } n && n.detach() } return o } function r(e, n, i, d, l) { var s = !1, c = "a, table, thead, tbody, tfoot, tr, col, colgroup, object, embed, param, ol, ul, dl, blockquote, select, optgroup, option, textarea, script, style", u = "script, .dotdotdot-keep"; return e.contents().detach().each(function () { var h = this, f = t(h); if ("undefined" == typeof h) return !0; if (f.is(u)) e.append(f); else { if (s) return !0; e.append(f), !l || f.is(d.after) || f.find(d.after).length || e[e.is(c) ? "after" : "append"](l), a(i, d) && (s = 3 == h.nodeType ? o(f, n, i, d, l) : r(f, n, i, d, l), s || (f.detach(), s = !0)), s || l && l.detach() } }), n.addClass("is-truncated"), s } function o(e, n, r, o, d) { var c = e[0]; if (!c) return !1; var h = s(c), f = -1 !== h.indexOf(" ") ? " " : "　", p = "letter" == o.wrap ? "" : f, g = h.split(p), v = -1, w = -1, b = 0, y = g.length - 1; for (o.fallbackToLetter && 0 == b && 0 == y && (p = "", g = h.split(p), y = g.length - 1) ; y >= b && (0 != b || 0 != y) ;) { var m = Math.floor((b + y) / 2); if (m == w) break; w = m, l(c, g.slice(0, w + 1).join(p) + o.ellipsis), r.children().each(function () { t(this).toggle().toggle() }), a(r, o) ? (y = w, o.fallbackToLetter && 0 == b && 0 == y && (p = "", g = g[0].split(p), v = -1, w = -1, b = 0, y = g.length - 1)) : (v = w, b = w) } if (-1 == v || 1 == g.length && 0 == g[0].length) { var x = e.parent(); e.detach(); var T = d && d.closest(x).length ? d.length : 0; x.contents().length > T ? c = u(x.contents().eq(-1 - T), n) : (c = u(x, n, !0), T || x.detach()), c && (h = i(s(c), o), l(c, h), T && d && t(c).parent().append(d)) } else h = i(g.slice(0, v + 1).join(p), o), l(c, h); return !0 } function a(t, e) { return t.innerHeight() > e.maxHeight } function i(e, n) { for (; t.inArray(e.slice(-1), n.lastCharacter.remove) > -1;) e = e.slice(0, -1); return t.inArray(e.slice(-1), n.lastCharacter.noEllipsis) < 0 && (e += n.ellipsis), e } function d(t) { return { width: t.innerWidth(), height: t.innerHeight() } } function l(t, e) { t.innerText ? t.innerText = e : t.nodeValue ? t.nodeValue = e : t.textContent && (t.textContent = e) } function s(t) { return t.innerText ? t.innerText : t.nodeValue ? t.nodeValue : t.textContent ? t.textContent : "" } function c(t) { do t = t.previousSibling; while (t && 1 !== t.nodeType && 3 !== t.nodeType); return t } function u(e, n, r) { var o, a = e && e[0]; if (a) { if (!r) { if (3 === a.nodeType) return a; if (t.trim(e.text())) return u(e.contents().last(), n) } for (o = c(a) ; !o;) { if (e = e.parent(), e.is(n) || !e.length) return !1; o = c(e[0]) } if (o) return u(t(o), n) } return !1 } function h(e, n) { return e ? "string" == typeof e ? (e = t(e, n), e.length ? e : !1) : e.jquery ? e : !1 : !1 } function f(t) { for (var e = t.innerHeight(), n = ["paddingTop", "paddingBottom"], r = 0, o = n.length; o > r; r++) { var a = parseInt(t.css(n[r]), 10); isNaN(a) && (a = 0), e -= a } return e } if (!t.fn.dotdotdot) { t.fn.dotdotdot = function (e) { if (0 == this.length) return t.fn.dotdotdot.debug('No element found for "' + this.selector + '".'), this; if (this.length > 1) return this.each(function () { t(this).dotdotdot(e) }); var o = this; o.data("dotdotdot") && o.trigger("destroy.dot"), o.data("dotdotdot-style", o.attr("style") || ""), o.css("word-wrap", "break-word"), "nowrap" === o.css("white-space") && o.css("white-space", "normal"), o.bind_events = function () { return o.bind("update.dot", function (e, d) { switch (o.removeClass("is-truncated"), e.preventDefault(), e.stopPropagation(), typeof l.height) { case "number": l.maxHeight = l.height; break; case "function": l.maxHeight = l.height.call(o[0]); break; default: l.maxHeight = f(o) } l.maxHeight += l.tolerance, "undefined" != typeof d && (("string" == typeof d || "nodeType" in d && 1 === d.nodeType) && (d = t("<div />").append(d).contents()), d instanceof t && (i = d)), g = o.wrapInner('<div class="dotdotdot" />').children(), g.contents().detach().end().append(i.clone(!0)).find("br").replaceWith("  <br />  ").end().css({ height: "auto", width: "auto", border: "none", padding: 0, margin: 0 }); var c = !1, u = !1; return s.afterElement && (c = s.afterElement.clone(!0), c.show(), s.afterElement.detach()), a(g, l) && (u = "children" == l.wrap ? n(g, l, c) : r(g, o, g, l, c)), g.replaceWith(g.contents()), g = null, t.isFunction(l.callback) && l.callback.call(o[0], u, i), s.isTruncated = u, u }).bind("isTruncated.dot", function (t, e) { return t.preventDefault(), t.stopPropagation(), "function" == typeof e && e.call(o[0], s.isTruncated), s.isTruncated }).bind("originalContent.dot", function (t, e) { return t.preventDefault(), t.stopPropagation(), "function" == typeof e && e.call(o[0], i), i }).bind("destroy.dot", function (t) { t.preventDefault(), t.stopPropagation(), o.unwatch().unbind_events().contents().detach().end().append(i).attr("style", o.data("dotdotdot-style") || "").data("dotdotdot", !1) }), o }, o.unbind_events = function () { return o.unbind(".dot"), o }, o.watch = function () { if (o.unwatch(), "window" == l.watch) { var e = t(window), n = e.width(), r = e.height(); e.bind("resize.dot" + s.dotId, function () { n == e.width() && r == e.height() && l.windowResizeFix || (n = e.width(), r = e.height(), u && clearInterval(u), u = setTimeout(function () { o.trigger("update.dot") }, 100)) }) } else c = d(o), u = setInterval(function () { if (o.is(":visible")) { var t = d(o); (c.width != t.width || c.height != t.height) && (o.trigger("update.dot"), c = t) } }, 500); return o }, o.unwatch = function () { return t(window).unbind("resize.dot" + s.dotId), u && clearInterval(u), o }; var i = o.contents(), l = t.extend(!0, {}, t.fn.dotdotdot.defaults, e), s = {}, c = {}, u = null, g = null; return l.lastCharacter.remove instanceof Array || (l.lastCharacter.remove = t.fn.dotdotdot.defaultArrays.lastCharacter.remove), l.lastCharacter.noEllipsis instanceof Array || (l.lastCharacter.noEllipsis = t.fn.dotdotdot.defaultArrays.lastCharacter.noEllipsis), s.afterElement = h(l.after, o), s.isTruncated = !1, s.dotId = p++, o.data("dotdotdot", !0).bind_events().trigger("update.dot"), l.watch && o.watch(), o }, t.fn.dotdotdot.defaults = { ellipsis: "... ", wrap: "word", fallbackToLetter: !0, lastCharacter: {}, tolerance: 0, callback: null, after: null, height: null, watch: !1, windowResizeFix: !0 }, t.fn.dotdotdot.defaultArrays = { lastCharacter: { remove: [" ", "　", ",", ";", ".", "!", "?"], noEllipsis: [] } }, t.fn.dotdotdot.debug = function () { }; var p = 1, g = t.fn.html; t.fn.html = function (n) { return n != e && !t.isFunction(n) && this.data("dotdotdot") ? this.trigger("update", [n]) : g.apply(this, arguments) }; var v = t.fn.text; t.fn.text = function (n) { return n != e && !t.isFunction(n) && this.data("dotdotdot") ? (n = t("<div />").text(n).html(), this.trigger("update", [n])) : v.apply(this, arguments) } } }(typeof _MTS_JQUERY === "function" ? _MTS_JQUERY : $);
﻿var _searchWidgets = {};
_searchWidgets.search = [];
_searchWidgets.tag = [];

function TagResults(obj)
{
   this.obj = obj;

   this.Init = function ()
   {
      var that = this;
      var parent = this.obj;
      if (parent.length == 0)
         return;

      if (parent.find(".ranOnce").length > 0)
         return false;

      parent.append("<input type='hidden' class='ranOnce' />");

      this.resizeTagList();

      parent.on("click", ".clearFilters", function ()
      {
         _MTS_JQUERY(this).parents().find(".filterDisabled").removeClass("filterDisabled");
         parent.find("#start, #end, #sort").val("");
         _MTS_adv = false;
         MTS_handleEz(0, null, parent.find("#searchPhrase"));
      });

      parent.on("click", ".searchClose", function ()
      {
         parent.parents(".uploadTagWrapper").removeClass("showTagWrapper");
         parent.parents(".hiddenContainer").removeClass("showHidden");
         parent.parents(".photoUploadContainer").find("#phuDragDrop").removeClass("hideIt");
         parent.parents("body").removeClass("overflow");
      });

      parent.on("keydown", "#searchPhrase", function (e)
      {
         if (e.which === 13)
         {
            e.preventDefault();
            MTS_handleEz(0, null, this);
         }
      });

      parent.on("click", ".showFilterBtn", function ()
      {
         _MTS_toggleMobileFilters();
      });

      parent.on("click", "#ezAdv", function (e)
      {
         e.stopPropagation();
         parent.find(".filterRow").toggleClass("filterRowOpen");
         _MTS_JQUERY(".searchScroll").scrollTop(0);
      });

      parent.on("click", ".direction", function ()
      {
			_MTS_adv = true;
			$(this).toggleClass("rotateDir");
         MTS_handleEz(0, null, parent.find("#searchPhrase"));
      });

      parent.on("click", ".dateWrap input", function ()
      {
         var date = new Date(_MTS_JQUERY.trim(this.value)), me = _MTS_JQUERY(this);
         if (isNaN(date))
            date = new Date();

         _cal.GetMiniCalendar("select", "Select Date", date, function (m, d, y)
         {
            me.val(m.toString() + "/" + d.toString() + "/" + y.toString());
         }, true);

         _MTS_adv = true;
         MTS_handleEz(0, null, parent.find("#searchPhrase"));
      });

      parent.on("click", ".chosen-drop", function ()
      {
         _MTS_adv = true;
         MTS_handleEz(0, null, parent.find("#searchPhrase"));
      });

      parent.on("click", ".filterColumn", function ()
      {
         var fd = "filterDisabled",
            filters = parent.find(".filterColumn:visible");
         if (this.id != "recentDataFilter" && this.id != "frequentFilter" && filters.filter("." + fd).length == 0)
            filters.toggleClass(fd);

         _MTS_JQUERY(this).toggleClass(fd);

         parent.find(".uploadTagWrapper .result").each(function ()
         {
            var tr = _MTS_JQUERY(this).children(".topRow").outerWidth();
            var br = _MTS_JQUERY(this).children(".logoContainer").width();
            var fw = _MTS_JQUERY(this).width();
            var infoWidth = fw - (tr + br);
            _MTS_JQUERY(this).children(".botRow").css({
               "width": (infoWidth - 10) + "px",
               "height": _MTS_JQUERY(this).height() + "px"
            });
         });
      });

      parent.find("#cancelButton").click(function ()
      {
         parent.find("input.text").val("");
         parent.find("select").val(-1);
         parent.find("input[name=gender]")[0].checked = true;
      });

      parent.on("click", ".result", function ()
      {
         _MTS_JQUERY(this).addClass("selectedTag");
      });

      _MTS_JQUERY(window).resize(function ()
      {
         that.resizeTagList();
      });
   };

   this.sizeTagItems = function ()
   {
      var ftfc = this.obj.find(".findTeamFormContainer").outerHeight();
      var ffc = this.obj.find(".formFilterContainer").outerHeight();
		var mpc = this.obj.find(".morePagesContainer").outerHeight();
      var sum = ftfc + ffc + mpc;
      var h = window.innerHeight - sum;

      if (window.matchMedia("(min-width: 768px)").matches)
      {
         h -= this.obj.find(".searchScroll").parents(".uploadTagWrapper, .hiddenContainer").length > 0 ? 40 : 0;
         this.obj.find(".searchScroll").css({ "height": h + "px" });
      }
      else
      {
         this.obj.find(".searchScroll").css({ "height": h + "px" });
      }

      this.obj.find(".morePagesContainer").removeAttr("style");
      this.obj.find(".searchResultsAdjust").removeAttr("style");

      var info = this.obj.find(".info");

      info.each(function ()
      {
         var result = _MTS_JQUERY(this).parents(".result");
         var resultWidth = result.width();
         var lc = result.find(".logoContainer").width();
         var li = result.find(".leftIcon").width();
         var width = resultWidth - (lc + li + 100);
         _MTS_JQUERY(this).css({ "width": width + "px" });
      });

      this.obj.parents(".uploadTagWrapper").css({ "height": (_MTS_JQUERY(window).height() - 40) + "px" });
   };

   this.overallTags = function ()
   {
      var ftfc = this.obj.find(".findTeamFormContainer:visible").outerHeight();
      var ffc = this.obj.find(".formFilterContainer:visible").outerHeight();
      var sum = ftfc + ffc + 40;
      var res = this.obj.find(".searchResults");
      res.css({
         "min-height": _MTS_JQUERY(window).height() - sum + "px"
      });

      _MTS_JQUERY(window.parent.document.body).addClass("overflow");

      _MTS_JQUERY(window.parent.document).find(".mce-close").click(function ()
      {
         if (_MTS_JQUERY(window.parent.document).find(".mce-close").length == 0)
            _MTS_JQUERY(this).parents("body").removeClass("overflow");
      });
   };

   this.resizeTagList = function ()
   {
      this.sizeTagItems();
      if (this.obj.parents(".overallTags").length > 0)
         this.overallTags();
   };
}

function SearchResults(obj)
{
   this.obj = obj;

   this.Init = function ()
   {
      var that = this;
      var parent = this.obj;
      if (parent.length == 0)
         return;

      if (parent.find(".ranOnce").length > 0)
         return false;

      parent.append("<input type='hidden' class='ranOnce' />");

      this.sizeItems();

      parent.on("click", ".clearFilters", function ()
      {
         _MTS_JQUERY(this).parents().find(".filterDisabled").removeClass("filterDisabled");
         parent.find("#start, #end, #sort").val("");
         _MTS_adv = false;
         MTS_handleEz(0, null, parent.find("#searchPhrase"));
      });

      parent.on("click", ".showFilterBtn", function ()
      {
         _MTS_toggleMobileFilters();
         _MTS_adv = false;
      });

      parent.on("click", ".searchClose", function ()
      {
         parent.find(".searchWrapper, .tagWrapper, .background, .uploadTagWrapper, .uploadBackground").hide();
      });

		parent.on("click", ".direction", function () {
			_MTS_adv = true;
			$(this).toggleClass("rotateDir");
         MTS_handleEz(0, null, parent.find("#searchPhrase"));
		});

      parent.on("click", ".dateWrap input", function ()
      {
         var date = new Date(_MTS_JQUERY.trim(this.value)), me = _MTS_JQUERY(this);
         if (isNaN(date))
            date = new Date();

         _cal.GetMiniCalendar("select", "Select Date", date, function (m, d, y)
         {
            me.val(m.toString() + "/" + d.toString() + "/" + y.toString());
         }, true);

         _MTS_adv = true;
         MTS_handleEz(0, null, parent.find("#searchPhrase"));
      });

      parent.on("click", ".chosen-drop", function ()
      {
         _MTS_adv = true;
         MTS_handleEz(0, null, parent.find("#searchPhrase"));
      });

      parent.on("keydown", "#searchPhrase", function (e)
      {
         if (e.which === 13)
         {
            e.preventDefault();
            MTS_handleEz(0, null, this);
         }
      });

      parent.on("click", "#doSearch", function ()
      {
         var name = parent.find("input[name='searchTxt']").last().val();
         var sport = parent.find("#sport").val();

         if (name == "" && sport == "")
         {
            parent.find(".errorNoTeams").html("Please specify at least a search phrase or sport");
            return false;
         }

         parent.find("#findform").submit();
      });

      parent.on("click", ".becomeFanBox", function (e)
      {
         e.stopPropagation();
         e.preventDefault();
         var id = this.id.split('_')[1];
         var button = this;

         if (_userId > 0)
         {
            var p = [];
            p.push({
               name: "id", value: id
            });
            p.push({
               name: "mode", value: "addFan"
            });

            ajax("/api/updateUserTeamLinks.aspx", p, function (ret)
            {
               var o; eval("o = " + ret + ";");
               if (o.ok)
                  _MTS_JQUERY(button).replaceWith("<img class='iamFan' src='" + _mediaUrl + "images/iAmFan.png' alt='Fan Of Team'>");
            });
         }
         else
            window.location = "/user/register/?teamId=" + id + "&mode=fan&target=/team/news/" + id + "/team/";
      });

      parent.on("click", ".filterColumn", function ()
      {
         var fd = "filterDisabled",
            filters = parent.find(".filterColumn:visible");
         if (this.id != "recentDataFilter" && filters.filter("." + fd).length == 0)
            filters.toggleClass(fd);

         _MTS_JQUERY(this).toggleClass(fd);

         parent.find(".uploadTagWrapper .result").each(function ()
         {
            var tr = _MTS_JQUERY(this).children(".topRow").outerWidth();
            var br = _MTS_JQUERY(this).children(".logoContainer").width();
            var fw = _MTS_JQUERY(this).width();
            var infoWidth = fw - (tr + br);
            _MTS_JQUERY(this).children(".botRow").css({
               "width": (infoWidth - 10) + "px",
               "height": _MTS_JQUERY(this).height() + "px"
            });
         });
      });

      parent.find("#cancelButton").click(function ()
      {
         parent.find("input.text").val("");
         parent.find("select").val(-1);
         parent.find("input[name=gender]")[0].checked = true;
      });

      _MTS_JQUERY(window).resize(function ()
      {
         that.sizeItems();
      });
   };

   this.sizeItems = function ()
   {
      if (this.obj.width() > 767)
      {
//         var mp = this.obj.find(".morePagesContainer").detach();
//         this.obj.find(".searchScroll").append(mp);
         this.obj.find(".filterRow").addClass("filterRowOpen");
         var fh = this.obj.find(".filterRowOpen").height() - this.obj.find(".morePagesContainer").outerHeight();
         this.obj.find(".searchResults").css({"overflow-y": "auto", "overflow-x": "hidden" });
      }
      else
      {
         this.obj.find(".searchResults").removeAttr("style");
         this.obj.find(".morePagesContainer").removeAttr("style");
      }

      var info = this.obj.find(".info");


      this.obj.parents(".uploadTagWrapper").css({ "height": (_MTS_JQUERY(window).height() - 40) + "px" });
   };
}

(function ()
{
   var _itv = -1;

   if (_MTS_widgetsReady)
      init();
   else
   {
      _MTS_JQUERY(document).one("widgetsloaded", init);
   }

    function init() {
        _MTS_JQUERY(".search_widget").each(function (idx) {
            var s = null;
            var searchType = _MTS_JQUERY(this).find("input[name='searchType']").val();
            _MTS_JQUERY(this).addClass(searchType).attr("id", "searchWidget_" + idx);
            if (searchType == "Search") {
                s = new SearchResults(_MTS_JQUERY(this));
                _searchWidgets.search[idx] = s;
            }
            else {
                s = new TagResults(_MTS_JQUERY(this));
                _searchWidgets.tag[idx] = s;
            }

            s.Init();
        });

        if (window.location.pathname !== "/")
            RestoreSearchFromHistory();

        if (typeof (_cal) != "undefined")
            _cal.initialize();


        set_MTS_SaveHistoryState(function () {
            var state = [];
            objArray = [];

            _MTS_JQUERY(".search_widget").each(function () {
                var s = {};
                var obj = _MTS_JQUERY(this);
                s.search = obj.find("#searchPhrase").val();
                s.page = parseInt(obj.find(".pageActive:first").html()) - 1;
                s.disabled = "";
                obj.find(".filterDisabled").each(function () {
                    s.disabled += (s.disabled.length > 0 ? ", #" : "#") + this.id;
                });

                objArray.push(s);
            });

            state.push({ "name": "objArray", "value": objArray });
            history.replaceState(state, "");
        });

    }

   function RestoreSearchFromHistory()
   {
      try
      {
         if (history.state != null)
         {
            var objArray = [];
            var o = _MTS_JQUERY(history.state, function (e)
            {
               return e.name == "objArray";
            });

            if (o.length > 0)
               objArray = o[0].value;

            for (var i = 0; i < objArray.length; i++)
            {
               var obj = _MTS_JQUERY("#searchWidget_" + i);
               var state = objArray[i];

               if (obj.length == 0 || state == null)
                  continue;

               if (state.search != null)
               {
                  obj.find("#searchPhrase").val(state.search);
                  obj.find("#searchPhrase").data("prev-val", state.search);
               }

               if (state.disabled != null)
               {
                  obj.find(".filterDisabled").removeClass("filterDisabled");
                  obj.find(state.disabled).addClass("filterDisabled");
                  obj.find(".filterRow").data("prev-val", obj.find(".filterDisabled:visible").length);
               }

               if (state.page != null)
                  MTS_handleEz(state.page, null, obj.find("#searchPhrase"))
            }
         }
      } catch (ex)
      {
         console.log(ex);
      }
   }
})();

function _MTS_toggleMobileFilters()
{
   _MTS_JQUERY(".filterRow").toggleClass("filterRowOpen");
}
﻿/**
 * Swiper 9.3.2
 * Most modern mobile touch slider and framework with hardware accelerated transitions
 * https://swiperjs.com
 *
 * Copyright 2014-2023 Vladimir Kharlampidi
 *
 * Released under the MIT License
 *
 * Released on: May 15, 2023
 */

(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Swiper = factory());
})(this, (function () { 'use strict';

    /**
     * SSR Window 4.0.2
     * Better handling for window object in SSR environment
     * https://github.com/nolimits4web/ssr-window
     *
     * Copyright 2021, Vladimir Kharlampidi
     *
     * Licensed under MIT
     *
     * Released on: December 13, 2021
     */
    /* eslint-disable no-param-reassign */
    function isObject$1(obj) {
      return obj !== null && typeof obj === 'object' && 'constructor' in obj && obj.constructor === Object;
    }
    function extend$1(target, src) {
      if (target === void 0) {
        target = {};
      }
      if (src === void 0) {
        src = {};
      }
      Object.keys(src).forEach(key => {
        if (typeof target[key] === 'undefined') target[key] = src[key];else if (isObject$1(src[key]) && isObject$1(target[key]) && Object.keys(src[key]).length > 0) {
          extend$1(target[key], src[key]);
        }
      });
    }
    const ssrDocument = {
      body: {},
      addEventListener() {},
      removeEventListener() {},
      activeElement: {
        blur() {},
        nodeName: ''
      },
      querySelector() {
        return null;
      },
      querySelectorAll() {
        return [];
      },
      getElementById() {
        return null;
      },
      createEvent() {
        return {
          initEvent() {}
        };
      },
      createElement() {
        return {
          children: [],
          childNodes: [],
          style: {},
          setAttribute() {},
          getElementsByTagName() {
            return [];
          }
        };
      },
      createElementNS() {
        return {};
      },
      importNode() {
        return null;
      },
      location: {
        hash: '',
        host: '',
        hostname: '',
        href: '',
        origin: '',
        pathname: '',
        protocol: '',
        search: ''
      }
    };
    function getDocument() {
      const doc = typeof document !== 'undefined' ? document : {};
      extend$1(doc, ssrDocument);
      return doc;
    }
    const ssrWindow = {
      document: ssrDocument,
      navigator: {
        userAgent: ''
      },
      location: {
        hash: '',
        host: '',
        hostname: '',
        href: '',
        origin: '',
        pathname: '',
        protocol: '',
        search: ''
      },
      history: {
        replaceState() {},
        pushState() {},
        go() {},
        back() {}
      },
      CustomEvent: function CustomEvent() {
        return this;
      },
      addEventListener() {},
      removeEventListener() {},
      getComputedStyle() {
        return {
          getPropertyValue() {
            return '';
          }
        };
      },
      Image() {},
      Date() {},
      screen: {},
      setTimeout() {},
      clearTimeout() {},
      matchMedia() {
        return {};
      },
      requestAnimationFrame(callback) {
        if (typeof setTimeout === 'undefined') {
          callback();
          return null;
        }
        return setTimeout(callback, 0);
      },
      cancelAnimationFrame(id) {
        if (typeof setTimeout === 'undefined') {
          return;
        }
        clearTimeout(id);
      }
    };
    function getWindow() {
      const win = typeof window !== 'undefined' ? window : {};
      extend$1(win, ssrWindow);
      return win;
    }

    function deleteProps(obj) {
      const object = obj;
      Object.keys(object).forEach(key => {
        try {
          object[key] = null;
        } catch (e) {
          // no getter for object
        }
        try {
          delete object[key];
        } catch (e) {
          // something got wrong
        }
      });
    }
    function nextTick(callback, delay) {
      if (delay === void 0) {
        delay = 0;
      }
      return setTimeout(callback, delay);
    }
    function now() {
      return Date.now();
    }
    function getComputedStyle$1(el) {
      const window = getWindow();
      let style;
      if (window.getComputedStyle) {
        style = window.getComputedStyle(el, null);
      }
      if (!style && el.currentStyle) {
        style = el.currentStyle;
      }
      if (!style) {
        style = el.style;
      }
      return style;
    }
    function getTranslate(el, axis) {
      if (axis === void 0) {
        axis = 'x';
      }
      const window = getWindow();
      let matrix;
      let curTransform;
      let transformMatrix;
      const curStyle = getComputedStyle$1(el);
      if (window.WebKitCSSMatrix) {
        curTransform = curStyle.transform || curStyle.webkitTransform;
        if (curTransform.split(',').length > 6) {
          curTransform = curTransform.split(', ').map(a => a.replace(',', '.')).join(', ');
        }
        // Some old versions of Webkit choke when 'none' is passed; pass
        // empty string instead in this case
        transformMatrix = new window.WebKitCSSMatrix(curTransform === 'none' ? '' : curTransform);
      } else {
        transformMatrix = curStyle.MozTransform || curStyle.OTransform || curStyle.MsTransform || curStyle.msTransform || curStyle.transform || curStyle.getPropertyValue('transform').replace('translate(', 'matrix(1, 0, 0, 1,');
        matrix = transformMatrix.toString().split(',');
      }
      if (axis === 'x') {
        // Latest Chrome and webkits Fix
        if (window.WebKitCSSMatrix) curTransform = transformMatrix.m41;
        // Crazy IE10 Matrix
        else if (matrix.length === 16) curTransform = parseFloat(matrix[12]);
        // Normal Browsers
        else curTransform = parseFloat(matrix[4]);
      }
      if (axis === 'y') {
        // Latest Chrome and webkits Fix
        if (window.WebKitCSSMatrix) curTransform = transformMatrix.m42;
        // Crazy IE10 Matrix
        else if (matrix.length === 16) curTransform = parseFloat(matrix[13]);
        // Normal Browsers
        else curTransform = parseFloat(matrix[5]);
      }
      return curTransform || 0;
    }
    function isObject(o) {
      return typeof o === 'object' && o !== null && o.constructor && Object.prototype.toString.call(o).slice(8, -1) === 'Object';
    }
    function isNode(node) {
      // eslint-disable-next-line
      if (typeof window !== 'undefined' && typeof window.HTMLElement !== 'undefined') {
        return node instanceof HTMLElement;
      }
      return node && (node.nodeType === 1 || node.nodeType === 11);
    }
    function extend() {
      const to = Object(arguments.length <= 0 ? undefined : arguments[0]);
      const noExtend = ['__proto__', 'constructor', 'prototype'];
      for (let i = 1; i < arguments.length; i += 1) {
        const nextSource = i < 0 || arguments.length <= i ? undefined : arguments[i];
        if (nextSource !== undefined && nextSource !== null && !isNode(nextSource)) {
          const keysArray = Object.keys(Object(nextSource)).filter(key => noExtend.indexOf(key) < 0);
          for (let nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex += 1) {
            const nextKey = keysArray[nextIndex];
            const desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
            if (desc !== undefined && desc.enumerable) {
              if (isObject(to[nextKey]) && isObject(nextSource[nextKey])) {
                if (nextSource[nextKey].__swiper__) {
                  to[nextKey] = nextSource[nextKey];
                } else {
                  extend(to[nextKey], nextSource[nextKey]);
                }
              } else if (!isObject(to[nextKey]) && isObject(nextSource[nextKey])) {
                to[nextKey] = {};
                if (nextSource[nextKey].__swiper__) {
                  to[nextKey] = nextSource[nextKey];
                } else {
                  extend(to[nextKey], nextSource[nextKey]);
                }
              } else {
                to[nextKey] = nextSource[nextKey];
              }
            }
          }
        }
      }
      return to;
    }
    function setCSSProperty(el, varName, varValue) {
      el.style.setProperty(varName, varValue);
    }
    function animateCSSModeScroll(_ref) {
      let {
        swiper,
        targetPosition,
        side
      } = _ref;
      const window = getWindow();
      const startPosition = -swiper.translate;
      let startTime = null;
      let time;
      const duration = swiper.params.speed;
      swiper.wrapperEl.style.scrollSnapType = 'none';
      window.cancelAnimationFrame(swiper.cssModeFrameID);
      const dir = targetPosition > startPosition ? 'next' : 'prev';
      const isOutOfBound = (current, target) => {
        return dir === 'next' && current >= target || dir === 'prev' && current <= target;
      };
      const animate = () => {
        time = new Date().getTime();
        if (startTime === null) {
          startTime = time;
        }
        const progress = Math.max(Math.min((time - startTime) / duration, 1), 0);
        const easeProgress = 0.5 - Math.cos(progress * Math.PI) / 2;
        let currentPosition = startPosition + easeProgress * (targetPosition - startPosition);
        if (isOutOfBound(currentPosition, targetPosition)) {
          currentPosition = targetPosition;
        }
        swiper.wrapperEl.scrollTo({
          [side]: currentPosition
        });
        if (isOutOfBound(currentPosition, targetPosition)) {
          swiper.wrapperEl.style.overflow = 'hidden';
          swiper.wrapperEl.style.scrollSnapType = '';
          setTimeout(() => {
            swiper.wrapperEl.style.overflow = '';
            swiper.wrapperEl.scrollTo({
              [side]: currentPosition
            });
          });
          window.cancelAnimationFrame(swiper.cssModeFrameID);
          return;
        }
        swiper.cssModeFrameID = window.requestAnimationFrame(animate);
      };
      animate();
    }
    function getSlideTransformEl(slideEl) {
      return slideEl.querySelector('.swiper-slide-transform') || slideEl.shadowEl && slideEl.shadowEl.querySelector('.swiper-slide-transform') || slideEl;
    }
    function elementChildren(element, selector) {
      if (selector === void 0) {
        selector = '';
      }
      return [...element.children].filter(el => el.matches(selector));
    }
    function createElement(tag, classes) {
      if (classes === void 0) {
        classes = [];
      }
      const el = document.createElement(tag);
      el.classList.add(...(Array.isArray(classes) ? classes : [classes]));
      return el;
    }
    function elementOffset(el) {
      const window = getWindow();
      const document = getDocument();
      const box = el.getBoundingClientRect();
      const body = document.body;
      const clientTop = el.clientTop || body.clientTop || 0;
      const clientLeft = el.clientLeft || body.clientLeft || 0;
      const scrollTop = el === window ? window.scrollY : el.scrollTop;
      const scrollLeft = el === window ? window.scrollX : el.scrollLeft;
      return {
        top: box.top + scrollTop - clientTop,
        left: box.left + scrollLeft - clientLeft
      };
    }
    function elementPrevAll(el, selector) {
      const prevEls = [];
      while (el.previousElementSibling) {
        const prev = el.previousElementSibling; // eslint-disable-line
        if (selector) {
          if (prev.matches(selector)) prevEls.push(prev);
        } else prevEls.push(prev);
        el = prev;
      }
      return prevEls;
    }
    function elementNextAll(el, selector) {
      const nextEls = [];
      while (el.nextElementSibling) {
        const next = el.nextElementSibling; // eslint-disable-line
        if (selector) {
          if (next.matches(selector)) nextEls.push(next);
        } else nextEls.push(next);
        el = next;
      }
      return nextEls;
    }
    function elementStyle(el, prop) {
      const window = getWindow();
      return window.getComputedStyle(el, null).getPropertyValue(prop);
    }
    function elementIndex(el) {
      let child = el;
      let i;
      if (child) {
        i = 0;
        // eslint-disable-next-line
        while ((child = child.previousSibling) !== null) {
          if (child.nodeType === 1) i += 1;
        }
        return i;
      }
      return undefined;
    }
    function elementParents(el, selector) {
      const parents = []; // eslint-disable-line
      let parent = el.parentElement; // eslint-disable-line
      while (parent) {
        if (selector) {
          if (parent.matches(selector)) parents.push(parent);
        } else {
          parents.push(parent);
        }
        parent = parent.parentElement;
      }
      return parents;
    }
    function elementTransitionEnd(el, callback) {
      function fireCallBack(e) {
        if (e.target !== el) return;
        callback.call(el, e);
        el.removeEventListener('transitionend', fireCallBack);
      }
      if (callback) {
        el.addEventListener('transitionend', fireCallBack);
      }
    }
    function elementOuterSize(el, size, includeMargins) {
      const window = getWindow();
      if (includeMargins) {
        return el[size === 'width' ? 'offsetWidth' : 'offsetHeight'] + parseFloat(window.getComputedStyle(el, null).getPropertyValue(size === 'width' ? 'margin-right' : 'margin-top')) + parseFloat(window.getComputedStyle(el, null).getPropertyValue(size === 'width' ? 'margin-left' : 'margin-bottom'));
      }
      return el.offsetWidth;
    }

    let support;
    function calcSupport() {
      const window = getWindow();
      const document = getDocument();
      return {
        smoothScroll: document.documentElement && document.documentElement.style && 'scrollBehavior' in document.documentElement.style,
        touch: !!('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch)
      };
    }
    function getSupport() {
      if (!support) {
        support = calcSupport();
      }
      return support;
    }

    let deviceCached;
    function calcDevice(_temp) {
      let {
        userAgent
      } = _temp === void 0 ? {} : _temp;
      const support = getSupport();
      const window = getWindow();
      const platform = window.navigator.platform;
      const ua = userAgent || window.navigator.userAgent;
      const device = {
        ios: false,
        android: false
      };
      const screenWidth = window.screen.width;
      const screenHeight = window.screen.height;
      const android = ua.match(/(Android);?[\s\/]+([\d.]+)?/); // eslint-disable-line
      let ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
      const ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
      const iphone = !ipad && ua.match(/(iPhone\sOS|iOS)\s([\d_]+)/);
      const windows = platform === 'Win32';
      let macos = platform === 'MacIntel';

      // iPadOs 13 fix
      const iPadScreens = ['1024x1366', '1366x1024', '834x1194', '1194x834', '834x1112', '1112x834', '768x1024', '1024x768', '820x1180', '1180x820', '810x1080', '1080x810'];
      if (!ipad && macos && support.touch && iPadScreens.indexOf(`${screenWidth}x${screenHeight}`) >= 0) {
        ipad = ua.match(/(Version)\/([\d.]+)/);
        if (!ipad) ipad = [0, 1, '13_0_0'];
        macos = false;
      }

      // Android
      if (android && !windows) {
        device.os = 'android';
        device.android = true;
      }
      if (ipad || iphone || ipod) {
        device.os = 'ios';
        device.ios = true;
      }

      // Export object
      return device;
    }
    function getDevice(overrides) {
      if (overrides === void 0) {
        overrides = {};
      }
      if (!deviceCached) {
        deviceCached = calcDevice(overrides);
      }
      return deviceCached;
    }

    let browser;
    function calcBrowser() {
      const window = getWindow();
      let needPerspectiveFix = false;
      function isSafari() {
        const ua = window.navigator.userAgent.toLowerCase();
        return ua.indexOf('safari') >= 0 && ua.indexOf('chrome') < 0 && ua.indexOf('android') < 0;
      }
      if (isSafari()) {
        const ua = String(window.navigator.userAgent);
        if (ua.includes('Version/')) {
          const [major, minor] = ua.split('Version/')[1].split(' ')[0].split('.').map(num => Number(num));
          needPerspectiveFix = major < 16 || major === 16 && minor < 2;
        }
      }
      return {
        isSafari: needPerspectiveFix || isSafari(),
        needPerspectiveFix,
        isWebView: /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(window.navigator.userAgent)
      };
    }
    function getBrowser() {
      if (!browser) {
        browser = calcBrowser();
      }
      return browser;
    }

    function Resize(_ref) {
      let {
        swiper,
        on,
        emit
      } = _ref;
      const window = getWindow();
      let observer = null;
      let animationFrame = null;
      const resizeHandler = () => {
        if (!swiper || swiper.destroyed || !swiper.initialized) return;
        emit('beforeResize');
        emit('resize');
      };
      const createObserver = () => {
        if (!swiper || swiper.destroyed || !swiper.initialized) return;
        observer = new ResizeObserver(entries => {
          animationFrame = window.requestAnimationFrame(() => {
            const {
              width,
              height
            } = swiper;
            let newWidth = width;
            let newHeight = height;
            entries.forEach(_ref2 => {
              let {
                contentBoxSize,
                contentRect,
                target
              } = _ref2;
              if (target && target !== swiper.el) return;
              newWidth = contentRect ? contentRect.width : (contentBoxSize[0] || contentBoxSize).inlineSize;
              newHeight = contentRect ? contentRect.height : (contentBoxSize[0] || contentBoxSize).blockSize;
            });
            if (newWidth !== width || newHeight !== height) {
              resizeHandler();
            }
          });
        });
        observer.observe(swiper.el);
      };
      const removeObserver = () => {
        if (animationFrame) {
          window.cancelAnimationFrame(animationFrame);
        }
        if (observer && observer.unobserve && swiper.el) {
          observer.unobserve(swiper.el);
          observer = null;
        }
      };
      const orientationChangeHandler = () => {
        if (!swiper || swiper.destroyed || !swiper.initialized) return;
        emit('orientationchange');
      };
      on('init', () => {
        if (swiper.params.resizeObserver && typeof window.ResizeObserver !== 'undefined') {
          createObserver();
          return;
        }
        window.addEventListener('resize', resizeHandler);
        window.addEventListener('orientationchange', orientationChangeHandler);
      });
      on('destroy', () => {
        removeObserver();
        window.removeEventListener('resize', resizeHandler);
        window.removeEventListener('orientationchange', orientationChangeHandler);
      });
    }

    function Observer(_ref) {
      let {
        swiper,
        extendParams,
        on,
        emit
      } = _ref;
      const observers = [];
      const window = getWindow();
      const attach = function (target, options) {
        if (options === void 0) {
          options = {};
        }
        const ObserverFunc = window.MutationObserver || window.WebkitMutationObserver;
        const observer = new ObserverFunc(mutations => {
          // The observerUpdate event should only be triggered
          // once despite the number of mutations.  Additional
          // triggers are redundant and are very costly
          if (swiper.__preventObserver__) return;
          if (mutations.length === 1) {
            emit('observerUpdate', mutations[0]);
            return;
          }
          const observerUpdate = function observerUpdate() {
            emit('observerUpdate', mutations[0]);
          };
          if (window.requestAnimationFrame) {
            window.requestAnimationFrame(observerUpdate);
          } else {
            window.setTimeout(observerUpdate, 0);
          }
        });
        observer.observe(target, {
          attributes: typeof options.attributes === 'undefined' ? true : options.attributes,
          childList: typeof options.childList === 'undefined' ? true : options.childList,
          characterData: typeof options.characterData === 'undefined' ? true : options.characterData
        });
        observers.push(observer);
      };
      const init = () => {
        if (!swiper.params.observer) return;
        if (swiper.params.observeParents) {
          const containerParents = elementParents(swiper.el);
          for (let i = 0; i < containerParents.length; i += 1) {
            attach(containerParents[i]);
          }
        }
        // Observe container
        attach(swiper.el, {
          childList: swiper.params.observeSlideChildren
        });

        // Observe wrapper
        attach(swiper.wrapperEl, {
          attributes: false
        });
      };
      const destroy = () => {
        observers.forEach(observer => {
          observer.disconnect();
        });
        observers.splice(0, observers.length);
      };
      extendParams({
        observer: false,
        observeParents: false,
        observeSlideChildren: false
      });
      on('init', init);
      on('destroy', destroy);
    }

    /* eslint-disable no-underscore-dangle */

    var eventsEmitter = {
      on(events, handler, priority) {
        const self = this;
        if (!self.eventsListeners || self.destroyed) return self;
        if (typeof handler !== 'function') return self;
        const method = priority ? 'unshift' : 'push';
        events.split(' ').forEach(event => {
          if (!self.eventsListeners[event]) self.eventsListeners[event] = [];
          self.eventsListeners[event][method](handler);
        });
        return self;
      },
      once(events, handler, priority) {
        const self = this;
        if (!self.eventsListeners || self.destroyed) return self;
        if (typeof handler !== 'function') return self;
        function onceHandler() {
          self.off(events, onceHandler);
          if (onceHandler.__emitterProxy) {
            delete onceHandler.__emitterProxy;
          }
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          handler.apply(self, args);
        }
        onceHandler.__emitterProxy = handler;
        return self.on(events, onceHandler, priority);
      },
      onAny(handler, priority) {
        const self = this;
        if (!self.eventsListeners || self.destroyed) return self;
        if (typeof handler !== 'function') return self;
        const method = priority ? 'unshift' : 'push';
        if (self.eventsAnyListeners.indexOf(handler) < 0) {
          self.eventsAnyListeners[method](handler);
        }
        return self;
      },
      offAny(handler) {
        const self = this;
        if (!self.eventsListeners || self.destroyed) return self;
        if (!self.eventsAnyListeners) return self;
        const index = self.eventsAnyListeners.indexOf(handler);
        if (index >= 0) {
          self.eventsAnyListeners.splice(index, 1);
        }
        return self;
      },
      off(events, handler) {
        const self = this;
        if (!self.eventsListeners || self.destroyed) return self;
        if (!self.eventsListeners) return self;
        events.split(' ').forEach(event => {
          if (typeof handler === 'undefined') {
            self.eventsListeners[event] = [];
          } else if (self.eventsListeners[event]) {
            self.eventsListeners[event].forEach((eventHandler, index) => {
              if (eventHandler === handler || eventHandler.__emitterProxy && eventHandler.__emitterProxy === handler) {
                self.eventsListeners[event].splice(index, 1);
              }
            });
          }
        });
        return self;
      },
      emit() {
        const self = this;
        if (!self.eventsListeners || self.destroyed) return self;
        if (!self.eventsListeners) return self;
        let events;
        let data;
        let context;
        for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          args[_key2] = arguments[_key2];
        }
        if (typeof args[0] === 'string' || Array.isArray(args[0])) {
          events = args[0];
          data = args.slice(1, args.length);
          context = self;
        } else {
          events = args[0].events;
          data = args[0].data;
          context = args[0].context || self;
        }
        data.unshift(context);
        const eventsArray = Array.isArray(events) ? events : events.split(' ');
        eventsArray.forEach(event => {
          if (self.eventsAnyListeners && self.eventsAnyListeners.length) {
            self.eventsAnyListeners.forEach(eventHandler => {
              eventHandler.apply(context, [event, ...data]);
            });
          }
          if (self.eventsListeners && self.eventsListeners[event]) {
            self.eventsListeners[event].forEach(eventHandler => {
              eventHandler.apply(context, data);
            });
          }
        });
        return self;
      }
    };

    function updateSize() {
      const swiper = this;
      let width;
      let height;
      const el = swiper.el;
      if (typeof swiper.params.width !== 'undefined' && swiper.params.width !== null) {
        width = swiper.params.width;
      } else {
        width = el.clientWidth;
      }
      if (typeof swiper.params.height !== 'undefined' && swiper.params.height !== null) {
        height = swiper.params.height;
      } else {
        height = el.clientHeight;
      }
      if (width === 0 && swiper.isHorizontal() || height === 0 && swiper.isVertical()) {
        return;
      }

      // Subtract paddings
      width = width - parseInt(elementStyle(el, 'padding-left') || 0, 10) - parseInt(elementStyle(el, 'padding-right') || 0, 10);
      height = height - parseInt(elementStyle(el, 'padding-top') || 0, 10) - parseInt(elementStyle(el, 'padding-bottom') || 0, 10);
      if (Number.isNaN(width)) width = 0;
      if (Number.isNaN(height)) height = 0;
      Object.assign(swiper, {
        width,
        height,
        size: swiper.isHorizontal() ? width : height
      });
    }

    function updateSlides() {
      const swiper = this;
      function getDirectionLabel(property) {
        if (swiper.isHorizontal()) {
          return property;
        }
        // prettier-ignore
        return {
          'width': 'height',
          'margin-top': 'margin-left',
          'margin-bottom ': 'margin-right',
          'margin-left': 'margin-top',
          'margin-right': 'margin-bottom',
          'padding-left': 'padding-top',
          'padding-right': 'padding-bottom',
          'marginRight': 'marginBottom'
        }[property];
      }
      function getDirectionPropertyValue(node, label) {
        return parseFloat(node.getPropertyValue(getDirectionLabel(label)) || 0);
      }
      const params = swiper.params;
      const {
        wrapperEl,
        slidesEl,
        size: swiperSize,
        rtlTranslate: rtl,
        wrongRTL
      } = swiper;
      const isVirtual = swiper.virtual && params.virtual.enabled;
      const previousSlidesLength = isVirtual ? swiper.virtual.slides.length : swiper.slides.length;
      const slides = elementChildren(slidesEl, `.${swiper.params.slideClass}, swiper-slide`);
      const slidesLength = isVirtual ? swiper.virtual.slides.length : slides.length;
      let snapGrid = [];
      const slidesGrid = [];
      const slidesSizesGrid = [];
      let offsetBefore = params.slidesOffsetBefore;
      if (typeof offsetBefore === 'function') {
        offsetBefore = params.slidesOffsetBefore.call(swiper);
      }
      let offsetAfter = params.slidesOffsetAfter;
      if (typeof offsetAfter === 'function') {
        offsetAfter = params.slidesOffsetAfter.call(swiper);
      }
      const previousSnapGridLength = swiper.snapGrid.length;
      const previousSlidesGridLength = swiper.slidesGrid.length;
      let spaceBetween = params.spaceBetween;
      let slidePosition = -offsetBefore;
      let prevSlideSize = 0;
      let index = 0;
      if (typeof swiperSize === 'undefined') {
        return;
      }
      if (typeof spaceBetween === 'string' && spaceBetween.indexOf('%') >= 0) {
        spaceBetween = parseFloat(spaceBetween.replace('%', '')) / 100 * swiperSize;
      } else if (typeof spaceBetween === 'string') {
        spaceBetween = parseFloat(spaceBetween);
      }
      swiper.virtualSize = -spaceBetween;

      // reset margins
      slides.forEach(slideEl => {
        if (rtl) {
          slideEl.style.marginLeft = '';
        } else {
          slideEl.style.marginRight = '';
        }
        slideEl.style.marginBottom = '';
        slideEl.style.marginTop = '';
      });

      // reset cssMode offsets
      if (params.centeredSlides && params.cssMode) {
        setCSSProperty(wrapperEl, '--swiper-centered-offset-before', '');
        setCSSProperty(wrapperEl, '--swiper-centered-offset-after', '');
      }
      const gridEnabled = params.grid && params.grid.rows > 1 && swiper.grid;
      if (gridEnabled) {
        swiper.grid.initSlides(slidesLength);
      }

      // Calc slides
      let slideSize;
      const shouldResetSlideSize = params.slidesPerView === 'auto' && params.breakpoints && Object.keys(params.breakpoints).filter(key => {
        return typeof params.breakpoints[key].slidesPerView !== 'undefined';
      }).length > 0;
      for (let i = 0; i < slidesLength; i += 1) {
        slideSize = 0;
        let slide;
        if (slides[i]) slide = slides[i];
        if (gridEnabled) {
          swiper.grid.updateSlide(i, slide, slidesLength, getDirectionLabel);
        }
        if (slides[i] && elementStyle(slide, 'display') === 'none') continue; // eslint-disable-line

        if (params.slidesPerView === 'auto') {
          if (shouldResetSlideSize) {
            slides[i].style[getDirectionLabel('width')] = ``;
          }
          const slideStyles = getComputedStyle(slide);
          const currentTransform = slide.style.transform;
          const currentWebKitTransform = slide.style.webkitTransform;
          if (currentTransform) {
            slide.style.transform = 'none';
          }
          if (currentWebKitTransform) {
            slide.style.webkitTransform = 'none';
          }
          if (params.roundLengths) {
            slideSize = swiper.isHorizontal() ? elementOuterSize(slide, 'width', true) : elementOuterSize(slide, 'height', true);
          } else {
            // eslint-disable-next-line
            const width = getDirectionPropertyValue(slideStyles, 'width');
            const paddingLeft = getDirectionPropertyValue(slideStyles, 'padding-left');
            const paddingRight = getDirectionPropertyValue(slideStyles, 'padding-right');
            const marginLeft = getDirectionPropertyValue(slideStyles, 'margin-left');
            const marginRight = getDirectionPropertyValue(slideStyles, 'margin-right');
            const boxSizing = slideStyles.getPropertyValue('box-sizing');
            if (boxSizing && boxSizing === 'border-box') {
              slideSize = width + marginLeft + marginRight;
            } else {
              const {
                clientWidth,
                offsetWidth
              } = slide;
              slideSize = width + paddingLeft + paddingRight + marginLeft + marginRight + (offsetWidth - clientWidth);
            }
          }
          if (currentTransform) {
            slide.style.transform = currentTransform;
          }
          if (currentWebKitTransform) {
            slide.style.webkitTransform = currentWebKitTransform;
          }
          if (params.roundLengths) slideSize = Math.floor(slideSize);
        } else {
          slideSize = (swiperSize - (params.slidesPerView - 1) * spaceBetween) / params.slidesPerView;
          if (params.roundLengths) slideSize = Math.floor(slideSize);
          if (slides[i]) {
            slides[i].style[getDirectionLabel('width')] = `${slideSize}px`;
          }
        }
        if (slides[i]) {
          slides[i].swiperSlideSize = slideSize;
        }
        slidesSizesGrid.push(slideSize);
        if (params.centeredSlides) {
          slidePosition = slidePosition + slideSize / 2 + prevSlideSize / 2 + spaceBetween;
          if (prevSlideSize === 0 && i !== 0) slidePosition = slidePosition - swiperSize / 2 - spaceBetween;
          if (i === 0) slidePosition = slidePosition - swiperSize / 2 - spaceBetween;
          if (Math.abs(slidePosition) < 1 / 1000) slidePosition = 0;
          if (params.roundLengths) slidePosition = Math.floor(slidePosition);
          if (index % params.slidesPerGroup === 0) snapGrid.push(slidePosition);
          slidesGrid.push(slidePosition);
        } else {
          if (params.roundLengths) slidePosition = Math.floor(slidePosition);
          if ((index - Math.min(swiper.params.slidesPerGroupSkip, index)) % swiper.params.slidesPerGroup === 0) snapGrid.push(slidePosition);
          slidesGrid.push(slidePosition);
          slidePosition = slidePosition + slideSize + spaceBetween;
        }
        swiper.virtualSize += slideSize + spaceBetween;
        prevSlideSize = slideSize;
        index += 1;
      }
      swiper.virtualSize = Math.max(swiper.virtualSize, swiperSize) + offsetAfter;
      if (rtl && wrongRTL && (params.effect === 'slide' || params.effect === 'coverflow')) {
        wrapperEl.style.width = `${swiper.virtualSize + spaceBetween}px`;
      }
      if (params.setWrapperSize) {
        wrapperEl.style[getDirectionLabel('width')] = `${swiper.virtualSize + spaceBetween}px`;
      }
      if (gridEnabled) {
        swiper.grid.updateWrapperSize(slideSize, snapGrid, getDirectionLabel);
      }

      // Remove last grid elements depending on width
      if (!params.centeredSlides) {
        const newSlidesGrid = [];
        for (let i = 0; i < snapGrid.length; i += 1) {
          let slidesGridItem = snapGrid[i];
          if (params.roundLengths) slidesGridItem = Math.floor(slidesGridItem);
          if (snapGrid[i] <= swiper.virtualSize - swiperSize) {
            newSlidesGrid.push(slidesGridItem);
          }
        }
        snapGrid = newSlidesGrid;
        if (Math.floor(swiper.virtualSize - swiperSize) - Math.floor(snapGrid[snapGrid.length - 1]) > 1) {
          snapGrid.push(swiper.virtualSize - swiperSize);
        }
      }
      if (isVirtual && params.loop) {
        const size = slidesSizesGrid[0] + spaceBetween;
        if (params.slidesPerGroup > 1) {
          const groups = Math.ceil((swiper.virtual.slidesBefore + swiper.virtual.slidesAfter) / params.slidesPerGroup);
          const groupSize = size * params.slidesPerGroup;
          for (let i = 0; i < groups; i += 1) {
            snapGrid.push(snapGrid[snapGrid.length - 1] + groupSize);
          }
        }
        for (let i = 0; i < swiper.virtual.slidesBefore + swiper.virtual.slidesAfter; i += 1) {
          if (params.slidesPerGroup === 1) {
            snapGrid.push(snapGrid[snapGrid.length - 1] + size);
          }
          slidesGrid.push(slidesGrid[slidesGrid.length - 1] + size);
          swiper.virtualSize += size;
        }
      }
      if (snapGrid.length === 0) snapGrid = [0];
      if (spaceBetween !== 0) {
        const key = swiper.isHorizontal() && rtl ? 'marginLeft' : getDirectionLabel('marginRight');
        slides.filter((_, slideIndex) => {
          if (!params.cssMode || params.loop) return true;
          if (slideIndex === slides.length - 1) {
            return false;
          }
          return true;
        }).forEach(slideEl => {
          slideEl.style[key] = `${spaceBetween}px`;
        });
      }
      if (params.centeredSlides && params.centeredSlidesBounds) {
        let allSlidesSize = 0;
        slidesSizesGrid.forEach(slideSizeValue => {
          allSlidesSize += slideSizeValue + (spaceBetween || 0);
        });
        allSlidesSize -= spaceBetween;
        const maxSnap = allSlidesSize - swiperSize;
        snapGrid = snapGrid.map(snap => {
          if (snap < 0) return -offsetBefore;
          if (snap > maxSnap) return maxSnap + offsetAfter;
          return snap;
        });
      }
      if (params.centerInsufficientSlides) {
        let allSlidesSize = 0;
        slidesSizesGrid.forEach(slideSizeValue => {
          allSlidesSize += slideSizeValue + (spaceBetween || 0);
        });
        allSlidesSize -= spaceBetween;
        if (allSlidesSize < swiperSize) {
          const allSlidesOffset = (swiperSize - allSlidesSize) / 2;
          snapGrid.forEach((snap, snapIndex) => {
            snapGrid[snapIndex] = snap - allSlidesOffset;
          });
          slidesGrid.forEach((snap, snapIndex) => {
            slidesGrid[snapIndex] = snap + allSlidesOffset;
          });
        }
      }
      Object.assign(swiper, {
        slides,
        snapGrid,
        slidesGrid,
        slidesSizesGrid
      });
      if (params.centeredSlides && params.cssMode && !params.centeredSlidesBounds) {
        setCSSProperty(wrapperEl, '--swiper-centered-offset-before', `${-snapGrid[0]}px`);
        setCSSProperty(wrapperEl, '--swiper-centered-offset-after', `${swiper.size / 2 - slidesSizesGrid[slidesSizesGrid.length - 1] / 2}px`);
        const addToSnapGrid = -swiper.snapGrid[0];
        const addToSlidesGrid = -swiper.slidesGrid[0];
        swiper.snapGrid = swiper.snapGrid.map(v => v + addToSnapGrid);
        swiper.slidesGrid = swiper.slidesGrid.map(v => v + addToSlidesGrid);
      }
      if (slidesLength !== previousSlidesLength) {
        swiper.emit('slidesLengthChange');
      }
      if (snapGrid.length !== previousSnapGridLength) {
        if (swiper.params.watchOverflow) swiper.checkOverflow();
        swiper.emit('snapGridLengthChange');
      }
      if (slidesGrid.length !== previousSlidesGridLength) {
        swiper.emit('slidesGridLengthChange');
      }
      if (params.watchSlidesProgress) {
        swiper.updateSlidesOffset();
      }
      if (!isVirtual && !params.cssMode && (params.effect === 'slide' || params.effect === 'fade')) {
        const backFaceHiddenClass = `${params.containerModifierClass}backface-hidden`;
        const hasClassBackfaceClassAdded = swiper.el.classList.contains(backFaceHiddenClass);
        if (slidesLength <= params.maxBackfaceHiddenSlides) {
          if (!hasClassBackfaceClassAdded) swiper.el.classList.add(backFaceHiddenClass);
        } else if (hasClassBackfaceClassAdded) {
          swiper.el.classList.remove(backFaceHiddenClass);
        }
      }
    }

    function updateAutoHeight(speed) {
      const swiper = this;
      const activeSlides = [];
      const isVirtual = swiper.virtual && swiper.params.virtual.enabled;
      let newHeight = 0;
      let i;
      if (typeof speed === 'number') {
        swiper.setTransition(speed);
      } else if (speed === true) {
        swiper.setTransition(swiper.params.speed);
      }
      const getSlideByIndex = index => {
        if (isVirtual) {
          return swiper.slides[swiper.getSlideIndexByData(index)];
        }
        return swiper.slides[index];
      };
      // Find slides currently in view
      if (swiper.params.slidesPerView !== 'auto' && swiper.params.slidesPerView > 1) {
        if (swiper.params.centeredSlides) {
          (swiper.visibleSlides || []).forEach(slide => {
            activeSlides.push(slide);
          });
        } else {
          for (i = 0; i < Math.ceil(swiper.params.slidesPerView); i += 1) {
            const index = swiper.activeIndex + i;
            if (index > swiper.slides.length && !isVirtual) break;
            activeSlides.push(getSlideByIndex(index));
          }
        }
      } else {
        activeSlides.push(getSlideByIndex(swiper.activeIndex));
      }

      // Find new height from highest slide in view
      for (i = 0; i < activeSlides.length; i += 1) {
        if (typeof activeSlides[i] !== 'undefined') {
          const height = activeSlides[i].offsetHeight;
          newHeight = height > newHeight ? height : newHeight;
        }
      }

      // Update Height
      if (newHeight || newHeight === 0) swiper.wrapperEl.style.height = `${newHeight}px`;
    }

    function updateSlidesOffset() {
      const swiper = this;
      const slides = swiper.slides;
      // eslint-disable-next-line
      const minusOffset = swiper.isElement ? swiper.isHorizontal() ? swiper.wrapperEl.offsetLeft : swiper.wrapperEl.offsetTop : 0;
      for (let i = 0; i < slides.length; i += 1) {
        slides[i].swiperSlideOffset = (swiper.isHorizontal() ? slides[i].offsetLeft : slides[i].offsetTop) - minusOffset - swiper.cssOverflowAdjustment();
      }
    }

    function updateSlidesProgress(translate) {
      if (translate === void 0) {
        translate = this && this.translate || 0;
      }
      const swiper = this;
      const params = swiper.params;
      const {
        slides,
        rtlTranslate: rtl,
        snapGrid
      } = swiper;
      if (slides.length === 0) return;
      if (typeof slides[0].swiperSlideOffset === 'undefined') swiper.updateSlidesOffset();
      let offsetCenter = -translate;
      if (rtl) offsetCenter = translate;

      // Visible Slides
      slides.forEach(slideEl => {
        slideEl.classList.remove(params.slideVisibleClass);
      });
      swiper.visibleSlidesIndexes = [];
      swiper.visibleSlides = [];
      let spaceBetween = params.spaceBetween;
      if (typeof spaceBetween === 'string' && spaceBetween.indexOf('%') >= 0) {
        spaceBetween = parseFloat(spaceBetween.replace('%', '')) / 100 * swiper.size;
      } else if (typeof spaceBetween === 'string') {
        spaceBetween = parseFloat(spaceBetween);
      }
      for (let i = 0; i < slides.length; i += 1) {
        const slide = slides[i];
        let slideOffset = slide.swiperSlideOffset;
        if (params.cssMode && params.centeredSlides) {
          slideOffset -= slides[0].swiperSlideOffset;
        }
        const slideProgress = (offsetCenter + (params.centeredSlides ? swiper.minTranslate() : 0) - slideOffset) / (slide.swiperSlideSize + spaceBetween);
        const originalSlideProgress = (offsetCenter - snapGrid[0] + (params.centeredSlides ? swiper.minTranslate() : 0) - slideOffset) / (slide.swiperSlideSize + spaceBetween);
        const slideBefore = -(offsetCenter - slideOffset);
        const slideAfter = slideBefore + swiper.slidesSizesGrid[i];
        const isVisible = slideBefore >= 0 && slideBefore < swiper.size - 1 || slideAfter > 1 && slideAfter <= swiper.size || slideBefore <= 0 && slideAfter >= swiper.size;
        if (isVisible) {
          swiper.visibleSlides.push(slide);
          swiper.visibleSlidesIndexes.push(i);
          slides[i].classList.add(params.slideVisibleClass);
        }
        slide.progress = rtl ? -slideProgress : slideProgress;
        slide.originalProgress = rtl ? -originalSlideProgress : originalSlideProgress;
      }
    }

    function updateProgress(translate) {
      const swiper = this;
      if (typeof translate === 'undefined') {
        const multiplier = swiper.rtlTranslate ? -1 : 1;
        // eslint-disable-next-line
        translate = swiper && swiper.translate && swiper.translate * multiplier || 0;
      }
      const params = swiper.params;
      const translatesDiff = swiper.maxTranslate() - swiper.minTranslate();
      let {
        progress,
        isBeginning,
        isEnd,
        progressLoop
      } = swiper;
      const wasBeginning = isBeginning;
      const wasEnd = isEnd;
      if (translatesDiff === 0) {
        progress = 0;
        isBeginning = true;
        isEnd = true;
      } else {
        progress = (translate - swiper.minTranslate()) / translatesDiff;
        const isBeginningRounded = Math.abs(translate - swiper.minTranslate()) < 1;
        const isEndRounded = Math.abs(translate - swiper.maxTranslate()) < 1;
        isBeginning = isBeginningRounded || progress <= 0;
        isEnd = isEndRounded || progress >= 1;
        if (isBeginningRounded) progress = 0;
        if (isEndRounded) progress = 1;
      }
      if (params.loop) {
        const firstSlideIndex = swiper.getSlideIndexByData(0);
        const lastSlideIndex = swiper.getSlideIndexByData(swiper.slides.length - 1);
        const firstSlideTranslate = swiper.slidesGrid[firstSlideIndex];
        const lastSlideTranslate = swiper.slidesGrid[lastSlideIndex];
        const translateMax = swiper.slidesGrid[swiper.slidesGrid.length - 1];
        const translateAbs = Math.abs(translate);
        if (translateAbs >= firstSlideTranslate) {
          progressLoop = (translateAbs - firstSlideTranslate) / translateMax;
        } else {
          progressLoop = (translateAbs + translateMax - lastSlideTranslate) / translateMax;
        }
        if (progressLoop > 1) progressLoop -= 1;
      }
      Object.assign(swiper, {
        progress,
        progressLoop,
        isBeginning,
        isEnd
      });
      if (params.watchSlidesProgress || params.centeredSlides && params.autoHeight) swiper.updateSlidesProgress(translate);
      if (isBeginning && !wasBeginning) {
        swiper.emit('reachBeginning toEdge');
      }
      if (isEnd && !wasEnd) {
        swiper.emit('reachEnd toEdge');
      }
      if (wasBeginning && !isBeginning || wasEnd && !isEnd) {
        swiper.emit('fromEdge');
      }
      swiper.emit('progress', progress);
    }

    function updateSlidesClasses() {
      const swiper = this;
      const {
        slides,
        params,
        slidesEl,
        activeIndex
      } = swiper;
      const isVirtual = swiper.virtual && params.virtual.enabled;
      const getFilteredSlide = selector => {
        return elementChildren(slidesEl, `.${params.slideClass}${selector}, swiper-slide${selector}`)[0];
      };
      slides.forEach(slideEl => {
        slideEl.classList.remove(params.slideActiveClass, params.slideNextClass, params.slidePrevClass);
      });
      let activeSlide;
      if (isVirtual) {
        if (params.loop) {
          let slideIndex = activeIndex - swiper.virtual.slidesBefore;
          if (slideIndex < 0) slideIndex = swiper.virtual.slides.length + slideIndex;
          if (slideIndex >= swiper.virtual.slides.length) slideIndex -= swiper.virtual.slides.length;
          activeSlide = getFilteredSlide(`[data-swiper-slide-index="${slideIndex}"]`);
        } else {
          activeSlide = getFilteredSlide(`[data-swiper-slide-index="${activeIndex}"]`);
        }
      } else {
        activeSlide = slides[activeIndex];
      }
      if (activeSlide) {
        // Active classes
        activeSlide.classList.add(params.slideActiveClass);

        // Next Slide
        let nextSlide = elementNextAll(activeSlide, `.${params.slideClass}, swiper-slide`)[0];
        if (params.loop && !nextSlide) {
          nextSlide = slides[0];
        }
        if (nextSlide) {
          nextSlide.classList.add(params.slideNextClass);
        }
        // Prev Slide
        let prevSlide = elementPrevAll(activeSlide, `.${params.slideClass}, swiper-slide`)[0];
        if (params.loop && !prevSlide === 0) {
          prevSlide = slides[slides.length - 1];
        }
        if (prevSlide) {
          prevSlide.classList.add(params.slidePrevClass);
        }
      }
      swiper.emitSlidesClasses();
    }

    const processLazyPreloader = (swiper, imageEl) => {
      if (!swiper || swiper.destroyed || !swiper.params) return;
      const slideSelector = () => swiper.isElement ? `swiper-slide` : `.${swiper.params.slideClass}`;
      const slideEl = imageEl.closest(slideSelector());
      if (slideEl) {
        const lazyEl = slideEl.querySelector(`.${swiper.params.lazyPreloaderClass}`);
        if (lazyEl) lazyEl.remove();
      }
    };
    const unlazy = (swiper, index) => {
      if (!swiper.slides[index]) return;
      const imageEl = swiper.slides[index].querySelector('[loading="lazy"]');
      if (imageEl) imageEl.removeAttribute('loading');
    };
    const preload = swiper => {
      if (!swiper || swiper.destroyed || !swiper.params) return;
      let amount = swiper.params.lazyPreloadPrevNext;
      const len = swiper.slides.length;
      if (!len || !amount || amount < 0) return;
      amount = Math.min(amount, len);
      const slidesPerView = swiper.params.slidesPerView === 'auto' ? swiper.slidesPerViewDynamic() : Math.ceil(swiper.params.slidesPerView);
      const activeIndex = swiper.activeIndex;
      const slideIndexLastInView = activeIndex + slidesPerView - 1;
      if (swiper.params.rewind) {
        for (let i = activeIndex - amount; i <= slideIndexLastInView + amount; i += 1) {
          const realIndex = (i % len + len) % len;
          if (realIndex !== activeIndex && realIndex > slideIndexLastInView) unlazy(swiper, realIndex);
        }
      } else {
        for (let i = Math.max(slideIndexLastInView - amount, 0); i <= Math.min(slideIndexLastInView + amount, len - 1); i += 1) {
          if (i !== activeIndex && i > slideIndexLastInView) unlazy(swiper, i);
        }
      }
    };

    function getActiveIndexByTranslate(swiper) {
      const {
        slidesGrid,
        params
      } = swiper;
      const translate = swiper.rtlTranslate ? swiper.translate : -swiper.translate;
      let activeIndex;
      for (let i = 0; i < slidesGrid.length; i += 1) {
        if (typeof slidesGrid[i + 1] !== 'undefined') {
          if (translate >= slidesGrid[i] && translate < slidesGrid[i + 1] - (slidesGrid[i + 1] - slidesGrid[i]) / 2) {
            activeIndex = i;
          } else if (translate >= slidesGrid[i] && translate < slidesGrid[i + 1]) {
            activeIndex = i + 1;
          }
        } else if (translate >= slidesGrid[i]) {
          activeIndex = i;
        }
      }
      // Normalize slideIndex
      if (params.normalizeSlideIndex) {
        if (activeIndex < 0 || typeof activeIndex === 'undefined') activeIndex = 0;
      }
      return activeIndex;
    }
    function updateActiveIndex(newActiveIndex) {
      const swiper = this;
      const translate = swiper.rtlTranslate ? swiper.translate : -swiper.translate;
      const {
        snapGrid,
        params,
        activeIndex: previousIndex,
        realIndex: previousRealIndex,
        snapIndex: previousSnapIndex
      } = swiper;
      let activeIndex = newActiveIndex;
      let snapIndex;
      const getVirtualRealIndex = aIndex => {
        let realIndex = aIndex - swiper.virtual.slidesBefore;
        if (realIndex < 0) {
          realIndex = swiper.virtual.slides.length + realIndex;
        }
        if (realIndex >= swiper.virtual.slides.length) {
          realIndex -= swiper.virtual.slides.length;
        }
        return realIndex;
      };
      if (typeof activeIndex === 'undefined') {
        activeIndex = getActiveIndexByTranslate(swiper);
      }
      if (snapGrid.indexOf(translate) >= 0) {
        snapIndex = snapGrid.indexOf(translate);
      } else {
        const skip = Math.min(params.slidesPerGroupSkip, activeIndex);
        snapIndex = skip + Math.floor((activeIndex - skip) / params.slidesPerGroup);
      }
      if (snapIndex >= snapGrid.length) snapIndex = snapGrid.length - 1;
      if (activeIndex === previousIndex) {
        if (snapIndex !== previousSnapIndex) {
          swiper.snapIndex = snapIndex;
          swiper.emit('snapIndexChange');
        }
        if (swiper.params.loop && swiper.virtual && swiper.params.virtual.enabled) {
          swiper.realIndex = getVirtualRealIndex(activeIndex);
        }
        return;
      }
      // Get real index
      let realIndex;
      if (swiper.virtual && params.virtual.enabled && params.loop) {
        realIndex = getVirtualRealIndex(activeIndex);
      } else if (swiper.slides[activeIndex]) {
        realIndex = parseInt(swiper.slides[activeIndex].getAttribute('data-swiper-slide-index') || activeIndex, 10);
      } else {
        realIndex = activeIndex;
      }
      Object.assign(swiper, {
        previousSnapIndex,
        snapIndex,
        previousRealIndex,
        realIndex,
        previousIndex,
        activeIndex
      });
      if (swiper.initialized) {
        preload(swiper);
      }
      swiper.emit('activeIndexChange');
      swiper.emit('snapIndexChange');
      if (previousRealIndex !== realIndex) {
        swiper.emit('realIndexChange');
      }
      if (swiper.initialized || swiper.params.runCallbacksOnInit) {
        swiper.emit('slideChange');
      }
    }

    function updateClickedSlide(e) {
      const swiper = this;
      const params = swiper.params;
      const slide = e.closest(`.${params.slideClass}, swiper-slide`);
      let slideFound = false;
      let slideIndex;
      if (slide) {
        for (let i = 0; i < swiper.slides.length; i += 1) {
          if (swiper.slides[i] === slide) {
            slideFound = true;
            slideIndex = i;
            break;
          }
        }
      }
      if (slide && slideFound) {
        swiper.clickedSlide = slide;
        if (swiper.virtual && swiper.params.virtual.enabled) {
          swiper.clickedIndex = parseInt(slide.getAttribute('data-swiper-slide-index'), 10);
        } else {
          swiper.clickedIndex = slideIndex;
        }
      } else {
        swiper.clickedSlide = undefined;
        swiper.clickedIndex = undefined;
        return;
      }
      if (params.slideToClickedSlide && swiper.clickedIndex !== undefined && swiper.clickedIndex !== swiper.activeIndex) {
        swiper.slideToClickedSlide();
      }
    }

    var update = {
      updateSize,
      updateSlides,
      updateAutoHeight,
      updateSlidesOffset,
      updateSlidesProgress,
      updateProgress,
      updateSlidesClasses,
      updateActiveIndex,
      updateClickedSlide
    };

    function getSwiperTranslate(axis) {
      if (axis === void 0) {
        axis = this.isHorizontal() ? 'x' : 'y';
      }
      const swiper = this;
      const {
        params,
        rtlTranslate: rtl,
        translate,
        wrapperEl
      } = swiper;
      if (params.virtualTranslate) {
        return rtl ? -translate : translate;
      }
      if (params.cssMode) {
        return translate;
      }
      let currentTranslate = getTranslate(wrapperEl, axis);
      currentTranslate += swiper.cssOverflowAdjustment();
      if (rtl) currentTranslate = -currentTranslate;
      return currentTranslate || 0;
    }

    function setTranslate(translate, byController) {
      const swiper = this;
      const {
        rtlTranslate: rtl,
        params,
        wrapperEl,
        progress
      } = swiper;
      let x = 0;
      let y = 0;
      const z = 0;
      if (swiper.isHorizontal()) {
        x = rtl ? -translate : translate;
      } else {
        y = translate;
      }
      if (params.roundLengths) {
        x = Math.floor(x);
        y = Math.floor(y);
      }
      swiper.previousTranslate = swiper.translate;
      swiper.translate = swiper.isHorizontal() ? x : y;
      if (params.cssMode) {
        wrapperEl[swiper.isHorizontal() ? 'scrollLeft' : 'scrollTop'] = swiper.isHorizontal() ? -x : -y;
      } else if (!params.virtualTranslate) {
        if (swiper.isHorizontal()) {
          x -= swiper.cssOverflowAdjustment();
        } else {
          y -= swiper.cssOverflowAdjustment();
        }
        wrapperEl.style.transform = `translate3d(${x}px, ${y}px, ${z}px)`;
      }

      // Check if we need to update progress
      let newProgress;
      const translatesDiff = swiper.maxTranslate() - swiper.minTranslate();
      if (translatesDiff === 0) {
        newProgress = 0;
      } else {
        newProgress = (translate - swiper.minTranslate()) / translatesDiff;
      }
      if (newProgress !== progress) {
        swiper.updateProgress(translate);
      }
      swiper.emit('setTranslate', swiper.translate, byController);
    }

    function minTranslate() {
      return -this.snapGrid[0];
    }

    function maxTranslate() {
      return -this.snapGrid[this.snapGrid.length - 1];
    }

    function translateTo(translate, speed, runCallbacks, translateBounds, internal) {
      if (translate === void 0) {
        translate = 0;
      }
      if (speed === void 0) {
        speed = this.params.speed;
      }
      if (runCallbacks === void 0) {
        runCallbacks = true;
      }
      if (translateBounds === void 0) {
        translateBounds = true;
      }
      const swiper = this;
      const {
        params,
        wrapperEl
      } = swiper;
      if (swiper.animating && params.preventInteractionOnTransition) {
        return false;
      }
      const minTranslate = swiper.minTranslate();
      const maxTranslate = swiper.maxTranslate();
      let newTranslate;
      if (translateBounds && translate > minTranslate) newTranslate = minTranslate;else if (translateBounds && translate < maxTranslate) newTranslate = maxTranslate;else newTranslate = translate;

      // Update progress
      swiper.updateProgress(newTranslate);
      if (params.cssMode) {
        const isH = swiper.isHorizontal();
        if (speed === 0) {
          wrapperEl[isH ? 'scrollLeft' : 'scrollTop'] = -newTranslate;
        } else {
          if (!swiper.support.smoothScroll) {
            animateCSSModeScroll({
              swiper,
              targetPosition: -newTranslate,
              side: isH ? 'left' : 'top'
            });
            return true;
          }
          wrapperEl.scrollTo({
            [isH ? 'left' : 'top']: -newTranslate,
            behavior: 'smooth'
          });
        }
        return true;
      }
      if (speed === 0) {
        swiper.setTransition(0);
        swiper.setTranslate(newTranslate);
        if (runCallbacks) {
          swiper.emit('beforeTransitionStart', speed, internal);
          swiper.emit('transitionEnd');
        }
      } else {
        swiper.setTransition(speed);
        swiper.setTranslate(newTranslate);
        if (runCallbacks) {
          swiper.emit('beforeTransitionStart', speed, internal);
          swiper.emit('transitionStart');
        }
        if (!swiper.animating) {
          swiper.animating = true;
          if (!swiper.onTranslateToWrapperTransitionEnd) {
            swiper.onTranslateToWrapperTransitionEnd = function transitionEnd(e) {
              if (!swiper || swiper.destroyed) return;
              if (e.target !== this) return;
              swiper.wrapperEl.removeEventListener('transitionend', swiper.onTranslateToWrapperTransitionEnd);
              swiper.onTranslateToWrapperTransitionEnd = null;
              delete swiper.onTranslateToWrapperTransitionEnd;
              if (runCallbacks) {
                swiper.emit('transitionEnd');
              }
            };
          }
          swiper.wrapperEl.addEventListener('transitionend', swiper.onTranslateToWrapperTransitionEnd);
        }
      }
      return true;
    }

    var translate = {
      getTranslate: getSwiperTranslate,
      setTranslate,
      minTranslate,
      maxTranslate,
      translateTo
    };

    function setTransition(duration, byController) {
      const swiper = this;
      if (!swiper.params.cssMode) {
        swiper.wrapperEl.style.transitionDuration = `${duration}ms`;
      }
      swiper.emit('setTransition', duration, byController);
    }

    function transitionEmit(_ref) {
      let {
        swiper,
        runCallbacks,
        direction,
        step
      } = _ref;
      const {
        activeIndex,
        previousIndex
      } = swiper;
      let dir = direction;
      if (!dir) {
        if (activeIndex > previousIndex) dir = 'next';else if (activeIndex < previousIndex) dir = 'prev';else dir = 'reset';
      }
      swiper.emit(`transition${step}`);
      if (runCallbacks && activeIndex !== previousIndex) {
        if (dir === 'reset') {
          swiper.emit(`slideResetTransition${step}`);
          return;
        }
        swiper.emit(`slideChangeTransition${step}`);
        if (dir === 'next') {
          swiper.emit(`slideNextTransition${step}`);
        } else {
          swiper.emit(`slidePrevTransition${step}`);
        }
      }
    }

    function transitionStart(runCallbacks, direction) {
      if (runCallbacks === void 0) {
        runCallbacks = true;
      }
      const swiper = this;
      const {
        params
      } = swiper;
      if (params.cssMode) return;
      if (params.autoHeight) {
        swiper.updateAutoHeight();
      }
      transitionEmit({
        swiper,
        runCallbacks,
        direction,
        step: 'Start'
      });
    }

    function transitionEnd(runCallbacks, direction) {
      if (runCallbacks === void 0) {
        runCallbacks = true;
      }
      const swiper = this;
      const {
        params
      } = swiper;
      swiper.animating = false;
      if (params.cssMode) return;
      swiper.setTransition(0);
      transitionEmit({
        swiper,
        runCallbacks,
        direction,
        step: 'End'
      });
    }

    var transition = {
      setTransition,
      transitionStart,
      transitionEnd
    };

    function slideTo(index, speed, runCallbacks, internal, initial) {
      if (index === void 0) {
        index = 0;
      }
      if (speed === void 0) {
        speed = this.params.speed;
      }
      if (runCallbacks === void 0) {
        runCallbacks = true;
      }
      if (typeof index === 'string') {
        index = parseInt(index, 10);
      }
      const swiper = this;
      let slideIndex = index;
      if (slideIndex < 0) slideIndex = 0;
      const {
        params,
        snapGrid,
        slidesGrid,
        previousIndex,
        activeIndex,
        rtlTranslate: rtl,
        wrapperEl,
        enabled
      } = swiper;
      if (swiper.animating && params.preventInteractionOnTransition || !enabled && !internal && !initial) {
        return false;
      }
      const skip = Math.min(swiper.params.slidesPerGroupSkip, slideIndex);
      let snapIndex = skip + Math.floor((slideIndex - skip) / swiper.params.slidesPerGroup);
      if (snapIndex >= snapGrid.length) snapIndex = snapGrid.length - 1;
      const translate = -snapGrid[snapIndex];
      // Normalize slideIndex
      if (params.normalizeSlideIndex) {
        for (let i = 0; i < slidesGrid.length; i += 1) {
          const normalizedTranslate = -Math.floor(translate * 100);
          const normalizedGrid = Math.floor(slidesGrid[i] * 100);
          const normalizedGridNext = Math.floor(slidesGrid[i + 1] * 100);
          if (typeof slidesGrid[i + 1] !== 'undefined') {
            if (normalizedTranslate >= normalizedGrid && normalizedTranslate < normalizedGridNext - (normalizedGridNext - normalizedGrid) / 2) {
              slideIndex = i;
            } else if (normalizedTranslate >= normalizedGrid && normalizedTranslate < normalizedGridNext) {
              slideIndex = i + 1;
            }
          } else if (normalizedTranslate >= normalizedGrid) {
            slideIndex = i;
          }
        }
      }
      // Directions locks
      if (swiper.initialized && slideIndex !== activeIndex) {
        if (!swiper.allowSlideNext && translate < swiper.translate && translate < swiper.minTranslate()) {
          return false;
        }
        if (!swiper.allowSlidePrev && translate > swiper.translate && translate > swiper.maxTranslate()) {
          if ((activeIndex || 0) !== slideIndex) {
            return false;
          }
        }
      }
      if (slideIndex !== (previousIndex || 0) && runCallbacks) {
        swiper.emit('beforeSlideChangeStart');
      }

      // Update progress
      swiper.updateProgress(translate);
      let direction;
      if (slideIndex > activeIndex) direction = 'next';else if (slideIndex < activeIndex) direction = 'prev';else direction = 'reset';

      // Update Index
      if (rtl && -translate === swiper.translate || !rtl && translate === swiper.translate) {
        swiper.updateActiveIndex(slideIndex);
        // Update Height
        if (params.autoHeight) {
          swiper.updateAutoHeight();
        }
        swiper.updateSlidesClasses();
        if (params.effect !== 'slide') {
          swiper.setTranslate(translate);
        }
        if (direction !== 'reset') {
          swiper.transitionStart(runCallbacks, direction);
          swiper.transitionEnd(runCallbacks, direction);
        }
        return false;
      }
      if (params.cssMode) {
        const isH = swiper.isHorizontal();
        const t = rtl ? translate : -translate;
        if (speed === 0) {
          const isVirtual = swiper.virtual && swiper.params.virtual.enabled;
          if (isVirtual) {
            swiper.wrapperEl.style.scrollSnapType = 'none';
            swiper._immediateVirtual = true;
          }
          if (isVirtual && !swiper._cssModeVirtualInitialSet && swiper.params.initialSlide > 0) {
            swiper._cssModeVirtualInitialSet = true;
            requestAnimationFrame(() => {
              wrapperEl[isH ? 'scrollLeft' : 'scrollTop'] = t;
            });
          } else {
            wrapperEl[isH ? 'scrollLeft' : 'scrollTop'] = t;
          }
          if (isVirtual) {
            requestAnimationFrame(() => {
              swiper.wrapperEl.style.scrollSnapType = '';
              swiper._immediateVirtual = false;
            });
          }
        } else {
          if (!swiper.support.smoothScroll) {
            animateCSSModeScroll({
              swiper,
              targetPosition: t,
              side: isH ? 'left' : 'top'
            });
            return true;
          }
          wrapperEl.scrollTo({
            [isH ? 'left' : 'top']: t,
            behavior: 'smooth'
          });
        }
        return true;
      }
      swiper.setTransition(speed);
      swiper.setTranslate(translate);
      swiper.updateActiveIndex(slideIndex);
      swiper.updateSlidesClasses();
      swiper.emit('beforeTransitionStart', speed, internal);
      swiper.transitionStart(runCallbacks, direction);
      if (speed === 0) {
        swiper.transitionEnd(runCallbacks, direction);
      } else if (!swiper.animating) {
        swiper.animating = true;
        if (!swiper.onSlideToWrapperTransitionEnd) {
          swiper.onSlideToWrapperTransitionEnd = function transitionEnd(e) {
            if (!swiper || swiper.destroyed) return;
            if (e.target !== this) return;
            swiper.wrapperEl.removeEventListener('transitionend', swiper.onSlideToWrapperTransitionEnd);
            swiper.onSlideToWrapperTransitionEnd = null;
            delete swiper.onSlideToWrapperTransitionEnd;
            swiper.transitionEnd(runCallbacks, direction);
          };
        }
        swiper.wrapperEl.addEventListener('transitionend', swiper.onSlideToWrapperTransitionEnd);
      }
      return true;
    }

    function slideToLoop(index, speed, runCallbacks, internal) {
      if (index === void 0) {
        index = 0;
      }
      if (speed === void 0) {
        speed = this.params.speed;
      }
      if (runCallbacks === void 0) {
        runCallbacks = true;
      }
      if (typeof index === 'string') {
        const indexAsNumber = parseInt(index, 10);
        index = indexAsNumber;
      }
      const swiper = this;
      let newIndex = index;
      if (swiper.params.loop) {
        if (swiper.virtual && swiper.params.virtual.enabled) {
          // eslint-disable-next-line
          newIndex = newIndex + swiper.virtual.slidesBefore;
        } else {
          newIndex = swiper.getSlideIndexByData(newIndex);
        }
      }
      return swiper.slideTo(newIndex, speed, runCallbacks, internal);
    }

    /* eslint no-unused-vars: "off" */
    function slideNext(speed, runCallbacks, internal) {
      if (speed === void 0) {
        speed = this.params.speed;
      }
      if (runCallbacks === void 0) {
        runCallbacks = true;
      }
      const swiper = this;
      const {
        enabled,
        params,
        animating
      } = swiper;
      if (!enabled) return swiper;
      let perGroup = params.slidesPerGroup;
      if (params.slidesPerView === 'auto' && params.slidesPerGroup === 1 && params.slidesPerGroupAuto) {
        perGroup = Math.max(swiper.slidesPerViewDynamic('current', true), 1);
      }
      const increment = swiper.activeIndex < params.slidesPerGroupSkip ? 1 : perGroup;
      const isVirtual = swiper.virtual && params.virtual.enabled;
      if (params.loop) {
        if (animating && !isVirtual && params.loopPreventsSliding) return false;
        swiper.loopFix({
          direction: 'next'
        });
        // eslint-disable-next-line
        swiper._clientLeft = swiper.wrapperEl.clientLeft;
      }
      if (params.rewind && swiper.isEnd) {
        return swiper.slideTo(0, speed, runCallbacks, internal);
      }
      return swiper.slideTo(swiper.activeIndex + increment, speed, runCallbacks, internal);
    }

    /* eslint no-unused-vars: "off" */
    function slidePrev(speed, runCallbacks, internal) {
      if (speed === void 0) {
        speed = this.params.speed;
      }
      if (runCallbacks === void 0) {
        runCallbacks = true;
      }
      const swiper = this;
      const {
        params,
        snapGrid,
        slidesGrid,
        rtlTranslate,
        enabled,
        animating
      } = swiper;
      if (!enabled) return swiper;
      const isVirtual = swiper.virtual && params.virtual.enabled;
      if (params.loop) {
        if (animating && !isVirtual && params.loopPreventsSliding) return false;
        swiper.loopFix({
          direction: 'prev'
        });
        // eslint-disable-next-line
        swiper._clientLeft = swiper.wrapperEl.clientLeft;
      }
      const translate = rtlTranslate ? swiper.translate : -swiper.translate;
      function normalize(val) {
        if (val < 0) return -Math.floor(Math.abs(val));
        return Math.floor(val);
      }
      const normalizedTranslate = normalize(translate);
      const normalizedSnapGrid = snapGrid.map(val => normalize(val));
      let prevSnap = snapGrid[normalizedSnapGrid.indexOf(normalizedTranslate) - 1];
      if (typeof prevSnap === 'undefined' && params.cssMode) {
        let prevSnapIndex;
        snapGrid.forEach((snap, snapIndex) => {
          if (normalizedTranslate >= snap) {
            // prevSnap = snap;
            prevSnapIndex = snapIndex;
          }
        });
        if (typeof prevSnapIndex !== 'undefined') {
          prevSnap = snapGrid[prevSnapIndex > 0 ? prevSnapIndex - 1 : prevSnapIndex];
        }
      }
      let prevIndex = 0;
      if (typeof prevSnap !== 'undefined') {
        prevIndex = slidesGrid.indexOf(prevSnap);
        if (prevIndex < 0) prevIndex = swiper.activeIndex - 1;
        if (params.slidesPerView === 'auto' && params.slidesPerGroup === 1 && params.slidesPerGroupAuto) {
          prevIndex = prevIndex - swiper.slidesPerViewDynamic('previous', true) + 1;
          prevIndex = Math.max(prevIndex, 0);
        }
      }
      if (params.rewind && swiper.isBeginning) {
        const lastIndex = swiper.params.virtual && swiper.params.virtual.enabled && swiper.virtual ? swiper.virtual.slides.length - 1 : swiper.slides.length - 1;
        return swiper.slideTo(lastIndex, speed, runCallbacks, internal);
      }
      return swiper.slideTo(prevIndex, speed, runCallbacks, internal);
    }

    /* eslint no-unused-vars: "off" */
    function slideReset(speed, runCallbacks, internal) {
      if (speed === void 0) {
        speed = this.params.speed;
      }
      if (runCallbacks === void 0) {
        runCallbacks = true;
      }
      const swiper = this;
      return swiper.slideTo(swiper.activeIndex, speed, runCallbacks, internal);
    }

    /* eslint no-unused-vars: "off" */
    function slideToClosest(speed, runCallbacks, internal, threshold) {
      if (speed === void 0) {
        speed = this.params.speed;
      }
      if (runCallbacks === void 0) {
        runCallbacks = true;
      }
      if (threshold === void 0) {
        threshold = 0.5;
      }
      const swiper = this;
      let index = swiper.activeIndex;
      const skip = Math.min(swiper.params.slidesPerGroupSkip, index);
      const snapIndex = skip + Math.floor((index - skip) / swiper.params.slidesPerGroup);
      const translate = swiper.rtlTranslate ? swiper.translate : -swiper.translate;
      if (translate >= swiper.snapGrid[snapIndex]) {
        // The current translate is on or after the current snap index, so the choice
        // is between the current index and the one after it.
        const currentSnap = swiper.snapGrid[snapIndex];
        const nextSnap = swiper.snapGrid[snapIndex + 1];
        if (translate - currentSnap > (nextSnap - currentSnap) * threshold) {
          index += swiper.params.slidesPerGroup;
        }
      } else {
        // The current translate is before the current snap index, so the choice
        // is between the current index and the one before it.
        const prevSnap = swiper.snapGrid[snapIndex - 1];
        const currentSnap = swiper.snapGrid[snapIndex];
        if (translate - prevSnap <= (currentSnap - prevSnap) * threshold) {
          index -= swiper.params.slidesPerGroup;
        }
      }
      index = Math.max(index, 0);
      index = Math.min(index, swiper.slidesGrid.length - 1);
      return swiper.slideTo(index, speed, runCallbacks, internal);
    }

    function slideToClickedSlide() {
      const swiper = this;
      const {
        params,
        slidesEl
      } = swiper;
      const slidesPerView = params.slidesPerView === 'auto' ? swiper.slidesPerViewDynamic() : params.slidesPerView;
      let slideToIndex = swiper.clickedIndex;
      let realIndex;
      const slideSelector = swiper.isElement ? `swiper-slide` : `.${params.slideClass}`;
      if (params.loop) {
        if (swiper.animating) return;
        realIndex = parseInt(swiper.clickedSlide.getAttribute('data-swiper-slide-index'), 10);
        if (params.centeredSlides) {
          if (slideToIndex < swiper.loopedSlides - slidesPerView / 2 || slideToIndex > swiper.slides.length - swiper.loopedSlides + slidesPerView / 2) {
            swiper.loopFix();
            slideToIndex = swiper.getSlideIndex(elementChildren(slidesEl, `${slideSelector}[data-swiper-slide-index="${realIndex}"]`)[0]);
            nextTick(() => {
              swiper.slideTo(slideToIndex);
            });
          } else {
            swiper.slideTo(slideToIndex);
          }
        } else if (slideToIndex > swiper.slides.length - slidesPerView) {
          swiper.loopFix();
          slideToIndex = swiper.getSlideIndex(elementChildren(slidesEl, `${slideSelector}[data-swiper-slide-index="${realIndex}"]`)[0]);
          nextTick(() => {
            swiper.slideTo(slideToIndex);
          });
        } else {
          swiper.slideTo(slideToIndex);
        }
      } else {
        swiper.slideTo(slideToIndex);
      }
    }

    var slide = {
      slideTo,
      slideToLoop,
      slideNext,
      slidePrev,
      slideReset,
      slideToClosest,
      slideToClickedSlide
    };

    function loopCreate(slideRealIndex) {
      const swiper = this;
      const {
        params,
        slidesEl
      } = swiper;
      if (!params.loop || swiper.virtual && swiper.params.virtual.enabled) return;
      const slides = elementChildren(slidesEl, `.${params.slideClass}, swiper-slide`);
      slides.forEach((el, index) => {
        el.setAttribute('data-swiper-slide-index', index);
      });
      swiper.loopFix({
        slideRealIndex,
        direction: params.centeredSlides ? undefined : 'next'
      });
    }

    function loopFix(_temp) {
      let {
        slideRealIndex,
        slideTo = true,
        direction,
        setTranslate,
        activeSlideIndex,
        byController,
        byMousewheel
      } = _temp === void 0 ? {} : _temp;
      const swiper = this;
      if (!swiper.params.loop) return;
      swiper.emit('beforeLoopFix');
      const {
        slides,
        allowSlidePrev,
        allowSlideNext,
        slidesEl,
        params
      } = swiper;
      swiper.allowSlidePrev = true;
      swiper.allowSlideNext = true;
      if (swiper.virtual && params.virtual.enabled) {
        if (slideTo) {
          if (!params.centeredSlides && swiper.snapIndex === 0) {
            swiper.slideTo(swiper.virtual.slides.length, 0, false, true);
          } else if (params.centeredSlides && swiper.snapIndex < params.slidesPerView) {
            swiper.slideTo(swiper.virtual.slides.length + swiper.snapIndex, 0, false, true);
          } else if (swiper.snapIndex === swiper.snapGrid.length - 1) {
            swiper.slideTo(swiper.virtual.slidesBefore, 0, false, true);
          }
        }
        swiper.allowSlidePrev = allowSlidePrev;
        swiper.allowSlideNext = allowSlideNext;
        swiper.emit('loopFix');
        return;
      }
      const slidesPerView = params.slidesPerView === 'auto' ? swiper.slidesPerViewDynamic() : Math.ceil(parseFloat(params.slidesPerView, 10));
      let loopedSlides = params.loopedSlides || slidesPerView;
      if (loopedSlides % params.slidesPerGroup !== 0) {
        loopedSlides += params.slidesPerGroup - loopedSlides % params.slidesPerGroup;
      }
      swiper.loopedSlides = loopedSlides;
      const prependSlidesIndexes = [];
      const appendSlidesIndexes = [];
      let activeIndex = swiper.activeIndex;
      if (typeof activeSlideIndex === 'undefined') {
        activeSlideIndex = swiper.getSlideIndex(swiper.slides.filter(el => el.classList.contains(params.slideActiveClass))[0]);
      } else {
        activeIndex = activeSlideIndex;
      }
      const isNext = direction === 'next' || !direction;
      const isPrev = direction === 'prev' || !direction;
      let slidesPrepended = 0;
      let slidesAppended = 0;
      // prepend last slides before start
      if (activeSlideIndex < loopedSlides) {
        slidesPrepended = Math.max(loopedSlides - activeSlideIndex, params.slidesPerGroup);
        for (let i = 0; i < loopedSlides - activeSlideIndex; i += 1) {
          const index = i - Math.floor(i / slides.length) * slides.length;
          prependSlidesIndexes.push(slides.length - index - 1);
        }
      } else if (activeSlideIndex /* + slidesPerView */ > swiper.slides.length - loopedSlides * 2) {
        slidesAppended = Math.max(activeSlideIndex - (swiper.slides.length - loopedSlides * 2), params.slidesPerGroup);
        for (let i = 0; i < slidesAppended; i += 1) {
          const index = i - Math.floor(i / slides.length) * slides.length;
          appendSlidesIndexes.push(index);
        }
      }
      if (isPrev) {
        prependSlidesIndexes.forEach(index => {
          swiper.slides[index].swiperLoopMoveDOM = true;
          slidesEl.prepend(swiper.slides[index]);
          swiper.slides[index].swiperLoopMoveDOM = false;
        });
      }
      if (isNext) {
        appendSlidesIndexes.forEach(index => {
          swiper.slides[index].swiperLoopMoveDOM = true;
          slidesEl.append(swiper.slides[index]);
          swiper.slides[index].swiperLoopMoveDOM = false;
        });
      }
      swiper.recalcSlides();
      if (params.slidesPerView === 'auto') {
        swiper.updateSlides();
      }
      if (params.watchSlidesProgress) {
        swiper.updateSlidesOffset();
      }
      if (slideTo) {
        if (prependSlidesIndexes.length > 0 && isPrev) {
          if (typeof slideRealIndex === 'undefined') {
            const currentSlideTranslate = swiper.slidesGrid[activeIndex];
            const newSlideTranslate = swiper.slidesGrid[activeIndex + slidesPrepended];
            const diff = newSlideTranslate - currentSlideTranslate;
            if (byMousewheel) {
              swiper.setTranslate(swiper.translate - diff);
            } else {
              swiper.slideTo(activeIndex + slidesPrepended, 0, false, true);
              if (setTranslate) {
                swiper.touches[swiper.isHorizontal() ? 'startX' : 'startY'] += diff;
              }
            }
          } else {
            if (setTranslate) {
              swiper.slideToLoop(slideRealIndex, 0, false, true);
            }
          }
        } else if (appendSlidesIndexes.length > 0 && isNext) {
          if (typeof slideRealIndex === 'undefined') {
            const currentSlideTranslate = swiper.slidesGrid[activeIndex];
            const newSlideTranslate = swiper.slidesGrid[activeIndex - slidesAppended];
            const diff = newSlideTranslate - currentSlideTranslate;
            if (byMousewheel) {
              swiper.setTranslate(swiper.translate - diff);
            } else {
              swiper.slideTo(activeIndex - slidesAppended, 0, false, true);
              if (setTranslate) {
                swiper.touches[swiper.isHorizontal() ? 'startX' : 'startY'] += diff;
              }
            }
          } else {
            swiper.slideToLoop(slideRealIndex, 0, false, true);
          }
        }
      }
      swiper.allowSlidePrev = allowSlidePrev;
      swiper.allowSlideNext = allowSlideNext;
      if (swiper.controller && swiper.controller.control && !byController) {
        const loopParams = {
          slideRealIndex,
          slideTo: false,
          direction,
          setTranslate,
          activeSlideIndex,
          byController: true
        };
        if (Array.isArray(swiper.controller.control)) {
          swiper.controller.control.forEach(c => {
            if (!c.destroyed && c.params.loop) c.loopFix(loopParams);
          });
        } else if (swiper.controller.control instanceof swiper.constructor && swiper.controller.control.params.loop) {
          swiper.controller.control.loopFix(loopParams);
        }
      }
      swiper.emit('loopFix');
    }

    function loopDestroy() {
      const swiper = this;
      const {
        params,
        slidesEl
      } = swiper;
      if (!params.loop || swiper.virtual && swiper.params.virtual.enabled) return;
      swiper.recalcSlides();
      const newSlidesOrder = [];
      swiper.slides.forEach(slideEl => {
        const index = typeof slideEl.swiperSlideIndex === 'undefined' ? slideEl.getAttribute('data-swiper-slide-index') * 1 : slideEl.swiperSlideIndex;
        newSlidesOrder[index] = slideEl;
      });
      swiper.slides.forEach(slideEl => {
        slideEl.removeAttribute('data-swiper-slide-index');
      });
      newSlidesOrder.forEach(slideEl => {
        slidesEl.append(slideEl);
      });
      swiper.recalcSlides();
      swiper.slideTo(swiper.realIndex, 0);
    }

    var loop = {
      loopCreate,
      loopFix,
      loopDestroy
    };

    function setGrabCursor(moving) {
      const swiper = this;
      if (!swiper.params.simulateTouch || swiper.params.watchOverflow && swiper.isLocked || swiper.params.cssMode) return;
      const el = swiper.params.touchEventsTarget === 'container' ? swiper.el : swiper.wrapperEl;
      if (swiper.isElement) {
        swiper.__preventObserver__ = true;
      }
      el.style.cursor = 'move';
      el.style.cursor = moving ? 'grabbing' : 'grab';
      if (swiper.isElement) {
        requestAnimationFrame(() => {
          swiper.__preventObserver__ = false;
        });
      }
    }

    function unsetGrabCursor() {
      const swiper = this;
      if (swiper.params.watchOverflow && swiper.isLocked || swiper.params.cssMode) {
        return;
      }
      if (swiper.isElement) {
        swiper.__preventObserver__ = true;
      }
      swiper[swiper.params.touchEventsTarget === 'container' ? 'el' : 'wrapperEl'].style.cursor = '';
      if (swiper.isElement) {
        requestAnimationFrame(() => {
          swiper.__preventObserver__ = false;
        });
      }
    }

    var grabCursor = {
      setGrabCursor,
      unsetGrabCursor
    };

    // Modified from https://stackoverflow.com/questions/54520554/custom-element-getrootnode-closest-function-crossing-multiple-parent-shadowd
    function closestElement(selector, base) {
      if (base === void 0) {
        base = this;
      }
      function __closestFrom(el) {
        if (!el || el === getDocument() || el === getWindow()) return null;
        if (el.assignedSlot) el = el.assignedSlot;
        const found = el.closest(selector);
        if (!found && !el.getRootNode) {
          return null;
        }
        return found || __closestFrom(el.getRootNode().host);
      }
      return __closestFrom(base);
    }
    function onTouchStart(event) {
      const swiper = this;
      const document = getDocument();
      const window = getWindow();
      const data = swiper.touchEventsData;
      data.evCache.push(event);
      const {
        params,
        touches,
        enabled
      } = swiper;
      if (!enabled) return;
      if (!params.simulateTouch && event.pointerType === 'mouse') return;
      if (swiper.animating && params.preventInteractionOnTransition) {
        return;
      }
      if (!swiper.animating && params.cssMode && params.loop) {
        swiper.loopFix();
      }
      let e = event;
      if (e.originalEvent) e = e.originalEvent;
      let targetEl = e.target;
      if (params.touchEventsTarget === 'wrapper') {
        if (!swiper.wrapperEl.contains(targetEl)) return;
      }
      if ('which' in e && e.which === 3) return;
      if ('button' in e && e.button > 0) return;
      if (data.isTouched && data.isMoved) return;

      // change target el for shadow root component
      const swipingClassHasValue = !!params.noSwipingClass && params.noSwipingClass !== '';
      // eslint-disable-next-line
      const eventPath = event.composedPath ? event.composedPath() : event.path;
      if (swipingClassHasValue && e.target && e.target.shadowRoot && eventPath) {
        targetEl = eventPath[0];
      }
      const noSwipingSelector = params.noSwipingSelector ? params.noSwipingSelector : `.${params.noSwipingClass}`;
      const isTargetShadow = !!(e.target && e.target.shadowRoot);

      // use closestElement for shadow root element to get the actual closest for nested shadow root element
      if (params.noSwiping && (isTargetShadow ? closestElement(noSwipingSelector, targetEl) : targetEl.closest(noSwipingSelector))) {
        swiper.allowClick = true;
        return;
      }
      if (params.swipeHandler) {
        if (!targetEl.closest(params.swipeHandler)) return;
      }
      touches.currentX = e.pageX;
      touches.currentY = e.pageY;
      const startX = touches.currentX;
      const startY = touches.currentY;

      // Do NOT start if iOS edge swipe is detected. Otherwise iOS app cannot swipe-to-go-back anymore

      const edgeSwipeDetection = params.edgeSwipeDetection || params.iOSEdgeSwipeDetection;
      const edgeSwipeThreshold = params.edgeSwipeThreshold || params.iOSEdgeSwipeThreshold;
      if (edgeSwipeDetection && (startX <= edgeSwipeThreshold || startX >= window.innerWidth - edgeSwipeThreshold)) {
        if (edgeSwipeDetection === 'prevent') {
          event.preventDefault();
        } else {
          return;
        }
      }
      Object.assign(data, {
        isTouched: true,
        isMoved: false,
        allowTouchCallbacks: true,
        isScrolling: undefined,
        startMoving: undefined
      });
      touches.startX = startX;
      touches.startY = startY;
      data.touchStartTime = now();
      swiper.allowClick = true;
      swiper.updateSize();
      swiper.swipeDirection = undefined;
      if (params.threshold > 0) data.allowThresholdMove = false;
      let preventDefault = true;
      if (targetEl.matches(data.focusableElements)) {
        preventDefault = false;
        if (targetEl.nodeName === 'SELECT') {
          data.isTouched = false;
        }
      }
      if (document.activeElement && document.activeElement.matches(data.focusableElements) && document.activeElement !== targetEl) {
        document.activeElement.blur();
      }
      const shouldPreventDefault = preventDefault && swiper.allowTouchMove && params.touchStartPreventDefault;
      if ((params.touchStartForcePreventDefault || shouldPreventDefault) && !targetEl.isContentEditable) {
        e.preventDefault();
      }
      if (swiper.params.freeMode && swiper.params.freeMode.enabled && swiper.freeMode && swiper.animating && !params.cssMode) {
        swiper.freeMode.onTouchStart();
      }
      swiper.emit('touchStart', e);
    }

    function onTouchMove(event) {
      const document = getDocument();
      const swiper = this;
      const data = swiper.touchEventsData;
      const {
        params,
        touches,
        rtlTranslate: rtl,
        enabled
      } = swiper;
      if (!enabled) return;
      if (!params.simulateTouch && event.pointerType === 'mouse') return;
      let e = event;
      if (e.originalEvent) e = e.originalEvent;
      if (!data.isTouched) {
        if (data.startMoving && data.isScrolling) {
          swiper.emit('touchMoveOpposite', e);
        }
        return;
      }
      const pointerIndex = data.evCache.findIndex(cachedEv => cachedEv.pointerId === e.pointerId);
      if (pointerIndex >= 0) data.evCache[pointerIndex] = e;
      const targetTouch = data.evCache.length > 1 ? data.evCache[0] : e;
      const pageX = targetTouch.pageX;
      const pageY = targetTouch.pageY;
      if (e.preventedByNestedSwiper) {
        touches.startX = pageX;
        touches.startY = pageY;
        return;
      }
      if (!swiper.allowTouchMove) {
        if (!e.target.matches(data.focusableElements)) {
          swiper.allowClick = false;
        }
        if (data.isTouched) {
          Object.assign(touches, {
            startX: pageX,
            startY: pageY,
            prevX: swiper.touches.currentX,
            prevY: swiper.touches.currentY,
            currentX: pageX,
            currentY: pageY
          });
          data.touchStartTime = now();
        }
        return;
      }
      if (params.touchReleaseOnEdges && !params.loop) {
        if (swiper.isVertical()) {
          // Vertical
          if (pageY < touches.startY && swiper.translate <= swiper.maxTranslate() || pageY > touches.startY && swiper.translate >= swiper.minTranslate()) {
            data.isTouched = false;
            data.isMoved = false;
            return;
          }
        } else if (pageX < touches.startX && swiper.translate <= swiper.maxTranslate() || pageX > touches.startX && swiper.translate >= swiper.minTranslate()) {
          return;
        }
      }
      if (document.activeElement) {
        if (e.target === document.activeElement && e.target.matches(data.focusableElements)) {
          data.isMoved = true;
          swiper.allowClick = false;
          return;
        }
      }
      if (data.allowTouchCallbacks) {
        swiper.emit('touchMove', e);
      }
      if (e.targetTouches && e.targetTouches.length > 1) return;
      touches.currentX = pageX;
      touches.currentY = pageY;
      const diffX = touches.currentX - touches.startX;
      const diffY = touches.currentY - touches.startY;
      if (swiper.params.threshold && Math.sqrt(diffX ** 2 + diffY ** 2) < swiper.params.threshold) return;
      if (typeof data.isScrolling === 'undefined') {
        let touchAngle;
        if (swiper.isHorizontal() && touches.currentY === touches.startY || swiper.isVertical() && touches.currentX === touches.startX) {
          data.isScrolling = false;
        } else {
          // eslint-disable-next-line
          if (diffX * diffX + diffY * diffY >= 25) {
            touchAngle = Math.atan2(Math.abs(diffY), Math.abs(diffX)) * 180 / Math.PI;
            data.isScrolling = swiper.isHorizontal() ? touchAngle > params.touchAngle : 90 - touchAngle > params.touchAngle;
          }
        }
      }
      if (data.isScrolling) {
        swiper.emit('touchMoveOpposite', e);
      }
      if (typeof data.startMoving === 'undefined') {
        if (touches.currentX !== touches.startX || touches.currentY !== touches.startY) {
          data.startMoving = true;
        }
      }
      if (data.isScrolling || swiper.zoom && swiper.params.zoom && swiper.params.zoom.enabled && data.evCache.length > 1) {
        data.isTouched = false;
        return;
      }
      if (!data.startMoving) {
        return;
      }
      swiper.allowClick = false;
      if (!params.cssMode && e.cancelable) {
        e.preventDefault();
      }
      if (params.touchMoveStopPropagation && !params.nested) {
        e.stopPropagation();
      }
      let diff = swiper.isHorizontal() ? diffX : diffY;
      let touchesDiff = swiper.isHorizontal() ? touches.currentX - touches.previousX : touches.currentY - touches.previousY;
      if (params.oneWayMovement) {
        diff = Math.abs(diff) * (rtl ? 1 : -1);
        touchesDiff = Math.abs(touchesDiff) * (rtl ? 1 : -1);
      }
      touches.diff = diff;
      diff *= params.touchRatio;
      if (rtl) {
        diff = -diff;
        touchesDiff = -touchesDiff;
      }
      const prevTouchesDirection = swiper.touchesDirection;
      swiper.swipeDirection = diff > 0 ? 'prev' : 'next';
      swiper.touchesDirection = touchesDiff > 0 ? 'prev' : 'next';
      const isLoop = swiper.params.loop && !params.cssMode;
      if (!data.isMoved) {
        if (isLoop) {
          swiper.loopFix({
            direction: swiper.swipeDirection
          });
        }
        data.startTranslate = swiper.getTranslate();
        swiper.setTransition(0);
        if (swiper.animating) {
          const evt = new window.CustomEvent('transitionend', {
            bubbles: true,
            cancelable: true
          });
          swiper.wrapperEl.dispatchEvent(evt);
        }
        data.allowMomentumBounce = false;
        // Grab Cursor
        if (params.grabCursor && (swiper.allowSlideNext === true || swiper.allowSlidePrev === true)) {
          swiper.setGrabCursor(true);
        }
        swiper.emit('sliderFirstMove', e);
      }
      let loopFixed;
      if (data.isMoved && prevTouchesDirection !== swiper.touchesDirection && isLoop && Math.abs(diff) >= 1) {
        // need another loop fix
        swiper.loopFix({
          direction: swiper.swipeDirection,
          setTranslate: true
        });
        loopFixed = true;
      }
      swiper.emit('sliderMove', e);
      data.isMoved = true;
      data.currentTranslate = diff + data.startTranslate;
      let disableParentSwiper = true;
      let resistanceRatio = params.resistanceRatio;
      if (params.touchReleaseOnEdges) {
        resistanceRatio = 0;
      }
      if (diff > 0) {
        if (isLoop && !loopFixed && data.currentTranslate > (params.centeredSlides ? swiper.minTranslate() - swiper.size / 2 : swiper.minTranslate())) {
          swiper.loopFix({
            direction: 'prev',
            setTranslate: true,
            activeSlideIndex: 0
          });
        }
        if (data.currentTranslate > swiper.minTranslate()) {
          disableParentSwiper = false;
          if (params.resistance) {
            data.currentTranslate = swiper.minTranslate() - 1 + (-swiper.minTranslate() + data.startTranslate + diff) ** resistanceRatio;
          }
        }
      } else if (diff < 0) {
        if (isLoop && !loopFixed && data.currentTranslate < (params.centeredSlides ? swiper.maxTranslate() + swiper.size / 2 : swiper.maxTranslate())) {
          swiper.loopFix({
            direction: 'next',
            setTranslate: true,
            activeSlideIndex: swiper.slides.length - (params.slidesPerView === 'auto' ? swiper.slidesPerViewDynamic() : Math.ceil(parseFloat(params.slidesPerView, 10)))
          });
        }
        if (data.currentTranslate < swiper.maxTranslate()) {
          disableParentSwiper = false;
          if (params.resistance) {
            data.currentTranslate = swiper.maxTranslate() + 1 - (swiper.maxTranslate() - data.startTranslate - diff) ** resistanceRatio;
          }
        }
      }
      if (disableParentSwiper) {
        e.preventedByNestedSwiper = true;
      }

      // Directions locks
      if (!swiper.allowSlideNext && swiper.swipeDirection === 'next' && data.currentTranslate < data.startTranslate) {
        data.currentTranslate = data.startTranslate;
      }
      if (!swiper.allowSlidePrev && swiper.swipeDirection === 'prev' && data.currentTranslate > data.startTranslate) {
        data.currentTranslate = data.startTranslate;
      }
      if (!swiper.allowSlidePrev && !swiper.allowSlideNext) {
        data.currentTranslate = data.startTranslate;
      }

      // Threshold
      if (params.threshold > 0) {
        if (Math.abs(diff) > params.threshold || data.allowThresholdMove) {
          if (!data.allowThresholdMove) {
            data.allowThresholdMove = true;
            touches.startX = touches.currentX;
            touches.startY = touches.currentY;
            data.currentTranslate = data.startTranslate;
            touches.diff = swiper.isHorizontal() ? touches.currentX - touches.startX : touches.currentY - touches.startY;
            return;
          }
        } else {
          data.currentTranslate = data.startTranslate;
          return;
        }
      }
      if (!params.followFinger || params.cssMode) return;

      // Update active index in free mode
      if (params.freeMode && params.freeMode.enabled && swiper.freeMode || params.watchSlidesProgress) {
        swiper.updateActiveIndex();
        swiper.updateSlidesClasses();
      }
      if (swiper.params.freeMode && params.freeMode.enabled && swiper.freeMode) {
        swiper.freeMode.onTouchMove();
      }
      // Update progress
      swiper.updateProgress(data.currentTranslate);
      // Update translate
      swiper.setTranslate(data.currentTranslate);
    }

    function onTouchEnd(event) {
      const swiper = this;
      const data = swiper.touchEventsData;
      const pointerIndex = data.evCache.findIndex(cachedEv => cachedEv.pointerId === event.pointerId);
      if (pointerIndex >= 0) {
        data.evCache.splice(pointerIndex, 1);
      }
      if (['pointercancel', 'pointerout', 'pointerleave'].includes(event.type)) {
        const proceed = event.type === 'pointercancel' && (swiper.browser.isSafari || swiper.browser.isWebView);
        if (!proceed) {
          return;
        }
      }
      const {
        params,
        touches,
        rtlTranslate: rtl,
        slidesGrid,
        enabled
      } = swiper;
      if (!enabled) return;
      if (!params.simulateTouch && event.pointerType === 'mouse') return;
      let e = event;
      if (e.originalEvent) e = e.originalEvent;
      if (data.allowTouchCallbacks) {
        swiper.emit('touchEnd', e);
      }
      data.allowTouchCallbacks = false;
      if (!data.isTouched) {
        if (data.isMoved && params.grabCursor) {
          swiper.setGrabCursor(false);
        }
        data.isMoved = false;
        data.startMoving = false;
        return;
      }
      // Return Grab Cursor
      if (params.grabCursor && data.isMoved && data.isTouched && (swiper.allowSlideNext === true || swiper.allowSlidePrev === true)) {
        swiper.setGrabCursor(false);
      }

      // Time diff
      const touchEndTime = now();
      const timeDiff = touchEndTime - data.touchStartTime;

      // Tap, doubleTap, Click
      if (swiper.allowClick) {
        const pathTree = e.path || e.composedPath && e.composedPath();
        swiper.updateClickedSlide(pathTree && pathTree[0] || e.target);
        swiper.emit('tap click', e);
        if (timeDiff < 300 && touchEndTime - data.lastClickTime < 300) {
          swiper.emit('doubleTap doubleClick', e);
        }
      }
      data.lastClickTime = now();
      nextTick(() => {
        if (!swiper.destroyed) swiper.allowClick = true;
      });
      if (!data.isTouched || !data.isMoved || !swiper.swipeDirection || touches.diff === 0 || data.currentTranslate === data.startTranslate) {
        data.isTouched = false;
        data.isMoved = false;
        data.startMoving = false;
        return;
      }
      data.isTouched = false;
      data.isMoved = false;
      data.startMoving = false;
      let currentPos;
      if (params.followFinger) {
        currentPos = rtl ? swiper.translate : -swiper.translate;
      } else {
        currentPos = -data.currentTranslate;
      }
      if (params.cssMode) {
        return;
      }
      if (swiper.params.freeMode && params.freeMode.enabled) {
        swiper.freeMode.onTouchEnd({
          currentPos
        });
        return;
      }

      // Find current slide
      let stopIndex = 0;
      let groupSize = swiper.slidesSizesGrid[0];
      for (let i = 0; i < slidesGrid.length; i += i < params.slidesPerGroupSkip ? 1 : params.slidesPerGroup) {
        const increment = i < params.slidesPerGroupSkip - 1 ? 1 : params.slidesPerGroup;
        if (typeof slidesGrid[i + increment] !== 'undefined') {
          if (currentPos >= slidesGrid[i] && currentPos < slidesGrid[i + increment]) {
            stopIndex = i;
            groupSize = slidesGrid[i + increment] - slidesGrid[i];
          }
        } else if (currentPos >= slidesGrid[i]) {
          stopIndex = i;
          groupSize = slidesGrid[slidesGrid.length - 1] - slidesGrid[slidesGrid.length - 2];
        }
      }
      let rewindFirstIndex = null;
      let rewindLastIndex = null;
      if (params.rewind) {
        if (swiper.isBeginning) {
          rewindLastIndex = swiper.params.virtual && swiper.params.virtual.enabled && swiper.virtual ? swiper.virtual.slides.length - 1 : swiper.slides.length - 1;
        } else if (swiper.isEnd) {
          rewindFirstIndex = 0;
        }
      }
      // Find current slide size
      const ratio = (currentPos - slidesGrid[stopIndex]) / groupSize;
      const increment = stopIndex < params.slidesPerGroupSkip - 1 ? 1 : params.slidesPerGroup;
      if (timeDiff > params.longSwipesMs) {
        // Long touches
        if (!params.longSwipes) {
          swiper.slideTo(swiper.activeIndex);
          return;
        }
        if (swiper.swipeDirection === 'next') {
          if (ratio >= params.longSwipesRatio) swiper.slideTo(params.rewind && swiper.isEnd ? rewindFirstIndex : stopIndex + increment);else swiper.slideTo(stopIndex);
        }
        if (swiper.swipeDirection === 'prev') {
          if (ratio > 1 - params.longSwipesRatio) {
            swiper.slideTo(stopIndex + increment);
          } else if (rewindLastIndex !== null && ratio < 0 && Math.abs(ratio) > params.longSwipesRatio) {
            swiper.slideTo(rewindLastIndex);
          } else {
            swiper.slideTo(stopIndex);
          }
        }
      } else {
        // Short swipes
        if (!params.shortSwipes) {
          swiper.slideTo(swiper.activeIndex);
          return;
        }
        const isNavButtonTarget = swiper.navigation && (e.target === swiper.navigation.nextEl || e.target === swiper.navigation.prevEl);
        if (!isNavButtonTarget) {
          if (swiper.swipeDirection === 'next') {
            swiper.slideTo(rewindFirstIndex !== null ? rewindFirstIndex : stopIndex + increment);
          }
          if (swiper.swipeDirection === 'prev') {
            swiper.slideTo(rewindLastIndex !== null ? rewindLastIndex : stopIndex);
          }
        } else if (e.target === swiper.navigation.nextEl) {
          swiper.slideTo(stopIndex + increment);
        } else {
          swiper.slideTo(stopIndex);
        }
      }
    }

    function onResize() {
      const swiper = this;
      const {
        params,
        el
      } = swiper;
      if (el && el.offsetWidth === 0) return;

      // Breakpoints
      if (params.breakpoints) {
        swiper.setBreakpoint();
      }

      // Save locks
      const {
        allowSlideNext,
        allowSlidePrev,
        snapGrid
      } = swiper;
      const isVirtual = swiper.virtual && swiper.params.virtual.enabled;

      // Disable locks on resize
      swiper.allowSlideNext = true;
      swiper.allowSlidePrev = true;
      swiper.updateSize();
      swiper.updateSlides();
      swiper.updateSlidesClasses();
      const isVirtualLoop = isVirtual && params.loop;
      if ((params.slidesPerView === 'auto' || params.slidesPerView > 1) && swiper.isEnd && !swiper.isBeginning && !swiper.params.centeredSlides && !isVirtualLoop) {
        swiper.slideTo(swiper.slides.length - 1, 0, false, true);
      } else {
        if (swiper.params.loop && !isVirtual) {
          swiper.slideToLoop(swiper.realIndex, 0, false, true);
        } else {
          swiper.slideTo(swiper.activeIndex, 0, false, true);
        }
      }
      if (swiper.autoplay && swiper.autoplay.running && swiper.autoplay.paused) {
        clearTimeout(swiper.autoplay.resizeTimeout);
        swiper.autoplay.resizeTimeout = setTimeout(() => {
          if (swiper.autoplay && swiper.autoplay.running && swiper.autoplay.paused) {
            swiper.autoplay.resume();
          }
        }, 500);
      }
      // Return locks after resize
      swiper.allowSlidePrev = allowSlidePrev;
      swiper.allowSlideNext = allowSlideNext;
      if (swiper.params.watchOverflow && snapGrid !== swiper.snapGrid) {
        swiper.checkOverflow();
      }
    }

    function onClick(e) {
      const swiper = this;
      if (!swiper.enabled) return;
      if (!swiper.allowClick) {
        if (swiper.params.preventClicks) e.preventDefault();
        if (swiper.params.preventClicksPropagation && swiper.animating) {
          e.stopPropagation();
          e.stopImmediatePropagation();
        }
      }
    }

    function onScroll() {
      const swiper = this;
      const {
        wrapperEl,
        rtlTranslate,
        enabled
      } = swiper;
      if (!enabled) return;
      swiper.previousTranslate = swiper.translate;
      if (swiper.isHorizontal()) {
        swiper.translate = -wrapperEl.scrollLeft;
      } else {
        swiper.translate = -wrapperEl.scrollTop;
      }
      // eslint-disable-next-line
      if (swiper.translate === 0) swiper.translate = 0;
      swiper.updateActiveIndex();
      swiper.updateSlidesClasses();
      let newProgress;
      const translatesDiff = swiper.maxTranslate() - swiper.minTranslate();
      if (translatesDiff === 0) {
        newProgress = 0;
      } else {
        newProgress = (swiper.translate - swiper.minTranslate()) / translatesDiff;
      }
      if (newProgress !== swiper.progress) {
        swiper.updateProgress(rtlTranslate ? -swiper.translate : swiper.translate);
      }
      swiper.emit('setTranslate', swiper.translate, false);
    }

    function onLoad(e) {
      const swiper = this;
      processLazyPreloader(swiper, e.target);
      if (swiper.params.cssMode || swiper.params.slidesPerView !== 'auto' && !swiper.params.autoHeight) {
        return;
      }
      swiper.update();
    }

    let dummyEventAttached = false;
    function dummyEventListener() {}
    const events = (swiper, method) => {
      const document = getDocument();
      const {
        params,
        el,
        wrapperEl,
        device
      } = swiper;
      const capture = !!params.nested;
      const domMethod = method === 'on' ? 'addEventListener' : 'removeEventListener';
      const swiperMethod = method;

      // Touch Events
      el[domMethod]('pointerdown', swiper.onTouchStart, {
        passive: false
      });
      document[domMethod]('pointermove', swiper.onTouchMove, {
        passive: false,
        capture
      });
      document[domMethod]('pointerup', swiper.onTouchEnd, {
        passive: true
      });
      document[domMethod]('pointercancel', swiper.onTouchEnd, {
        passive: true
      });
      document[domMethod]('pointerout', swiper.onTouchEnd, {
        passive: true
      });
      document[domMethod]('pointerleave', swiper.onTouchEnd, {
        passive: true
      });

      // Prevent Links Clicks
      if (params.preventClicks || params.preventClicksPropagation) {
        el[domMethod]('click', swiper.onClick, true);
      }
      if (params.cssMode) {
        wrapperEl[domMethod]('scroll', swiper.onScroll);
      }

      // Resize handler
      if (params.updateOnWindowResize) {
        swiper[swiperMethod](device.ios || device.android ? 'resize orientationchange observerUpdate' : 'resize observerUpdate', onResize, true);
      } else {
        swiper[swiperMethod]('observerUpdate', onResize, true);
      }

      // Images loader
      el[domMethod]('load', swiper.onLoad, {
        capture: true
      });
    };
    function attachEvents() {
      const swiper = this;
      const document = getDocument();
      const {
        params
      } = swiper;
      swiper.onTouchStart = onTouchStart.bind(swiper);
      swiper.onTouchMove = onTouchMove.bind(swiper);
      swiper.onTouchEnd = onTouchEnd.bind(swiper);
      if (params.cssMode) {
        swiper.onScroll = onScroll.bind(swiper);
      }
      swiper.onClick = onClick.bind(swiper);
      swiper.onLoad = onLoad.bind(swiper);
      if (!dummyEventAttached) {
        document.addEventListener('touchstart', dummyEventListener);
        dummyEventAttached = true;
      }
      events(swiper, 'on');
    }
    function detachEvents() {
      const swiper = this;
      events(swiper, 'off');
    }
    var events$1 = {
      attachEvents,
      detachEvents
    };

    const isGridEnabled = (swiper, params) => {
      return swiper.grid && params.grid && params.grid.rows > 1;
    };
    function setBreakpoint() {
      const swiper = this;
      const {
        realIndex,
        initialized,
        params,
        el
      } = swiper;
      const breakpoints = params.breakpoints;
      if (!breakpoints || breakpoints && Object.keys(breakpoints).length === 0) return;

      // Get breakpoint for window width and update parameters
      const breakpoint = swiper.getBreakpoint(breakpoints, swiper.params.breakpointsBase, swiper.el);
      if (!breakpoint || swiper.currentBreakpoint === breakpoint) return;
      const breakpointOnlyParams = breakpoint in breakpoints ? breakpoints[breakpoint] : undefined;
      const breakpointParams = breakpointOnlyParams || swiper.originalParams;
      const wasMultiRow = isGridEnabled(swiper, params);
      const isMultiRow = isGridEnabled(swiper, breakpointParams);
      const wasEnabled = params.enabled;
      if (wasMultiRow && !isMultiRow) {
        el.classList.remove(`${params.containerModifierClass}grid`, `${params.containerModifierClass}grid-column`);
        swiper.emitContainerClasses();
      } else if (!wasMultiRow && isMultiRow) {
        el.classList.add(`${params.containerModifierClass}grid`);
        if (breakpointParams.grid.fill && breakpointParams.grid.fill === 'column' || !breakpointParams.grid.fill && params.grid.fill === 'column') {
          el.classList.add(`${params.containerModifierClass}grid-column`);
        }
        swiper.emitContainerClasses();
      }

      // Toggle navigation, pagination, scrollbar
      ['navigation', 'pagination', 'scrollbar'].forEach(prop => {
        const wasModuleEnabled = params[prop] && params[prop].enabled;
        const isModuleEnabled = breakpointParams[prop] && breakpointParams[prop].enabled;
        if (wasModuleEnabled && !isModuleEnabled) {
          swiper[prop].disable();
        }
        if (!wasModuleEnabled && isModuleEnabled) {
          swiper[prop].enable();
        }
      });
      const directionChanged = breakpointParams.direction && breakpointParams.direction !== params.direction;
      const needsReLoop = params.loop && (breakpointParams.slidesPerView !== params.slidesPerView || directionChanged);
      if (directionChanged && initialized) {
        swiper.changeDirection();
      }
      extend(swiper.params, breakpointParams);
      const isEnabled = swiper.params.enabled;
      Object.assign(swiper, {
        allowTouchMove: swiper.params.allowTouchMove,
        allowSlideNext: swiper.params.allowSlideNext,
        allowSlidePrev: swiper.params.allowSlidePrev
      });
      if (wasEnabled && !isEnabled) {
        swiper.disable();
      } else if (!wasEnabled && isEnabled) {
        swiper.enable();
      }
      swiper.currentBreakpoint = breakpoint;
      swiper.emit('_beforeBreakpoint', breakpointParams);
      if (needsReLoop && initialized) {
        swiper.loopDestroy();
        swiper.loopCreate(realIndex);
        swiper.updateSlides();
      }
      swiper.emit('breakpoint', breakpointParams);
    }

    function getBreakpoint(breakpoints, base, containerEl) {
      if (base === void 0) {
        base = 'window';
      }
      if (!breakpoints || base === 'container' && !containerEl) return undefined;
      let breakpoint = false;
      const window = getWindow();
      const currentHeight = base === 'window' ? window.innerHeight : containerEl.clientHeight;
      const points = Object.keys(breakpoints).map(point => {
        if (typeof point === 'string' && point.indexOf('@') === 0) {
          const minRatio = parseFloat(point.substr(1));
          const value = currentHeight * minRatio;
          return {
            value,
            point
          };
        }
        return {
          value: point,
          point
        };
      });
      points.sort((a, b) => parseInt(a.value, 10) - parseInt(b.value, 10));
      for (let i = 0; i < points.length; i += 1) {
        const {
          point,
          value
        } = points[i];
        if (base === 'window') {
          if (window.matchMedia(`(min-width: ${value}px)`).matches) {
            breakpoint = point;
          }
        } else if (value <= containerEl.clientWidth) {
          breakpoint = point;
        }
      }
      return breakpoint || 'max';
    }

    var breakpoints = {
      setBreakpoint,
      getBreakpoint
    };

    function prepareClasses(entries, prefix) {
      const resultClasses = [];
      entries.forEach(item => {
        if (typeof item === 'object') {
          Object.keys(item).forEach(classNames => {
            if (item[classNames]) {
              resultClasses.push(prefix + classNames);
            }
          });
        } else if (typeof item === 'string') {
          resultClasses.push(prefix + item);
        }
      });
      return resultClasses;
    }
    function addClasses() {
      const swiper = this;
      const {
        classNames,
        params,
        rtl,
        el,
        device
      } = swiper;
      // prettier-ignore
      const suffixes = prepareClasses(['initialized', params.direction, {
        'free-mode': swiper.params.freeMode && params.freeMode.enabled
      }, {
        'autoheight': params.autoHeight
      }, {
        'rtl': rtl
      }, {
        'grid': params.grid && params.grid.rows > 1
      }, {
        'grid-column': params.grid && params.grid.rows > 1 && params.grid.fill === 'column'
      }, {
        'android': device.android
      }, {
        'ios': device.ios
      }, {
        'css-mode': params.cssMode
      }, {
        'centered': params.cssMode && params.centeredSlides
      }, {
        'watch-progress': params.watchSlidesProgress
      }], params.containerModifierClass);
      classNames.push(...suffixes);
      el.classList.add(...classNames);
      swiper.emitContainerClasses();
    }

    function removeClasses() {
      const swiper = this;
      const {
        el,
        classNames
      } = swiper;
      el.classList.remove(...classNames);
      swiper.emitContainerClasses();
    }

    var classes = {
      addClasses,
      removeClasses
    };

    function checkOverflow() {
      const swiper = this;
      const {
        isLocked: wasLocked,
        params
      } = swiper;
      const {
        slidesOffsetBefore
      } = params;
      if (slidesOffsetBefore) {
        const lastSlideIndex = swiper.slides.length - 1;
        const lastSlideRightEdge = swiper.slidesGrid[lastSlideIndex] + swiper.slidesSizesGrid[lastSlideIndex] + slidesOffsetBefore * 2;
        swiper.isLocked = swiper.size > lastSlideRightEdge;
      } else {
        swiper.isLocked = swiper.snapGrid.length === 1;
      }
      if (params.allowSlideNext === true) {
        swiper.allowSlideNext = !swiper.isLocked;
      }
      if (params.allowSlidePrev === true) {
        swiper.allowSlidePrev = !swiper.isLocked;
      }
      if (wasLocked && wasLocked !== swiper.isLocked) {
        swiper.isEnd = false;
      }
      if (wasLocked !== swiper.isLocked) {
        swiper.emit(swiper.isLocked ? 'lock' : 'unlock');
      }
    }
    var checkOverflow$1 = {
      checkOverflow
    };

    var defaults = {
      init: true,
      direction: 'horizontal',
      oneWayMovement: false,
      touchEventsTarget: 'wrapper',
      initialSlide: 0,
      speed: 300,
      cssMode: false,
      updateOnWindowResize: true,
      resizeObserver: true,
      nested: false,
      createElements: false,
      enabled: true,
      focusableElements: 'input, select, option, textarea, button, video, label',
      // Overrides
      width: null,
      height: null,
      //
      preventInteractionOnTransition: false,
      // ssr
      userAgent: null,
      url: null,
      // To support iOS's swipe-to-go-back gesture (when being used in-app).
      edgeSwipeDetection: false,
      edgeSwipeThreshold: 20,
      // Autoheight
      autoHeight: false,
      // Set wrapper width
      setWrapperSize: false,
      // Virtual Translate
      virtualTranslate: false,
      // Effects
      effect: 'slide',
      // 'slide' or 'fade' or 'cube' or 'coverflow' or 'flip'

      // Breakpoints
      breakpoints: undefined,
      breakpointsBase: 'window',
      // Slides grid
      spaceBetween: 0,
      slidesPerView: 1,
      slidesPerGroup: 1,
      slidesPerGroupSkip: 0,
      slidesPerGroupAuto: false,
      centeredSlides: false,
      centeredSlidesBounds: false,
      slidesOffsetBefore: 0,
      // in px
      slidesOffsetAfter: 0,
      // in px
      normalizeSlideIndex: true,
      centerInsufficientSlides: false,
      // Disable swiper and hide navigation when container not overflow
      watchOverflow: true,
      // Round length
      roundLengths: false,
      // Touches
      touchRatio: 1,
      touchAngle: 45,
      simulateTouch: true,
      shortSwipes: true,
      longSwipes: true,
      longSwipesRatio: 0.5,
      longSwipesMs: 300,
      followFinger: true,
      allowTouchMove: true,
      threshold: 5,
      touchMoveStopPropagation: false,
      touchStartPreventDefault: true,
      touchStartForcePreventDefault: false,
      touchReleaseOnEdges: false,
      // Unique Navigation Elements
      uniqueNavElements: true,
      // Resistance
      resistance: true,
      resistanceRatio: 0.85,
      // Progress
      watchSlidesProgress: false,
      // Cursor
      grabCursor: false,
      // Clicks
      preventClicks: true,
      preventClicksPropagation: true,
      slideToClickedSlide: false,
      // loop
      loop: false,
      loopedSlides: null,
      loopPreventsSliding: true,
      // rewind
      rewind: false,
      // Swiping/no swiping
      allowSlidePrev: true,
      allowSlideNext: true,
      swipeHandler: null,
      // '.swipe-handler',
      noSwiping: true,
      noSwipingClass: 'swiper-no-swiping',
      noSwipingSelector: null,
      // Passive Listeners
      passiveListeners: true,
      maxBackfaceHiddenSlides: 10,
      // NS
      containerModifierClass: 'swiper-',
      // NEW
      slideClass: 'swiper-slide',
      slideActiveClass: 'swiper-slide-active',
      slideVisibleClass: 'swiper-slide-visible',
      slideNextClass: 'swiper-slide-next',
      slidePrevClass: 'swiper-slide-prev',
      wrapperClass: 'swiper-wrapper',
      lazyPreloaderClass: 'swiper-lazy-preloader',
      lazyPreloadPrevNext: 0,
      // Callbacks
      runCallbacksOnInit: true,
      // Internals
      _emitClasses: false
    };

    function moduleExtendParams(params, allModulesParams) {
      return function extendParams(obj) {
        if (obj === void 0) {
          obj = {};
        }
        const moduleParamName = Object.keys(obj)[0];
        const moduleParams = obj[moduleParamName];
        if (typeof moduleParams !== 'object' || moduleParams === null) {
          extend(allModulesParams, obj);
          return;
        }
        if (['navigation', 'pagination', 'scrollbar'].indexOf(moduleParamName) >= 0 && params[moduleParamName] === true) {
          params[moduleParamName] = {
            auto: true
          };
        }
        if (!(moduleParamName in params && 'enabled' in moduleParams)) {
          extend(allModulesParams, obj);
          return;
        }
        if (params[moduleParamName] === true) {
          params[moduleParamName] = {
            enabled: true
          };
        }
        if (typeof params[moduleParamName] === 'object' && !('enabled' in params[moduleParamName])) {
          params[moduleParamName].enabled = true;
        }
        if (!params[moduleParamName]) params[moduleParamName] = {
          enabled: false
        };
        extend(allModulesParams, obj);
      };
    }

    /* eslint no-param-reassign: "off" */
    const prototypes = {
      eventsEmitter,
      update,
      translate,
      transition,
      slide,
      loop,
      grabCursor,
      events: events$1,
      breakpoints,
      checkOverflow: checkOverflow$1,
      classes
    };
    const extendedDefaults = {};
    class Swiper {
      constructor() {
        let el;
        let params;
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        if (args.length === 1 && args[0].constructor && Object.prototype.toString.call(args[0]).slice(8, -1) === 'Object') {
          params = args[0];
        } else {
          [el, params] = args;
        }
        if (!params) params = {};
        params = extend({}, params);
        if (el && !params.el) params.el = el;
        const document = getDocument();
        if (params.el && typeof params.el === 'string' && document.querySelectorAll(params.el).length > 1) {
          const swipers = [];
          document.querySelectorAll(params.el).forEach(containerEl => {
            const newParams = extend({}, params, {
              el: containerEl
            });
            swipers.push(new Swiper(newParams));
          });
          // eslint-disable-next-line no-constructor-return
          return swipers;
        }

        // Swiper Instance
        const swiper = this;
        swiper.__swiper__ = true;
        swiper.support = getSupport();
        swiper.device = getDevice({
          userAgent: params.userAgent
        });
        swiper.browser = getBrowser();
        swiper.eventsListeners = {};
        swiper.eventsAnyListeners = [];
        swiper.modules = [...swiper.__modules__];
        if (params.modules && Array.isArray(params.modules)) {
          swiper.modules.push(...params.modules);
        }
        const allModulesParams = {};
        swiper.modules.forEach(mod => {
          mod({
            params,
            swiper,
            extendParams: moduleExtendParams(params, allModulesParams),
            on: swiper.on.bind(swiper),
            once: swiper.once.bind(swiper),
            off: swiper.off.bind(swiper),
            emit: swiper.emit.bind(swiper)
          });
        });

        // Extend defaults with modules params
        const swiperParams = extend({}, defaults, allModulesParams);

        // Extend defaults with passed params
        swiper.params = extend({}, swiperParams, extendedDefaults, params);
        swiper.originalParams = extend({}, swiper.params);
        swiper.passedParams = extend({}, params);

        // add event listeners
        if (swiper.params && swiper.params.on) {
          Object.keys(swiper.params.on).forEach(eventName => {
            swiper.on(eventName, swiper.params.on[eventName]);
          });
        }
        if (swiper.params && swiper.params.onAny) {
          swiper.onAny(swiper.params.onAny);
        }

        // Extend Swiper
        Object.assign(swiper, {
          enabled: swiper.params.enabled,
          el,
          // Classes
          classNames: [],
          // Slides
          slides: [],
          slidesGrid: [],
          snapGrid: [],
          slidesSizesGrid: [],
          // isDirection
          isHorizontal() {
            return swiper.params.direction === 'horizontal';
          },
          isVertical() {
            return swiper.params.direction === 'vertical';
          },
          // Indexes
          activeIndex: 0,
          realIndex: 0,
          //
          isBeginning: true,
          isEnd: false,
          // Props
          translate: 0,
          previousTranslate: 0,
          progress: 0,
          velocity: 0,
          animating: false,
          cssOverflowAdjustment() {
            // Returns 0 unless `translate` is > 2**23
            // Should be subtracted from css values to prevent overflow
            return Math.trunc(this.translate / 2 ** 23) * 2 ** 23;
          },
          // Locks
          allowSlideNext: swiper.params.allowSlideNext,
          allowSlidePrev: swiper.params.allowSlidePrev,
          // Touch Events
          touchEventsData: {
            isTouched: undefined,
            isMoved: undefined,
            allowTouchCallbacks: undefined,
            touchStartTime: undefined,
            isScrolling: undefined,
            currentTranslate: undefined,
            startTranslate: undefined,
            allowThresholdMove: undefined,
            // Form elements to match
            focusableElements: swiper.params.focusableElements,
            // Last click time
            lastClickTime: 0,
            clickTimeout: undefined,
            // Velocities
            velocities: [],
            allowMomentumBounce: undefined,
            startMoving: undefined,
            evCache: []
          },
          // Clicks
          allowClick: true,
          // Touches
          allowTouchMove: swiper.params.allowTouchMove,
          touches: {
            startX: 0,
            startY: 0,
            currentX: 0,
            currentY: 0,
            diff: 0
          },
          // Images
          imagesToLoad: [],
          imagesLoaded: 0
        });
        swiper.emit('_swiper');

        // Init
        if (swiper.params.init) {
          swiper.init();
        }

        // Return app instance
        // eslint-disable-next-line no-constructor-return
        return swiper;
      }
      getSlideIndex(slideEl) {
        const {
          slidesEl,
          params
        } = this;
        const slides = elementChildren(slidesEl, `.${params.slideClass}, swiper-slide`);
        const firstSlideIndex = elementIndex(slides[0]);
        return elementIndex(slideEl) - firstSlideIndex;
      }
      getSlideIndexByData(index) {
        return this.getSlideIndex(this.slides.filter(slideEl => slideEl.getAttribute('data-swiper-slide-index') * 1 === index)[0]);
      }
      recalcSlides() {
        const swiper = this;
        const {
          slidesEl,
          params
        } = swiper;
        swiper.slides = elementChildren(slidesEl, `.${params.slideClass}, swiper-slide`);
      }
      enable() {
        const swiper = this;
        if (swiper.enabled) return;
        swiper.enabled = true;
        if (swiper.params.grabCursor) {
          swiper.setGrabCursor();
        }
        swiper.emit('enable');
      }
      disable() {
        const swiper = this;
        if (!swiper.enabled) return;
        swiper.enabled = false;
        if (swiper.params.grabCursor) {
          swiper.unsetGrabCursor();
        }
        swiper.emit('disable');
      }
      setProgress(progress, speed) {
        const swiper = this;
        progress = Math.min(Math.max(progress, 0), 1);
        const min = swiper.minTranslate();
        const max = swiper.maxTranslate();
        const current = (max - min) * progress + min;
        swiper.translateTo(current, typeof speed === 'undefined' ? 0 : speed);
        swiper.updateActiveIndex();
        swiper.updateSlidesClasses();
      }
      emitContainerClasses() {
        const swiper = this;
        if (!swiper.params._emitClasses || !swiper.el) return;
        const cls = swiper.el.className.split(' ').filter(className => {
          return className.indexOf('swiper') === 0 || className.indexOf(swiper.params.containerModifierClass) === 0;
        });
        swiper.emit('_containerClasses', cls.join(' '));
      }
      getSlideClasses(slideEl) {
        const swiper = this;
        if (swiper.destroyed) return '';
        return slideEl.className.split(' ').filter(className => {
          return className.indexOf('swiper-slide') === 0 || className.indexOf(swiper.params.slideClass) === 0;
        }).join(' ');
      }
      emitSlidesClasses() {
        const swiper = this;
        if (!swiper.params._emitClasses || !swiper.el) return;
        const updates = [];
        swiper.slides.forEach(slideEl => {
          const classNames = swiper.getSlideClasses(slideEl);
          updates.push({
            slideEl,
            classNames
          });
          swiper.emit('_slideClass', slideEl, classNames);
        });
        swiper.emit('_slideClasses', updates);
      }
      slidesPerViewDynamic(view, exact) {
        if (view === void 0) {
          view = 'current';
        }
        if (exact === void 0) {
          exact = false;
        }
        const swiper = this;
        const {
          params,
          slides,
          slidesGrid,
          slidesSizesGrid,
          size: swiperSize,
          activeIndex
        } = swiper;
        let spv = 1;
        if (params.centeredSlides) {
          let slideSize = slides[activeIndex].swiperSlideSize;
          let breakLoop;
          for (let i = activeIndex + 1; i < slides.length; i += 1) {
            if (slides[i] && !breakLoop) {
              slideSize += slides[i].swiperSlideSize;
              spv += 1;
              if (slideSize > swiperSize) breakLoop = true;
            }
          }
          for (let i = activeIndex - 1; i >= 0; i -= 1) {
            if (slides[i] && !breakLoop) {
              slideSize += slides[i].swiperSlideSize;
              spv += 1;
              if (slideSize > swiperSize) breakLoop = true;
            }
          }
        } else {
          // eslint-disable-next-line
          if (view === 'current') {
            for (let i = activeIndex + 1; i < slides.length; i += 1) {
              const slideInView = exact ? slidesGrid[i] + slidesSizesGrid[i] - slidesGrid[activeIndex] < swiperSize : slidesGrid[i] - slidesGrid[activeIndex] < swiperSize;
              if (slideInView) {
                spv += 1;
              }
            }
          } else {
            // previous
            for (let i = activeIndex - 1; i >= 0; i -= 1) {
              const slideInView = slidesGrid[activeIndex] - slidesGrid[i] < swiperSize;
              if (slideInView) {
                spv += 1;
              }
            }
          }
        }
        return spv;
      }
      update() {
        const swiper = this;
        if (!swiper || swiper.destroyed) return;
        const {
          snapGrid,
          params
        } = swiper;
        // Breakpoints
        if (params.breakpoints) {
          swiper.setBreakpoint();
        }
        [...swiper.el.querySelectorAll('[loading="lazy"]')].forEach(imageEl => {
          if (imageEl.complete) {
            processLazyPreloader(swiper, imageEl);
          }
        });
        swiper.updateSize();
        swiper.updateSlides();
        swiper.updateProgress();
        swiper.updateSlidesClasses();
        function setTranslate() {
          const translateValue = swiper.rtlTranslate ? swiper.translate * -1 : swiper.translate;
          const newTranslate = Math.min(Math.max(translateValue, swiper.maxTranslate()), swiper.minTranslate());
          swiper.setTranslate(newTranslate);
          swiper.updateActiveIndex();
          swiper.updateSlidesClasses();
        }
        let translated;
        if (swiper.params.freeMode && swiper.params.freeMode.enabled) {
          setTranslate();
          if (swiper.params.autoHeight) {
            swiper.updateAutoHeight();
          }
        } else {
          if ((swiper.params.slidesPerView === 'auto' || swiper.params.slidesPerView > 1) && swiper.isEnd && !swiper.params.centeredSlides) {
            const slides = swiper.virtual && swiper.params.virtual.enabled ? swiper.virtual.slides : swiper.slides;
            translated = swiper.slideTo(slides.length - 1, 0, false, true);
          } else {
            translated = swiper.slideTo(swiper.activeIndex, 0, false, true);
          }
          if (!translated) {
            setTranslate();
          }
        }
        if (params.watchOverflow && snapGrid !== swiper.snapGrid) {
          swiper.checkOverflow();
        }
        swiper.emit('update');
      }
      changeDirection(newDirection, needUpdate) {
        if (needUpdate === void 0) {
          needUpdate = true;
        }
        const swiper = this;
        const currentDirection = swiper.params.direction;
        if (!newDirection) {
          // eslint-disable-next-line
          newDirection = currentDirection === 'horizontal' ? 'vertical' : 'horizontal';
        }
        if (newDirection === currentDirection || newDirection !== 'horizontal' && newDirection !== 'vertical') {
          return swiper;
        }
        swiper.el.classList.remove(`${swiper.params.containerModifierClass}${currentDirection}`);
        swiper.el.classList.add(`${swiper.params.containerModifierClass}${newDirection}`);
        swiper.emitContainerClasses();
        swiper.params.direction = newDirection;
        swiper.slides.forEach(slideEl => {
          if (newDirection === 'vertical') {
            slideEl.style.width = '';
          } else {
            slideEl.style.height = '';
          }
        });
        swiper.emit('changeDirection');
        if (needUpdate) swiper.update();
        return swiper;
      }
      changeLanguageDirection(direction) {
        const swiper = this;
        if (swiper.rtl && direction === 'rtl' || !swiper.rtl && direction === 'ltr') return;
        swiper.rtl = direction === 'rtl';
        swiper.rtlTranslate = swiper.params.direction === 'horizontal' && swiper.rtl;
        if (swiper.rtl) {
          swiper.el.classList.add(`${swiper.params.containerModifierClass}rtl`);
          swiper.el.dir = 'rtl';
        } else {
          swiper.el.classList.remove(`${swiper.params.containerModifierClass}rtl`);
          swiper.el.dir = 'ltr';
        }
        swiper.update();
      }
      mount(element) {
        const swiper = this;
        if (swiper.mounted) return true;

        // Find el
        let el = element || swiper.params.el;
        if (typeof el === 'string') {
          el = document.querySelector(el);
        }
        if (!el) {
          return false;
        }
        el.swiper = swiper;
        if (el.shadowEl) {
          swiper.isElement = true;
        }
        const getWrapperSelector = () => {
          return `.${(swiper.params.wrapperClass || '').trim().split(' ').join('.')}`;
        };
        const getWrapper = () => {
          if (el && el.shadowRoot && el.shadowRoot.querySelector) {
            const res = el.shadowRoot.querySelector(getWrapperSelector());
            // Children needs to return slot items
            return res;
          }
          return elementChildren(el, getWrapperSelector())[0];
        };
        // Find Wrapper
        let wrapperEl = getWrapper();
        if (!wrapperEl && swiper.params.createElements) {
          wrapperEl = createElement('div', swiper.params.wrapperClass);
          el.append(wrapperEl);
          elementChildren(el, `.${swiper.params.slideClass}`).forEach(slideEl => {
            wrapperEl.append(slideEl);
          });
        }
        Object.assign(swiper, {
          el,
          wrapperEl,
          slidesEl: swiper.isElement ? el : wrapperEl,
          mounted: true,
          // RTL
          rtl: el.dir.toLowerCase() === 'rtl' || elementStyle(el, 'direction') === 'rtl',
          rtlTranslate: swiper.params.direction === 'horizontal' && (el.dir.toLowerCase() === 'rtl' || elementStyle(el, 'direction') === 'rtl'),
          wrongRTL: elementStyle(wrapperEl, 'display') === '-webkit-box'
        });
        return true;
      }
      init(el) {
        const swiper = this;
        if (swiper.initialized) return swiper;
        const mounted = swiper.mount(el);
        if (mounted === false) return swiper;
        swiper.emit('beforeInit');

        // Set breakpoint
        if (swiper.params.breakpoints) {
          swiper.setBreakpoint();
        }

        // Add Classes
        swiper.addClasses();

        // Update size
        swiper.updateSize();

        // Update slides
        swiper.updateSlides();
        if (swiper.params.watchOverflow) {
          swiper.checkOverflow();
        }

        // Set Grab Cursor
        if (swiper.params.grabCursor && swiper.enabled) {
          swiper.setGrabCursor();
        }

        // Slide To Initial Slide
        if (swiper.params.loop && swiper.virtual && swiper.params.virtual.enabled) {
          swiper.slideTo(swiper.params.initialSlide + swiper.virtual.slidesBefore, 0, swiper.params.runCallbacksOnInit, false, true);
        } else {
          swiper.slideTo(swiper.params.initialSlide, 0, swiper.params.runCallbacksOnInit, false, true);
        }

        // Create loop
        if (swiper.params.loop) {
          swiper.loopCreate();
        }

        // Attach events
        swiper.attachEvents();
        [...swiper.el.querySelectorAll('[loading="lazy"]')].forEach(imageEl => {
          if (imageEl.complete) {
            processLazyPreloader(swiper, imageEl);
          } else {
            imageEl.addEventListener('load', e => {
              processLazyPreloader(swiper, e.target);
            });
          }
        });
        preload(swiper);

        // Init Flag
        swiper.initialized = true;
        preload(swiper);

        // Emit
        swiper.emit('init');
        swiper.emit('afterInit');
        return swiper;
      }
      destroy(deleteInstance, cleanStyles) {
        if (deleteInstance === void 0) {
          deleteInstance = true;
        }
        if (cleanStyles === void 0) {
          cleanStyles = true;
        }
        const swiper = this;
        const {
          params,
          el,
          wrapperEl,
          slides
        } = swiper;
        if (typeof swiper.params === 'undefined' || swiper.destroyed) {
          return null;
        }
        swiper.emit('beforeDestroy');

        // Init Flag
        swiper.initialized = false;

        // Detach events
        swiper.detachEvents();

        // Destroy loop
        if (params.loop) {
          swiper.loopDestroy();
        }

        // Cleanup styles
        if (cleanStyles) {
          swiper.removeClasses();
          el.removeAttribute('style');
          wrapperEl.removeAttribute('style');
          if (slides && slides.length) {
            slides.forEach(slideEl => {
              slideEl.classList.remove(params.slideVisibleClass, params.slideActiveClass, params.slideNextClass, params.slidePrevClass);
              slideEl.removeAttribute('style');
              slideEl.removeAttribute('data-swiper-slide-index');
            });
          }
        }
        swiper.emit('destroy');

        // Detach emitter events
        Object.keys(swiper.eventsListeners).forEach(eventName => {
          swiper.off(eventName);
        });
        if (deleteInstance !== false) {
          swiper.el.swiper = null;
          deleteProps(swiper);
        }
        swiper.destroyed = true;
        return null;
      }
      static extendDefaults(newDefaults) {
        extend(extendedDefaults, newDefaults);
      }
      static get extendedDefaults() {
        return extendedDefaults;
      }
      static get defaults() {
        return defaults;
      }
      static installModule(mod) {
        if (!Swiper.prototype.__modules__) Swiper.prototype.__modules__ = [];
        const modules = Swiper.prototype.__modules__;
        if (typeof mod === 'function' && modules.indexOf(mod) < 0) {
          modules.push(mod);
        }
      }
      static use(module) {
        if (Array.isArray(module)) {
          module.forEach(m => Swiper.installModule(m));
          return Swiper;
        }
        Swiper.installModule(module);
        return Swiper;
      }
    }
    Object.keys(prototypes).forEach(prototypeGroup => {
      Object.keys(prototypes[prototypeGroup]).forEach(protoMethod => {
        Swiper.prototype[protoMethod] = prototypes[prototypeGroup][protoMethod];
      });
    });
    Swiper.use([Resize, Observer]);

    function Virtual(_ref) {
      let {
        swiper,
        extendParams,
        on,
        emit
      } = _ref;
      extendParams({
        virtual: {
          enabled: false,
          slides: [],
          cache: true,
          renderSlide: null,
          renderExternal: null,
          renderExternalUpdate: true,
          addSlidesBefore: 0,
          addSlidesAfter: 0
        }
      });
      let cssModeTimeout;
      const document = getDocument();
      swiper.virtual = {
        cache: {},
        from: undefined,
        to: undefined,
        slides: [],
        offset: 0,
        slidesGrid: []
      };
      const tempDOM = document.createElement('div');
      function renderSlide(slide, index) {
        const params = swiper.params.virtual;
        if (params.cache && swiper.virtual.cache[index]) {
          return swiper.virtual.cache[index];
        }
        // eslint-disable-next-line
        let slideEl;
        if (params.renderSlide) {
          slideEl = params.renderSlide.call(swiper, slide, index);
          if (typeof slideEl === 'string') {
            tempDOM.innerHTML = slideEl;
            slideEl = tempDOM.children[0];
          }
        } else if (swiper.isElement) {
          slideEl = createElement('swiper-slide');
        } else {
          slideEl = createElement('div', swiper.params.slideClass);
        }
        slideEl.setAttribute('data-swiper-slide-index', index);
        if (!params.renderSlide) {
          slideEl.innerHTML = slide;
        }
        if (params.cache) swiper.virtual.cache[index] = slideEl;
        return slideEl;
      }
      function update(force) {
        const {
          slidesPerView,
          slidesPerGroup,
          centeredSlides,
          loop: isLoop
        } = swiper.params;
        const {
          addSlidesBefore,
          addSlidesAfter
        } = swiper.params.virtual;
        const {
          from: previousFrom,
          to: previousTo,
          slides,
          slidesGrid: previousSlidesGrid,
          offset: previousOffset
        } = swiper.virtual;
        if (!swiper.params.cssMode) {
          swiper.updateActiveIndex();
        }
        const activeIndex = swiper.activeIndex || 0;
        let offsetProp;
        if (swiper.rtlTranslate) offsetProp = 'right';else offsetProp = swiper.isHorizontal() ? 'left' : 'top';
        let slidesAfter;
        let slidesBefore;
        if (centeredSlides) {
          slidesAfter = Math.floor(slidesPerView / 2) + slidesPerGroup + addSlidesAfter;
          slidesBefore = Math.floor(slidesPerView / 2) + slidesPerGroup + addSlidesBefore;
        } else {
          slidesAfter = slidesPerView + (slidesPerGroup - 1) + addSlidesAfter;
          slidesBefore = (isLoop ? slidesPerView : slidesPerGroup) + addSlidesBefore;
        }
        let from = activeIndex - slidesBefore;
        let to = activeIndex + slidesAfter;
        if (!isLoop) {
          from = Math.max(from, 0);
          to = Math.min(to, slides.length - 1);
        }
        let offset = (swiper.slidesGrid[from] || 0) - (swiper.slidesGrid[0] || 0);
        if (isLoop && activeIndex >= slidesBefore) {
          from -= slidesBefore;
          if (!centeredSlides) offset += swiper.slidesGrid[0];
        } else if (isLoop && activeIndex < slidesBefore) {
          from = -slidesBefore;
          if (centeredSlides) offset += swiper.slidesGrid[0];
        }
        Object.assign(swiper.virtual, {
          from,
          to,
          offset,
          slidesGrid: swiper.slidesGrid,
          slidesBefore,
          slidesAfter
        });
        function onRendered() {
          swiper.updateSlides();
          swiper.updateProgress();
          swiper.updateSlidesClasses();
          emit('virtualUpdate');
        }
        if (previousFrom === from && previousTo === to && !force) {
          if (swiper.slidesGrid !== previousSlidesGrid && offset !== previousOffset) {
            swiper.slides.forEach(slideEl => {
              slideEl.style[offsetProp] = `${offset - Math.abs(swiper.cssOverflowAdjustment())}px`;
            });
          }
          swiper.updateProgress();
          emit('virtualUpdate');
          return;
        }
        if (swiper.params.virtual.renderExternal) {
          swiper.params.virtual.renderExternal.call(swiper, {
            offset,
            from,
            to,
            slides: function getSlides() {
              const slidesToRender = [];
              for (let i = from; i <= to; i += 1) {
                slidesToRender.push(slides[i]);
              }
              return slidesToRender;
            }()
          });
          if (swiper.params.virtual.renderExternalUpdate) {
            onRendered();
          } else {
            emit('virtualUpdate');
          }
          return;
        }
        const prependIndexes = [];
        const appendIndexes = [];
        const getSlideIndex = index => {
          let slideIndex = index;
          if (index < 0) {
            slideIndex = slides.length + index;
          } else if (slideIndex >= slides.length) {
            // eslint-disable-next-line
            slideIndex = slideIndex - slides.length;
          }
          return slideIndex;
        };
        if (force) {
          swiper.slidesEl.querySelectorAll(`.${swiper.params.slideClass}, swiper-slide`).forEach(slideEl => {
            slideEl.remove();
          });
        } else {
          for (let i = previousFrom; i <= previousTo; i += 1) {
            if (i < from || i > to) {
              const slideIndex = getSlideIndex(i);
              swiper.slidesEl.querySelectorAll(`.${swiper.params.slideClass}[data-swiper-slide-index="${slideIndex}"], swiper-slide[data-swiper-slide-index="${slideIndex}"]`).forEach(slideEl => {
                slideEl.remove();
              });
            }
          }
        }
        const loopFrom = isLoop ? -slides.length : 0;
        const loopTo = isLoop ? slides.length * 2 : slides.length;
        for (let i = loopFrom; i < loopTo; i += 1) {
          if (i >= from && i <= to) {
            const slideIndex = getSlideIndex(i);
            if (typeof previousTo === 'undefined' || force) {
              appendIndexes.push(slideIndex);
            } else {
              if (i > previousTo) appendIndexes.push(slideIndex);
              if (i < previousFrom) prependIndexes.push(slideIndex);
            }
          }
        }
        appendIndexes.forEach(index => {
          swiper.slidesEl.append(renderSlide(slides[index], index));
        });
        if (isLoop) {
          for (let i = prependIndexes.length - 1; i >= 0; i -= 1) {
            const index = prependIndexes[i];
            swiper.slidesEl.prepend(renderSlide(slides[index], index));
          }
        } else {
          prependIndexes.sort((a, b) => b - a);
          prependIndexes.forEach(index => {
            swiper.slidesEl.prepend(renderSlide(slides[index], index));
          });
        }
        elementChildren(swiper.slidesEl, '.swiper-slide, swiper-slide').forEach(slideEl => {
          slideEl.style[offsetProp] = `${offset - Math.abs(swiper.cssOverflowAdjustment())}px`;
        });
        onRendered();
      }
      function appendSlide(slides) {
        if (typeof slides === 'object' && 'length' in slides) {
          for (let i = 0; i < slides.length; i += 1) {
            if (slides[i]) swiper.virtual.slides.push(slides[i]);
          }
        } else {
          swiper.virtual.slides.push(slides);
        }
        update(true);
      }
      function prependSlide(slides) {
        const activeIndex = swiper.activeIndex;
        let newActiveIndex = activeIndex + 1;
        let numberOfNewSlides = 1;
        if (Array.isArray(slides)) {
          for (let i = 0; i < slides.length; i += 1) {
            if (slides[i]) swiper.virtual.slides.unshift(slides[i]);
          }
          newActiveIndex = activeIndex + slides.length;
          numberOfNewSlides = slides.length;
        } else {
          swiper.virtual.slides.unshift(slides);
        }
        if (swiper.params.virtual.cache) {
          const cache = swiper.virtual.cache;
          const newCache = {};
          Object.keys(cache).forEach(cachedIndex => {
            const cachedEl = cache[cachedIndex];
            const cachedElIndex = cachedEl.getAttribute('data-swiper-slide-index');
            if (cachedElIndex) {
              cachedEl.setAttribute('data-swiper-slide-index', parseInt(cachedElIndex, 10) + numberOfNewSlides);
            }
            newCache[parseInt(cachedIndex, 10) + numberOfNewSlides] = cachedEl;
          });
          swiper.virtual.cache = newCache;
        }
        update(true);
        swiper.slideTo(newActiveIndex, 0);
      }
      function removeSlide(slidesIndexes) {
        if (typeof slidesIndexes === 'undefined' || slidesIndexes === null) return;
        let activeIndex = swiper.activeIndex;
        if (Array.isArray(slidesIndexes)) {
          for (let i = slidesIndexes.length - 1; i >= 0; i -= 1) {
            swiper.virtual.slides.splice(slidesIndexes[i], 1);
            if (swiper.params.virtual.cache) {
              delete swiper.virtual.cache[slidesIndexes[i]];
            }
            if (slidesIndexes[i] < activeIndex) activeIndex -= 1;
            activeIndex = Math.max(activeIndex, 0);
          }
        } else {
          swiper.virtual.slides.splice(slidesIndexes, 1);
          if (swiper.params.virtual.cache) {
            delete swiper.virtual.cache[slidesIndexes];
          }
          if (slidesIndexes < activeIndex) activeIndex -= 1;
          activeIndex = Math.max(activeIndex, 0);
        }
        update(true);
        swiper.slideTo(activeIndex, 0);
      }
      function removeAllSlides() {
        swiper.virtual.slides = [];
        if (swiper.params.virtual.cache) {
          swiper.virtual.cache = {};
        }
        update(true);
        swiper.slideTo(0, 0);
      }
      on('beforeInit', () => {
        if (!swiper.params.virtual.enabled) return;
        let domSlidesAssigned;
        if (typeof swiper.passedParams.virtual.slides === 'undefined') {
          const slides = [...swiper.slidesEl.children].filter(el => el.matches(`.${swiper.params.slideClass}, swiper-slide`));
          if (slides && slides.length) {
            swiper.virtual.slides = [...slides];
            domSlidesAssigned = true;
            slides.forEach((slideEl, slideIndex) => {
              slideEl.setAttribute('data-swiper-slide-index', slideIndex);
              swiper.virtual.cache[slideIndex] = slideEl;
              slideEl.remove();
            });
          }
        }
        if (!domSlidesAssigned) {
          swiper.virtual.slides = swiper.params.virtual.slides;
        }
        swiper.classNames.push(`${swiper.params.containerModifierClass}virtual`);
        swiper.params.watchSlidesProgress = true;
        swiper.originalParams.watchSlidesProgress = true;
        if (!swiper.params.initialSlide) {
          update();
        }
      });
      on('setTranslate', () => {
        if (!swiper.params.virtual.enabled) return;
        if (swiper.params.cssMode && !swiper._immediateVirtual) {
          clearTimeout(cssModeTimeout);
          cssModeTimeout = setTimeout(() => {
            update();
          }, 100);
        } else {
          update();
        }
      });
      on('init update resize', () => {
        if (!swiper.params.virtual.enabled) return;
        if (swiper.params.cssMode) {
          setCSSProperty(swiper.wrapperEl, '--swiper-virtual-size', `${swiper.virtualSize}px`);
        }
      });
      Object.assign(swiper.virtual, {
        appendSlide,
        prependSlide,
        removeSlide,
        removeAllSlides,
        update
      });
    }

    /* eslint-disable consistent-return */
    function Keyboard(_ref) {
      let {
        swiper,
        extendParams,
        on,
        emit
      } = _ref;
      const document = getDocument();
      const window = getWindow();
      swiper.keyboard = {
        enabled: false
      };
      extendParams({
        keyboard: {
          enabled: false,
          onlyInViewport: true,
          pageUpDown: true
        }
      });
      function handle(event) {
        if (!swiper.enabled) return;
        const {
          rtlTranslate: rtl
        } = swiper;
        let e = event;
        if (e.originalEvent) e = e.originalEvent; // jquery fix
        const kc = e.keyCode || e.charCode;
        const pageUpDown = swiper.params.keyboard.pageUpDown;
        const isPageUp = pageUpDown && kc === 33;
        const isPageDown = pageUpDown && kc === 34;
        const isArrowLeft = kc === 37;
        const isArrowRight = kc === 39;
        const isArrowUp = kc === 38;
        const isArrowDown = kc === 40;
        // Directions locks
        if (!swiper.allowSlideNext && (swiper.isHorizontal() && isArrowRight || swiper.isVertical() && isArrowDown || isPageDown)) {
          return false;
        }
        if (!swiper.allowSlidePrev && (swiper.isHorizontal() && isArrowLeft || swiper.isVertical() && isArrowUp || isPageUp)) {
          return false;
        }
        if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) {
          return undefined;
        }
        if (document.activeElement && document.activeElement.nodeName && (document.activeElement.nodeName.toLowerCase() === 'input' || document.activeElement.nodeName.toLowerCase() === 'textarea')) {
          return undefined;
        }
        if (swiper.params.keyboard.onlyInViewport && (isPageUp || isPageDown || isArrowLeft || isArrowRight || isArrowUp || isArrowDown)) {
          let inView = false;
          // Check that swiper should be inside of visible area of window
          if (elementParents(swiper.el, `.${swiper.params.slideClass}, swiper-slide`).length > 0 && elementParents(swiper.el, `.${swiper.params.slideActiveClass}`).length === 0) {
            return undefined;
          }
          const el = swiper.el;
          const swiperWidth = el.clientWidth;
          const swiperHeight = el.clientHeight;
          const windowWidth = window.innerWidth;
          const windowHeight = window.innerHeight;
          const swiperOffset = elementOffset(el);
          if (rtl) swiperOffset.left -= el.scrollLeft;
          const swiperCoord = [[swiperOffset.left, swiperOffset.top], [swiperOffset.left + swiperWidth, swiperOffset.top], [swiperOffset.left, swiperOffset.top + swiperHeight], [swiperOffset.left + swiperWidth, swiperOffset.top + swiperHeight]];
          for (let i = 0; i < swiperCoord.length; i += 1) {
            const point = swiperCoord[i];
            if (point[0] >= 0 && point[0] <= windowWidth && point[1] >= 0 && point[1] <= windowHeight) {
              if (point[0] === 0 && point[1] === 0) continue; // eslint-disable-line
              inView = true;
            }
          }
          if (!inView) return undefined;
        }
        if (swiper.isHorizontal()) {
          if (isPageUp || isPageDown || isArrowLeft || isArrowRight) {
            if (e.preventDefault) e.preventDefault();else e.returnValue = false;
          }
          if ((isPageDown || isArrowRight) && !rtl || (isPageUp || isArrowLeft) && rtl) swiper.slideNext();
          if ((isPageUp || isArrowLeft) && !rtl || (isPageDown || isArrowRight) && rtl) swiper.slidePrev();
        } else {
          if (isPageUp || isPageDown || isArrowUp || isArrowDown) {
            if (e.preventDefault) e.preventDefault();else e.returnValue = false;
          }
          if (isPageDown || isArrowDown) swiper.slideNext();
          if (isPageUp || isArrowUp) swiper.slidePrev();
        }
        emit('keyPress', kc);
        return undefined;
      }
      function enable() {
        if (swiper.keyboard.enabled) return;
        document.addEventListener('keydown', handle);
        swiper.keyboard.enabled = true;
      }
      function disable() {
        if (!swiper.keyboard.enabled) return;
        document.removeEventListener('keydown', handle);
        swiper.keyboard.enabled = false;
      }
      on('init', () => {
        if (swiper.params.keyboard.enabled) {
          enable();
        }
      });
      on('destroy', () => {
        if (swiper.keyboard.enabled) {
          disable();
        }
      });
      Object.assign(swiper.keyboard, {
        enable,
        disable
      });
    }

    /* eslint-disable consistent-return */
    function Mousewheel(_ref) {
      let {
        swiper,
        extendParams,
        on,
        emit
      } = _ref;
      const window = getWindow();
      extendParams({
        mousewheel: {
          enabled: false,
          releaseOnEdges: false,
          invert: false,
          forceToAxis: false,
          sensitivity: 1,
          eventsTarget: 'container',
          thresholdDelta: null,
          thresholdTime: null,
          noMousewheelClass: 'swiper-no-mousewheel'
        }
      });
      swiper.mousewheel = {
        enabled: false
      };
      let timeout;
      let lastScrollTime = now();
      let lastEventBeforeSnap;
      const recentWheelEvents = [];
      function normalize(e) {
        // Reasonable defaults
        const PIXEL_STEP = 10;
        const LINE_HEIGHT = 40;
        const PAGE_HEIGHT = 800;
        let sX = 0;
        let sY = 0; // spinX, spinY
        let pX = 0;
        let pY = 0; // pixelX, pixelY

        // Legacy
        if ('detail' in e) {
          sY = e.detail;
        }
        if ('wheelDelta' in e) {
          sY = -e.wheelDelta / 120;
        }
        if ('wheelDeltaY' in e) {
          sY = -e.wheelDeltaY / 120;
        }
        if ('wheelDeltaX' in e) {
          sX = -e.wheelDeltaX / 120;
        }

        // side scrolling on FF with DOMMouseScroll
        if ('axis' in e && e.axis === e.HORIZONTAL_AXIS) {
          sX = sY;
          sY = 0;
        }
        pX = sX * PIXEL_STEP;
        pY = sY * PIXEL_STEP;
        if ('deltaY' in e) {
          pY = e.deltaY;
        }
        if ('deltaX' in e) {
          pX = e.deltaX;
        }
        if (e.shiftKey && !pX) {
          // if user scrolls with shift he wants horizontal scroll
          pX = pY;
          pY = 0;
        }
        if ((pX || pY) && e.deltaMode) {
          if (e.deltaMode === 1) {
            // delta in LINE units
            pX *= LINE_HEIGHT;
            pY *= LINE_HEIGHT;
          } else {
            // delta in PAGE units
            pX *= PAGE_HEIGHT;
            pY *= PAGE_HEIGHT;
          }
        }

        // Fall-back if spin cannot be determined
        if (pX && !sX) {
          sX = pX < 1 ? -1 : 1;
        }
        if (pY && !sY) {
          sY = pY < 1 ? -1 : 1;
        }
        return {
          spinX: sX,
          spinY: sY,
          pixelX: pX,
          pixelY: pY
        };
      }
      function handleMouseEnter() {
        if (!swiper.enabled) return;
        swiper.mouseEntered = true;
      }
      function handleMouseLeave() {
        if (!swiper.enabled) return;
        swiper.mouseEntered = false;
      }
      function animateSlider(newEvent) {
        if (swiper.params.mousewheel.thresholdDelta && newEvent.delta < swiper.params.mousewheel.thresholdDelta) {
          // Prevent if delta of wheel scroll delta is below configured threshold
          return false;
        }
        if (swiper.params.mousewheel.thresholdTime && now() - lastScrollTime < swiper.params.mousewheel.thresholdTime) {
          // Prevent if time between scrolls is below configured threshold
          return false;
        }

        // If the movement is NOT big enough and
        // if the last time the user scrolled was too close to the current one (avoid continuously triggering the slider):
        //   Don't go any further (avoid insignificant scroll movement).
        if (newEvent.delta >= 6 && now() - lastScrollTime < 60) {
          // Return false as a default
          return true;
        }
        // If user is scrolling towards the end:
        //   If the slider hasn't hit the latest slide or
        //   if the slider is a loop and
        //   if the slider isn't moving right now:
        //     Go to next slide and
        //     emit a scroll event.
        // Else (the user is scrolling towards the beginning) and
        // if the slider hasn't hit the first slide or
        // if the slider is a loop and
        // if the slider isn't moving right now:
        //   Go to prev slide and
        //   emit a scroll event.
        if (newEvent.direction < 0) {
          if ((!swiper.isEnd || swiper.params.loop) && !swiper.animating) {
            swiper.slideNext();
            emit('scroll', newEvent.raw);
          }
        } else if ((!swiper.isBeginning || swiper.params.loop) && !swiper.animating) {
          swiper.slidePrev();
          emit('scroll', newEvent.raw);
        }
        // If you got here is because an animation has been triggered so store the current time
        lastScrollTime = new window.Date().getTime();
        // Return false as a default
        return false;
      }
      function releaseScroll(newEvent) {
        const params = swiper.params.mousewheel;
        if (newEvent.direction < 0) {
          if (swiper.isEnd && !swiper.params.loop && params.releaseOnEdges) {
            // Return true to animate scroll on edges
            return true;
          }
        } else if (swiper.isBeginning && !swiper.params.loop && params.releaseOnEdges) {
          // Return true to animate scroll on edges
          return true;
        }
        return false;
      }
      function handle(event) {
        let e = event;
        let disableParentSwiper = true;
        if (!swiper.enabled) return;

        // Ignore event if the target or its parents have the swiper-no-mousewheel class
        if (event.target.closest(`.${swiper.params.mousewheel.noMousewheelClass}`)) return;
        const params = swiper.params.mousewheel;
        if (swiper.params.cssMode) {
          e.preventDefault();
        }
        let targetEl = swiper.el;
        if (swiper.params.mousewheel.eventsTarget !== 'container') {
          targetEl = document.querySelector(swiper.params.mousewheel.eventsTarget);
        }
        const targetElContainsTarget = targetEl && targetEl.contains(e.target);
        if (!swiper.mouseEntered && !targetElContainsTarget && !params.releaseOnEdges) return true;
        if (e.originalEvent) e = e.originalEvent; // jquery fix
        let delta = 0;
        const rtlFactor = swiper.rtlTranslate ? -1 : 1;
        const data = normalize(e);
        if (params.forceToAxis) {
          if (swiper.isHorizontal()) {
            if (Math.abs(data.pixelX) > Math.abs(data.pixelY)) delta = -data.pixelX * rtlFactor;else return true;
          } else if (Math.abs(data.pixelY) > Math.abs(data.pixelX)) delta = -data.pixelY;else return true;
        } else {
          delta = Math.abs(data.pixelX) > Math.abs(data.pixelY) ? -data.pixelX * rtlFactor : -data.pixelY;
        }
        if (delta === 0) return true;
        if (params.invert) delta = -delta;

        // Get the scroll positions
        let positions = swiper.getTranslate() + delta * params.sensitivity;
        if (positions >= swiper.minTranslate()) positions = swiper.minTranslate();
        if (positions <= swiper.maxTranslate()) positions = swiper.maxTranslate();

        // When loop is true:
        //     the disableParentSwiper will be true.
        // When loop is false:
        //     if the scroll positions is not on edge,
        //     then the disableParentSwiper will be true.
        //     if the scroll on edge positions,
        //     then the disableParentSwiper will be false.
        disableParentSwiper = swiper.params.loop ? true : !(positions === swiper.minTranslate() || positions === swiper.maxTranslate());
        if (disableParentSwiper && swiper.params.nested) e.stopPropagation();
        if (!swiper.params.freeMode || !swiper.params.freeMode.enabled) {
          // Register the new event in a variable which stores the relevant data
          const newEvent = {
            time: now(),
            delta: Math.abs(delta),
            direction: Math.sign(delta),
            raw: event
          };

          // Keep the most recent events
          if (recentWheelEvents.length >= 2) {
            recentWheelEvents.shift(); // only store the last N events
          }

          const prevEvent = recentWheelEvents.length ? recentWheelEvents[recentWheelEvents.length - 1] : undefined;
          recentWheelEvents.push(newEvent);

          // If there is at least one previous recorded event:
          //   If direction has changed or
          //   if the scroll is quicker than the previous one:
          //     Animate the slider.
          // Else (this is the first time the wheel is moved):
          //     Animate the slider.
          if (prevEvent) {
            if (newEvent.direction !== prevEvent.direction || newEvent.delta > prevEvent.delta || newEvent.time > prevEvent.time + 150) {
              animateSlider(newEvent);
            }
          } else {
            animateSlider(newEvent);
          }

          // If it's time to release the scroll:
          //   Return now so you don't hit the preventDefault.
          if (releaseScroll(newEvent)) {
            return true;
          }
        } else {
          // Freemode or scrollContainer:

          // If we recently snapped after a momentum scroll, then ignore wheel events
          // to give time for the deceleration to finish. Stop ignoring after 500 msecs
          // or if it's a new scroll (larger delta or inverse sign as last event before
          // an end-of-momentum snap).
          const newEvent = {
            time: now(),
            delta: Math.abs(delta),
            direction: Math.sign(delta)
          };
          const ignoreWheelEvents = lastEventBeforeSnap && newEvent.time < lastEventBeforeSnap.time + 500 && newEvent.delta <= lastEventBeforeSnap.delta && newEvent.direction === lastEventBeforeSnap.direction;
          if (!ignoreWheelEvents) {
            lastEventBeforeSnap = undefined;
            let position = swiper.getTranslate() + delta * params.sensitivity;
            const wasBeginning = swiper.isBeginning;
            const wasEnd = swiper.isEnd;
            if (position >= swiper.minTranslate()) position = swiper.minTranslate();
            if (position <= swiper.maxTranslate()) position = swiper.maxTranslate();
            swiper.setTransition(0);
            swiper.setTranslate(position);
            swiper.updateProgress();
            swiper.updateActiveIndex();
            swiper.updateSlidesClasses();
            if (!wasBeginning && swiper.isBeginning || !wasEnd && swiper.isEnd) {
              swiper.updateSlidesClasses();
            }
            if (swiper.params.loop) {
              swiper.loopFix({
                direction: newEvent.direction < 0 ? 'next' : 'prev',
                byMousewheel: true
              });
            }
            if (swiper.params.freeMode.sticky) {
              // When wheel scrolling starts with sticky (aka snap) enabled, then detect
              // the end of a momentum scroll by storing recent (N=15?) wheel events.
              // 1. do all N events have decreasing or same (absolute value) delta?
              // 2. did all N events arrive in the last M (M=500?) msecs?
              // 3. does the earliest event have an (absolute value) delta that's
              //    at least P (P=1?) larger than the most recent event's delta?
              // 4. does the latest event have a delta that's smaller than Q (Q=6?) pixels?
              // If 1-4 are "yes" then we're near the end of a momentum scroll deceleration.
              // Snap immediately and ignore remaining wheel events in this scroll.
              // See comment above for "remaining wheel events in this scroll" determination.
              // If 1-4 aren't satisfied, then wait to snap until 500ms after the last event.
              clearTimeout(timeout);
              timeout = undefined;
              if (recentWheelEvents.length >= 15) {
                recentWheelEvents.shift(); // only store the last N events
              }

              const prevEvent = recentWheelEvents.length ? recentWheelEvents[recentWheelEvents.length - 1] : undefined;
              const firstEvent = recentWheelEvents[0];
              recentWheelEvents.push(newEvent);
              if (prevEvent && (newEvent.delta > prevEvent.delta || newEvent.direction !== prevEvent.direction)) {
                // Increasing or reverse-sign delta means the user started scrolling again. Clear the wheel event log.
                recentWheelEvents.splice(0);
              } else if (recentWheelEvents.length >= 15 && newEvent.time - firstEvent.time < 500 && firstEvent.delta - newEvent.delta >= 1 && newEvent.delta <= 6) {
                // We're at the end of the deceleration of a momentum scroll, so there's no need
                // to wait for more events. Snap ASAP on the next tick.
                // Also, because there's some remaining momentum we'll bias the snap in the
                // direction of the ongoing scroll because it's better UX for the scroll to snap
                // in the same direction as the scroll instead of reversing to snap.  Therefore,
                // if it's already scrolled more than 20% in the current direction, keep going.
                const snapToThreshold = delta > 0 ? 0.8 : 0.2;
                lastEventBeforeSnap = newEvent;
                recentWheelEvents.splice(0);
                timeout = nextTick(() => {
                  swiper.slideToClosest(swiper.params.speed, true, undefined, snapToThreshold);
                }, 0); // no delay; move on next tick
              }

              if (!timeout) {
                // if we get here, then we haven't detected the end of a momentum scroll, so
                // we'll consider a scroll "complete" when there haven't been any wheel events
                // for 500ms.
                timeout = nextTick(() => {
                  const snapToThreshold = 0.5;
                  lastEventBeforeSnap = newEvent;
                  recentWheelEvents.splice(0);
                  swiper.slideToClosest(swiper.params.speed, true, undefined, snapToThreshold);
                }, 500);
              }
            }

            // Emit event
            if (!ignoreWheelEvents) emit('scroll', e);

            // Stop autoplay
            if (swiper.params.autoplay && swiper.params.autoplayDisableOnInteraction) swiper.autoplay.stop();
            // Return page scroll on edge positions
            if (position === swiper.minTranslate() || position === swiper.maxTranslate()) return true;
          }
        }
        if (e.preventDefault) e.preventDefault();else e.returnValue = false;
        return false;
      }
      function events(method) {
        let targetEl = swiper.el;
        if (swiper.params.mousewheel.eventsTarget !== 'container') {
          targetEl = document.querySelector(swiper.params.mousewheel.eventsTarget);
        }
        targetEl[method]('mouseenter', handleMouseEnter);
        targetEl[method]('mouseleave', handleMouseLeave);
        targetEl[method]('wheel', handle);
      }
      function enable() {
        if (swiper.params.cssMode) {
          swiper.wrapperEl.removeEventListener('wheel', handle);
          return true;
        }
        if (swiper.mousewheel.enabled) return false;
        events('addEventListener');
        swiper.mousewheel.enabled = true;
        return true;
      }
      function disable() {
        if (swiper.params.cssMode) {
          swiper.wrapperEl.addEventListener(event, handle);
          return true;
        }
        if (!swiper.mousewheel.enabled) return false;
        events('removeEventListener');
        swiper.mousewheel.enabled = false;
        return true;
      }
      on('init', () => {
        if (!swiper.params.mousewheel.enabled && swiper.params.cssMode) {
          disable();
        }
        if (swiper.params.mousewheel.enabled) enable();
      });
      on('destroy', () => {
        if (swiper.params.cssMode) {
          enable();
        }
        if (swiper.mousewheel.enabled) disable();
      });
      Object.assign(swiper.mousewheel, {
        enable,
        disable
      });
    }

    function createElementIfNotDefined(swiper, originalParams, params, checkProps) {
      if (swiper.params.createElements) {
        Object.keys(checkProps).forEach(key => {
          if (!params[key] && params.auto === true) {
            let element = elementChildren(swiper.el, `.${checkProps[key]}`)[0];
            if (!element) {
              element = createElement('div', checkProps[key]);
              element.className = checkProps[key];
              swiper.el.append(element);
            }
            params[key] = element;
            originalParams[key] = element;
          }
        });
      }
      return params;
    }

    function Navigation(_ref) {
      let {
        swiper,
        extendParams,
        on,
        emit
      } = _ref;
      extendParams({
        navigation: {
          nextEl: null,
          prevEl: null,
          hideOnClick: false,
          disabledClass: 'swiper-button-disabled',
          hiddenClass: 'swiper-button-hidden',
          lockClass: 'swiper-button-lock',
          navigationDisabledClass: 'swiper-navigation-disabled'
        }
      });
      swiper.navigation = {
        nextEl: null,
        prevEl: null
      };
      const makeElementsArray = el => {
        if (!Array.isArray(el)) el = [el].filter(e => !!e);
        return el;
      };
      function getEl(el) {
        let res;
        if (el && typeof el === 'string' && swiper.isElement) {
          res = swiper.el.shadowRoot.querySelector(el);
          if (res) return res;
        }
        if (el) {
          if (typeof el === 'string') res = [...document.querySelectorAll(el)];
          if (swiper.params.uniqueNavElements && typeof el === 'string' && res.length > 1 && swiper.el.querySelectorAll(el).length === 1) {
            res = swiper.el.querySelector(el);
          }
        }
        if (el && !res) return el;
        // if (Array.isArray(res) && res.length === 1) res = res[0];
        return res;
      }
      function toggleEl(el, disabled) {
        const params = swiper.params.navigation;
        el = makeElementsArray(el);
        el.forEach(subEl => {
          if (subEl) {
            subEl.classList[disabled ? 'add' : 'remove'](...params.disabledClass.split(' '));
            if (subEl.tagName === 'BUTTON') subEl.disabled = disabled;
            if (swiper.params.watchOverflow && swiper.enabled) {
              subEl.classList[swiper.isLocked ? 'add' : 'remove'](params.lockClass);
            }
          }
        });
      }
      function update() {
        // Update Navigation Buttons
        const {
          nextEl,
          prevEl
        } = swiper.navigation;
        if (swiper.params.loop) {
          toggleEl(prevEl, false);
          toggleEl(nextEl, false);
          return;
        }
        toggleEl(prevEl, swiper.isBeginning && !swiper.params.rewind);
        toggleEl(nextEl, swiper.isEnd && !swiper.params.rewind);
      }
      function onPrevClick(e) {
        e.preventDefault();
        if (swiper.isBeginning && !swiper.params.loop && !swiper.params.rewind) return;
        swiper.slidePrev();
        emit('navigationPrev');
      }
      function onNextClick(e) {
        e.preventDefault();
        if (swiper.isEnd && !swiper.params.loop && !swiper.params.rewind) return;
        swiper.slideNext();
        emit('navigationNext');
      }
      function init() {
        const params = swiper.params.navigation;
        swiper.params.navigation = createElementIfNotDefined(swiper, swiper.originalParams.navigation, swiper.params.navigation, {
          nextEl: 'swiper-button-next',
          prevEl: 'swiper-button-prev'
        });
        if (!(params.nextEl || params.prevEl)) return;
        let nextEl = getEl(params.nextEl);
        let prevEl = getEl(params.prevEl);
        Object.assign(swiper.navigation, {
          nextEl,
          prevEl
        });
        nextEl = makeElementsArray(nextEl);
        prevEl = makeElementsArray(prevEl);
        const initButton = (el, dir) => {
          if (el) {
            el.addEventListener('click', dir === 'next' ? onNextClick : onPrevClick);
          }
          if (!swiper.enabled && el) {
            el.classList.add(...params.lockClass.split(' '));
          }
        };
        nextEl.forEach(el => initButton(el, 'next'));
        prevEl.forEach(el => initButton(el, 'prev'));
      }
      function destroy() {
        let {
          nextEl,
          prevEl
        } = swiper.navigation;
        nextEl = makeElementsArray(nextEl);
        prevEl = makeElementsArray(prevEl);
        const destroyButton = (el, dir) => {
          el.removeEventListener('click', dir === 'next' ? onNextClick : onPrevClick);
          el.classList.remove(...swiper.params.navigation.disabledClass.split(' '));
        };
        nextEl.forEach(el => destroyButton(el, 'next'));
        prevEl.forEach(el => destroyButton(el, 'prev'));
      }
      on('init', () => {
        if (swiper.params.navigation.enabled === false) {
          // eslint-disable-next-line
          disable();
        } else {
          init();
          update();
        }
      });
      on('toEdge fromEdge lock unlock', () => {
        update();
      });
      on('destroy', () => {
        destroy();
      });
      on('enable disable', () => {
        let {
          nextEl,
          prevEl
        } = swiper.navigation;
        nextEl = makeElementsArray(nextEl);
        prevEl = makeElementsArray(prevEl);
        [...nextEl, ...prevEl].filter(el => !!el).forEach(el => el.classList[swiper.enabled ? 'remove' : 'add'](swiper.params.navigation.lockClass));
      });
      on('click', (_s, e) => {
        let {
          nextEl,
          prevEl
        } = swiper.navigation;
        nextEl = makeElementsArray(nextEl);
        prevEl = makeElementsArray(prevEl);
        const targetEl = e.target;
        if (swiper.params.navigation.hideOnClick && !prevEl.includes(targetEl) && !nextEl.includes(targetEl)) {
          if (swiper.pagination && swiper.params.pagination && swiper.params.pagination.clickable && (swiper.pagination.el === targetEl || swiper.pagination.el.contains(targetEl))) return;
          let isHidden;
          if (nextEl.length) {
            isHidden = nextEl[0].classList.contains(swiper.params.navigation.hiddenClass);
          } else if (prevEl.length) {
            isHidden = prevEl[0].classList.contains(swiper.params.navigation.hiddenClass);
          }
          if (isHidden === true) {
            emit('navigationShow');
          } else {
            emit('navigationHide');
          }
          [...nextEl, ...prevEl].filter(el => !!el).forEach(el => el.classList.toggle(swiper.params.navigation.hiddenClass));
        }
      });
      const enable = () => {
        swiper.el.classList.remove(...swiper.params.navigation.navigationDisabledClass.split(' '));
        init();
        update();
      };
      const disable = () => {
        swiper.el.classList.add(...swiper.params.navigation.navigationDisabledClass.split(' '));
        destroy();
      };
      Object.assign(swiper.navigation, {
        enable,
        disable,
        update,
        init,
        destroy
      });
    }

    function classesToSelector(classes) {
      if (classes === void 0) {
        classes = '';
      }
      return `.${classes.trim().replace(/([\.:!+\/])/g, '\\$1') // eslint-disable-line
  .replace(/ /g, '.')}`;
    }

    function Pagination(_ref) {
      let {
        swiper,
        extendParams,
        on,
        emit
      } = _ref;
      const pfx = 'swiper-pagination';
      extendParams({
        pagination: {
          el: null,
          bulletElement: 'span',
          clickable: false,
          hideOnClick: false,
          renderBullet: null,
          renderProgressbar: null,
          renderFraction: null,
          renderCustom: null,
          progressbarOpposite: false,
          type: 'bullets',
          // 'bullets' or 'progressbar' or 'fraction' or 'custom'
          dynamicBullets: false,
          dynamicMainBullets: 1,
          formatFractionCurrent: number => number,
          formatFractionTotal: number => number,
          bulletClass: `${pfx}-bullet`,
          bulletActiveClass: `${pfx}-bullet-active`,
          modifierClass: `${pfx}-`,
          currentClass: `${pfx}-current`,
          totalClass: `${pfx}-total`,
          hiddenClass: `${pfx}-hidden`,
          progressbarFillClass: `${pfx}-progressbar-fill`,
          progressbarOppositeClass: `${pfx}-progressbar-opposite`,
          clickableClass: `${pfx}-clickable`,
          lockClass: `${pfx}-lock`,
          horizontalClass: `${pfx}-horizontal`,
          verticalClass: `${pfx}-vertical`,
          paginationDisabledClass: `${pfx}-disabled`
        }
      });
      swiper.pagination = {
        el: null,
        bullets: []
      };
      let bulletSize;
      let dynamicBulletIndex = 0;
      const makeElementsArray = el => {
        if (!Array.isArray(el)) el = [el].filter(e => !!e);
        return el;
      };
      function isPaginationDisabled() {
        return !swiper.params.pagination.el || !swiper.pagination.el || Array.isArray(swiper.pagination.el) && swiper.pagination.el.length === 0;
      }
      function setSideBullets(bulletEl, position) {
        const {
          bulletActiveClass
        } = swiper.params.pagination;
        if (!bulletEl) return;
        bulletEl = bulletEl[`${position === 'prev' ? 'previous' : 'next'}ElementSibling`];
        if (bulletEl) {
          bulletEl.classList.add(`${bulletActiveClass}-${position}`);
          bulletEl = bulletEl[`${position === 'prev' ? 'previous' : 'next'}ElementSibling`];
          if (bulletEl) {
            bulletEl.classList.add(`${bulletActiveClass}-${position}-${position}`);
          }
        }
      }
      function onBulletClick(e) {
        const bulletEl = e.target.closest(classesToSelector(swiper.params.pagination.bulletClass));
        if (!bulletEl) {
          return;
        }
        e.preventDefault();
        const index = elementIndex(bulletEl) * swiper.params.slidesPerGroup;
        if (swiper.params.loop) {
          if (swiper.realIndex === index) return;
          const newSlideIndex = swiper.getSlideIndexByData(index);
          const currentSlideIndex = swiper.getSlideIndexByData(swiper.realIndex);
          if (newSlideIndex > swiper.slides.length - swiper.loopedSlides) {
            swiper.loopFix({
              direction: newSlideIndex > currentSlideIndex ? 'next' : 'prev',
              activeSlideIndex: newSlideIndex,
              slideTo: false
            });
          }
          swiper.slideToLoop(index);
        } else {
          swiper.slideTo(index);
        }
      }
      function update() {
        // Render || Update Pagination bullets/items
        const rtl = swiper.rtl;
        const params = swiper.params.pagination;
        if (isPaginationDisabled()) return;
        let el = swiper.pagination.el;
        el = makeElementsArray(el);
        // Current/Total
        let current;
        let previousIndex;
        const slidesLength = swiper.virtual && swiper.params.virtual.enabled ? swiper.virtual.slides.length : swiper.slides.length;
        const total = swiper.params.loop ? Math.ceil(slidesLength / swiper.params.slidesPerGroup) : swiper.snapGrid.length;
        if (swiper.params.loop) {
          previousIndex = swiper.previousRealIndex || 0;
          current = swiper.params.slidesPerGroup > 1 ? Math.floor(swiper.realIndex / swiper.params.slidesPerGroup) : swiper.realIndex;
        } else if (typeof swiper.snapIndex !== 'undefined') {
          current = swiper.snapIndex;
          previousIndex = swiper.previousSnapIndex;
        } else {
          previousIndex = swiper.previousIndex || 0;
          current = swiper.activeIndex || 0;
        }
        // Types
        if (params.type === 'bullets' && swiper.pagination.bullets && swiper.pagination.bullets.length > 0) {
          const bullets = swiper.pagination.bullets;
          let firstIndex;
          let lastIndex;
          let midIndex;
          if (params.dynamicBullets) {
            bulletSize = elementOuterSize(bullets[0], swiper.isHorizontal() ? 'width' : 'height', true);
            el.forEach(subEl => {
              subEl.style[swiper.isHorizontal() ? 'width' : 'height'] = `${bulletSize * (params.dynamicMainBullets + 4)}px`;
            });
            if (params.dynamicMainBullets > 1 && previousIndex !== undefined) {
              dynamicBulletIndex += current - (previousIndex || 0);
              if (dynamicBulletIndex > params.dynamicMainBullets - 1) {
                dynamicBulletIndex = params.dynamicMainBullets - 1;
              } else if (dynamicBulletIndex < 0) {
                dynamicBulletIndex = 0;
              }
            }
            firstIndex = Math.max(current - dynamicBulletIndex, 0);
            lastIndex = firstIndex + (Math.min(bullets.length, params.dynamicMainBullets) - 1);
            midIndex = (lastIndex + firstIndex) / 2;
          }
          bullets.forEach(bulletEl => {
            const classesToRemove = [...['', '-next', '-next-next', '-prev', '-prev-prev', '-main'].map(suffix => `${params.bulletActiveClass}${suffix}`)].map(s => typeof s === 'string' && s.includes(' ') ? s.split(' ') : s).flat();
            bulletEl.classList.remove(...classesToRemove);
          });
          if (el.length > 1) {
            bullets.forEach(bullet => {
              const bulletIndex = elementIndex(bullet);
              if (bulletIndex === current) {
                bullet.classList.add(...params.bulletActiveClass.split(' '));
              }
              if (params.dynamicBullets) {
                if (bulletIndex >= firstIndex && bulletIndex <= lastIndex) {
                  bullet.classList.add(...`${params.bulletActiveClass}-main`.split(' '));
                }
                if (bulletIndex === firstIndex) {
                  setSideBullets(bullet, 'prev');
                }
                if (bulletIndex === lastIndex) {
                  setSideBullets(bullet, 'next');
                }
              }
            });
          } else {
            const bullet = bullets[current];
            if (bullet) {
              bullet.classList.add(...params.bulletActiveClass.split(' '));
            }
            if (params.dynamicBullets) {
              const firstDisplayedBullet = bullets[firstIndex];
              const lastDisplayedBullet = bullets[lastIndex];
              for (let i = firstIndex; i <= lastIndex; i += 1) {
                if (bullets[i]) {
                  bullets[i].classList.add(...`${params.bulletActiveClass}-main`.split(' '));
                }
              }
              setSideBullets(firstDisplayedBullet, 'prev');
              setSideBullets(lastDisplayedBullet, 'next');
            }
          }
          if (params.dynamicBullets) {
            const dynamicBulletsLength = Math.min(bullets.length, params.dynamicMainBullets + 4);
            const bulletsOffset = (bulletSize * dynamicBulletsLength - bulletSize) / 2 - midIndex * bulletSize;
            const offsetProp = rtl ? 'right' : 'left';
            bullets.forEach(bullet => {
              bullet.style[swiper.isHorizontal() ? offsetProp : 'top'] = `${bulletsOffset}px`;
            });
          }
        }
        el.forEach((subEl, subElIndex) => {
          if (params.type === 'fraction') {
            subEl.querySelectorAll(classesToSelector(params.currentClass)).forEach(fractionEl => {
              fractionEl.textContent = params.formatFractionCurrent(current + 1);
            });
            subEl.querySelectorAll(classesToSelector(params.totalClass)).forEach(totalEl => {
              totalEl.textContent = params.formatFractionTotal(total);
            });
          }
          if (params.type === 'progressbar') {
            let progressbarDirection;
            if (params.progressbarOpposite) {
              progressbarDirection = swiper.isHorizontal() ? 'vertical' : 'horizontal';
            } else {
              progressbarDirection = swiper.isHorizontal() ? 'horizontal' : 'vertical';
            }
            const scale = (current + 1) / total;
            let scaleX = 1;
            let scaleY = 1;
            if (progressbarDirection === 'horizontal') {
              scaleX = scale;
            } else {
              scaleY = scale;
            }
            subEl.querySelectorAll(classesToSelector(params.progressbarFillClass)).forEach(progressEl => {
              progressEl.style.transform = `translate3d(0,0,0) scaleX(${scaleX}) scaleY(${scaleY})`;
              progressEl.style.transitionDuration = `${swiper.params.speed}ms`;
            });
          }
          if (params.type === 'custom' && params.renderCustom) {
            subEl.innerHTML = params.renderCustom(swiper, current + 1, total);
            if (subElIndex === 0) emit('paginationRender', subEl);
          } else {
            if (subElIndex === 0) emit('paginationRender', subEl);
            emit('paginationUpdate', subEl);
          }
          if (swiper.params.watchOverflow && swiper.enabled) {
            subEl.classList[swiper.isLocked ? 'add' : 'remove'](params.lockClass);
          }
        });
      }
      function render() {
        // Render Container
        const params = swiper.params.pagination;
        if (isPaginationDisabled()) return;
        const slidesLength = swiper.virtual && swiper.params.virtual.enabled ? swiper.virtual.slides.length : swiper.slides.length;
        let el = swiper.pagination.el;
        el = makeElementsArray(el);
        let paginationHTML = '';
        if (params.type === 'bullets') {
          let numberOfBullets = swiper.params.loop ? Math.ceil(slidesLength / swiper.params.slidesPerGroup) : swiper.snapGrid.length;
          if (swiper.params.freeMode && swiper.params.freeMode.enabled && numberOfBullets > slidesLength) {
            numberOfBullets = slidesLength;
          }
          for (let i = 0; i < numberOfBullets; i += 1) {
            if (params.renderBullet) {
              paginationHTML += params.renderBullet.call(swiper, i, params.bulletClass);
            } else {
              paginationHTML += `<${params.bulletElement} class="${params.bulletClass}"></${params.bulletElement}>`;
            }
          }
        }
        if (params.type === 'fraction') {
          if (params.renderFraction) {
            paginationHTML = params.renderFraction.call(swiper, params.currentClass, params.totalClass);
          } else {
            paginationHTML = `<span class="${params.currentClass}"></span>` + ' / ' + `<span class="${params.totalClass}"></span>`;
          }
        }
        if (params.type === 'progressbar') {
          if (params.renderProgressbar) {
            paginationHTML = params.renderProgressbar.call(swiper, params.progressbarFillClass);
          } else {
            paginationHTML = `<span class="${params.progressbarFillClass}"></span>`;
          }
        }
        swiper.pagination.bullets = [];
        el.forEach(subEl => {
          if (params.type !== 'custom') {
            subEl.innerHTML = paginationHTML || '';
          }
          if (params.type === 'bullets') {
            swiper.pagination.bullets.push(...subEl.querySelectorAll(classesToSelector(params.bulletClass)));
          }
        });
        if (params.type !== 'custom') {
          emit('paginationRender', el[0]);
        }
      }
      function init() {
        swiper.params.pagination = createElementIfNotDefined(swiper, swiper.originalParams.pagination, swiper.params.pagination, {
          el: 'swiper-pagination'
        });
        const params = swiper.params.pagination;
        if (!params.el) return;
        let el;
        if (typeof params.el === 'string' && swiper.isElement) {
          el = swiper.el.shadowRoot.querySelector(params.el);
        }
        if (!el && typeof params.el === 'string') {
          el = [...document.querySelectorAll(params.el)];
        }
        if (!el) {
          el = params.el;
        }
        if (!el || el.length === 0) return;
        if (swiper.params.uniqueNavElements && typeof params.el === 'string' && Array.isArray(el) && el.length > 1) {
          el = [...swiper.el.querySelectorAll(params.el)];
          // check if it belongs to another nested Swiper
          if (el.length > 1) {
            el = el.filter(subEl => {
              if (elementParents(subEl, '.swiper')[0] !== swiper.el) return false;
              return true;
            })[0];
          }
        }
        if (Array.isArray(el) && el.length === 1) el = el[0];
        Object.assign(swiper.pagination, {
          el
        });
        el = makeElementsArray(el);
        el.forEach(subEl => {
          if (params.type === 'bullets' && params.clickable) {
            subEl.classList.add(params.clickableClass);
          }
          subEl.classList.add(params.modifierClass + params.type);
          subEl.classList.add(swiper.isHorizontal() ? params.horizontalClass : params.verticalClass);
          if (params.type === 'bullets' && params.dynamicBullets) {
            subEl.classList.add(`${params.modifierClass}${params.type}-dynamic`);
            dynamicBulletIndex = 0;
            if (params.dynamicMainBullets < 1) {
              params.dynamicMainBullets = 1;
            }
          }
          if (params.type === 'progressbar' && params.progressbarOpposite) {
            subEl.classList.add(params.progressbarOppositeClass);
          }
          if (params.clickable) {
            subEl.addEventListener('click', onBulletClick);
          }
          if (!swiper.enabled) {
            subEl.classList.add(params.lockClass);
          }
        });
      }
      function destroy() {
        const params = swiper.params.pagination;
        if (isPaginationDisabled()) return;
        let el = swiper.pagination.el;
        if (el) {
          el = makeElementsArray(el);
          el.forEach(subEl => {
            subEl.classList.remove(params.hiddenClass);
            subEl.classList.remove(params.modifierClass + params.type);
            subEl.classList.remove(swiper.isHorizontal() ? params.horizontalClass : params.verticalClass);
            if (params.clickable) {
              subEl.removeEventListener('click', onBulletClick);
            }
          });
        }
        if (swiper.pagination.bullets) swiper.pagination.bullets.forEach(subEl => subEl.classList.remove(...params.bulletActiveClass.split(' ')));
      }
      on('changeDirection', () => {
        if (!swiper.pagination || !swiper.pagination.el) return;
        const params = swiper.params.pagination;
        let {
          el
        } = swiper.pagination;
        el = makeElementsArray(el);
        el.forEach(subEl => {
          subEl.classList.remove(params.horizontalClass, params.verticalClass);
          subEl.classList.add(swiper.isHorizontal() ? params.horizontalClass : params.verticalClass);
        });
      });
      on('init', () => {
        if (swiper.params.pagination.enabled === false) {
          // eslint-disable-next-line
          disable();
        } else {
          init();
          render();
          update();
        }
      });
      on('activeIndexChange', () => {
        if (typeof swiper.snapIndex === 'undefined') {
          update();
        }
      });
      on('snapIndexChange', () => {
        update();
      });
      on('snapGridLengthChange', () => {
        render();
        update();
      });
      on('destroy', () => {
        destroy();
      });
      on('enable disable', () => {
        let {
          el
        } = swiper.pagination;
        if (el) {
          el = makeElementsArray(el);
          el.forEach(subEl => subEl.classList[swiper.enabled ? 'remove' : 'add'](swiper.params.pagination.lockClass));
        }
      });
      on('lock unlock', () => {
        update();
      });
      on('click', (_s, e) => {
        const targetEl = e.target;
        let {
          el
        } = swiper.pagination;
        if (!Array.isArray(el)) el = [el].filter(element => !!element);
        if (swiper.params.pagination.el && swiper.params.pagination.hideOnClick && el && el.length > 0 && !targetEl.classList.contains(swiper.params.pagination.bulletClass)) {
          if (swiper.navigation && (swiper.navigation.nextEl && targetEl === swiper.navigation.nextEl || swiper.navigation.prevEl && targetEl === swiper.navigation.prevEl)) return;
          const isHidden = el[0].classList.contains(swiper.params.pagination.hiddenClass);
          if (isHidden === true) {
            emit('paginationShow');
          } else {
            emit('paginationHide');
          }
          el.forEach(subEl => subEl.classList.toggle(swiper.params.pagination.hiddenClass));
        }
      });
      const enable = () => {
        swiper.el.classList.remove(swiper.params.pagination.paginationDisabledClass);
        let {
          el
        } = swiper.pagination;
        if (el) {
          el = makeElementsArray(el);
          el.forEach(subEl => subEl.classList.remove(swiper.params.pagination.paginationDisabledClass));
        }
        init();
        render();
        update();
      };
      const disable = () => {
        swiper.el.classList.add(swiper.params.pagination.paginationDisabledClass);
        let {
          el
        } = swiper.pagination;
        if (el) {
          el = makeElementsArray(el);
          el.forEach(subEl => subEl.classList.add(swiper.params.pagination.paginationDisabledClass));
        }
        destroy();
      };
      Object.assign(swiper.pagination, {
        enable,
        disable,
        render,
        update,
        init,
        destroy
      });
    }

    function Scrollbar(_ref) {
      let {
        swiper,
        extendParams,
        on,
        emit
      } = _ref;
      const document = getDocument();
      let isTouched = false;
      let timeout = null;
      let dragTimeout = null;
      let dragStartPos;
      let dragSize;
      let trackSize;
      let divider;
      extendParams({
        scrollbar: {
          el: null,
          dragSize: 'auto',
          hide: false,
          draggable: false,
          snapOnRelease: true,
          lockClass: 'swiper-scrollbar-lock',
          dragClass: 'swiper-scrollbar-drag',
          scrollbarDisabledClass: 'swiper-scrollbar-disabled',
          horizontalClass: `swiper-scrollbar-horizontal`,
          verticalClass: `swiper-scrollbar-vertical`
        }
      });
      swiper.scrollbar = {
        el: null,
        dragEl: null
      };
      function setTranslate() {
        if (!swiper.params.scrollbar.el || !swiper.scrollbar.el) return;
        const {
          scrollbar,
          rtlTranslate: rtl
        } = swiper;
        const {
          dragEl,
          el
        } = scrollbar;
        const params = swiper.params.scrollbar;
        const progress = swiper.params.loop ? swiper.progressLoop : swiper.progress;
        let newSize = dragSize;
        let newPos = (trackSize - dragSize) * progress;
        if (rtl) {
          newPos = -newPos;
          if (newPos > 0) {
            newSize = dragSize - newPos;
            newPos = 0;
          } else if (-newPos + dragSize > trackSize) {
            newSize = trackSize + newPos;
          }
        } else if (newPos < 0) {
          newSize = dragSize + newPos;
          newPos = 0;
        } else if (newPos + dragSize > trackSize) {
          newSize = trackSize - newPos;
        }
        if (swiper.isHorizontal()) {
          dragEl.style.transform = `translate3d(${newPos}px, 0, 0)`;
          dragEl.style.width = `${newSize}px`;
        } else {
          dragEl.style.transform = `translate3d(0px, ${newPos}px, 0)`;
          dragEl.style.height = `${newSize}px`;
        }
        if (params.hide) {
          clearTimeout(timeout);
          el.style.opacity = 1;
          timeout = setTimeout(() => {
            el.style.opacity = 0;
            el.style.transitionDuration = '400ms';
          }, 1000);
        }
      }
      function setTransition(duration) {
        if (!swiper.params.scrollbar.el || !swiper.scrollbar.el) return;
        swiper.scrollbar.dragEl.style.transitionDuration = `${duration}ms`;
      }
      function updateSize() {
        if (!swiper.params.scrollbar.el || !swiper.scrollbar.el) return;
        const {
          scrollbar
        } = swiper;
        const {
          dragEl,
          el
        } = scrollbar;
        dragEl.style.width = '';
        dragEl.style.height = '';
        trackSize = swiper.isHorizontal() ? el.offsetWidth : el.offsetHeight;
        divider = swiper.size / (swiper.virtualSize + swiper.params.slidesOffsetBefore - (swiper.params.centeredSlides ? swiper.snapGrid[0] : 0));
        if (swiper.params.scrollbar.dragSize === 'auto') {
          dragSize = trackSize * divider;
        } else {
          dragSize = parseInt(swiper.params.scrollbar.dragSize, 10);
        }
        if (swiper.isHorizontal()) {
          dragEl.style.width = `${dragSize}px`;
        } else {
          dragEl.style.height = `${dragSize}px`;
        }
        if (divider >= 1) {
          el.style.display = 'none';
        } else {
          el.style.display = '';
        }
        if (swiper.params.scrollbar.hide) {
          el.style.opacity = 0;
        }
        if (swiper.params.watchOverflow && swiper.enabled) {
          scrollbar.el.classList[swiper.isLocked ? 'add' : 'remove'](swiper.params.scrollbar.lockClass);
        }
      }
      function getPointerPosition(e) {
        return swiper.isHorizontal() ? e.clientX : e.clientY;
      }
      function setDragPosition(e) {
        const {
          scrollbar,
          rtlTranslate: rtl
        } = swiper;
        const {
          el
        } = scrollbar;
        let positionRatio;
        positionRatio = (getPointerPosition(e) - elementOffset(el)[swiper.isHorizontal() ? 'left' : 'top'] - (dragStartPos !== null ? dragStartPos : dragSize / 2)) / (trackSize - dragSize);
        positionRatio = Math.max(Math.min(positionRatio, 1), 0);
        if (rtl) {
          positionRatio = 1 - positionRatio;
        }
        const position = swiper.minTranslate() + (swiper.maxTranslate() - swiper.minTranslate()) * positionRatio;
        swiper.updateProgress(position);
        swiper.setTranslate(position);
        swiper.updateActiveIndex();
        swiper.updateSlidesClasses();
      }
      function onDragStart(e) {
        const params = swiper.params.scrollbar;
        const {
          scrollbar,
          wrapperEl
        } = swiper;
        const {
          el,
          dragEl
        } = scrollbar;
        isTouched = true;
        dragStartPos = e.target === dragEl ? getPointerPosition(e) - e.target.getBoundingClientRect()[swiper.isHorizontal() ? 'left' : 'top'] : null;
        e.preventDefault();
        e.stopPropagation();
        wrapperEl.style.transitionDuration = '100ms';
        dragEl.style.transitionDuration = '100ms';
        setDragPosition(e);
        clearTimeout(dragTimeout);
        el.style.transitionDuration = '0ms';
        if (params.hide) {
          el.style.opacity = 1;
        }
        if (swiper.params.cssMode) {
          swiper.wrapperEl.style['scroll-snap-type'] = 'none';
        }
        emit('scrollbarDragStart', e);
      }
      function onDragMove(e) {
        const {
          scrollbar,
          wrapperEl
        } = swiper;
        const {
          el,
          dragEl
        } = scrollbar;
        if (!isTouched) return;
        if (e.preventDefault) e.preventDefault();else e.returnValue = false;
        setDragPosition(e);
        wrapperEl.style.transitionDuration = '0ms';
        el.style.transitionDuration = '0ms';
        dragEl.style.transitionDuration = '0ms';
        emit('scrollbarDragMove', e);
      }
      function onDragEnd(e) {
        const params = swiper.params.scrollbar;
        const {
          scrollbar,
          wrapperEl
        } = swiper;
        const {
          el
        } = scrollbar;
        if (!isTouched) return;
        isTouched = false;
        if (swiper.params.cssMode) {
          swiper.wrapperEl.style['scroll-snap-type'] = '';
          wrapperEl.style.transitionDuration = '';
        }
        if (params.hide) {
          clearTimeout(dragTimeout);
          dragTimeout = nextTick(() => {
            el.style.opacity = 0;
            el.style.transitionDuration = '400ms';
          }, 1000);
        }
        emit('scrollbarDragEnd', e);
        if (params.snapOnRelease) {
          swiper.slideToClosest();
        }
      }
      function events(method) {
        const {
          scrollbar,
          params
        } = swiper;
        const el = scrollbar.el;
        if (!el) return;
        const target = el;
        const activeListener = params.passiveListeners ? {
          passive: false,
          capture: false
        } : false;
        const passiveListener = params.passiveListeners ? {
          passive: true,
          capture: false
        } : false;
        if (!target) return;
        const eventMethod = method === 'on' ? 'addEventListener' : 'removeEventListener';
        target[eventMethod]('pointerdown', onDragStart, activeListener);
        document[eventMethod]('pointermove', onDragMove, activeListener);
        document[eventMethod]('pointerup', onDragEnd, passiveListener);
      }
      function enableDraggable() {
        if (!swiper.params.scrollbar.el || !swiper.scrollbar.el) return;
        events('on');
      }
      function disableDraggable() {
        if (!swiper.params.scrollbar.el || !swiper.scrollbar.el) return;
        events('off');
      }
      function init() {
        const {
          scrollbar,
          el: swiperEl
        } = swiper;
        swiper.params.scrollbar = createElementIfNotDefined(swiper, swiper.originalParams.scrollbar, swiper.params.scrollbar, {
          el: 'swiper-scrollbar'
        });
        const params = swiper.params.scrollbar;
        if (!params.el) return;
        let el;
        if (typeof params.el === 'string' && swiper.isElement) {
          el = swiper.el.shadowRoot.querySelector(params.el);
        }
        if (!el && typeof params.el === 'string') {
          el = document.querySelectorAll(params.el);
        } else if (!el) {
          el = params.el;
        }
        if (swiper.params.uniqueNavElements && typeof params.el === 'string' && el.length > 1 && swiperEl.querySelectorAll(params.el).length === 1) {
          el = swiperEl.querySelector(params.el);
        }
        if (el.length > 0) el = el[0];
        el.classList.add(swiper.isHorizontal() ? params.horizontalClass : params.verticalClass);
        let dragEl;
        if (el) {
          dragEl = el.querySelector(`.${swiper.params.scrollbar.dragClass}`);
          if (!dragEl) {
            dragEl = createElement('div', swiper.params.scrollbar.dragClass);
            el.append(dragEl);
          }
        }
        Object.assign(scrollbar, {
          el,
          dragEl
        });
        if (params.draggable) {
          enableDraggable();
        }
        if (el) {
          el.classList[swiper.enabled ? 'remove' : 'add'](swiper.params.scrollbar.lockClass);
        }
      }
      function destroy() {
        const params = swiper.params.scrollbar;
        const el = swiper.scrollbar.el;
        if (el) {
          el.classList.remove(swiper.isHorizontal() ? params.horizontalClass : params.verticalClass);
        }
        disableDraggable();
      }
      on('init', () => {
        if (swiper.params.scrollbar.enabled === false) {
          // eslint-disable-next-line
          disable();
        } else {
          init();
          updateSize();
          setTranslate();
        }
      });
      on('update resize observerUpdate lock unlock', () => {
        updateSize();
      });
      on('setTranslate', () => {
        setTranslate();
      });
      on('setTransition', (_s, duration) => {
        setTransition(duration);
      });
      on('enable disable', () => {
        const {
          el
        } = swiper.scrollbar;
        if (el) {
          el.classList[swiper.enabled ? 'remove' : 'add'](swiper.params.scrollbar.lockClass);
        }
      });
      on('destroy', () => {
        destroy();
      });
      const enable = () => {
        swiper.el.classList.remove(swiper.params.scrollbar.scrollbarDisabledClass);
        if (swiper.scrollbar.el) {
          swiper.scrollbar.el.classList.remove(swiper.params.scrollbar.scrollbarDisabledClass);
        }
        init();
        updateSize();
        setTranslate();
      };
      const disable = () => {
        swiper.el.classList.add(swiper.params.scrollbar.scrollbarDisabledClass);
        if (swiper.scrollbar.el) {
          swiper.scrollbar.el.classList.add(swiper.params.scrollbar.scrollbarDisabledClass);
        }
        destroy();
      };
      Object.assign(swiper.scrollbar, {
        enable,
        disable,
        updateSize,
        setTranslate,
        init,
        destroy
      });
    }

    function Parallax(_ref) {
      let {
        swiper,
        extendParams,
        on
      } = _ref;
      extendParams({
        parallax: {
          enabled: false
        }
      });
      const setTransform = (el, progress) => {
        const {
          rtl
        } = swiper;
        const rtlFactor = rtl ? -1 : 1;
        const p = el.getAttribute('data-swiper-parallax') || '0';
        let x = el.getAttribute('data-swiper-parallax-x');
        let y = el.getAttribute('data-swiper-parallax-y');
        const scale = el.getAttribute('data-swiper-parallax-scale');
        const opacity = el.getAttribute('data-swiper-parallax-opacity');
        const rotate = el.getAttribute('data-swiper-parallax-rotate');
        if (x || y) {
          x = x || '0';
          y = y || '0';
        } else if (swiper.isHorizontal()) {
          x = p;
          y = '0';
        } else {
          y = p;
          x = '0';
        }
        if (x.indexOf('%') >= 0) {
          x = `${parseInt(x, 10) * progress * rtlFactor}%`;
        } else {
          x = `${x * progress * rtlFactor}px`;
        }
        if (y.indexOf('%') >= 0) {
          y = `${parseInt(y, 10) * progress}%`;
        } else {
          y = `${y * progress}px`;
        }
        if (typeof opacity !== 'undefined' && opacity !== null) {
          const currentOpacity = opacity - (opacity - 1) * (1 - Math.abs(progress));
          el.style.opacity = currentOpacity;
        }
        let transform = `translate3d(${x}, ${y}, 0px)`;
        if (typeof scale !== 'undefined' && scale !== null) {
          const currentScale = scale - (scale - 1) * (1 - Math.abs(progress));
          transform += ` scale(${currentScale})`;
        }
        if (rotate && typeof rotate !== 'undefined' && rotate !== null) {
          const currentRotate = rotate * progress * -1;
          transform += ` rotate(${currentRotate}deg)`;
        }
        el.style.transform = transform;
      };
      const setTranslate = () => {
        const {
          el,
          slides,
          progress,
          snapGrid
        } = swiper;
        elementChildren(el, '[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y], [data-swiper-parallax-opacity], [data-swiper-parallax-scale]').forEach(subEl => {
          setTransform(subEl, progress);
        });
        slides.forEach((slideEl, slideIndex) => {
          let slideProgress = slideEl.progress;
          if (swiper.params.slidesPerGroup > 1 && swiper.params.slidesPerView !== 'auto') {
            slideProgress += Math.ceil(slideIndex / 2) - progress * (snapGrid.length - 1);
          }
          slideProgress = Math.min(Math.max(slideProgress, -1), 1);
          slideEl.querySelectorAll('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y], [data-swiper-parallax-opacity], [data-swiper-parallax-scale], [data-swiper-parallax-rotate]').forEach(subEl => {
            setTransform(subEl, slideProgress);
          });
        });
      };
      const setTransition = function (duration) {
        if (duration === void 0) {
          duration = swiper.params.speed;
        }
        const {
          el
        } = swiper;
        el.querySelectorAll('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y], [data-swiper-parallax-opacity], [data-swiper-parallax-scale]').forEach(parallaxEl => {
          let parallaxDuration = parseInt(parallaxEl.getAttribute('data-swiper-parallax-duration'), 10) || duration;
          if (duration === 0) parallaxDuration = 0;
          parallaxEl.style.transitionDuration = `${parallaxDuration}ms`;
        });
      };
      on('beforeInit', () => {
        if (!swiper.params.parallax.enabled) return;
        swiper.params.watchSlidesProgress = true;
        swiper.originalParams.watchSlidesProgress = true;
      });
      on('init', () => {
        if (!swiper.params.parallax.enabled) return;
        setTranslate();
      });
      on('setTranslate', () => {
        if (!swiper.params.parallax.enabled) return;
        setTranslate();
      });
      on('setTransition', (_swiper, duration) => {
        if (!swiper.params.parallax.enabled) return;
        setTransition(duration);
      });
    }

    function Zoom(_ref) {
      let {
        swiper,
        extendParams,
        on,
        emit
      } = _ref;
      const window = getWindow();
      extendParams({
        zoom: {
          enabled: false,
          maxRatio: 3,
          minRatio: 1,
          toggle: true,
          containerClass: 'swiper-zoom-container',
          zoomedSlideClass: 'swiper-slide-zoomed'
        }
      });
      swiper.zoom = {
        enabled: false
      };
      let currentScale = 1;
      let isScaling = false;
      let fakeGestureTouched;
      let fakeGestureMoved;
      const evCache = [];
      const gesture = {
        originX: 0,
        originY: 0,
        slideEl: undefined,
        slideWidth: undefined,
        slideHeight: undefined,
        imageEl: undefined,
        imageWrapEl: undefined,
        maxRatio: 3
      };
      const image = {
        isTouched: undefined,
        isMoved: undefined,
        currentX: undefined,
        currentY: undefined,
        minX: undefined,
        minY: undefined,
        maxX: undefined,
        maxY: undefined,
        width: undefined,
        height: undefined,
        startX: undefined,
        startY: undefined,
        touchesStart: {},
        touchesCurrent: {}
      };
      const velocity = {
        x: undefined,
        y: undefined,
        prevPositionX: undefined,
        prevPositionY: undefined,
        prevTime: undefined
      };
      let scale = 1;
      Object.defineProperty(swiper.zoom, 'scale', {
        get() {
          return scale;
        },
        set(value) {
          if (scale !== value) {
            const imageEl = gesture.imageEl;
            const slideEl = gesture.slideEl;
            emit('zoomChange', value, imageEl, slideEl);
          }
          scale = value;
        }
      });
      function getDistanceBetweenTouches() {
        if (evCache.length < 2) return 1;
        const x1 = evCache[0].pageX;
        const y1 = evCache[0].pageY;
        const x2 = evCache[1].pageX;
        const y2 = evCache[1].pageY;
        const distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
        return distance;
      }
      function getScaleOrigin() {
        if (evCache.length < 2) return {
          x: null,
          y: null
        };
        const box = gesture.imageEl.getBoundingClientRect();
        return [(evCache[0].pageX + (evCache[1].pageX - evCache[0].pageX) / 2 - box.x) / currentScale, (evCache[0].pageY + (evCache[1].pageY - evCache[0].pageY) / 2 - box.y) / currentScale];
      }
      function getSlideSelector() {
        return swiper.isElement ? `swiper-slide` : `.${swiper.params.slideClass}`;
      }
      function eventWithinSlide(e) {
        const slideSelector = getSlideSelector();
        if (e.target.matches(slideSelector)) return true;
        if (swiper.slides.filter(slideEl => slideEl.contains(e.target)).length > 0) return true;
        return false;
      }
      function eventWithinZoomContainer(e) {
        const selector = `.${swiper.params.zoom.containerClass}`;
        if (e.target.matches(selector)) return true;
        if ([...swiper.el.querySelectorAll(selector)].filter(containerEl => containerEl.contains(e.target)).length > 0) return true;
        return false;
      }

      // Events
      function onGestureStart(e) {
        if (e.pointerType === 'mouse') {
          evCache.splice(0, evCache.length);
        }
        if (!eventWithinSlide(e)) return;
        const params = swiper.params.zoom;
        fakeGestureTouched = false;
        fakeGestureMoved = false;
        evCache.push(e);
        if (evCache.length < 2) {
          return;
        }
        fakeGestureTouched = true;
        gesture.scaleStart = getDistanceBetweenTouches();
        if (!gesture.slideEl) {
          gesture.slideEl = e.target.closest(`.${swiper.params.slideClass}, swiper-slide`);
          if (!gesture.slideEl) gesture.slideEl = swiper.slides[swiper.activeIndex];
          let imageEl = gesture.slideEl.querySelector(`.${params.containerClass}`);
          if (imageEl) {
            imageEl = imageEl.querySelectorAll('picture, img, svg, canvas, .swiper-zoom-target')[0];
          }
          gesture.imageEl = imageEl;
          if (imageEl) {
            gesture.imageWrapEl = elementParents(gesture.imageEl, `.${params.containerClass}`)[0];
          } else {
            gesture.imageWrapEl = undefined;
          }
          if (!gesture.imageWrapEl) {
            gesture.imageEl = undefined;
            return;
          }
          gesture.maxRatio = gesture.imageWrapEl.getAttribute('data-swiper-zoom') || params.maxRatio;
        }
        if (gesture.imageEl) {
          const [originX, originY] = getScaleOrigin();
          gesture.originX = originX;
          gesture.originY = originY;
          gesture.imageEl.style.transitionDuration = '0ms';
        }
        isScaling = true;
      }
      function onGestureChange(e) {
        if (!eventWithinSlide(e)) return;
        const params = swiper.params.zoom;
        const zoom = swiper.zoom;
        const pointerIndex = evCache.findIndex(cachedEv => cachedEv.pointerId === e.pointerId);
        if (pointerIndex >= 0) evCache[pointerIndex] = e;
        if (evCache.length < 2) {
          return;
        }
        fakeGestureMoved = true;
        gesture.scaleMove = getDistanceBetweenTouches();
        if (!gesture.imageEl) {
          return;
        }
        zoom.scale = gesture.scaleMove / gesture.scaleStart * currentScale;
        if (zoom.scale > gesture.maxRatio) {
          zoom.scale = gesture.maxRatio - 1 + (zoom.scale - gesture.maxRatio + 1) ** 0.5;
        }
        if (zoom.scale < params.minRatio) {
          zoom.scale = params.minRatio + 1 - (params.minRatio - zoom.scale + 1) ** 0.5;
        }
        gesture.imageEl.style.transform = `translate3d(0,0,0) scale(${zoom.scale})`;
      }
      function onGestureEnd(e) {
        if (!eventWithinSlide(e)) return;
        if (e.pointerType === 'mouse' && e.type === 'pointerout') return;
        const params = swiper.params.zoom;
        const zoom = swiper.zoom;
        const pointerIndex = evCache.findIndex(cachedEv => cachedEv.pointerId === e.pointerId);
        if (pointerIndex >= 0) evCache.splice(pointerIndex, 1);
        if (!fakeGestureTouched || !fakeGestureMoved) {
          return;
        }
        fakeGestureTouched = false;
        fakeGestureMoved = false;
        if (!gesture.imageEl) return;
        zoom.scale = Math.max(Math.min(zoom.scale, gesture.maxRatio), params.minRatio);
        gesture.imageEl.style.transitionDuration = `${swiper.params.speed}ms`;
        gesture.imageEl.style.transform = `translate3d(0,0,0) scale(${zoom.scale})`;
        currentScale = zoom.scale;
        isScaling = false;
        if (zoom.scale > 1 && gesture.slideEl) {
          gesture.slideEl.classList.add(`${params.zoomedSlideClass}`);
        } else if (zoom.scale <= 1 && gesture.slideEl) {
          gesture.slideEl.classList.remove(`${params.zoomedSlideClass}`);
        }
        if (zoom.scale === 1) {
          gesture.originX = 0;
          gesture.originY = 0;
          gesture.slideEl = undefined;
        }
      }
      function onTouchStart(e) {
        const device = swiper.device;
        if (!gesture.imageEl) return;
        if (image.isTouched) return;
        if (device.android && e.cancelable) e.preventDefault();
        image.isTouched = true;
        const event = evCache.length > 0 ? evCache[0] : e;
        image.touchesStart.x = event.pageX;
        image.touchesStart.y = event.pageY;
      }
      function onTouchMove(e) {
        if (!eventWithinSlide(e) || !eventWithinZoomContainer(e)) return;
        const zoom = swiper.zoom;
        if (!gesture.imageEl) return;
        if (!image.isTouched || !gesture.slideEl) return;
        if (!image.isMoved) {
          image.width = gesture.imageEl.offsetWidth;
          image.height = gesture.imageEl.offsetHeight;
          image.startX = getTranslate(gesture.imageWrapEl, 'x') || 0;
          image.startY = getTranslate(gesture.imageWrapEl, 'y') || 0;
          gesture.slideWidth = gesture.slideEl.offsetWidth;
          gesture.slideHeight = gesture.slideEl.offsetHeight;
          gesture.imageWrapEl.style.transitionDuration = '0ms';
        }
        // Define if we need image drag
        const scaledWidth = image.width * zoom.scale;
        const scaledHeight = image.height * zoom.scale;
        if (scaledWidth < gesture.slideWidth && scaledHeight < gesture.slideHeight) return;
        image.minX = Math.min(gesture.slideWidth / 2 - scaledWidth / 2, 0);
        image.maxX = -image.minX;
        image.minY = Math.min(gesture.slideHeight / 2 - scaledHeight / 2, 0);
        image.maxY = -image.minY;
        image.touchesCurrent.x = evCache.length > 0 ? evCache[0].pageX : e.pageX;
        image.touchesCurrent.y = evCache.length > 0 ? evCache[0].pageY : e.pageY;
        const touchesDiff = Math.max(Math.abs(image.touchesCurrent.x - image.touchesStart.x), Math.abs(image.touchesCurrent.y - image.touchesStart.y));
        if (touchesDiff > 5) {
          swiper.allowClick = false;
        }
        if (!image.isMoved && !isScaling) {
          if (swiper.isHorizontal() && (Math.floor(image.minX) === Math.floor(image.startX) && image.touchesCurrent.x < image.touchesStart.x || Math.floor(image.maxX) === Math.floor(image.startX) && image.touchesCurrent.x > image.touchesStart.x)) {
            image.isTouched = false;
            return;
          }
          if (!swiper.isHorizontal() && (Math.floor(image.minY) === Math.floor(image.startY) && image.touchesCurrent.y < image.touchesStart.y || Math.floor(image.maxY) === Math.floor(image.startY) && image.touchesCurrent.y > image.touchesStart.y)) {
            image.isTouched = false;
            return;
          }
        }
        if (e.cancelable) {
          e.preventDefault();
        }
        e.stopPropagation();
        image.isMoved = true;
        const scaleRatio = (zoom.scale - currentScale) / (gesture.maxRatio - swiper.params.zoom.minRatio);
        const {
          originX,
          originY
        } = gesture;
        image.currentX = image.touchesCurrent.x - image.touchesStart.x + image.startX + scaleRatio * (image.width - originX * 2);
        image.currentY = image.touchesCurrent.y - image.touchesStart.y + image.startY + scaleRatio * (image.height - originY * 2);
        if (image.currentX < image.minX) {
          image.currentX = image.minX + 1 - (image.minX - image.currentX + 1) ** 0.8;
        }
        if (image.currentX > image.maxX) {
          image.currentX = image.maxX - 1 + (image.currentX - image.maxX + 1) ** 0.8;
        }
        if (image.currentY < image.minY) {
          image.currentY = image.minY + 1 - (image.minY - image.currentY + 1) ** 0.8;
        }
        if (image.currentY > image.maxY) {
          image.currentY = image.maxY - 1 + (image.currentY - image.maxY + 1) ** 0.8;
        }

        // Velocity
        if (!velocity.prevPositionX) velocity.prevPositionX = image.touchesCurrent.x;
        if (!velocity.prevPositionY) velocity.prevPositionY = image.touchesCurrent.y;
        if (!velocity.prevTime) velocity.prevTime = Date.now();
        velocity.x = (image.touchesCurrent.x - velocity.prevPositionX) / (Date.now() - velocity.prevTime) / 2;
        velocity.y = (image.touchesCurrent.y - velocity.prevPositionY) / (Date.now() - velocity.prevTime) / 2;
        if (Math.abs(image.touchesCurrent.x - velocity.prevPositionX) < 2) velocity.x = 0;
        if (Math.abs(image.touchesCurrent.y - velocity.prevPositionY) < 2) velocity.y = 0;
        velocity.prevPositionX = image.touchesCurrent.x;
        velocity.prevPositionY = image.touchesCurrent.y;
        velocity.prevTime = Date.now();
        gesture.imageWrapEl.style.transform = `translate3d(${image.currentX}px, ${image.currentY}px,0)`;
      }
      function onTouchEnd() {
        const zoom = swiper.zoom;
        if (!gesture.imageEl) return;
        if (!image.isTouched || !image.isMoved) {
          image.isTouched = false;
          image.isMoved = false;
          return;
        }
        image.isTouched = false;
        image.isMoved = false;
        let momentumDurationX = 300;
        let momentumDurationY = 300;
        const momentumDistanceX = velocity.x * momentumDurationX;
        const newPositionX = image.currentX + momentumDistanceX;
        const momentumDistanceY = velocity.y * momentumDurationY;
        const newPositionY = image.currentY + momentumDistanceY;

        // Fix duration
        if (velocity.x !== 0) momentumDurationX = Math.abs((newPositionX - image.currentX) / velocity.x);
        if (velocity.y !== 0) momentumDurationY = Math.abs((newPositionY - image.currentY) / velocity.y);
        const momentumDuration = Math.max(momentumDurationX, momentumDurationY);
        image.currentX = newPositionX;
        image.currentY = newPositionY;
        // Define if we need image drag
        const scaledWidth = image.width * zoom.scale;
        const scaledHeight = image.height * zoom.scale;
        image.minX = Math.min(gesture.slideWidth / 2 - scaledWidth / 2, 0);
        image.maxX = -image.minX;
        image.minY = Math.min(gesture.slideHeight / 2 - scaledHeight / 2, 0);
        image.maxY = -image.minY;
        image.currentX = Math.max(Math.min(image.currentX, image.maxX), image.minX);
        image.currentY = Math.max(Math.min(image.currentY, image.maxY), image.minY);
        gesture.imageWrapEl.style.transitionDuration = `${momentumDuration}ms`;
        gesture.imageWrapEl.style.transform = `translate3d(${image.currentX}px, ${image.currentY}px,0)`;
      }
      function onTransitionEnd() {
        const zoom = swiper.zoom;
        if (gesture.slideEl && swiper.activeIndex !== swiper.slides.indexOf(gesture.slideEl)) {
          if (gesture.imageEl) {
            gesture.imageEl.style.transform = 'translate3d(0,0,0) scale(1)';
          }
          if (gesture.imageWrapEl) {
            gesture.imageWrapEl.style.transform = 'translate3d(0,0,0)';
          }
          gesture.slideEl.classList.remove(`${swiper.params.zoom.zoomedSlideClass}`);
          zoom.scale = 1;
          currentScale = 1;
          gesture.slideEl = undefined;
          gesture.imageEl = undefined;
          gesture.imageWrapEl = undefined;
          gesture.originX = 0;
          gesture.originY = 0;
        }
      }
      function zoomIn(e) {
        const zoom = swiper.zoom;
        const params = swiper.params.zoom;
        if (!gesture.slideEl) {
          if (e && e.target) {
            gesture.slideEl = e.target.closest(`.${swiper.params.slideClass}, swiper-slide`);
          }
          if (!gesture.slideEl) {
            if (swiper.params.virtual && swiper.params.virtual.enabled && swiper.virtual) {
              gesture.slideEl = elementChildren(swiper.slidesEl, `.${swiper.params.slideActiveClass}`)[0];
            } else {
              gesture.slideEl = swiper.slides[swiper.activeIndex];
            }
          }
          let imageEl = gesture.slideEl.querySelector(`.${params.containerClass}`);
          if (imageEl) {
            imageEl = imageEl.querySelectorAll('picture, img, svg, canvas, .swiper-zoom-target')[0];
          }
          gesture.imageEl = imageEl;
          if (imageEl) {
            gesture.imageWrapEl = elementParents(gesture.imageEl, `.${params.containerClass}`)[0];
          } else {
            gesture.imageWrapEl = undefined;
          }
        }
        if (!gesture.imageEl || !gesture.imageWrapEl) return;
        if (swiper.params.cssMode) {
          swiper.wrapperEl.style.overflow = 'hidden';
          swiper.wrapperEl.style.touchAction = 'none';
        }
        gesture.slideEl.classList.add(`${params.zoomedSlideClass}`);
        let touchX;
        let touchY;
        let offsetX;
        let offsetY;
        let diffX;
        let diffY;
        let translateX;
        let translateY;
        let imageWidth;
        let imageHeight;
        let scaledWidth;
        let scaledHeight;
        let translateMinX;
        let translateMinY;
        let translateMaxX;
        let translateMaxY;
        let slideWidth;
        let slideHeight;
        if (typeof image.touchesStart.x === 'undefined' && e) {
          touchX = e.pageX;
          touchY = e.pageY;
        } else {
          touchX = image.touchesStart.x;
          touchY = image.touchesStart.y;
        }
        const forceZoomRatio = typeof e === 'number' ? e : null;
        if (currentScale === 1 && forceZoomRatio) {
          touchX = undefined;
          touchY = undefined;
        }
        zoom.scale = forceZoomRatio || gesture.imageWrapEl.getAttribute('data-swiper-zoom') || params.maxRatio;
        currentScale = forceZoomRatio || gesture.imageWrapEl.getAttribute('data-swiper-zoom') || params.maxRatio;
        if (e && !(currentScale === 1 && forceZoomRatio)) {
          slideWidth = gesture.slideEl.offsetWidth;
          slideHeight = gesture.slideEl.offsetHeight;
          offsetX = elementOffset(gesture.slideEl).left + window.scrollX;
          offsetY = elementOffset(gesture.slideEl).top + window.scrollY;
          diffX = offsetX + slideWidth / 2 - touchX;
          diffY = offsetY + slideHeight / 2 - touchY;
          imageWidth = gesture.imageEl.offsetWidth;
          imageHeight = gesture.imageEl.offsetHeight;
          scaledWidth = imageWidth * zoom.scale;
          scaledHeight = imageHeight * zoom.scale;
          translateMinX = Math.min(slideWidth / 2 - scaledWidth / 2, 0);
          translateMinY = Math.min(slideHeight / 2 - scaledHeight / 2, 0);
          translateMaxX = -translateMinX;
          translateMaxY = -translateMinY;
          translateX = diffX * zoom.scale;
          translateY = diffY * zoom.scale;
          if (translateX < translateMinX) {
            translateX = translateMinX;
          }
          if (translateX > translateMaxX) {
            translateX = translateMaxX;
          }
          if (translateY < translateMinY) {
            translateY = translateMinY;
          }
          if (translateY > translateMaxY) {
            translateY = translateMaxY;
          }
        } else {
          translateX = 0;
          translateY = 0;
        }
        if (forceZoomRatio && zoom.scale === 1) {
          gesture.originX = 0;
          gesture.originY = 0;
        }
        gesture.imageWrapEl.style.transitionDuration = '300ms';
        gesture.imageWrapEl.style.transform = `translate3d(${translateX}px, ${translateY}px,0)`;
        gesture.imageEl.style.transitionDuration = '300ms';
        gesture.imageEl.style.transform = `translate3d(0,0,0) scale(${zoom.scale})`;
      }
      function zoomOut() {
        const zoom = swiper.zoom;
        const params = swiper.params.zoom;
        if (!gesture.slideEl) {
          if (swiper.params.virtual && swiper.params.virtual.enabled && swiper.virtual) {
            gesture.slideEl = elementChildren(swiper.slidesEl, `.${swiper.params.slideActiveClass}`)[0];
          } else {
            gesture.slideEl = swiper.slides[swiper.activeIndex];
          }
          let imageEl = gesture.slideEl.querySelector(`.${params.containerClass}`);
          if (imageEl) {
            imageEl = imageEl.querySelectorAll('picture, img, svg, canvas, .swiper-zoom-target')[0];
          }
          gesture.imageEl = imageEl;
          if (imageEl) {
            gesture.imageWrapEl = elementParents(gesture.imageEl, `.${params.containerClass}`)[0];
          } else {
            gesture.imageWrapEl = undefined;
          }
        }
        if (!gesture.imageEl || !gesture.imageWrapEl) return;
        if (swiper.params.cssMode) {
          swiper.wrapperEl.style.overflow = '';
          swiper.wrapperEl.style.touchAction = '';
        }
        zoom.scale = 1;
        currentScale = 1;
        gesture.imageWrapEl.style.transitionDuration = '300ms';
        gesture.imageWrapEl.style.transform = 'translate3d(0,0,0)';
        gesture.imageEl.style.transitionDuration = '300ms';
        gesture.imageEl.style.transform = 'translate3d(0,0,0) scale(1)';
        gesture.slideEl.classList.remove(`${params.zoomedSlideClass}`);
        gesture.slideEl = undefined;
        gesture.originX = 0;
        gesture.originY = 0;
      }

      // Toggle Zoom
      function zoomToggle(e) {
        const zoom = swiper.zoom;
        if (zoom.scale && zoom.scale !== 1) {
          // Zoom Out
          zoomOut();
        } else {
          // Zoom In
          zoomIn(e);
        }
      }
      function getListeners() {
        const passiveListener = swiper.params.passiveListeners ? {
          passive: true,
          capture: false
        } : false;
        const activeListenerWithCapture = swiper.params.passiveListeners ? {
          passive: false,
          capture: true
        } : true;
        return {
          passiveListener,
          activeListenerWithCapture
        };
      }

      // Attach/Detach Events
      function enable() {
        const zoom = swiper.zoom;
        if (zoom.enabled) return;
        zoom.enabled = true;
        const {
          passiveListener,
          activeListenerWithCapture
        } = getListeners();

        // Scale image
        swiper.wrapperEl.addEventListener('pointerdown', onGestureStart, passiveListener);
        swiper.wrapperEl.addEventListener('pointermove', onGestureChange, activeListenerWithCapture);
        ['pointerup', 'pointercancel', 'pointerout'].forEach(eventName => {
          swiper.wrapperEl.addEventListener(eventName, onGestureEnd, passiveListener);
        });

        // Move image
        swiper.wrapperEl.addEventListener('pointermove', onTouchMove, activeListenerWithCapture);
      }
      function disable() {
        const zoom = swiper.zoom;
        if (!zoom.enabled) return;
        zoom.enabled = false;
        const {
          passiveListener,
          activeListenerWithCapture
        } = getListeners();

        // Scale image
        swiper.wrapperEl.removeEventListener('pointerdown', onGestureStart, passiveListener);
        swiper.wrapperEl.removeEventListener('pointermove', onGestureChange, activeListenerWithCapture);
        ['pointerup', 'pointercancel', 'pointerout'].forEach(eventName => {
          swiper.wrapperEl.removeEventListener(eventName, onGestureEnd, passiveListener);
        });

        // Move image
        swiper.wrapperEl.removeEventListener('pointermove', onTouchMove, activeListenerWithCapture);
      }
      on('init', () => {
        if (swiper.params.zoom.enabled) {
          enable();
        }
      });
      on('destroy', () => {
        disable();
      });
      on('touchStart', (_s, e) => {
        if (!swiper.zoom.enabled) return;
        onTouchStart(e);
      });
      on('touchEnd', (_s, e) => {
        if (!swiper.zoom.enabled) return;
        onTouchEnd();
      });
      on('doubleTap', (_s, e) => {
        if (!swiper.animating && swiper.params.zoom.enabled && swiper.zoom.enabled && swiper.params.zoom.toggle) {
          zoomToggle(e);
        }
      });
      on('transitionEnd', () => {
        if (swiper.zoom.enabled && swiper.params.zoom.enabled) {
          onTransitionEnd();
        }
      });
      on('slideChange', () => {
        if (swiper.zoom.enabled && swiper.params.zoom.enabled && swiper.params.cssMode) {
          onTransitionEnd();
        }
      });
      Object.assign(swiper.zoom, {
        enable,
        disable,
        in: zoomIn,
        out: zoomOut,
        toggle: zoomToggle
      });
    }

    /* eslint no-bitwise: ["error", { "allow": [">>"] }] */
    function Controller(_ref) {
      let {
        swiper,
        extendParams,
        on
      } = _ref;
      extendParams({
        controller: {
          control: undefined,
          inverse: false,
          by: 'slide' // or 'container'
        }
      });

      swiper.controller = {
        control: undefined
      };
      function LinearSpline(x, y) {
        const binarySearch = function search() {
          let maxIndex;
          let minIndex;
          let guess;
          return (array, val) => {
            minIndex = -1;
            maxIndex = array.length;
            while (maxIndex - minIndex > 1) {
              guess = maxIndex + minIndex >> 1;
              if (array[guess] <= val) {
                minIndex = guess;
              } else {
                maxIndex = guess;
              }
            }
            return maxIndex;
          };
        }();
        this.x = x;
        this.y = y;
        this.lastIndex = x.length - 1;
        // Given an x value (x2), return the expected y2 value:
        // (x1,y1) is the known point before given value,
        // (x3,y3) is the known point after given value.
        let i1;
        let i3;
        this.interpolate = function interpolate(x2) {
          if (!x2) return 0;

          // Get the indexes of x1 and x3 (the array indexes before and after given x2):
          i3 = binarySearch(this.x, x2);
          i1 = i3 - 1;

          // We have our indexes i1 & i3, so we can calculate already:
          // y2 := ((x2−x1) × (y3−y1)) ÷ (x3−x1) + y1
          return (x2 - this.x[i1]) * (this.y[i3] - this.y[i1]) / (this.x[i3] - this.x[i1]) + this.y[i1];
        };
        return this;
      }
      function getInterpolateFunction(c) {
        swiper.controller.spline = swiper.params.loop ? new LinearSpline(swiper.slidesGrid, c.slidesGrid) : new LinearSpline(swiper.snapGrid, c.snapGrid);
      }
      function setTranslate(_t, byController) {
        const controlled = swiper.controller.control;
        let multiplier;
        let controlledTranslate;
        const Swiper = swiper.constructor;
        function setControlledTranslate(c) {
          if (c.destroyed) return;

          // this will create an Interpolate function based on the snapGrids
          // x is the Grid of the scrolled scroller and y will be the controlled scroller
          // it makes sense to create this only once and recall it for the interpolation
          // the function does a lot of value caching for performance
          const translate = swiper.rtlTranslate ? -swiper.translate : swiper.translate;
          if (swiper.params.controller.by === 'slide') {
            getInterpolateFunction(c);
            // i am not sure why the values have to be multiplicated this way, tried to invert the snapGrid
            // but it did not work out
            controlledTranslate = -swiper.controller.spline.interpolate(-translate);
          }
          if (!controlledTranslate || swiper.params.controller.by === 'container') {
            multiplier = (c.maxTranslate() - c.minTranslate()) / (swiper.maxTranslate() - swiper.minTranslate());
            if (Number.isNaN(multiplier) || !Number.isFinite(multiplier)) {
              multiplier = 1;
            }
            controlledTranslate = (translate - swiper.minTranslate()) * multiplier + c.minTranslate();
          }
          if (swiper.params.controller.inverse) {
            controlledTranslate = c.maxTranslate() - controlledTranslate;
          }
          c.updateProgress(controlledTranslate);
          c.setTranslate(controlledTranslate, swiper);
          c.updateActiveIndex();
          c.updateSlidesClasses();
        }
        if (Array.isArray(controlled)) {
          for (let i = 0; i < controlled.length; i += 1) {
            if (controlled[i] !== byController && controlled[i] instanceof Swiper) {
              setControlledTranslate(controlled[i]);
            }
          }
        } else if (controlled instanceof Swiper && byController !== controlled) {
          setControlledTranslate(controlled);
        }
      }
      function setTransition(duration, byController) {
        const Swiper = swiper.constructor;
        const controlled = swiper.controller.control;
        let i;
        function setControlledTransition(c) {
          if (c.destroyed) return;
          c.setTransition(duration, swiper);
          if (duration !== 0) {
            c.transitionStart();
            if (c.params.autoHeight) {
              nextTick(() => {
                c.updateAutoHeight();
              });
            }
            elementTransitionEnd(c.wrapperEl, () => {
              if (!controlled) return;
              c.transitionEnd();
            });
          }
        }
        if (Array.isArray(controlled)) {
          for (i = 0; i < controlled.length; i += 1) {
            if (controlled[i] !== byController && controlled[i] instanceof Swiper) {
              setControlledTransition(controlled[i]);
            }
          }
        } else if (controlled instanceof Swiper && byController !== controlled) {
          setControlledTransition(controlled);
        }
      }
      function removeSpline() {
        if (!swiper.controller.control) return;
        if (swiper.controller.spline) {
          swiper.controller.spline = undefined;
          delete swiper.controller.spline;
        }
      }
      on('beforeInit', () => {
        if (typeof window !== 'undefined' && (
        // eslint-disable-line
        typeof swiper.params.controller.control === 'string' || swiper.params.controller.control instanceof HTMLElement)) {
          const controlElement = document.querySelector(swiper.params.controller.control);
          if (controlElement && controlElement.swiper) {
            swiper.controller.control = controlElement.swiper;
          } else if (controlElement) {
            const onControllerSwiper = e => {
              swiper.controller.control = e.detail[0];
              swiper.update();
              controlElement.removeEventListener('init', onControllerSwiper);
            };
            controlElement.addEventListener('init', onControllerSwiper);
          }
          return;
        }
        swiper.controller.control = swiper.params.controller.control;
      });
      on('update', () => {
        removeSpline();
      });
      on('resize', () => {
        removeSpline();
      });
      on('observerUpdate', () => {
        removeSpline();
      });
      on('setTranslate', (_s, translate, byController) => {
        if (!swiper.controller.control || swiper.controller.control.destroyed) return;
        swiper.controller.setTranslate(translate, byController);
      });
      on('setTransition', (_s, duration, byController) => {
        if (!swiper.controller.control || swiper.controller.control.destroyed) return;
        swiper.controller.setTransition(duration, byController);
      });
      Object.assign(swiper.controller, {
        setTranslate,
        setTransition
      });
    }

    function A11y(_ref) {
      let {
        swiper,
        extendParams,
        on
      } = _ref;
      extendParams({
        a11y: {
          enabled: true,
          notificationClass: 'swiper-notification',
          prevSlideMessage: 'Previous slide',
          nextSlideMessage: 'Next slide',
          firstSlideMessage: 'This is the first slide',
          lastSlideMessage: 'This is the last slide',
          paginationBulletMessage: 'Go to slide {{index}}',
          slideLabelMessage: '{{index}} / {{slidesLength}}',
          containerMessage: null,
          containerRoleDescriptionMessage: null,
          itemRoleDescriptionMessage: null,
          slideRole: 'group',
          id: null
        }
      });
      swiper.a11y = {
        clicked: false
      };
      let liveRegion = null;
      function notify(message) {
        const notification = liveRegion;
        if (notification.length === 0) return;
        notification.innerHTML = '';
        notification.innerHTML = message;
      }
      const makeElementsArray = el => {
        if (!Array.isArray(el)) el = [el].filter(e => !!e);
        return el;
      };
      function getRandomNumber(size) {
        if (size === void 0) {
          size = 16;
        }
        const randomChar = () => Math.round(16 * Math.random()).toString(16);
        return 'x'.repeat(size).replace(/x/g, randomChar);
      }
      function makeElFocusable(el) {
        el = makeElementsArray(el);
        el.forEach(subEl => {
          subEl.setAttribute('tabIndex', '0');
        });
      }
      function makeElNotFocusable(el) {
        el = makeElementsArray(el);
        el.forEach(subEl => {
          subEl.setAttribute('tabIndex', '-1');
        });
      }
      function addElRole(el, role) {
        el = makeElementsArray(el);
        el.forEach(subEl => {
          subEl.setAttribute('role', role);
        });
      }
      function addElRoleDescription(el, description) {
        el = makeElementsArray(el);
        el.forEach(subEl => {
          subEl.setAttribute('aria-roledescription', description);
        });
      }
      function addElControls(el, controls) {
        el = makeElementsArray(el);
        el.forEach(subEl => {
          subEl.setAttribute('aria-controls', controls);
        });
      }
      function addElLabel(el, label) {
        el = makeElementsArray(el);
        el.forEach(subEl => {
          subEl.setAttribute('aria-label', label);
        });
      }
      function addElId(el, id) {
        el = makeElementsArray(el);
        el.forEach(subEl => {
          subEl.setAttribute('id', id);
        });
      }
      function addElLive(el, live) {
        el = makeElementsArray(el);
        el.forEach(subEl => {
          subEl.setAttribute('aria-live', live);
        });
      }
      function disableEl(el) {
        el = makeElementsArray(el);
        el.forEach(subEl => {
          subEl.setAttribute('aria-disabled', true);
        });
      }
      function enableEl(el) {
        el = makeElementsArray(el);
        el.forEach(subEl => {
          subEl.setAttribute('aria-disabled', false);
        });
      }
      function onEnterOrSpaceKey(e) {
        if (e.keyCode !== 13 && e.keyCode !== 32) return;
        const params = swiper.params.a11y;
        const targetEl = e.target;
        if (swiper.pagination && swiper.pagination.el && (targetEl === swiper.pagination.el || swiper.pagination.el.contains(e.target))) {
          if (!e.target.matches(classesToSelector(swiper.params.pagination.bulletClass))) return;
        }
        if (swiper.navigation && swiper.navigation.nextEl && targetEl === swiper.navigation.nextEl) {
          if (!(swiper.isEnd && !swiper.params.loop)) {
            swiper.slideNext();
          }
          if (swiper.isEnd) {
            notify(params.lastSlideMessage);
          } else {
            notify(params.nextSlideMessage);
          }
        }
        if (swiper.navigation && swiper.navigation.prevEl && targetEl === swiper.navigation.prevEl) {
          if (!(swiper.isBeginning && !swiper.params.loop)) {
            swiper.slidePrev();
          }
          if (swiper.isBeginning) {
            notify(params.firstSlideMessage);
          } else {
            notify(params.prevSlideMessage);
          }
        }
        if (swiper.pagination && targetEl.matches(classesToSelector(swiper.params.pagination.bulletClass))) {
          targetEl.click();
        }
      }
      function updateNavigation() {
        if (swiper.params.loop || swiper.params.rewind || !swiper.navigation) return;
        const {
          nextEl,
          prevEl
        } = swiper.navigation;
        if (prevEl) {
          if (swiper.isBeginning) {
            disableEl(prevEl);
            makeElNotFocusable(prevEl);
          } else {
            enableEl(prevEl);
            makeElFocusable(prevEl);
          }
        }
        if (nextEl) {
          if (swiper.isEnd) {
            disableEl(nextEl);
            makeElNotFocusable(nextEl);
          } else {
            enableEl(nextEl);
            makeElFocusable(nextEl);
          }
        }
      }
      function hasPagination() {
        return swiper.pagination && swiper.pagination.bullets && swiper.pagination.bullets.length;
      }
      function hasClickablePagination() {
        return hasPagination() && swiper.params.pagination.clickable;
      }
      function updatePagination() {
        const params = swiper.params.a11y;
        if (!hasPagination()) return;
        swiper.pagination.bullets.forEach(bulletEl => {
          if (swiper.params.pagination.clickable) {
            makeElFocusable(bulletEl);
            if (!swiper.params.pagination.renderBullet) {
              addElRole(bulletEl, 'button');
              addElLabel(bulletEl, params.paginationBulletMessage.replace(/\{\{index\}\}/, elementIndex(bulletEl) + 1));
            }
          }
          if (bulletEl.matches(classesToSelector(swiper.params.pagination.bulletActiveClass))) {
            bulletEl.setAttribute('aria-current', 'true');
          } else {
            bulletEl.removeAttribute('aria-current');
          }
        });
      }
      const initNavEl = (el, wrapperId, message) => {
        makeElFocusable(el);
        if (el.tagName !== 'BUTTON') {
          addElRole(el, 'button');
          el.addEventListener('keydown', onEnterOrSpaceKey);
        }
        addElLabel(el, message);
        addElControls(el, wrapperId);
      };
      const handlePointerDown = () => {
        swiper.a11y.clicked = true;
      };
      const handlePointerUp = () => {
        requestAnimationFrame(() => {
          requestAnimationFrame(() => {
            if (!swiper.destroyed) {
              swiper.a11y.clicked = false;
            }
          });
        });
      };
      const handleFocus = e => {
        if (swiper.a11y.clicked) return;
        const slideEl = e.target.closest(`.${swiper.params.slideClass}, swiper-slide`);
        if (!slideEl || !swiper.slides.includes(slideEl)) return;
        const isActive = swiper.slides.indexOf(slideEl) === swiper.activeIndex;
        const isVisible = swiper.params.watchSlidesProgress && swiper.visibleSlides && swiper.visibleSlides.includes(slideEl);
        if (isActive || isVisible) return;
        if (e.sourceCapabilities && e.sourceCapabilities.firesTouchEvents) return;
        if (swiper.isHorizontal()) {
          swiper.el.scrollLeft = 0;
        } else {
          swiper.el.scrollTop = 0;
        }
        swiper.slideTo(swiper.slides.indexOf(slideEl), 0);
      };
      const initSlides = () => {
        const params = swiper.params.a11y;
        if (params.itemRoleDescriptionMessage) {
          addElRoleDescription(swiper.slides, params.itemRoleDescriptionMessage);
        }
        if (params.slideRole) {
          addElRole(swiper.slides, params.slideRole);
        }
        const slidesLength = swiper.slides.length;
        if (params.slideLabelMessage) {
          swiper.slides.forEach((slideEl, index) => {
            const slideIndex = swiper.params.loop ? parseInt(slideEl.getAttribute('data-swiper-slide-index'), 10) : index;
            const ariaLabelMessage = params.slideLabelMessage.replace(/\{\{index\}\}/, slideIndex + 1).replace(/\{\{slidesLength\}\}/, slidesLength);
            addElLabel(slideEl, ariaLabelMessage);
          });
        }
      };
      const init = () => {
        const params = swiper.params.a11y;
        if (swiper.isElement) {
          swiper.el.shadowEl.append(liveRegion);
        } else {
          swiper.el.append(liveRegion);
        }

        // Container
        const containerEl = swiper.el;
        if (params.containerRoleDescriptionMessage) {
          addElRoleDescription(containerEl, params.containerRoleDescriptionMessage);
        }
        if (params.containerMessage) {
          addElLabel(containerEl, params.containerMessage);
        }

        // Wrapper
        const wrapperEl = swiper.wrapperEl;
        const wrapperId = params.id || wrapperEl.getAttribute('id') || `swiper-wrapper-${getRandomNumber(16)}`;
        const live = swiper.params.autoplay && swiper.params.autoplay.enabled ? 'off' : 'polite';
        addElId(wrapperEl, wrapperId);
        addElLive(wrapperEl, live);

        // Slide
        initSlides();

        // Navigation
        let {
          nextEl,
          prevEl
        } = swiper.navigation ? swiper.navigation : {};
        nextEl = makeElementsArray(nextEl);
        prevEl = makeElementsArray(prevEl);
        if (nextEl) {
          nextEl.forEach(el => initNavEl(el, wrapperId, params.nextSlideMessage));
        }
        if (prevEl) {
          prevEl.forEach(el => initNavEl(el, wrapperId, params.prevSlideMessage));
        }

        // Pagination
        if (hasClickablePagination()) {
          const paginationEl = Array.isArray(swiper.pagination.el) ? swiper.pagination.el : [swiper.pagination.el];
          paginationEl.forEach(el => {
            el.addEventListener('keydown', onEnterOrSpaceKey);
          });
        }

        // Tab focus
        swiper.el.addEventListener('focus', handleFocus, true);
        swiper.el.addEventListener('pointerdown', handlePointerDown, true);
        swiper.el.addEventListener('pointerup', handlePointerUp, true);
      };
      function destroy() {
        if (liveRegion) liveRegion.remove();
        let {
          nextEl,
          prevEl
        } = swiper.navigation ? swiper.navigation : {};
        nextEl = makeElementsArray(nextEl);
        prevEl = makeElementsArray(prevEl);
        if (nextEl) {
          nextEl.forEach(el => el.removeEventListener('keydown', onEnterOrSpaceKey));
        }
        if (prevEl) {
          prevEl.forEach(el => el.removeEventListener('keydown', onEnterOrSpaceKey));
        }

        // Pagination
        if (hasClickablePagination()) {
          const paginationEl = Array.isArray(swiper.pagination.el) ? swiper.pagination.el : [swiper.pagination.el];
          paginationEl.forEach(el => {
            el.removeEventListener('keydown', onEnterOrSpaceKey);
          });
        }

        // Tab focus
        swiper.el.removeEventListener('focus', handleFocus, true);
        swiper.el.removeEventListener('pointerdown', handlePointerDown, true);
        swiper.el.removeEventListener('pointerup', handlePointerUp, true);
      }
      on('beforeInit', () => {
        liveRegion = createElement('span', swiper.params.a11y.notificationClass);
        liveRegion.setAttribute('aria-live', 'assertive');
        liveRegion.setAttribute('aria-atomic', 'true');
      });
      on('afterInit', () => {
        if (!swiper.params.a11y.enabled) return;
        init();
      });
      on('slidesLengthChange snapGridLengthChange slidesGridLengthChange', () => {
        if (!swiper.params.a11y.enabled) return;
        initSlides();
      });
      on('fromEdge toEdge afterInit lock unlock', () => {
        if (!swiper.params.a11y.enabled) return;
        updateNavigation();
      });
      on('paginationUpdate', () => {
        if (!swiper.params.a11y.enabled) return;
        updatePagination();
      });
      on('destroy', () => {
        if (!swiper.params.a11y.enabled) return;
        destroy();
      });
    }

    function History(_ref) {
      let {
        swiper,
        extendParams,
        on
      } = _ref;
      extendParams({
        history: {
          enabled: false,
          root: '',
          replaceState: false,
          key: 'slides',
          keepQuery: false
        }
      });
      let initialized = false;
      let paths = {};
      const slugify = text => {
        return text.toString().replace(/\s+/g, '-').replace(/[^\w-]+/g, '').replace(/--+/g, '-').replace(/^-+/, '').replace(/-+$/, '');
      };
      const getPathValues = urlOverride => {
        const window = getWindow();
        let location;
        if (urlOverride) {
          location = new URL(urlOverride);
        } else {
          location = window.location;
        }
        const pathArray = location.pathname.slice(1).split('/').filter(part => part !== '');
        const total = pathArray.length;
        const key = pathArray[total - 2];
        const value = pathArray[total - 1];
        return {
          key,
          value
        };
      };
      const setHistory = (key, index) => {
        const window = getWindow();
        if (!initialized || !swiper.params.history.enabled) return;
        let location;
        if (swiper.params.url) {
          location = new URL(swiper.params.url);
        } else {
          location = window.location;
        }
        const slide = swiper.slides[index];
        let value = slugify(slide.getAttribute('data-history'));
        if (swiper.params.history.root.length > 0) {
          let root = swiper.params.history.root;
          if (root[root.length - 1] === '/') root = root.slice(0, root.length - 1);
          value = `${root}/${key ? `${key}/` : ''}${value}`;
        } else if (!location.pathname.includes(key)) {
          value = `${key ? `${key}/` : ''}${value}`;
        }
        if (swiper.params.history.keepQuery) {
          value += location.search;
        }
        const currentState = window.history.state;
        if (currentState && currentState.value === value) {
          return;
        }
        if (swiper.params.history.replaceState) {
          window.history.replaceState({
            value
          }, null, value);
        } else {
          window.history.pushState({
            value
          }, null, value);
        }
      };
      const scrollToSlide = (speed, value, runCallbacks) => {
        if (value) {
          for (let i = 0, length = swiper.slides.length; i < length; i += 1) {
            const slide = swiper.slides[i];
            const slideHistory = slugify(slide.getAttribute('data-history'));
            if (slideHistory === value) {
              const index = swiper.getSlideIndex(slide);
              swiper.slideTo(index, speed, runCallbacks);
            }
          }
        } else {
          swiper.slideTo(0, speed, runCallbacks);
        }
      };
      const setHistoryPopState = () => {
        paths = getPathValues(swiper.params.url);
        scrollToSlide(swiper.params.speed, paths.value, false);
      };
      const init = () => {
        const window = getWindow();
        if (!swiper.params.history) return;
        if (!window.history || !window.history.pushState) {
          swiper.params.history.enabled = false;
          swiper.params.hashNavigation.enabled = true;
          return;
        }
        initialized = true;
        paths = getPathValues(swiper.params.url);
        if (!paths.key && !paths.value) {
          if (!swiper.params.history.replaceState) {
            window.addEventListener('popstate', setHistoryPopState);
          }
          return;
        }
        scrollToSlide(0, paths.value, swiper.params.runCallbacksOnInit);
        if (!swiper.params.history.replaceState) {
          window.addEventListener('popstate', setHistoryPopState);
        }
      };
      const destroy = () => {
        const window = getWindow();
        if (!swiper.params.history.replaceState) {
          window.removeEventListener('popstate', setHistoryPopState);
        }
      };
      on('init', () => {
        if (swiper.params.history.enabled) {
          init();
        }
      });
      on('destroy', () => {
        if (swiper.params.history.enabled) {
          destroy();
        }
      });
      on('transitionEnd _freeModeNoMomentumRelease', () => {
        if (initialized) {
          setHistory(swiper.params.history.key, swiper.activeIndex);
        }
      });
      on('slideChange', () => {
        if (initialized && swiper.params.cssMode) {
          setHistory(swiper.params.history.key, swiper.activeIndex);
        }
      });
    }

    function HashNavigation(_ref) {
      let {
        swiper,
        extendParams,
        emit,
        on
      } = _ref;
      let initialized = false;
      const document = getDocument();
      const window = getWindow();
      extendParams({
        hashNavigation: {
          enabled: false,
          replaceState: false,
          watchState: false,
          getSlideIndex(_s, hash) {
            if (swiper.virtual && swiper.params.virtual.enabled) {
              const slideWithHash = swiper.slides.filter(slideEl => slideEl.getAttribute('data-hash') === hash)[0];
              if (!slideWithHash) return 0;
              const index = parseInt(slideWithHash.getAttribute('data-swiper-slide-index'), 10);
              return index;
            }
            return swiper.getSlideIndex(elementChildren(swiper.slidesEl, `.${swiper.params.slideClass}[data-hash="${hash}"], swiper-slide[data-hash="${hash}"]`)[0]);
          }
        }
      });
      const onHashChange = () => {
        emit('hashChange');
        const newHash = document.location.hash.replace('#', '');
        const activeSlideEl = swiper.slidesEl.querySelector(`[data-swiper-slide-index="${swiper.activeIndex}"]`);
        const activeSlideHash = activeSlideEl ? activeSlideEl.getAttribute('data-hash') : '';
        if (newHash !== activeSlideHash) {
          const newIndex = swiper.params.hashNavigation.getSlideIndex(swiper, newHash);
          if (typeof newIndex === 'undefined' || Number.isNaN(newIndex)) return;
          swiper.slideTo(newIndex);
        }
      };
      const setHash = () => {
        if (!initialized || !swiper.params.hashNavigation.enabled) return;
        const activeSlideEl = swiper.slidesEl.querySelector(`[data-swiper-slide-index="${swiper.activeIndex}"]`);
        const activeSlideHash = activeSlideEl ? activeSlideEl.getAttribute('data-hash') || activeSlideEl.getAttribute('data-history') : '';
        if (swiper.params.hashNavigation.replaceState && window.history && window.history.replaceState) {
          window.history.replaceState(null, null, `#${activeSlideHash}` || '');
          emit('hashSet');
        } else {
          document.location.hash = activeSlideHash || '';
          emit('hashSet');
        }
      };
      const init = () => {
        if (!swiper.params.hashNavigation.enabled || swiper.params.history && swiper.params.history.enabled) return;
        initialized = true;
        const hash = document.location.hash.replace('#', '');
        if (hash) {
          const speed = 0;
          const index = swiper.params.hashNavigation.getSlideIndex(swiper, hash);
          swiper.slideTo(index || 0, speed, swiper.params.runCallbacksOnInit, true);
        }
        if (swiper.params.hashNavigation.watchState) {
          window.addEventListener('hashchange', onHashChange);
        }
      };
      const destroy = () => {
        if (swiper.params.hashNavigation.watchState) {
          window.removeEventListener('hashchange', onHashChange);
        }
      };
      on('init', () => {
        if (swiper.params.hashNavigation.enabled) {
          init();
        }
      });
      on('destroy', () => {
        if (swiper.params.hashNavigation.enabled) {
          destroy();
        }
      });
      on('transitionEnd _freeModeNoMomentumRelease', () => {
        if (initialized) {
          setHash();
        }
      });
      on('slideChange', () => {
        if (initialized && swiper.params.cssMode) {
          setHash();
        }
      });
    }

    /* eslint no-underscore-dangle: "off" */
    function Autoplay(_ref) {
      let {
        swiper,
        extendParams,
        on,
        emit,
        params
      } = _ref;
      swiper.autoplay = {
        running: false,
        paused: false,
        timeLeft: 0
      };
      extendParams({
        autoplay: {
          enabled: false,
          delay: 3000,
          waitForTransition: true,
          disableOnInteraction: true,
          stopOnLastSlide: false,
          reverseDirection: false,
          pauseOnMouseEnter: false
        }
      });
      let timeout;
      let raf;
      let autoplayDelayTotal = params && params.autoplay ? params.autoplay.delay : 3000;
      let autoplayDelayCurrent = params && params.autoplay ? params.autoplay.delay : 3000;
      let autoplayTimeLeft;
      let autoplayStartTime = new Date().getTime;
      let wasPaused;
      let isTouched;
      let pausedByTouch;
      let touchStartTimeout;
      let slideChanged;
      let pausedByInteraction;
      function onTransitionEnd(e) {
        if (!swiper || swiper.destroyed || !swiper.wrapperEl) return;
        if (e.target !== swiper.wrapperEl) return;
        swiper.wrapperEl.removeEventListener('transitionend', onTransitionEnd);
        resume();
      }
      const calcTimeLeft = () => {
        if (swiper.destroyed || !swiper.autoplay.running) return;
        if (swiper.autoplay.paused) {
          wasPaused = true;
        } else if (wasPaused) {
          autoplayDelayCurrent = autoplayTimeLeft;
          wasPaused = false;
        }
        const timeLeft = swiper.autoplay.paused ? autoplayTimeLeft : autoplayStartTime + autoplayDelayCurrent - new Date().getTime();
        swiper.autoplay.timeLeft = timeLeft;
        emit('autoplayTimeLeft', timeLeft, timeLeft / autoplayDelayTotal);
        raf = requestAnimationFrame(() => {
          calcTimeLeft();
        });
      };
      const getSlideDelay = () => {
        let activeSlideEl;
        if (swiper.virtual && swiper.params.virtual.enabled) {
          activeSlideEl = swiper.slides.filter(slideEl => slideEl.classList.contains('swiper-slide-active'))[0];
        } else {
          activeSlideEl = swiper.slides[swiper.activeIndex];
        }
        if (!activeSlideEl) return undefined;
        const currentSlideDelay = parseInt(activeSlideEl.getAttribute('data-swiper-autoplay'), 10);
        return currentSlideDelay;
      };
      const run = delayForce => {
        if (swiper.destroyed || !swiper.autoplay.running) return;
        cancelAnimationFrame(raf);
        calcTimeLeft();
        let delay = typeof delayForce === 'undefined' ? swiper.params.autoplay.delay : delayForce;
        autoplayDelayTotal = swiper.params.autoplay.delay;
        autoplayDelayCurrent = swiper.params.autoplay.delay;
        const currentSlideDelay = getSlideDelay();
        if (!Number.isNaN(currentSlideDelay) && currentSlideDelay > 0 && typeof delayForce === 'undefined') {
          delay = currentSlideDelay;
          autoplayDelayTotal = currentSlideDelay;
          autoplayDelayCurrent = currentSlideDelay;
        }
        autoplayTimeLeft = delay;
        const speed = swiper.params.speed;
        const proceed = () => {
          if (!swiper || swiper.destroyed) return;
          if (swiper.params.autoplay.reverseDirection) {
            if (!swiper.isBeginning || swiper.params.loop || swiper.params.rewind) {
              swiper.slidePrev(speed, true, true);
              emit('autoplay');
            } else if (!swiper.params.autoplay.stopOnLastSlide) {
              swiper.slideTo(swiper.slides.length - 1, speed, true, true);
              emit('autoplay');
            }
          } else {
            if (!swiper.isEnd || swiper.params.loop || swiper.params.rewind) {
              swiper.slideNext(speed, true, true);
              emit('autoplay');
            } else if (!swiper.params.autoplay.stopOnLastSlide) {
              swiper.slideTo(0, speed, true, true);
              emit('autoplay');
            }
          }
          if (swiper.params.cssMode) {
            autoplayStartTime = new Date().getTime();
            requestAnimationFrame(() => {
              run();
            });
          }
        };
        if (delay > 0) {
          clearTimeout(timeout);
          timeout = setTimeout(() => {
            proceed();
          }, delay);
        } else {
          requestAnimationFrame(() => {
            proceed();
          });
        }

        // eslint-disable-next-line
        return delay;
      };
      const start = () => {
        swiper.autoplay.running = true;
        run();
        emit('autoplayStart');
      };
      const stop = () => {
        swiper.autoplay.running = false;
        clearTimeout(timeout);
        cancelAnimationFrame(raf);
        emit('autoplayStop');
      };
      const pause = (internal, reset) => {
        if (swiper.destroyed || !swiper.autoplay.running) return;
        clearTimeout(timeout);
        if (!internal) {
          pausedByInteraction = true;
        }
        const proceed = () => {
          emit('autoplayPause');
          if (swiper.params.autoplay.waitForTransition) {
            swiper.wrapperEl.addEventListener('transitionend', onTransitionEnd);
          } else {
            resume();
          }
        };
        swiper.autoplay.paused = true;
        if (reset) {
          if (slideChanged) {
            autoplayTimeLeft = swiper.params.autoplay.delay;
          }
          slideChanged = false;
          proceed();
          return;
        }
        const delay = autoplayTimeLeft || swiper.params.autoplay.delay;
        autoplayTimeLeft = delay - (new Date().getTime() - autoplayStartTime);
        if (swiper.isEnd && autoplayTimeLeft < 0 && !swiper.params.loop) return;
        if (autoplayTimeLeft < 0) autoplayTimeLeft = 0;
        proceed();
      };
      const resume = () => {
        if (swiper.isEnd && autoplayTimeLeft < 0 && !swiper.params.loop || swiper.destroyed || !swiper.autoplay.running) return;
        autoplayStartTime = new Date().getTime();
        if (pausedByInteraction) {
          pausedByInteraction = false;
          run(autoplayTimeLeft);
        } else {
          run();
        }
        swiper.autoplay.paused = false;
        emit('autoplayResume');
      };
      const onVisibilityChange = () => {
        if (swiper.destroyed || !swiper.autoplay.running) return;
        const document = getDocument();
        if (document.visibilityState === 'hidden') {
          pausedByInteraction = true;
          pause(true);
        }
        if (document.visibilityState === 'visible') {
          resume();
        }
      };
      const onPointerEnter = e => {
        if (e.pointerType !== 'mouse') return;
        pausedByInteraction = true;
        pause(true);
      };
      const onPointerLeave = e => {
        if (e.pointerType !== 'mouse') return;
        if (swiper.autoplay.paused) {
          resume();
        }
      };
      const attachMouseEvents = () => {
        if (swiper.params.autoplay.pauseOnMouseEnter) {
          swiper.el.addEventListener('pointerenter', onPointerEnter);
          swiper.el.addEventListener('pointerleave', onPointerLeave);
        }
      };
      const detachMouseEvents = () => {
        swiper.el.removeEventListener('pointerenter', onPointerEnter);
        swiper.el.removeEventListener('pointerleave', onPointerLeave);
      };
      const attachDocumentEvents = () => {
        const document = getDocument();
        document.addEventListener('visibilitychange', onVisibilityChange);
      };
      const detachDocumentEvents = () => {
        const document = getDocument();
        document.removeEventListener('visibilitychange', onVisibilityChange);
      };
      on('init', () => {
        if (swiper.params.autoplay.enabled) {
          attachMouseEvents();
          attachDocumentEvents();
          autoplayStartTime = new Date().getTime();
          start();
        }
      });
      on('destroy', () => {
        detachMouseEvents();
        detachDocumentEvents();
        if (swiper.autoplay.running) {
          stop();
        }
      });
      on('beforeTransitionStart', (_s, speed, internal) => {
        if (swiper.destroyed || !swiper.autoplay.running) return;
        if (internal || !swiper.params.autoplay.disableOnInteraction) {
          pause(true, true);
        } else {
          stop();
        }
      });
      on('sliderFirstMove', () => {
        if (swiper.destroyed || !swiper.autoplay.running) return;
        if (swiper.params.autoplay.disableOnInteraction) {
          stop();
          return;
        }
        isTouched = true;
        pausedByTouch = false;
        pausedByInteraction = false;
        touchStartTimeout = setTimeout(() => {
          pausedByInteraction = true;
          pausedByTouch = true;
          pause(true);
        }, 200);
      });
      on('touchEnd', () => {
        if (swiper.destroyed || !swiper.autoplay.running || !isTouched) return;
        clearTimeout(touchStartTimeout);
        clearTimeout(timeout);
        if (swiper.params.autoplay.disableOnInteraction) {
          pausedByTouch = false;
          isTouched = false;
          return;
        }
        if (pausedByTouch && swiper.params.cssMode) resume();
        pausedByTouch = false;
        isTouched = false;
      });
      on('slideChange', () => {
        if (swiper.destroyed || !swiper.autoplay.running) return;
        slideChanged = true;
      });
      Object.assign(swiper.autoplay, {
        start,
        stop,
        pause,
        resume
      });
    }

    function Thumb(_ref) {
      let {
        swiper,
        extendParams,
        on
      } = _ref;
      extendParams({
        thumbs: {
          swiper: null,
          multipleActiveThumbs: true,
          autoScrollOffset: 0,
          slideThumbActiveClass: 'swiper-slide-thumb-active',
          thumbsContainerClass: 'swiper-thumbs'
        }
      });
      let initialized = false;
      let swiperCreated = false;
      swiper.thumbs = {
        swiper: null
      };
      function onThumbClick() {
        const thumbsSwiper = swiper.thumbs.swiper;
        if (!thumbsSwiper || thumbsSwiper.destroyed) return;
        const clickedIndex = thumbsSwiper.clickedIndex;
        const clickedSlide = thumbsSwiper.clickedSlide;
        if (clickedSlide && clickedSlide.classList.contains(swiper.params.thumbs.slideThumbActiveClass)) return;
        if (typeof clickedIndex === 'undefined' || clickedIndex === null) return;
        let slideToIndex;
        if (thumbsSwiper.params.loop) {
          slideToIndex = parseInt(thumbsSwiper.clickedSlide.getAttribute('data-swiper-slide-index'), 10);
        } else {
          slideToIndex = clickedIndex;
        }
        if (swiper.params.loop) {
          swiper.slideToLoop(slideToIndex);
        } else {
          swiper.slideTo(slideToIndex);
        }
      }
      function init() {
        const {
          thumbs: thumbsParams
        } = swiper.params;
        if (initialized) return false;
        initialized = true;
        const SwiperClass = swiper.constructor;
        if (thumbsParams.swiper instanceof SwiperClass) {
          swiper.thumbs.swiper = thumbsParams.swiper;
          Object.assign(swiper.thumbs.swiper.originalParams, {
            watchSlidesProgress: true,
            slideToClickedSlide: false
          });
          Object.assign(swiper.thumbs.swiper.params, {
            watchSlidesProgress: true,
            slideToClickedSlide: false
          });
          swiper.thumbs.swiper.update();
        } else if (isObject(thumbsParams.swiper)) {
          const thumbsSwiperParams = Object.assign({}, thumbsParams.swiper);
          Object.assign(thumbsSwiperParams, {
            watchSlidesProgress: true,
            slideToClickedSlide: false
          });
          swiper.thumbs.swiper = new SwiperClass(thumbsSwiperParams);
          swiperCreated = true;
        }
        swiper.thumbs.swiper.el.classList.add(swiper.params.thumbs.thumbsContainerClass);
        swiper.thumbs.swiper.on('tap', onThumbClick);
        return true;
      }
      function update(initial) {
        const thumbsSwiper = swiper.thumbs.swiper;
        if (!thumbsSwiper || thumbsSwiper.destroyed) return;
        const slidesPerView = thumbsSwiper.params.slidesPerView === 'auto' ? thumbsSwiper.slidesPerViewDynamic() : thumbsSwiper.params.slidesPerView;

        // Activate thumbs
        let thumbsToActivate = 1;
        const thumbActiveClass = swiper.params.thumbs.slideThumbActiveClass;
        if (swiper.params.slidesPerView > 1 && !swiper.params.centeredSlides) {
          thumbsToActivate = swiper.params.slidesPerView;
        }
        if (!swiper.params.thumbs.multipleActiveThumbs) {
          thumbsToActivate = 1;
        }
        thumbsToActivate = Math.floor(thumbsToActivate);
        thumbsSwiper.slides.forEach(slideEl => slideEl.classList.remove(thumbActiveClass));
        if (thumbsSwiper.params.loop || thumbsSwiper.params.virtual && thumbsSwiper.params.virtual.enabled) {
          for (let i = 0; i < thumbsToActivate; i += 1) {
            elementChildren(thumbsSwiper.slidesEl, `[data-swiper-slide-index="${swiper.realIndex + i}"]`).forEach(slideEl => {
              slideEl.classList.add(thumbActiveClass);
            });
          }
        } else {
          for (let i = 0; i < thumbsToActivate; i += 1) {
            if (thumbsSwiper.slides[swiper.realIndex + i]) {
              thumbsSwiper.slides[swiper.realIndex + i].classList.add(thumbActiveClass);
            }
          }
        }
        const autoScrollOffset = swiper.params.thumbs.autoScrollOffset;
        const useOffset = autoScrollOffset && !thumbsSwiper.params.loop;
        if (swiper.realIndex !== thumbsSwiper.realIndex || useOffset) {
          const currentThumbsIndex = thumbsSwiper.activeIndex;
          let newThumbsIndex;
          let direction;
          if (thumbsSwiper.params.loop) {
            const newThumbsSlide = thumbsSwiper.slides.filter(slideEl => slideEl.getAttribute('data-swiper-slide-index') === `${swiper.realIndex}`)[0];
            newThumbsIndex = thumbsSwiper.slides.indexOf(newThumbsSlide);
            direction = swiper.activeIndex > swiper.previousIndex ? 'next' : 'prev';
          } else {
            newThumbsIndex = swiper.realIndex;
            direction = newThumbsIndex > swiper.previousIndex ? 'next' : 'prev';
          }
          if (useOffset) {
            newThumbsIndex += direction === 'next' ? autoScrollOffset : -1 * autoScrollOffset;
          }
          if (thumbsSwiper.visibleSlidesIndexes && thumbsSwiper.visibleSlidesIndexes.indexOf(newThumbsIndex) < 0) {
            if (thumbsSwiper.params.centeredSlides) {
              if (newThumbsIndex > currentThumbsIndex) {
                newThumbsIndex = newThumbsIndex - Math.floor(slidesPerView / 2) + 1;
              } else {
                newThumbsIndex = newThumbsIndex + Math.floor(slidesPerView / 2) - 1;
              }
            } else if (newThumbsIndex > currentThumbsIndex && thumbsSwiper.params.slidesPerGroup === 1) ;
            thumbsSwiper.slideTo(newThumbsIndex, initial ? 0 : undefined);
          }
        }
      }
      on('beforeInit', () => {
        const {
          thumbs
        } = swiper.params;
        if (!thumbs || !thumbs.swiper) return;
        if (typeof thumbs.swiper === 'string' || thumbs.swiper instanceof HTMLElement) {
          const document = getDocument();
          const getThumbsElementAndInit = () => {
            const thumbsElement = typeof thumbs.swiper === 'string' ? document.querySelector(thumbs.swiper) : thumbs.swiper;
            if (thumbsElement && thumbsElement.swiper) {
              thumbs.swiper = thumbsElement.swiper;
              init();
              update(true);
            } else if (thumbsElement) {
              const onThumbsSwiper = e => {
                thumbs.swiper = e.detail[0];
                thumbsElement.removeEventListener('init', onThumbsSwiper);
                init();
                update(true);
                thumbs.swiper.update();
                swiper.update();
              };
              thumbsElement.addEventListener('init', onThumbsSwiper);
            }
            return thumbsElement;
          };
          const watchForThumbsToAppear = () => {
            if (swiper.destroyed) return;
            const thumbsElement = getThumbsElementAndInit();
            if (!thumbsElement) {
              requestAnimationFrame(watchForThumbsToAppear);
            }
          };
          requestAnimationFrame(watchForThumbsToAppear);
        } else {
          init();
          update(true);
        }
      });
      on('slideChange update resize observerUpdate', () => {
        update();
      });
      on('setTransition', (_s, duration) => {
        const thumbsSwiper = swiper.thumbs.swiper;
        if (!thumbsSwiper || thumbsSwiper.destroyed) return;
        thumbsSwiper.setTransition(duration);
      });
      on('beforeDestroy', () => {
        const thumbsSwiper = swiper.thumbs.swiper;
        if (!thumbsSwiper || thumbsSwiper.destroyed) return;
        if (swiperCreated) {
          thumbsSwiper.destroy();
        }
      });
      Object.assign(swiper.thumbs, {
        init,
        update
      });
    }

    function freeMode(_ref) {
      let {
        swiper,
        extendParams,
        emit,
        once
      } = _ref;
      extendParams({
        freeMode: {
          enabled: false,
          momentum: true,
          momentumRatio: 1,
          momentumBounce: true,
          momentumBounceRatio: 1,
          momentumVelocityRatio: 1,
          sticky: false,
          minimumVelocity: 0.02
        }
      });
      function onTouchStart() {
        const translate = swiper.getTranslate();
        swiper.setTranslate(translate);
        swiper.setTransition(0);
        swiper.touchEventsData.velocities.length = 0;
        swiper.freeMode.onTouchEnd({
          currentPos: swiper.rtl ? swiper.translate : -swiper.translate
        });
      }
      function onTouchMove() {
        const {
          touchEventsData: data,
          touches
        } = swiper;
        // Velocity
        if (data.velocities.length === 0) {
          data.velocities.push({
            position: touches[swiper.isHorizontal() ? 'startX' : 'startY'],
            time: data.touchStartTime
          });
        }
        data.velocities.push({
          position: touches[swiper.isHorizontal() ? 'currentX' : 'currentY'],
          time: now()
        });
      }
      function onTouchEnd(_ref2) {
        let {
          currentPos
        } = _ref2;
        const {
          params,
          wrapperEl,
          rtlTranslate: rtl,
          snapGrid,
          touchEventsData: data
        } = swiper;
        // Time diff
        const touchEndTime = now();
        const timeDiff = touchEndTime - data.touchStartTime;
        if (currentPos < -swiper.minTranslate()) {
          swiper.slideTo(swiper.activeIndex);
          return;
        }
        if (currentPos > -swiper.maxTranslate()) {
          if (swiper.slides.length < snapGrid.length) {
            swiper.slideTo(snapGrid.length - 1);
          } else {
            swiper.slideTo(swiper.slides.length - 1);
          }
          return;
        }
        if (params.freeMode.momentum) {
          if (data.velocities.length > 1) {
            const lastMoveEvent = data.velocities.pop();
            const velocityEvent = data.velocities.pop();
            const distance = lastMoveEvent.position - velocityEvent.position;
            const time = lastMoveEvent.time - velocityEvent.time;
            swiper.velocity = distance / time;
            swiper.velocity /= 2;
            if (Math.abs(swiper.velocity) < params.freeMode.minimumVelocity) {
              swiper.velocity = 0;
            }
            // this implies that the user stopped moving a finger then released.
            // There would be no events with distance zero, so the last event is stale.
            if (time > 150 || now() - lastMoveEvent.time > 300) {
              swiper.velocity = 0;
            }
          } else {
            swiper.velocity = 0;
          }
          swiper.velocity *= params.freeMode.momentumVelocityRatio;
          data.velocities.length = 0;
          let momentumDuration = 1000 * params.freeMode.momentumRatio;
          const momentumDistance = swiper.velocity * momentumDuration;
          let newPosition = swiper.translate + momentumDistance;
          if (rtl) newPosition = -newPosition;
          let doBounce = false;
          let afterBouncePosition;
          const bounceAmount = Math.abs(swiper.velocity) * 20 * params.freeMode.momentumBounceRatio;
          let needsLoopFix;
          if (newPosition < swiper.maxTranslate()) {
            if (params.freeMode.momentumBounce) {
              if (newPosition + swiper.maxTranslate() < -bounceAmount) {
                newPosition = swiper.maxTranslate() - bounceAmount;
              }
              afterBouncePosition = swiper.maxTranslate();
              doBounce = true;
              data.allowMomentumBounce = true;
            } else {
              newPosition = swiper.maxTranslate();
            }
            if (params.loop && params.centeredSlides) needsLoopFix = true;
          } else if (newPosition > swiper.minTranslate()) {
            if (params.freeMode.momentumBounce) {
              if (newPosition - swiper.minTranslate() > bounceAmount) {
                newPosition = swiper.minTranslate() + bounceAmount;
              }
              afterBouncePosition = swiper.minTranslate();
              doBounce = true;
              data.allowMomentumBounce = true;
            } else {
              newPosition = swiper.minTranslate();
            }
            if (params.loop && params.centeredSlides) needsLoopFix = true;
          } else if (params.freeMode.sticky) {
            let nextSlide;
            for (let j = 0; j < snapGrid.length; j += 1) {
              if (snapGrid[j] > -newPosition) {
                nextSlide = j;
                break;
              }
            }
            if (Math.abs(snapGrid[nextSlide] - newPosition) < Math.abs(snapGrid[nextSlide - 1] - newPosition) || swiper.swipeDirection === 'next') {
              newPosition = snapGrid[nextSlide];
            } else {
              newPosition = snapGrid[nextSlide - 1];
            }
            newPosition = -newPosition;
          }
          if (needsLoopFix) {
            once('transitionEnd', () => {
              swiper.loopFix();
            });
          }
          // Fix duration
          if (swiper.velocity !== 0) {
            if (rtl) {
              momentumDuration = Math.abs((-newPosition - swiper.translate) / swiper.velocity);
            } else {
              momentumDuration = Math.abs((newPosition - swiper.translate) / swiper.velocity);
            }
            if (params.freeMode.sticky) {
              // If freeMode.sticky is active and the user ends a swipe with a slow-velocity
              // event, then durations can be 20+ seconds to slide one (or zero!) slides.
              // It's easy to see this when simulating touch with mouse events. To fix this,
              // limit single-slide swipes to the default slide duration. This also has the
              // nice side effect of matching slide speed if the user stopped moving before
              // lifting finger or mouse vs. moving slowly before lifting the finger/mouse.
              // For faster swipes, also apply limits (albeit higher ones).
              const moveDistance = Math.abs((rtl ? -newPosition : newPosition) - swiper.translate);
              const currentSlideSize = swiper.slidesSizesGrid[swiper.activeIndex];
              if (moveDistance < currentSlideSize) {
                momentumDuration = params.speed;
              } else if (moveDistance < 2 * currentSlideSize) {
                momentumDuration = params.speed * 1.5;
              } else {
                momentumDuration = params.speed * 2.5;
              }
            }
          } else if (params.freeMode.sticky) {
            swiper.slideToClosest();
            return;
          }
          if (params.freeMode.momentumBounce && doBounce) {
            swiper.updateProgress(afterBouncePosition);
            swiper.setTransition(momentumDuration);
            swiper.setTranslate(newPosition);
            swiper.transitionStart(true, swiper.swipeDirection);
            swiper.animating = true;
            elementTransitionEnd(wrapperEl, () => {
              if (!swiper || swiper.destroyed || !data.allowMomentumBounce) return;
              emit('momentumBounce');
              swiper.setTransition(params.speed);
              setTimeout(() => {
                swiper.setTranslate(afterBouncePosition);
                elementTransitionEnd(wrapperEl, () => {
                  if (!swiper || swiper.destroyed) return;
                  swiper.transitionEnd();
                });
              }, 0);
            });
          } else if (swiper.velocity) {
            emit('_freeModeNoMomentumRelease');
            swiper.updateProgress(newPosition);
            swiper.setTransition(momentumDuration);
            swiper.setTranslate(newPosition);
            swiper.transitionStart(true, swiper.swipeDirection);
            if (!swiper.animating) {
              swiper.animating = true;
              elementTransitionEnd(wrapperEl, () => {
                if (!swiper || swiper.destroyed) return;
                swiper.transitionEnd();
              });
            }
          } else {
            swiper.updateProgress(newPosition);
          }
          swiper.updateActiveIndex();
          swiper.updateSlidesClasses();
        } else if (params.freeMode.sticky) {
          swiper.slideToClosest();
          return;
        } else if (params.freeMode) {
          emit('_freeModeNoMomentumRelease');
        }
        if (!params.freeMode.momentum || timeDiff >= params.longSwipesMs) {
          swiper.updateProgress();
          swiper.updateActiveIndex();
          swiper.updateSlidesClasses();
        }
      }
      Object.assign(swiper, {
        freeMode: {
          onTouchStart,
          onTouchMove,
          onTouchEnd
        }
      });
    }

    function Grid(_ref) {
      let {
        swiper,
        extendParams
      } = _ref;
      extendParams({
        grid: {
          rows: 1,
          fill: 'column'
        }
      });
      let slidesNumberEvenToRows;
      let slidesPerRow;
      let numFullColumns;
      const getSpaceBetween = () => {
        let spaceBetween = swiper.params.spaceBetween;
        if (typeof spaceBetween === 'string' && spaceBetween.indexOf('%') >= 0) {
          spaceBetween = parseFloat(spaceBetween.replace('%', '')) / 100 * swiper.size;
        } else if (typeof spaceBetween === 'string') {
          spaceBetween = parseFloat(spaceBetween);
        }
        return spaceBetween;
      };
      const initSlides = slidesLength => {
        const {
          slidesPerView
        } = swiper.params;
        const {
          rows,
          fill
        } = swiper.params.grid;
        slidesPerRow = slidesNumberEvenToRows / rows;
        numFullColumns = Math.floor(slidesLength / rows);
        if (Math.floor(slidesLength / rows) === slidesLength / rows) {
          slidesNumberEvenToRows = slidesLength;
        } else {
          slidesNumberEvenToRows = Math.ceil(slidesLength / rows) * rows;
        }
        if (slidesPerView !== 'auto' && fill === 'row') {
          slidesNumberEvenToRows = Math.max(slidesNumberEvenToRows, slidesPerView * rows);
        }
      };
      const updateSlide = (i, slide, slidesLength, getDirectionLabel) => {
        const {
          slidesPerGroup
        } = swiper.params;
        const spaceBetween = getSpaceBetween();
        const {
          rows,
          fill
        } = swiper.params.grid;
        // Set slides order
        let newSlideOrderIndex;
        let column;
        let row;
        if (fill === 'row' && slidesPerGroup > 1) {
          const groupIndex = Math.floor(i / (slidesPerGroup * rows));
          const slideIndexInGroup = i - rows * slidesPerGroup * groupIndex;
          const columnsInGroup = groupIndex === 0 ? slidesPerGroup : Math.min(Math.ceil((slidesLength - groupIndex * rows * slidesPerGroup) / rows), slidesPerGroup);
          row = Math.floor(slideIndexInGroup / columnsInGroup);
          column = slideIndexInGroup - row * columnsInGroup + groupIndex * slidesPerGroup;
          newSlideOrderIndex = column + row * slidesNumberEvenToRows / rows;
          slide.style.order = newSlideOrderIndex;
        } else if (fill === 'column') {
          column = Math.floor(i / rows);
          row = i - column * rows;
          if (column > numFullColumns || column === numFullColumns && row === rows - 1) {
            row += 1;
            if (row >= rows) {
              row = 0;
              column += 1;
            }
          }
        } else {
          row = Math.floor(i / slidesPerRow);
          column = i - row * slidesPerRow;
        }
        slide.style[getDirectionLabel('margin-top')] = row !== 0 ? spaceBetween && `${spaceBetween}px` : '';
      };
      const updateWrapperSize = (slideSize, snapGrid, getDirectionLabel) => {
        const {
          centeredSlides,
          roundLengths
        } = swiper.params;
        const spaceBetween = getSpaceBetween();
        const {
          rows
        } = swiper.params.grid;
        swiper.virtualSize = (slideSize + spaceBetween) * slidesNumberEvenToRows;
        swiper.virtualSize = Math.ceil(swiper.virtualSize / rows) - spaceBetween;
        swiper.wrapperEl.style[getDirectionLabel('width')] = `${swiper.virtualSize + spaceBetween}px`;
        if (centeredSlides) {
          const newSlidesGrid = [];
          for (let i = 0; i < snapGrid.length; i += 1) {
            let slidesGridItem = snapGrid[i];
            if (roundLengths) slidesGridItem = Math.floor(slidesGridItem);
            if (snapGrid[i] < swiper.virtualSize + snapGrid[0]) newSlidesGrid.push(slidesGridItem);
          }
          snapGrid.splice(0, snapGrid.length);
          snapGrid.push(...newSlidesGrid);
        }
      };
      swiper.grid = {
        initSlides,
        updateSlide,
        updateWrapperSize
      };
    }

    function appendSlide(slides) {
      const swiper = this;
      const {
        params,
        slidesEl
      } = swiper;
      if (params.loop) {
        swiper.loopDestroy();
      }
      const appendElement = slideEl => {
        if (typeof slideEl === 'string') {
          const tempDOM = document.createElement('div');
          tempDOM.innerHTML = slideEl;
          slidesEl.append(tempDOM.children[0]);
          tempDOM.innerHTML = '';
        } else {
          slidesEl.append(slideEl);
        }
      };
      if (typeof slides === 'object' && 'length' in slides) {
        for (let i = 0; i < slides.length; i += 1) {
          if (slides[i]) appendElement(slides[i]);
        }
      } else {
        appendElement(slides);
      }
      swiper.recalcSlides();
      if (params.loop) {
        swiper.loopCreate();
      }
      if (!params.observer || swiper.isElement) {
        swiper.update();
      }
    }

    function prependSlide(slides) {
      const swiper = this;
      const {
        params,
        activeIndex,
        slidesEl
      } = swiper;
      if (params.loop) {
        swiper.loopDestroy();
      }
      let newActiveIndex = activeIndex + 1;
      const prependElement = slideEl => {
        if (typeof slideEl === 'string') {
          const tempDOM = document.createElement('div');
          tempDOM.innerHTML = slideEl;
          slidesEl.prepend(tempDOM.children[0]);
          tempDOM.innerHTML = '';
        } else {
          slidesEl.prepend(slideEl);
        }
      };
      if (typeof slides === 'object' && 'length' in slides) {
        for (let i = 0; i < slides.length; i += 1) {
          if (slides[i]) prependElement(slides[i]);
        }
        newActiveIndex = activeIndex + slides.length;
      } else {
        prependElement(slides);
      }
      swiper.recalcSlides();
      if (params.loop) {
        swiper.loopCreate();
      }
      if (!params.observer || swiper.isElement) {
        swiper.update();
      }
      swiper.slideTo(newActiveIndex, 0, false);
    }

    function addSlide(index, slides) {
      const swiper = this;
      const {
        params,
        activeIndex,
        slidesEl
      } = swiper;
      let activeIndexBuffer = activeIndex;
      if (params.loop) {
        activeIndexBuffer -= swiper.loopedSlides;
        swiper.loopDestroy();
        swiper.recalcSlides();
      }
      const baseLength = swiper.slides.length;
      if (index <= 0) {
        swiper.prependSlide(slides);
        return;
      }
      if (index >= baseLength) {
        swiper.appendSlide(slides);
        return;
      }
      let newActiveIndex = activeIndexBuffer > index ? activeIndexBuffer + 1 : activeIndexBuffer;
      const slidesBuffer = [];
      for (let i = baseLength - 1; i >= index; i -= 1) {
        const currentSlide = swiper.slides[i];
        currentSlide.remove();
        slidesBuffer.unshift(currentSlide);
      }
      if (typeof slides === 'object' && 'length' in slides) {
        for (let i = 0; i < slides.length; i += 1) {
          if (slides[i]) slidesEl.append(slides[i]);
        }
        newActiveIndex = activeIndexBuffer > index ? activeIndexBuffer + slides.length : activeIndexBuffer;
      } else {
        slidesEl.append(slides);
      }
      for (let i = 0; i < slidesBuffer.length; i += 1) {
        slidesEl.append(slidesBuffer[i]);
      }
      swiper.recalcSlides();
      if (params.loop) {
        swiper.loopCreate();
      }
      if (!params.observer || swiper.isElement) {
        swiper.update();
      }
      if (params.loop) {
        swiper.slideTo(newActiveIndex + swiper.loopedSlides, 0, false);
      } else {
        swiper.slideTo(newActiveIndex, 0, false);
      }
    }

    function removeSlide(slidesIndexes) {
      const swiper = this;
      const {
        params,
        activeIndex
      } = swiper;
      let activeIndexBuffer = activeIndex;
      if (params.loop) {
        activeIndexBuffer -= swiper.loopedSlides;
        swiper.loopDestroy();
      }
      let newActiveIndex = activeIndexBuffer;
      let indexToRemove;
      if (typeof slidesIndexes === 'object' && 'length' in slidesIndexes) {
        for (let i = 0; i < slidesIndexes.length; i += 1) {
          indexToRemove = slidesIndexes[i];
          if (swiper.slides[indexToRemove]) swiper.slides[indexToRemove].remove();
          if (indexToRemove < newActiveIndex) newActiveIndex -= 1;
        }
        newActiveIndex = Math.max(newActiveIndex, 0);
      } else {
        indexToRemove = slidesIndexes;
        if (swiper.slides[indexToRemove]) swiper.slides[indexToRemove].remove();
        if (indexToRemove < newActiveIndex) newActiveIndex -= 1;
        newActiveIndex = Math.max(newActiveIndex, 0);
      }
      swiper.recalcSlides();
      if (params.loop) {
        swiper.loopCreate();
      }
      if (!params.observer || swiper.isElement) {
        swiper.update();
      }
      if (params.loop) {
        swiper.slideTo(newActiveIndex + swiper.loopedSlides, 0, false);
      } else {
        swiper.slideTo(newActiveIndex, 0, false);
      }
    }

    function removeAllSlides() {
      const swiper = this;
      const slidesIndexes = [];
      for (let i = 0; i < swiper.slides.length; i += 1) {
        slidesIndexes.push(i);
      }
      swiper.removeSlide(slidesIndexes);
    }

    function Manipulation(_ref) {
      let {
        swiper
      } = _ref;
      Object.assign(swiper, {
        appendSlide: appendSlide.bind(swiper),
        prependSlide: prependSlide.bind(swiper),
        addSlide: addSlide.bind(swiper),
        removeSlide: removeSlide.bind(swiper),
        removeAllSlides: removeAllSlides.bind(swiper)
      });
    }

    function effectInit(params) {
      const {
        effect,
        swiper,
        on,
        setTranslate,
        setTransition,
        overwriteParams,
        perspective,
        recreateShadows,
        getEffectParams
      } = params;
      on('beforeInit', () => {
        if (swiper.params.effect !== effect) return;
        swiper.classNames.push(`${swiper.params.containerModifierClass}${effect}`);
        if (perspective && perspective()) {
          swiper.classNames.push(`${swiper.params.containerModifierClass}3d`);
        }
        const overwriteParamsResult = overwriteParams ? overwriteParams() : {};
        Object.assign(swiper.params, overwriteParamsResult);
        Object.assign(swiper.originalParams, overwriteParamsResult);
      });
      on('setTranslate', () => {
        if (swiper.params.effect !== effect) return;
        setTranslate();
      });
      on('setTransition', (_s, duration) => {
        if (swiper.params.effect !== effect) return;
        setTransition(duration);
      });
      on('transitionEnd', () => {
        if (swiper.params.effect !== effect) return;
        if (recreateShadows) {
          if (!getEffectParams || !getEffectParams().slideShadows) return;
          // remove shadows
          swiper.slides.forEach(slideEl => {
            slideEl.querySelectorAll('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').forEach(shadowEl => shadowEl.remove());
          });
          // create new one
          recreateShadows();
        }
      });
      let requireUpdateOnVirtual;
      on('virtualUpdate', () => {
        if (swiper.params.effect !== effect) return;
        if (!swiper.slides.length) {
          requireUpdateOnVirtual = true;
        }
        requestAnimationFrame(() => {
          if (requireUpdateOnVirtual && swiper.slides && swiper.slides.length) {
            setTranslate();
            requireUpdateOnVirtual = false;
          }
        });
      });
    }

    function effectTarget(effectParams, slideEl) {
      const transformEl = getSlideTransformEl(slideEl);
      if (transformEl !== slideEl) {
        transformEl.style.backfaceVisibility = 'hidden';
        transformEl.style['-webkit-backface-visibility'] = 'hidden';
      }
      return transformEl;
    }

    function effectVirtualTransitionEnd(_ref) {
      let {
        swiper,
        duration,
        transformElements,
        allSlides
      } = _ref;
      const {
        activeIndex
      } = swiper;
      const getSlide = el => {
        if (!el.parentElement) {
          // assume shadow root
          const slide = swiper.slides.filter(slideEl => slideEl.shadowEl && slideEl.shadowEl === el.parentNode)[0];
          return slide;
        }
        return el.parentElement;
      };
      if (swiper.params.virtualTranslate && duration !== 0) {
        let eventTriggered = false;
        let transitionEndTarget;
        if (allSlides) {
          transitionEndTarget = transformElements;
        } else {
          transitionEndTarget = transformElements.filter(transformEl => {
            const el = transformEl.classList.contains('swiper-slide-transform') ? getSlide(transformEl) : transformEl;
            return swiper.getSlideIndex(el) === activeIndex;
          });
        }
        transitionEndTarget.forEach(el => {
          elementTransitionEnd(el, () => {
            if (eventTriggered) return;
            if (!swiper || swiper.destroyed) return;
            eventTriggered = true;
            swiper.animating = false;
            const evt = new window.CustomEvent('transitionend', {
              bubbles: true,
              cancelable: true
            });
            swiper.wrapperEl.dispatchEvent(evt);
          });
        });
      }
    }

    function EffectFade(_ref) {
      let {
        swiper,
        extendParams,
        on
      } = _ref;
      extendParams({
        fadeEffect: {
          crossFade: false
        }
      });
      const setTranslate = () => {
        const {
          slides
        } = swiper;
        const params = swiper.params.fadeEffect;
        for (let i = 0; i < slides.length; i += 1) {
          const slideEl = swiper.slides[i];
          const offset = slideEl.swiperSlideOffset;
          let tx = -offset;
          if (!swiper.params.virtualTranslate) tx -= swiper.translate;
          let ty = 0;
          if (!swiper.isHorizontal()) {
            ty = tx;
            tx = 0;
          }
          const slideOpacity = swiper.params.fadeEffect.crossFade ? Math.max(1 - Math.abs(slideEl.progress), 0) : 1 + Math.min(Math.max(slideEl.progress, -1), 0);
          const targetEl = effectTarget(params, slideEl);
          targetEl.style.opacity = slideOpacity;
          targetEl.style.transform = `translate3d(${tx}px, ${ty}px, 0px)`;
        }
      };
      const setTransition = duration => {
        const transformElements = swiper.slides.map(slideEl => getSlideTransformEl(slideEl));
        transformElements.forEach(el => {
          el.style.transitionDuration = `${duration}ms`;
        });
        effectVirtualTransitionEnd({
          swiper,
          duration,
          transformElements,
          allSlides: true
        });
      };
      effectInit({
        effect: 'fade',
        swiper,
        on,
        setTranslate,
        setTransition,
        overwriteParams: () => ({
          slidesPerView: 1,
          slidesPerGroup: 1,
          watchSlidesProgress: true,
          spaceBetween: 0,
          virtualTranslate: !swiper.params.cssMode
        })
      });
    }

    function EffectCube(_ref) {
      let {
        swiper,
        extendParams,
        on
      } = _ref;
      extendParams({
        cubeEffect: {
          slideShadows: true,
          shadow: true,
          shadowOffset: 20,
          shadowScale: 0.94
        }
      });
      const createSlideShadows = (slideEl, progress, isHorizontal) => {
        let shadowBefore = isHorizontal ? slideEl.querySelector('.swiper-slide-shadow-left') : slideEl.querySelector('.swiper-slide-shadow-top');
        let shadowAfter = isHorizontal ? slideEl.querySelector('.swiper-slide-shadow-right') : slideEl.querySelector('.swiper-slide-shadow-bottom');
        if (!shadowBefore) {
          shadowBefore = createElement('div', `swiper-slide-shadow-${isHorizontal ? 'left' : 'top'}`);
          slideEl.append(shadowBefore);
        }
        if (!shadowAfter) {
          shadowAfter = createElement('div', `swiper-slide-shadow-${isHorizontal ? 'right' : 'bottom'}`);
          slideEl.append(shadowAfter);
        }
        if (shadowBefore) shadowBefore.style.opacity = Math.max(-progress, 0);
        if (shadowAfter) shadowAfter.style.opacity = Math.max(progress, 0);
      };
      const recreateShadows = () => {
        // create new ones
        const isHorizontal = swiper.isHorizontal();
        swiper.slides.forEach(slideEl => {
          const progress = Math.max(Math.min(slideEl.progress, 1), -1);
          createSlideShadows(slideEl, progress, isHorizontal);
        });
      };
      const setTranslate = () => {
        const {
          el,
          wrapperEl,
          slides,
          width: swiperWidth,
          height: swiperHeight,
          rtlTranslate: rtl,
          size: swiperSize,
          browser
        } = swiper;
        const params = swiper.params.cubeEffect;
        const isHorizontal = swiper.isHorizontal();
        const isVirtual = swiper.virtual && swiper.params.virtual.enabled;
        let wrapperRotate = 0;
        let cubeShadowEl;
        if (params.shadow) {
          if (isHorizontal) {
            cubeShadowEl = swiper.slidesEl.querySelector('.swiper-cube-shadow');
            if (!cubeShadowEl) {
              cubeShadowEl = createElement('div', 'swiper-cube-shadow');
              swiper.slidesEl.append(cubeShadowEl);
            }
            cubeShadowEl.style.height = `${swiperWidth}px`;
          } else {
            cubeShadowEl = el.querySelector('.swiper-cube-shadow');
            if (!cubeShadowEl) {
              cubeShadowEl = createElement('div', 'swiper-cube-shadow');
              el.append(cubeShadowEl);
            }
          }
        }
        for (let i = 0; i < slides.length; i += 1) {
          const slideEl = slides[i];
          let slideIndex = i;
          if (isVirtual) {
            slideIndex = parseInt(slideEl.getAttribute('data-swiper-slide-index'), 10);
          }
          let slideAngle = slideIndex * 90;
          let round = Math.floor(slideAngle / 360);
          if (rtl) {
            slideAngle = -slideAngle;
            round = Math.floor(-slideAngle / 360);
          }
          const progress = Math.max(Math.min(slideEl.progress, 1), -1);
          let tx = 0;
          let ty = 0;
          let tz = 0;
          if (slideIndex % 4 === 0) {
            tx = -round * 4 * swiperSize;
            tz = 0;
          } else if ((slideIndex - 1) % 4 === 0) {
            tx = 0;
            tz = -round * 4 * swiperSize;
          } else if ((slideIndex - 2) % 4 === 0) {
            tx = swiperSize + round * 4 * swiperSize;
            tz = swiperSize;
          } else if ((slideIndex - 3) % 4 === 0) {
            tx = -swiperSize;
            tz = 3 * swiperSize + swiperSize * 4 * round;
          }
          if (rtl) {
            tx = -tx;
          }
          if (!isHorizontal) {
            ty = tx;
            tx = 0;
          }
          const transform = `rotateX(${isHorizontal ? 0 : -slideAngle}deg) rotateY(${isHorizontal ? slideAngle : 0}deg) translate3d(${tx}px, ${ty}px, ${tz}px)`;
          if (progress <= 1 && progress > -1) {
            wrapperRotate = slideIndex * 90 + progress * 90;
            if (rtl) wrapperRotate = -slideIndex * 90 - progress * 90;
          }
          slideEl.style.transform = transform;
          if (params.slideShadows) {
            createSlideShadows(slideEl, progress, isHorizontal);
          }
        }
        wrapperEl.style.transformOrigin = `50% 50% -${swiperSize / 2}px`;
        wrapperEl.style['-webkit-transform-origin'] = `50% 50% -${swiperSize / 2}px`;
        if (params.shadow) {
          if (isHorizontal) {
            cubeShadowEl.style.transform = `translate3d(0px, ${swiperWidth / 2 + params.shadowOffset}px, ${-swiperWidth / 2}px) rotateX(90deg) rotateZ(0deg) scale(${params.shadowScale})`;
          } else {
            const shadowAngle = Math.abs(wrapperRotate) - Math.floor(Math.abs(wrapperRotate) / 90) * 90;
            const multiplier = 1.5 - (Math.sin(shadowAngle * 2 * Math.PI / 360) / 2 + Math.cos(shadowAngle * 2 * Math.PI / 360) / 2);
            const scale1 = params.shadowScale;
            const scale2 = params.shadowScale / multiplier;
            const offset = params.shadowOffset;
            cubeShadowEl.style.transform = `scale3d(${scale1}, 1, ${scale2}) translate3d(0px, ${swiperHeight / 2 + offset}px, ${-swiperHeight / 2 / scale2}px) rotateX(-90deg)`;
          }
        }
        const zFactor = (browser.isSafari || browser.isWebView) && browser.needPerspectiveFix ? -swiperSize / 2 : 0;
        wrapperEl.style.transform = `translate3d(0px,0,${zFactor}px) rotateX(${swiper.isHorizontal() ? 0 : wrapperRotate}deg) rotateY(${swiper.isHorizontal() ? -wrapperRotate : 0}deg)`;
        wrapperEl.style.setProperty('--swiper-cube-translate-z', `${zFactor}px`);
      };
      const setTransition = duration => {
        const {
          el,
          slides
        } = swiper;
        slides.forEach(slideEl => {
          slideEl.style.transitionDuration = `${duration}ms`;
          slideEl.querySelectorAll('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').forEach(subEl => {
            subEl.style.transitionDuration = `${duration}ms`;
          });
        });
        if (swiper.params.cubeEffect.shadow && !swiper.isHorizontal()) {
          const shadowEl = el.querySelector('.swiper-cube-shadow');
          if (shadowEl) shadowEl.style.transitionDuration = `${duration}ms`;
        }
      };
      effectInit({
        effect: 'cube',
        swiper,
        on,
        setTranslate,
        setTransition,
        recreateShadows,
        getEffectParams: () => swiper.params.cubeEffect,
        perspective: () => true,
        overwriteParams: () => ({
          slidesPerView: 1,
          slidesPerGroup: 1,
          watchSlidesProgress: true,
          resistanceRatio: 0,
          spaceBetween: 0,
          centeredSlides: false,
          virtualTranslate: true
        })
      });
    }

    function createShadow(params, slideEl, side) {
      const shadowClass = `swiper-slide-shadow${side ? `-${side}` : ''}`;
      const shadowContainer = getSlideTransformEl(slideEl);
      let shadowEl = shadowContainer.querySelector(`.${shadowClass}`);
      if (!shadowEl) {
        shadowEl = createElement('div', `swiper-slide-shadow${side ? `-${side}` : ''}`);
        shadowContainer.append(shadowEl);
      }
      return shadowEl;
    }

    function EffectFlip(_ref) {
      let {
        swiper,
        extendParams,
        on
      } = _ref;
      extendParams({
        flipEffect: {
          slideShadows: true,
          limitRotation: true
        }
      });
      const createSlideShadows = (slideEl, progress, params) => {
        let shadowBefore = swiper.isHorizontal() ? slideEl.querySelector('.swiper-slide-shadow-left') : slideEl.querySelector('.swiper-slide-shadow-top');
        let shadowAfter = swiper.isHorizontal() ? slideEl.querySelector('.swiper-slide-shadow-right') : slideEl.querySelector('.swiper-slide-shadow-bottom');
        if (!shadowBefore) {
          shadowBefore = createShadow(params, slideEl, swiper.isHorizontal() ? 'left' : 'top');
        }
        if (!shadowAfter) {
          shadowAfter = createShadow(params, slideEl, swiper.isHorizontal() ? 'right' : 'bottom');
        }
        if (shadowBefore) shadowBefore.style.opacity = Math.max(-progress, 0);
        if (shadowAfter) shadowAfter.style.opacity = Math.max(progress, 0);
      };
      const recreateShadows = () => {
        // Set shadows
        const params = swiper.params.flipEffect;
        swiper.slides.forEach(slideEl => {
          let progress = slideEl.progress;
          if (swiper.params.flipEffect.limitRotation) {
            progress = Math.max(Math.min(slideEl.progress, 1), -1);
          }
          createSlideShadows(slideEl, progress, params);
        });
      };
      const setTranslate = () => {
        const {
          slides,
          rtlTranslate: rtl
        } = swiper;
        const params = swiper.params.flipEffect;
        for (let i = 0; i < slides.length; i += 1) {
          const slideEl = slides[i];
          let progress = slideEl.progress;
          if (swiper.params.flipEffect.limitRotation) {
            progress = Math.max(Math.min(slideEl.progress, 1), -1);
          }
          const offset = slideEl.swiperSlideOffset;
          const rotate = -180 * progress;
          let rotateY = rotate;
          let rotateX = 0;
          let tx = swiper.params.cssMode ? -offset - swiper.translate : -offset;
          let ty = 0;
          if (!swiper.isHorizontal()) {
            ty = tx;
            tx = 0;
            rotateX = -rotateY;
            rotateY = 0;
          } else if (rtl) {
            rotateY = -rotateY;
          }
          slideEl.style.zIndex = -Math.abs(Math.round(progress)) + slides.length;
          if (params.slideShadows) {
            createSlideShadows(slideEl, progress, params);
          }
          const transform = `translate3d(${tx}px, ${ty}px, 0px) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
          const targetEl = effectTarget(params, slideEl);
          targetEl.style.transform = transform;
        }
      };
      const setTransition = duration => {
        const transformElements = swiper.slides.map(slideEl => getSlideTransformEl(slideEl));
        transformElements.forEach(el => {
          el.style.transitionDuration = `${duration}ms`;
          el.querySelectorAll('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').forEach(shadowEl => {
            shadowEl.style.transitionDuration = `${duration}ms`;
          });
        });
        effectVirtualTransitionEnd({
          swiper,
          duration,
          transformElements
        });
      };
      effectInit({
        effect: 'flip',
        swiper,
        on,
        setTranslate,
        setTransition,
        recreateShadows,
        getEffectParams: () => swiper.params.flipEffect,
        perspective: () => true,
        overwriteParams: () => ({
          slidesPerView: 1,
          slidesPerGroup: 1,
          watchSlidesProgress: true,
          spaceBetween: 0,
          virtualTranslate: !swiper.params.cssMode
        })
      });
    }

    function EffectCoverflow(_ref) {
      let {
        swiper,
        extendParams,
        on
      } = _ref;
      extendParams({
        coverflowEffect: {
          rotate: 50,
          stretch: 0,
          depth: 100,
          scale: 1,
          modifier: 1,
          slideShadows: true
        }
      });
      const setTranslate = () => {
        const {
          width: swiperWidth,
          height: swiperHeight,
          slides,
          slidesSizesGrid
        } = swiper;
        const params = swiper.params.coverflowEffect;
        const isHorizontal = swiper.isHorizontal();
        const transform = swiper.translate;
        const center = isHorizontal ? -transform + swiperWidth / 2 : -transform + swiperHeight / 2;
        const rotate = isHorizontal ? params.rotate : -params.rotate;
        const translate = params.depth;
        // Each slide offset from center
        for (let i = 0, length = slides.length; i < length; i += 1) {
          const slideEl = slides[i];
          const slideSize = slidesSizesGrid[i];
          const slideOffset = slideEl.swiperSlideOffset;
          const centerOffset = (center - slideOffset - slideSize / 2) / slideSize;
          const offsetMultiplier = typeof params.modifier === 'function' ? params.modifier(centerOffset) : centerOffset * params.modifier;
          let rotateY = isHorizontal ? rotate * offsetMultiplier : 0;
          let rotateX = isHorizontal ? 0 : rotate * offsetMultiplier;
          // var rotateZ = 0
          let translateZ = -translate * Math.abs(offsetMultiplier);
          let stretch = params.stretch;
          // Allow percentage to make a relative stretch for responsive sliders
          if (typeof stretch === 'string' && stretch.indexOf('%') !== -1) {
            stretch = parseFloat(params.stretch) / 100 * slideSize;
          }
          let translateY = isHorizontal ? 0 : stretch * offsetMultiplier;
          let translateX = isHorizontal ? stretch * offsetMultiplier : 0;
          let scale = 1 - (1 - params.scale) * Math.abs(offsetMultiplier);

          // Fix for ultra small values
          if (Math.abs(translateX) < 0.001) translateX = 0;
          if (Math.abs(translateY) < 0.001) translateY = 0;
          if (Math.abs(translateZ) < 0.001) translateZ = 0;
          if (Math.abs(rotateY) < 0.001) rotateY = 0;
          if (Math.abs(rotateX) < 0.001) rotateX = 0;
          if (Math.abs(scale) < 0.001) scale = 0;
          const slideTransform = `translate3d(${translateX}px,${translateY}px,${translateZ}px)  rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale(${scale})`;
          const targetEl = effectTarget(params, slideEl);
          targetEl.style.transform = slideTransform;
          slideEl.style.zIndex = -Math.abs(Math.round(offsetMultiplier)) + 1;
          if (params.slideShadows) {
            // Set shadows
            let shadowBeforeEl = isHorizontal ? slideEl.querySelector('.swiper-slide-shadow-left') : slideEl.querySelector('.swiper-slide-shadow-top');
            let shadowAfterEl = isHorizontal ? slideEl.querySelector('.swiper-slide-shadow-right') : slideEl.querySelector('.swiper-slide-shadow-bottom');
            if (!shadowBeforeEl) {
              shadowBeforeEl = createShadow(params, slideEl, isHorizontal ? 'left' : 'top');
            }
            if (!shadowAfterEl) {
              shadowAfterEl = createShadow(params, slideEl, isHorizontal ? 'right' : 'bottom');
            }
            if (shadowBeforeEl) shadowBeforeEl.style.opacity = offsetMultiplier > 0 ? offsetMultiplier : 0;
            if (shadowAfterEl) shadowAfterEl.style.opacity = -offsetMultiplier > 0 ? -offsetMultiplier : 0;
          }
        }
      };
      const setTransition = duration => {
        const transformElements = swiper.slides.map(slideEl => getSlideTransformEl(slideEl));
        transformElements.forEach(el => {
          el.style.transitionDuration = `${duration}ms`;
          el.querySelectorAll('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').forEach(shadowEl => {
            shadowEl.style.transitionDuration = `${duration}ms`;
          });
        });
      };
      effectInit({
        effect: 'coverflow',
        swiper,
        on,
        setTranslate,
        setTransition,
        perspective: () => true,
        overwriteParams: () => ({
          watchSlidesProgress: true
        })
      });
    }

    function EffectCreative(_ref) {
      let {
        swiper,
        extendParams,
        on
      } = _ref;
      extendParams({
        creativeEffect: {
          limitProgress: 1,
          shadowPerProgress: false,
          progressMultiplier: 1,
          perspective: true,
          prev: {
            translate: [0, 0, 0],
            rotate: [0, 0, 0],
            opacity: 1,
            scale: 1
          },
          next: {
            translate: [0, 0, 0],
            rotate: [0, 0, 0],
            opacity: 1,
            scale: 1
          }
        }
      });
      const getTranslateValue = value => {
        if (typeof value === 'string') return value;
        return `${value}px`;
      };
      const setTranslate = () => {
        const {
          slides,
          wrapperEl,
          slidesSizesGrid
        } = swiper;
        const params = swiper.params.creativeEffect;
        const {
          progressMultiplier: multiplier
        } = params;
        const isCenteredSlides = swiper.params.centeredSlides;
        if (isCenteredSlides) {
          const margin = slidesSizesGrid[0] / 2 - swiper.params.slidesOffsetBefore || 0;
          wrapperEl.style.transform = `translateX(calc(50% - ${margin}px))`;
        }
        for (let i = 0; i < slides.length; i += 1) {
          const slideEl = slides[i];
          const slideProgress = slideEl.progress;
          const progress = Math.min(Math.max(slideEl.progress, -params.limitProgress), params.limitProgress);
          let originalProgress = progress;
          if (!isCenteredSlides) {
            originalProgress = Math.min(Math.max(slideEl.originalProgress, -params.limitProgress), params.limitProgress);
          }
          const offset = slideEl.swiperSlideOffset;
          const t = [swiper.params.cssMode ? -offset - swiper.translate : -offset, 0, 0];
          const r = [0, 0, 0];
          let custom = false;
          if (!swiper.isHorizontal()) {
            t[1] = t[0];
            t[0] = 0;
          }
          let data = {
            translate: [0, 0, 0],
            rotate: [0, 0, 0],
            scale: 1,
            opacity: 1
          };
          if (progress < 0) {
            data = params.next;
            custom = true;
          } else if (progress > 0) {
            data = params.prev;
            custom = true;
          }
          // set translate
          t.forEach((value, index) => {
            t[index] = `calc(${value}px + (${getTranslateValue(data.translate[index])} * ${Math.abs(progress * multiplier)}))`;
          });
          // set rotates
          r.forEach((value, index) => {
            r[index] = data.rotate[index] * Math.abs(progress * multiplier);
          });
          slideEl.style.zIndex = -Math.abs(Math.round(slideProgress)) + slides.length;
          const translateString = t.join(', ');
          const rotateString = `rotateX(${r[0]}deg) rotateY(${r[1]}deg) rotateZ(${r[2]}deg)`;
          const scaleString = originalProgress < 0 ? `scale(${1 + (1 - data.scale) * originalProgress * multiplier})` : `scale(${1 - (1 - data.scale) * originalProgress * multiplier})`;
          const opacityString = originalProgress < 0 ? 1 + (1 - data.opacity) * originalProgress * multiplier : 1 - (1 - data.opacity) * originalProgress * multiplier;
          const transform = `translate3d(${translateString}) ${rotateString} ${scaleString}`;

          // Set shadows
          if (custom && data.shadow || !custom) {
            let shadowEl = slideEl.querySelector('.swiper-slide-shadow');
            if (!shadowEl && data.shadow) {
              shadowEl = createShadow(params, slideEl);
            }
            if (shadowEl) {
              const shadowOpacity = params.shadowPerProgress ? progress * (1 / params.limitProgress) : progress;
              shadowEl.style.opacity = Math.min(Math.max(Math.abs(shadowOpacity), 0), 1);
            }
          }
          const targetEl = effectTarget(params, slideEl);
          targetEl.style.transform = transform;
          targetEl.style.opacity = opacityString;
          if (data.origin) {
            targetEl.style.transformOrigin = data.origin;
          }
        }
      };
      const setTransition = duration => {
        const transformElements = swiper.slides.map(slideEl => getSlideTransformEl(slideEl));
        transformElements.forEach(el => {
          el.style.transitionDuration = `${duration}ms`;
          el.querySelectorAll('.swiper-slide-shadow').forEach(shadowEl => {
            shadowEl.style.transitionDuration = `${duration}ms`;
          });
        });
        effectVirtualTransitionEnd({
          swiper,
          duration,
          transformElements,
          allSlides: true
        });
      };
      effectInit({
        effect: 'creative',
        swiper,
        on,
        setTranslate,
        setTransition,
        perspective: () => swiper.params.creativeEffect.perspective,
        overwriteParams: () => ({
          watchSlidesProgress: true,
          virtualTranslate: !swiper.params.cssMode
        })
      });
    }

    function EffectCards(_ref) {
      let {
        swiper,
        extendParams,
        on
      } = _ref;
      extendParams({
        cardsEffect: {
          slideShadows: true,
          rotate: true,
          perSlideRotate: 2,
          perSlideOffset: 8
        }
      });
      const setTranslate = () => {
        const {
          slides,
          activeIndex
        } = swiper;
        const params = swiper.params.cardsEffect;
        const {
          startTranslate,
          isTouched
        } = swiper.touchEventsData;
        const currentTranslate = swiper.translate;
        for (let i = 0; i < slides.length; i += 1) {
          const slideEl = slides[i];
          const slideProgress = slideEl.progress;
          const progress = Math.min(Math.max(slideProgress, -4), 4);
          let offset = slideEl.swiperSlideOffset;
          if (swiper.params.centeredSlides && !swiper.params.cssMode) {
            swiper.wrapperEl.style.transform = `translateX(${swiper.minTranslate()}px)`;
          }
          if (swiper.params.centeredSlides && swiper.params.cssMode) {
            offset -= slides[0].swiperSlideOffset;
          }
          let tX = swiper.params.cssMode ? -offset - swiper.translate : -offset;
          let tY = 0;
          const tZ = -100 * Math.abs(progress);
          let scale = 1;
          let rotate = -params.perSlideRotate * progress;
          let tXAdd = params.perSlideOffset - Math.abs(progress) * 0.75;
          const slideIndex = swiper.virtual && swiper.params.virtual.enabled ? swiper.virtual.from + i : i;
          const isSwipeToNext = (slideIndex === activeIndex || slideIndex === activeIndex - 1) && progress > 0 && progress < 1 && (isTouched || swiper.params.cssMode) && currentTranslate < startTranslate;
          const isSwipeToPrev = (slideIndex === activeIndex || slideIndex === activeIndex + 1) && progress < 0 && progress > -1 && (isTouched || swiper.params.cssMode) && currentTranslate > startTranslate;
          if (isSwipeToNext || isSwipeToPrev) {
            const subProgress = (1 - Math.abs((Math.abs(progress) - 0.5) / 0.5)) ** 0.5;
            rotate += -28 * progress * subProgress;
            scale += -0.5 * subProgress;
            tXAdd += 96 * subProgress;
            tY = `${-25 * subProgress * Math.abs(progress)}%`;
          }
          if (progress < 0) {
            // next
            tX = `calc(${tX}px + (${tXAdd * Math.abs(progress)}%))`;
          } else if (progress > 0) {
            // prev
            tX = `calc(${tX}px + (-${tXAdd * Math.abs(progress)}%))`;
          } else {
            tX = `${tX}px`;
          }
          if (!swiper.isHorizontal()) {
            const prevY = tY;
            tY = tX;
            tX = prevY;
          }
          const scaleString = progress < 0 ? `${1 + (1 - scale) * progress}` : `${1 - (1 - scale) * progress}`;
          const transform = `
        translate3d(${tX}, ${tY}, ${tZ}px)
        rotateZ(${params.rotate ? rotate : 0}deg)
        scale(${scaleString})
      `;
          if (params.slideShadows) {
            // Set shadows
            let shadowEl = slideEl.querySelector('.swiper-slide-shadow');
            if (!shadowEl) {
              shadowEl = createShadow(params, slideEl);
            }
            if (shadowEl) shadowEl.style.opacity = Math.min(Math.max((Math.abs(progress) - 0.5) / 0.5, 0), 1);
          }
          slideEl.style.zIndex = -Math.abs(Math.round(slideProgress)) + slides.length;
          const targetEl = effectTarget(params, slideEl);
          targetEl.style.transform = transform;
        }
      };
      const setTransition = duration => {
        const transformElements = swiper.slides.map(slideEl => getSlideTransformEl(slideEl));
        transformElements.forEach(el => {
          el.style.transitionDuration = `${duration}ms`;
          el.querySelectorAll('.swiper-slide-shadow').forEach(shadowEl => {
            shadowEl.style.transitionDuration = `${duration}ms`;
          });
        });
        effectVirtualTransitionEnd({
          swiper,
          duration,
          transformElements
        });
      };
      effectInit({
        effect: 'cards',
        swiper,
        on,
        setTranslate,
        setTransition,
        perspective: () => true,
        overwriteParams: () => ({
          watchSlidesProgress: true,
          virtualTranslate: !swiper.params.cssMode
        })
      });
    }

    // Swiper Class
    const modules = [Virtual, Keyboard, Mousewheel, Navigation, Pagination, Scrollbar, Parallax, Zoom, Controller, A11y, History, HashNavigation, Autoplay, Thumb, freeMode, Grid, Manipulation, EffectFade, EffectCube, EffectFlip, EffectCoverflow, EffectCreative, EffectCards];
    Swiper.use(modules);

    return Swiper;

}));
﻿var /*json*/_currentImage = null;
var /*string*/_noCaptionCaptionText = "Click here to add a caption.";
var /*string*/_noCreditText = "Click here to add credits.";
var /*obj*/_slideShowTimer = null;
var /*bool*/_changingImage = false;
var /*bool*/_beforeUpload = false;
var /*bool*/_blockTag = false;
var /*array*/_tags = [];
var /*array*/_tagsLinkType = [];
var /*array*/_tagsLinkName = [];
var /*array*/_wiredTags = [];
var _archivedAlbum = [];
var _reloadThumbnails = false;
var _lightBoxEmailFrom = "From (Required)";
var _lightBoxEmailReq = "Recipients (Required)";
var _lightBoxEmailMsg = "Check out this photo I found at " + ((typeof (_portalName) != 'undefined' && _portalName.length > 0) ? _portalName + "!" : "My Team Scoop!");
var _albumEmailMsg = "Check out this photo album I found at " + ((typeof (_portalName) != 'undefined' && _portalName.length > 0) ? _portalName + "!" : "My Team Scoop!");
var _MTS_lightBoxRequired = true;
_MTS_JQUERY = typeof (_MTS_JQUERY) == "undefined" ? $ : _MTS_JQUERY;
var _MTS_countSinceLastAd = 1;
var _MTS_adCount = 1;
var _isAlbum = false;

if (_MTS_widgetsReady)
   WireUpLightbox();
else
   _MTS_JQUERY(document).one("widgetsloaded", WireUpLightbox);

function WireUpLightbox()
{
   if (_MTS_JQUERY("#whiteBox").length == 0)
   {
      if (_MTS_lightBoxRequired)
      {
         _MTS_lightBoxRequired = false;
         MTS_reloadWidget("", "/api/photoLightBox.aspx", null, null, null, WireUpLightbox);
         return false;
      }
      else
         return false; // failed to load lightbox after one try... bail wireup
   }

   var boxCheck = _MTS_JQUERY(".whiteBox");
   if (boxCheck && boxCheck.length > 1)
      _MTS_JQUERY(boxCheck[0]).remove();

   _MTS_JQUERY(".uploadTagWrapper").find("script").remove();
   _MTS_JQUERY("body").append(_MTS_JQUERY("#whiteBox"));
   _MTS_JQUERY("body").append(_MTS_JQUERY(".uploadTagWrapper"));
   _MTS_JQUERY("body").append(_MTS_JQUERY(".background"));
   _MTS_JQUERY("body").append(_MTS_JQUERY(".listingBg"));

   _MTS_JQUERY(document).on("#whiteBox").delegate(".whiteBackground, #whiteCloseButton, .imageBackBtn", "click", function ()
   {
       
       if (_MTS_JQUERY("#whiteBox").data("stayOpen"))
         return;
      
      CloseWiteBox();
      var fi = _MTS_JQUERY(".filterIcon");
      fi.removeClass('imageCloseButton');
      _MTS_JQUERY("body").removeClass('noScrolling');
      var rsc = _MTS_JQUERY(".rightSideCtr");
      rsc.removeClass("rsOpen");
      _MTS_JQUERY(".mtpShow").toggleClass("mtpShow");
      _MTS_JQUERY(".adminOptActive").toggleClass("adminOptActive");
      _MTS_JQUERY(".searchClose").click();
   });

   _MTS_JQUERY(document).on("#whiteBox").delegate(".toggleCaption", "click", function () {
      var tb = $(".titleBuy");
      var tbh = tb.outerHeight();
      var pbc = $(".asCtr");
      var whiteBoxImage = $("#whiteImage.withAlbum");
      tb.toggleClass("hideCaption");

      if (tb.hasClass("hideCaption")) {
         tb.css({ "bottom": "-" + tbh + "px" });
         pbc.css({ "bottom": "-100px" });
         whiteBoxImage.css({ "height": "calc(100%)" });
      } else {
         tb.removeAttr("style");
         pbc.removeAttr("style");
         whiteBoxImage.removeAttr("style");
		}
   });


   _MTS_JQUERY(document).on("#whiteBox").delegate(".mtGear", "click", function()
   {
      
       if (_currentImage)
         OpenUpload(undefined, undefined, true, undefined, undefined, undefined, undefined, _currentImage.id);
   });

   _MTS_JQUERY(document).on("#whiteBox").delegate("#fbPhotoShare", "click", function (e)
   {
      e.preventDefault();
      var left = (screen.width / 2) - 275;
      var top = (screen.height / 2) - 225;
      var link = _MTS_SITEURL + (_isAlbum && typeof (_selectedAlbum.url) !== 'undefined' ? _selectedAlbum.url : "photo-single/" + _currentImage.id + "/?mode=team");
      window.open("https://www.facebook.com/sharer/sharer.php?u=" + encodeURI(link) + "&amp;src=sdkpreparse", "facebook-share-dialog", "width=626,height=436", "facebookShare", "width=550, height=420, top=" + top + ", left=" + left);
   });

   _MTS_JQUERY(document).on("#whiteBox").delegate("#mailPhotoShare", "click", function ()
   {
      lightBoxEmailShare(_isAlbum && typeof(_selectedAlbum.id) !== 'undefined' ? _selectedAlbum.id : 0);
   });

   _MTS_JQUERY(window).resize(function()
   {
      var mtp = _MTS_JQUERY(".mediaToolPop");
      var mtg = _MTS_JQUERY(".mtGear");
      sizePhoto();
   });

   _MTS_JQUERY("#whiteBox").on("click", ".whiteLeftArrow, .mediaControlLeft", function (event)
   {
      MTS_slideLeft();
   });

   _MTS_JQUERY("#whiteBox").on("click", ".whiteRightArrow, .mediaControlRight", function (event)
   {
      MTS_slideRight();
   });

   function MTS_slideLeft()
   {
      if (!MTS_PHOTO_AD_CHECK())
         return false;

      var image = GetPreviousImage(_currentImage);
      ChangeWhiteBoxImage(image);

      ResetSlideShow();
   }

   function MTS_slideRight()
   {
      if (!MTS_PHOTO_AD_CHECK())
         return false;

      var image = GetNextImage(_currentImage);
      ChangeWhiteBoxImage(image);

      ResetSlideShow();
   }

   if (typeof (_MTS_JQUERY().swipe) == "function")
   {
      _MTS_JQUERY("#whiteImage").swipe(function (ret)
      {
         if (ret.directionX == "right")
         {
            MTS_slideLeft();
         }
         else
         {
            MTS_slideRight();
         }
      });
   }

   _MTS_JQUERY("#whiteBox").on("click", ".albumImageCtr", function (event)
   {
      if (!MTS_PHOTO_AD_CHECK())
         return false;

      var image = GetImageById(this.id.split('_')[1], true);
      ChangeWhiteBoxImage(image);

      ResetSlideShow();
   });

   _MTS_JQUERY("#whiteBox").on("click", ".mediaControlStop", function (event)
   {
      StopSlideShow();
   });

   _MTS_JQUERY("#whiteBox").on("click", ".mediaControlPlay", function (event)
   {
      StartSlideShow();
      this.setAttribute("class", "mediaControlPause");
   });

   _MTS_JQUERY("#whiteBox").on("click", ".mediaControlPause", function (event)
   {
      PauseSlideShow();
      this.setAttribute("class", "mediaControlPlay");
   });

   _MTS_JQUERY("#whiteBox").delegate("#whiteCheerButton", "click", function ()
   {
      var cheerBtn = this;
      var p = [];
      p.push({ name: "i", value: _currentImage.id });
      p.push({ name: "t", value: 3 });
      p.push({ name: "c", value: _currentImage.cheers });
      _MTS_ajaxPending = true;
      _MTS_JQUERY.getJSON(_MTS_SITEURL + "ext/UpdateCheer.aspx", p, function ()
      {
         if (_currentImage.cheered)
            _currentImage.cheers--;
         else
            _currentImage.cheers++;
            
         _currentImage.cheered = !_currentImage.cheered;
         MTS_reloadWidget("i=" + _currentImage.id.toString() + "&t=3", "/ext/FancyCheer.aspx", null, "#whiteCheerButton");
      });
   });

   _MTS_JQUERY("#whiteBox").delegate("#whiteImageDelete", "mouseenter mouseleave", function (event)
   {
      if (event.type === "mouseenter")
      {
         _MTS_JQUERY("#whiteImageDeleteImage").css("background-image", "url(/images/deletePhotoH.png)");
      }
      else
      {
         _MTS_JQUERY("#whiteImageDeleteImage").css("background-image", "url(/images/deletePhoto.png)");
      }
   });

   _MTS_JQUERY("#whiteBox").delegate("#editImgShowBtn", "click", function ()
   {
      var title = _MTS_JQUERY("#whiteTitleNewValue");
      if (title.length > 0)
         title.val(_MTS_JQUERY("#whiteTitle").text());

      var summary = _MTS_JQUERY("#whiteSummaryNewValue");
      if (summary.length > 0)
         summary.val(_MTS_JQUERY("#whiteSummary").text());

      var credit = _MTS_JQUERY("#whiteCreditEditText");
      if (credit.length > 0)
         credit.val(_MTS_JQUERY("#whiteCredit").text().replace("Credit: ", ""));

      ToggleEdit(true);
      var eii = _MTS_JQUERY(".editImgInfo");
      eii.addClass("editImgInfoHide");

   });

   _MTS_JQUERY("#whiteBox").delegate("#editImgCancel", "click", function ()
   {
      ToggleEdit(false);
      var eii = _MTS_JQUERY(".editImgInfo");
      eii.removeClass("editImgInfoHide");
   });

   _MTS_JQUERY("#whiteBox").delegate("#editImgSave", "click", function ()
   {
      var credit = _MTS_JQUERY("#whiteCreditEditText").val(),
         title = _MTS_JQUERY("#whiteTitleNewValue").val(),
         summary = _MTS_JQUERY("#whiteSummaryNewValue").val();
      UpdateImageText(_currentImage, credit, title, summary);
      ToggleEdit(false);
   });

   var spb = _MTS_JQUERY("#sharePhoto");
   spb.on("click", function ()
   {
      var sc = _MTS_JQUERY(".shareCtr");
      sc.toggleClass("tpsLeft");
   });

   _MTS_JQUERY("#whiteBox").delegate("#whiteImageDelete", "click", function ()
   {
      var popper = new PopupDialog();
      popper.NewYesNoPrompt("Would you like to permanently delete this image?", "Are you sure?", null, function (response)
      {
         if (response === false)
            return;

         DeleteImage(_currentImage, function (deleted)
         {
            if (deleted)
            {
               _MTS_JQUERY("#photo_" + _currentImage.id).hide();
               CloseWiteBox();
            }
            else
            {
               popper.Hide();
               popper.NewOkayAlert("An unknown error prevented us from deleting this image at this time.", "Error!");
            }
         });
      });
   });

   _MTS_JQUERY("#whiteBox").delegate("#whiteTagButton", "click", function ()
   {
      ToggleTagBox(true);
   });

   _MTS_JQUERY("#whiteBox").delegate("#whiteTagEditButtonSave", "click", function ()
   {
      var scheduleId = _MTS_JQUERY("#scheduleResultSelectBox").val();
      var scheduleEntryId = scheduleId > 0 ? _MTS_JQUERY("#scheduleEntryResultsSelectBox").val() : "-1";
      var rosterId = _MTS_JQUERY("#rosterTag").val();
      var newsId = _MTS_JQUERY("#newsTag").val();
      var containerName = "tagDropContainer";
      var selectContainer = _MTS_JQUERY(".albumSelect");

      var checkTags = _MTS_JQUERY(".albumSelect").parent().css("display") == "none";

      if (checkTags)
      {
         scheduleId = findSelectId("scheduleResultSelectBox", selectContainer, containerName);
         scheduleEntryId = findSelectId("scheduleEntryResultsSelectBox", _MTS_JQUERY(".scheduleEntrySelect"), containerName);
         rosterId = findSelectId("rosterTag", selectContainer, containerName);
         newsId = findSelectId("newsTag", selectContainer, containerName);
      }

      UpdateImageTag(_currentImage, scheduleEntryId, rosterId, newsId);

      ToggleTagBox(false);
   });

   _MTS_JQUERY("#whiteBox").delegate("#whiteTagEditButtonCancel", "click", function ()
   {
      ToggleTagBox(false);
   });

   _MTS_JQUERY("#whiteBox").delegate("#buyPhoto", "click", function ()
   {
      TrackPhoto(_currentImage.id);
      if (_currentImage.container && _currentImage.container.length > 0)
      {
         var cloudUrl = "", domainUrl = "";

         for (var i = _activeContainer.portals.length - 1; i >= 0; i--)
         {
            if (_activeContainer.portals[i].id == _currentImage.container)
            {
               cloudUrl = _activeContainer.portals[i].url;
               domainUrl = _activeContainer.portals[i].domain;
               break;
            }
         }

         if (cloudUrl == "" || domainUrl == "")
            return false;

         if (!window.location.origin)
            window.location.origin = window.location.protocol + "//" + window.location.host;

         var fullImgUrl = _MTS_PHOTO_TEMPLATE.replace("%%IMG_ID%%", _currentImage.id).replace("%%SIZE%%", 2).replace("%%TEAM_ID%%", _currentImage.teamId).replace("%%USER_ID%%", _currentImage.uploaderId).replace("%%TYPE%%", 0);
         if (typeof (FOTOMOTO) !== "undefined")
            FOTOMOTO.API.showWindow(10, fullImgUrl);
         else
         {
            var highRes = cloudUrl + "/" + _currentImage.id;
            var request;
            if (window.XMLHttpRequest)
               request = new XMLHttpRequest();
            else
               request = new ActiveXObject("Microsoft.XMLHTTP");

            try
            {
               request.open('GET', highRes, false);
               request.send();
               if (request.status === 404)
               {
                  highRes = cloudUrl + "/" + getBigInt(_currentImage.id) + _currentImage.id + "_original";
               }
            }
            catch (ex)
            {
               highRes = cloudUrl + "/" + getBigInt(_currentImage.id) + _currentImage.id + "_original";
            }

            window.open
            (
               "http://" + domainUrl + ".mycapture.com/mycapture/remoteimage.asp?"
               + "caption=" + escape(_currentImage.title)
               + "&image=" + fullImgUrl
               + "&notes=" + highRes
               + "&backtext=Back"
            );
         }
      }
   });

   _MTS_JQUERY("#whiteBox").delegate("#tagButton", "click", function ()
   {
      ToggleNewTag();
   });

   _MTS_JQUERY("#whiteBox").delegate("#cropButton", "click", function ()
   {
      StartImgCrop();
      var mtp = _MTS_JQUERY(".mediaToolPop");
      var mtg = _MTS_JQUERY(".mtGear");
      mtp.toggleClass("mtpShow");
      mtg.toggleClass("adminOptActive");
      var rsc = _MTS_JQUERY(".rightSideCtr");
      rsc.toggleClass("rsOpen");
   });

   _MTS_JQUERY("#whiteBox").delegate("#imageDelete", "click", function ()
   {
      DeleteImagePopup();
   });

   _MTS_JQUERY("#whiteBox").delegate("#whiteSubmitButton", "click", function ()
   {
      var title = _MTS_JQUERY("#whiteTitle").html();

      if (title == null || title == "undefined")
         title = "";

      submitHtml =
      "<div class='submitContainer' id='submitToPortal'>" +
         "<div class='textTitle'> Title </div>" +
         "<input type='text' id='submitTitle' value='' maxlength='256' class='titleTxt' />" +
         "<div class='textTitle'> Summary </div>" +
         "<textarea id='submitSummary' maxlength='1024' class='summaryTxt' />" +

         "<div class='submitBtnCon'>" +
            "<div class='submitBtn' id='cancelToPortal'> Cancel </div>" +
            "<div class='submitBtn' id='submitFinal'> Submit </div>" +
         "</div>" +

         "<div class='textTitle' id='erMsg'>" +
         "</div>" +
      "</div>";

      _MTS_JQUERY("body").append(submitHtml);

      _MTS_JQUERY("#submitTitle").val(title);

      var subContainer = _MTS_JQUERY(".submitContainer");
      subContainer.css("z-index", 160);

      _MTS_JQUERY(".background").show();
   });

   //_MTS_JQUERY(".background, .closeTag").click(function ()
   //{
   //   _MTS_JQUERY(".background").hide();
   //   _MTS_JQUERY(".tagWrapper").hide();
   //   _MTS_JQUERY(".submitContainer").remove();
   //});

   _MTS_JQUERY(".mainTPContainer").delegate(".startSlideButton", "click", function ()
   {
       
       var image = GetImageByPosition(0);
      OpenWhiteBox(image, true);
      StartSlideShow();
   });

   _MTS_JQUERY("#whiteBox").on("click", "#cancelFeatLink", function ()
   {
      _MTS_JQUERY("#photoEditFeatLink").html("Not Featured");
      _MTS_JQUERY(this).hide();
      _MTS_JQUERY("#featApply, #whiteSubmitButton").show();

      var params = [];
      params.push({ name: 'mode', value: 'photo' });
      params.push({ name: 'id', value: _currentImage.imageId });

      _MTS_ajaxPending = true;
      _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/editfeatured.aspx", params, function ()
      {
         _MTS_JQUERY("#featApply, #featureDate").hide();
         _MTS_JQUERY("#whiteSummary").html("");
      });
   });

   _MTS_JQUERY("#featureDate .editFeatLink").click(function ()
   {
      var self = this;
      GetMiniCalendarCustom("select", "Date Range", function (m, d, y)
      {
         var newdate = m.toString() + "/" + d.toString() + "/" + y.toString();
         var params = [];

         self.innerHTML = newdate;
         FeaturePhoto(newdate, _currentImage.imageId);
      }, _MTS_JQUERY.trim(self.innerHTML));
   });

   // Featured Photo
   _MTS_JQUERY("body").delegate("#cancelToPortal", "click", function ()
   {
      CloseSubmitBox();
   });

   _MTS_JQUERY("body").delegate("#submitFinal", "click", function ()
   {
      var errContainer = _MTS_JQUERY("#erMsg");
      var sTitle = _MTS_JQUERY.trim(_MTS_JQUERY("#submitTitle").val());
      var sSummary = _MTS_JQUERY.trim(_MTS_JQUERY("#submitSummary").val());
      var sCredit = _MTS_JQUERY.trim(_MTS_JQUERY("#whiteCredit").text().replace("Credit: ", ""));

      if (sTitle == "" || sSummary == "")
      {
         errContainer.html("Title and summary are required fields!");
         return;
      }

      if (_featurePhotos)
      {
         GetMiniCalendarCustom("select", "Featured Until", function (m, d, y)
         {
            var date = m.toString() + "/" + d.toString() + "/" + y.toString();
            SubmitPhoto(sTitle, sSummary, sCredit, date);
         });
      }
      else
         SubmitPhoto(sTitle, sSummary, sCredit);
   });

   if (typeof (MTS_lightBoxCallback) == "function")
      MTS_lightBoxCallback();
}

function MTS_PHOTO_AD_CHECK()
{
   if (typeof (_MTS_ITEM_ADS) !== "undefined" && _MTS_ITEM_ADS.length > 0 && typeof(_MTS_PHOTO_PER_AD) != "undefined" && _MTS_PHOTO_PER_AD.length > 0 && _MTS_PHOTO_PER_AD > 0)
   {
      var imgAndTitle = $(".whiteImgSrc, .titleBuy");
      if (_MTS_countSinceLastAd >= _MTS_PHOTO_PER_AD)
      {
         try
         {
            var id = "mts_ad_" + _MTS_adCount,
                  adBuilder = _MTS_JQUERY("<div id='" + id + "' class='_mts_floatingAd borderedAd'></div>");

            _MTS_adCount++;
            $("#whiteImage").append(adBuilder);

            ad = _MTS_ITEM_ADS[0];
            if (ad.location.indexOf("widget_") >= 0)
            {
               adBuilder.append("<div class='custom_widget'><input name='widgetName' type='hidden' value='" + ad.location.split('_')[1] + "' /></div></div>");

               if (typeof (MTS_loadWidgets) === "function")
                  MTS_loadWidgets();

               _MTS_JQUERY(document).one("widgetsloaded", function ()
               {
                  if (typeof (__gh__webApp) === "object")
                     __gh__webApp.ads.dfp.createLazySlot('.ad-lazy:visible:last');
               });
            }
            else
            {
               googletag.defineSlot(ad.location, [ad.width ? ad.width : 300, ad.height ? ad.height : 250], id)
                  .setTargeting(ad.target, ad.target2)
                  .setCollapseEmptyDiv(true)
                  .addService(googletag.pubads());
               googletag.display(id);
            }
         }
         catch (ex)
         {

         }

         imgAndTitle.hide();
         _MTS_countSinceLastAd = 0;
         return false;
      }
      else
      {
         _MTS_countSinceLastAd++;
         imgAndTitle.show();
         _MTS_JQUERY("._mts_floatingAd").remove();
      }
   }

   return true;
}

function /*void*/GetMiniCalendarCustom(/*string*/mode, /*string*/title, /*function*/callback, /*optional*/selected)
{
   var dte = new Date();
   var sDate = new Date(selected);

   if (sDate == "Invalid Date")
      sDate = new Date();

   _cal.clearRecycle();
   _cal.mode = mode;
   _cal.wndTitle = title;
   _cal.setContract(dte.getFullYear(), 0, 0);
   _cal.maxYear = (_cal.startContractYear + 5);
   _cal.setCallback(callback);

   _cal.setSelection(sDate.getMonth() + 1, sDate.getDate(), sDate.getFullYear());
   _cal.show(100, 100);

   _MTS_JQUERY(".listingBg").css({ "height": _MTS_JQUERY(document).height(), "zIndex": 113 });
   _MTS_JQUERY(".listingBg").show();
}

function /*void*/FeaturePhoto(/*date*/newdate, /*int*/photoId)
{
   var p = [];
   p.push({ name: 'mode', value: ('photo') });
   p.push({ name: 'id', value: photoId });
   p.push({ name: 'til', value: newdate });

   p.push({ name: 'title', value: _MTS_JQUERY.trim(_MTS_JQUERY("#whiteTitle").html()) });
   p.push({ name: 'desc', value: _MTS_JQUERY.trim(_MTS_JQUERY("#whiteSummary").html()) });

   _MTS_JQUERY("#featApply").show();
   _MTS_ajaxPending = true;
   _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/editfeatured.aspx", p, function (o)
   {
      if (o.error)
      {
         _MTS_JQUERY("#fdError").html("You must fill out the title and description.");
         _MTS_JQUERY("#fdError").show();
      }
      else
      {
         _MTS_JQUERY("#cancelFeatLink").show();
         _currentImage.featuredUntil = newdate;
      }

      _MTS_JQUERY("#featApply").hide();
   });
}

function /*void*/SubmitPhoto(/*string*/sTitle, /*string*/sSummary, /*string*/sCredit, /*string*/date)
{
   var errContainer = _MTS_JQUERY("#erMsg");

   var params = [];
   params.push({ name: "mode", value: "requestAuth" });
   params.push({ name: "title", value: sTitle });
   params.push({ name: "summary", value: sSummary });
   params.push({ name: "credit", value: sCredit });
   params.push({ name: "pid", value: _currentImage.id });
   params.push({ name: "email", value: "true" });

   if (date != null && date != "")
      params.push({ name: "date", value: date });

   _MTS_ajaxPending = true;
   _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/updatePortalPhoto.aspx", params, function (err)
   {
      errContainer.html("");
      if (err.ok == "true")
      {
         _currentImage.title = sTitle;
         _currentImage.summ = sSummary;
         _currentImage.id = err.imageId;
         if (date != null && date != "")
            _currentImage.featuredUntil = date;

         CloseSubmitBox();
        
         FillWhiteBox(_currentImage);
         
      }
      else
         errContainer.html(err.error);
   });
}

function /*void*/CloseSubmitBox()
{
   var subContainer = _MTS_JQUERY(".submitContainer");
   subContainer.remove();

   _MTS_JQUERY(".background").hide();
}

function /*void*/CloseWiteBox()
{
   ToggleEdit(false);
   _MTS_JQUERY("#whiteBox, .mediaTools").removeClass("animateLeft");
   setTimeout(function ()
   {
      var wbx = _MTS_JQUERY(".whiteBox");
      wbx.hide();
   }, 500);

   var miw = _MTS_JQUERY(".mediaInterfaceWrapper");
   miw.removeClass("snapMiw, fixmia");

   var mcw = _MTS_JQUERY(".masterMcWrap");
   var bdy = _MTS_JQUERY("body, html");
   mcw.removeClass("noScrolling");
   bdy.removeClass("noScrolling");

   if (history != null && history.state != null && typeof history.state.linkBack !== 'undefined' && history.state.linkBack > 0)
      history.go(history.state.linkBack * -1);
}

function /*void*/ChangeWhiteBoxImage(image)
{
   ToggleEdit(false);
   if (_changingImage || image == null)
      return;

   _changingImage = true;

   _currentImage = image;

   _MTS_JQUERY(".whiteImgSrc").fadeTo(100, 0, function ()
   {
      DisplayWhiteBox(image, true, function ()
      {
         _changingImage = false;
         sizePhoto();
      });
   });

   return;
}

function /*void*/OpenWhiteBox(/*obj*/image, /*bool*/showMediaControls, /*bool*/isAlbum, /*bool*/stayOpen, hideImage)
{
    
    if (_slideShowTimer != null)
      clearTimeout(_slideShowTimer);

   ToggleTagBox(false);

   // Give photo time to expand to full length to maximize document height for background
   setTimeout(function ()
   {
      _MTS_JQUERY(".whiteBackground").css("height", _MTS_JQUERY(document).height().toString());
      _MTS_JQUERY(".whiteBackground").fadeTo(0, .8);
   }, 500);

   _MTS_JQUERY("#whiteBox").show(function()
   {
      _MTS_JQUERY("#whiteBox, .mediaTools").addClass("animateLeft");

      var miw = _MTS_JQUERY(".mediaInterfaceWrapper");
      miw.addClass("fixmia");

      var mcw = _MTS_JQUERY("body");
      mcw.addClass("noScrolling");

      if(_MTS_JQUERY(window).width() < 1024)
      {
         var wi = _MTS_JQUERY("#whiteImage").outerHeight();
         var mt = _MTS_JQUERY(".mediaTools").outerHeight();
         var fi = _MTS_JQUERY(".filterIcon");

         fi.addClass("imageCloseButton");
      }

      setTimeout(function ()
      {
         sizePhoto();
      }, 0);
   }, 0);

   // Prevents the viewer from closing on pages like single photo page or album page where the viewer is the page content
   if (stayOpen)
      _MTS_JQUERY("#whiteBox").data("stayOpen", true);

   _isAlbum = !!isAlbum;

   DisplayWhiteBox(image, true, sizePhoto, hideImage);
}

function /*void*/DisplayWhiteBox(/*obj*/image, /*bool*/position, /*function*/callback, hideImage)
{
   
    if (image == null)
      return;

   _currentImage = image;

   var url = "photo-single/" + (image.imageId > 0 ? image.imageId : image.id) + "/" + (image.imageId > 0 ? "" : "?mode=team");
    
   OverwriteUrl(url);

   ShowWhiteLoader();

   if (_MTS_JQUERY("input[name='mts_ilvDisableImages']").val() === "true" && image.container <= 0)
      hideImage = true;

   FillWhiteBox(image, function ()
   {
      var containers = _MTS_JQUERY(".whiteLeftArrow, .whiteRightArrow, .albumScroller, .asCtr");
      if (_selectedAlbum.images.length <= 1)
         containers.hide();
      else
      {
         containers.show();
         var scroller = _MTS_JQUERY(".albumScroller");
         if (scroller.length > 0 && scroller.children().length == 0 || _reloadThumbnails)
         {
            var html = "";
            for (var i = 0, j = _selectedAlbum.images.length - 1; i <= j; i++)
            {
               html +=  "<div id='aic_" + _selectedAlbum.images[i].id + "' class='albumImageCtr " + (_selectedAlbum.images[i].id == image.id ? "glow" : "") + "'>" +
                           "<img class='albumImage' src='" + (_selectedAlbum.images[i].container <= 0 ? _MTS_MEDIAURL + "images/eventIcon.png" : getImageLink(_selectedAlbum.images[i], 0)) + "' alt='' />" +
                        "</div>";
            }
            scroller.html(html);
            AdjustSlider(1000);
            _reloadThumbnails = false;
         }
         else
         {
            _MTS_JQUERY(".albumImageCtr.glow").toggleClass("glow");
            _MTS_JQUERY("#aic_" + image.id + ".albumImageCtr").toggleClass("glow");
            AdjustSlider(1000);
         }
      }

      if (!_MTS_JQUERY.Query.notrack && typeof(trackItem) === "function")
         trackItem(image.imageId > 0 ? image.imageId : image.id, "Image");

      _MTS_JQUERY(".whiteLeftArrow, .whiteRightArrow").css("height", "100%");
      HideWhiteLoader();
      _MTS_JQUERY(".white").fadeTo(100, 1, function ()
      {
         if (typeof callback === "function" && callback != null)
            callback();
      });
   }, hideImage);
}

function AdjustSlider(timeout)
{
   setTimeout(function ()
   {
      var actr = _MTS_JQUERY(".asCtr");
      var ascr = _MTS_JQUERY(".albumScroller");
      var aict = _MTS_JQUERY(".albumImageCtr");
      var aimg = _MTS_JQUERY(".albumImage");
      var whte = _MTS_JQUERY(".white");
      var rctr = _MTS_JQUERY(".rightSideCtr");

      aict.css({ "height": actr.outerHeight() + "px" });
      ascr.css({ "height": actr.outerHeight() + "px" });
      aict.css({ "width": aict.outerHeight() });
      ascr.css({ "width": (aict.outerWidth() * aict.length) + "px" });
      if (_MTS_JQUERY(window).width() < 768)
      {
         rctr.css({ "padding-bottom": actr.outerHeight() + "px" });
      }

      if (ascr.width() < _MTS_JQUERY(window).width())
         ascr.addClass("mts_transform_left");
      else
      {
         ascr.removeClass("mts_transform_left");
         _MTS_JQUERY(".asCtr").animate({
            scrollLeft: (aict.outerHeight() * _MTS_JQUERY(".albumImageCtr.glow").prevAll().length) - (actr.outerWidth() / 2) + (aict.outerHeight() / 2)
         });
      }
   }, timeout);
}

function /*void*/ShowWhiteLoader()
{
   _MTS_JQUERY("#whiteLoader").show();
}

function /*void*/HideWhiteLoader()
{
   _MTS_JQUERY("#whiteLoader").hide();
}

function /*string*/InsertNewTag(/*string*/linkId, /*string*/tagId, /*string*/tagType, /*string*/scheduleId, /*string*/tagName,
/*bool*/startUp, /*string*/writerId, /*string*/tagURL, /*bool*/isTagged)
{
   if (tagURL == "" || tagName == "")
      return "";

   _MTS_JQUERY(".tagContainer").children("div[id!='currentTag']").remove();
   
   var tagHtml = "";

   if (!startUp && _MTS_JQUERY("#currentTag").html() === null)
      tagHtml += "<div class=\"currentTag\" id=\"currentTag\"><div class=\"currentTagLbl\">Current Tags:</div> ";

   tagHtml += "<div id=\"tag_" + tagType + "_" + linkId + "\" class=\"imageTag\"><a title='" + tagName + "' href=\"" + tagURL + "\">" + tagName + "</a>";

   //Attach link depending on type of tag
   var disableOption = "";
   if (tagType === "ScheduleEvent")
      disableOption = _MTS_JQUERY("#scheduleEntryResultsSelectBox option[value=\"" + linkId + "\"]");
   else if (tagType == "Roster")
      disableOption = _MTS_JQUERY("#rosterTag option[value=\"" + linkId + "\"]");
   else if (tagType == "NewsItem")
      disableOption = _MTS_JQUERY("#newsTag option[value=\"" + linkId + "\"]");

   if (disableOption != "")
      disableOption.attr("disabled", "disabled");

   var canEditTags = _MTS_JQUERY("#tagButton").length > 0;
   //Attach remove if you made link or are admin
   if (!isTagged && (!startUp || canEditTags || typeof _userId === "number" && !isNaN(_userId) &&
      (_userId === writerId || (typeof _canUpdate === "boolean" && _canUpdate))))
      tagHtml += "<div id=\"tagDelete_" + tagId + "\" title=\"Delete Tag\" class=\"imageTagRem\">x</div>";

   tagHtml += "</div> ";

   if (!startUp && _MTS_JQUERY("#currentTag").html() === null)
      tagHtml += "</div>";

   //Check if the click event already exists
   var cContainer = _MTS_JQUERY("#whiteBox").length > 0 ? _MTS_JQUERY._data(_MTS_JQUERY("#whiteBox")[0], 'events') : undefined;
   if (cContainer != undefined)
   {
      cContainer = cContainer.click;

      var cLength = cContainer.length;

      for (var i = 0; i < cLength; i++)
      {
         if (cContainer[i].selector === "#tagDelete_" + tagId)
            return tagHtml;
      }
   }

   WireImageTag(tagId, linkId, scheduleId, tagType);

   return tagHtml;
}

function /*void*/WireImageTag(/*string*/tagId, /*string*/linkId, /*string*/scheduleId, /*string*/tagType)
{
   _MTS_JQUERY("#whiteBox").delegate("#tagDelete_" + tagId, "click", function ()
   {
      tagPrompt(tagId, linkId, scheduleId, tagType);
   });
}

function /*void*/tagPrompt(/*string*/tagId, /*string*/linkId, /*string*/scheduleId, /*string*/tagType)
{
   var popper = new PopupDialog();
   popper.NewYesNoPrompt("Would you like to permanently delete this tag?", "Are you sure?", null, function (response)
   {
      if (response === false)
         return;

      DeleteTag(_currentImage, tagId, function (deleted)
      {
         if (deleted)
         {
            _MTS_JQUERY("#tag_" + tagType + "_" + linkId).remove();

            var SelectBox = ""
            if (tagType == "ScheduleEvent")
               SelectBox = "#scheduleEntryResultsSelectBox";
            else if (tagType == "Roster")
               SelectBox = "#rosterTag";
            else if (tagType == "NewsItem")
            {
               SelectBox = "#newsTag";
               _forceRefresh = true; //force refresh when selecting #home tab
            }

            _MTS_JQUERY(SelectBox + " option[value=\"" + linkId + "\"]").removeAttr("disabled");

            var cILength = _currentImage.links.length;
            var cIPos = -1;

            for (var i = 0; i < cILength; i++)
            {
               if (_currentImage.links[i].tagId == tagId)
               {
                  cIPos = i;
                  break;
               }
            }

            if (cIPos >= 0)
            {
               if (_MTS_JQUERY("#rP_" + linkId) != null)
                  _MTS_JQUERY("#rP_" + linkId).find("#photo_" + tagId).parent().remove();

               _currentImage.links.splice(cIPos, 1);
            }
         }
         else
         {
            popper.Hide();
            popper.NewOkayAlert("An unknown error prevented us from deleting this tag at this time.", "Error!");
         }
      });
   });
}

function lightBoxEmailShare(albId)
{
   var isAlbum = typeof (albId) !== 'undefined' && albId > 0;
   var emailHtml =
      "<div class='emailBg'>" +
         "<div class='emailTemplate' id='sendEmail'>" +
            "<div class='emailTempHead'>Share This " + (isAlbum ? "Album" : "Photo") + "</div>" +
            (_MTS_userId > 0 ? "" : "<input title='" + _lightBoxEmailFrom + "' type='text' class='emailTxt' id='emailFrom' value='" + _lightBoxEmailFrom + "' />") +
            "<input title='" + _lightBoxEmailReq + "' type='text' class='emailTxt' id='emailList' value='" + _lightBoxEmailReq + "' />" +
            "<textarea class='emailTxtArea' id='emailMsg'>" + (isAlbum ? _albumEmailMsg : _lightBoxEmailMsg) + "</textarea>" +
            "<div class='tempButtons'>" +
               "<div class='mts_cc_button tempButton' id='emailSend'>Send</div>" +
               "<input id='shareMode' type='hidden' value='" + (isAlbum ? "photoAlbum" : "photo") + "' />" +
               "<div class='mts_cc_button tempButton' id='emailCancel'>Cancel</div>" +
            "</div>" +
         "</div>" +
      "</div>";

   _MTS_JQUERY("body").append(emailHtml);
   _MTS_JQUERY(".emailTempExit").click(function ()
   {
      _MTS_JQUERY(".emailBg, .emailTemplate").remove();
   });
   _MTS_JQUERY(".emailBg").show();

   if (isAlbum)
      _curShareId = albId;
}

function /*void*/FillWhiteBox(/*obj*/image, /*function*/callback, hideImage)
{
   var tagHtml = "";
   var tagLength = image.links.length;
   var imageLink = getImageLink(image, 2);
   var imageLocation = _MTS_SITEURL + (_isAlbum && typeof (_selectedAlbum.url) !== 'undefined' ? _selectedAlbum.url : "photo-single/" + image.id + "/?mode=team");

   _MTS_JQUERY("#tagContainer").html("");
   _MTS_JQUERY(".scheduleEntrySelect").removeAttr("disabled");
   _MTS_JQUERY(".albumSelect").children().removeAttr('disabled');

   var albumTitle = "";
   if (tagLength > 0)
   {
      tagHtml = "<div class=\"currentTag\" id=\"currentTag\"><div class=\"currentTagLbl\">Current Tags:</div> ";
      for (var i = 0; i < tagLength; i++)
      {
         var curLink = image.links[i];
         if (albumTitle == "" && curLink.tagType == "PhotoAlbum")
            albumTitle = curLink.tagName;

         tagHtml += InsertNewTag(curLink.linkId, curLink.tagId, curLink.tagType, curLink.scheduleId, curLink.tagName, true,
            curLink.writerId, curLink.href, typeof image.isTagged === "boolean");
      }
      tagHtml += "</div>";

      _MTS_JQUERY("#tagContainer").html(tagHtml);
   }

   _MTS_JQUERY(".whiteAlbumTitle").html(albumTitle.length > 0 ? "<span style='font-weight: bold;'>Album: </span>" + albumTitle : "");
   _MTS_JQUERY("#whiteTitleNewValue").html("");
   _MTS_JQUERY("#whiteTitle").html(image.title + (image.description && image.description.length > 0 ? "<br><br>" + image.description : ""));
   _MTS_JQUERY("#whiteBox #fbTitle").val(_isAlbum && typeof (_selectedAlbum.urlName) !== 'undefined' ? _selectedAlbum.urlName : image.title);
   _MTS_JQUERY("#whiteBox #fbImgDefault").val(imageLink);
   _MTS_JQUERY("#whiteBox #fbLink").val(imageLocation);
   _MTS_JQUERY("#twitterPhotoShare").attr("href", "https://twitter.com/intent/tweet?hashtags=mts&original_referer=" + encodeURI(imageLocation) + "&text=" + encodeURI(_isAlbum && typeof (_selectedAlbum.urlName) !== 'undefined' ? _selectedAlbum.urlName : image.title) + "&tw_p=tweetbutton&url=" + encodeURI(imageLocation))
   _curShareId = _isAlbum && typeof (_selectedAlbum.Id) !== 'undefined' ? _selectedAlbum.id : image.id;

   _MTS_JQUERY("#whiteSummaryNewValue").html("");
   if (typeof (image.summ) !== 'undefined' && image.summ != "")
      _MTS_JQUERY("#whiteSummary").html(image.summ);
   else
      _MTS_JQUERY("#whiteSummary").html("");

   _MTS_JQUERY("#whiteCreditEditText").html("");

   var credit = _MTS_JQUERY("#whiteCredit");
   if (image.credit != "")
   {
      credit.html(" Credit: " + image.credit);
      credit.show();
   }
   else
   {
      credit.hide();
   }

   _MTS_JQUERY("#photoEditFeatLink").html("");
   if (typeof (image.featuredUntil) !== 'undefined' && image.featuredUntil != "")
   {
      var fud = new Date(image.featuredUntil);
      _MTS_JQUERY("#photoEditFeatLink").html((fud.getMonth() + 1) + "/" + fud.getDate() + "/" + fud.getFullYear());
      _MTS_JQUERY("#featureDate, #cancelFeatLink").show();
      _MTS_JQUERY("#whiteSubmitButton").hide();
   }
   else
   {
      _MTS_JQUERY("#photoEditFeatLink").html("");
      _MTS_JQUERY("#featureDate, #cancelFeatLink").hide();
      _MTS_JQUERY("#whiteSubmitButton").show();
   }

   var bPhoto = _MTS_JQUERY("#buyPhoto, .buyTxt");
   if (image.container && image.container != "" && parseInt(image.container) > -1 && typeof (_activeContainer) != "undefined")
   {
      var cloudUrl = "", domainUrl = "";

      for (var i = _activeContainer.portals.length - 1; i >= 0; i--)
      {
         if (_activeContainer.portals[i].id == _currentImage.container)
         {
            cloudUrl = _activeContainer.portals[i].url;
            domainUrl = _activeContainer.portals[i].domain;
            break;
         }
      }

      if (cloudUrl == "" || domainUrl == "")
         bPhoto.hide();
      else
         bPhoto.show();
   }
   else
   {
      bPhoto.hide();
   }

   ToggleTagBox(false);

   if (typeof image.isTagged === "undefined" && typeof _userId === "number" && !isNaN(_userId))
   {
      if (_userId === image.uploaderId || (typeof _canUpdate === "boolean" && _canUpdate))
         _MTS_JQUERY("#editImgShowBtn").show();
      else
         _MTS_JQUERY("#editImgShowBtn").hide();

      if (_userId === image.uploaderId || (typeof _canDelete === "boolean" && _canDelete))
         _MTS_JQUERY("#whiteImageDelete").show();
      else
         _MTS_JQUERY("#whiteImageDelete").hide();
   }
   else
   {
      _MTS_JQUERY("#whiteCaptionEdit").hide();
      _MTS_JQUERY("#whiteCreditEdit").hide();
   }

   // COMMENTED OUT (DO NOT REMOVE) - WILL BE SHOWN ONLY AT PUBLISHER'S REQUEST
   //_MTS_JQUERY("#whiteUploader").html("Uploaded By: " + "<span class=\"mts_cc_text\">" + image.uploaderName + "</div>");

   MTS_reloadWidget("i=" + image.id.toString() + "&t=3", "/ext/FancyFlag.aspx", null, "#whiteFlagButton");
   MTS_reloadWidget("i=" + image.id.toString() + "&t=3", "/ext/FancyCheer.aspx", null, "#whiteCheerButton");

   _MTS_JQUERY("#whiteImage").html
   (
      "<i class='far fa-chevron-left whiteLeftArrow'></i>" +
      "<div class='cropMarks'><div class='cmTopLeft'></div>" +
      "<div class='cmTopRight'></div><div class='cmBotRight'></div>" +
      "<div class='cmBotLeft'></div></div>" +
      "<img class='whiteImgSrc' src='" + imageLink + "' alt='[Image]'" + (hideImage ? " style='display: none;' " : "") + "/>" +
      "<i class='far fa-chevron-right whiteRightArrow'></i></div>"
   );

   _MTS_JQUERY("#downloadOriginal").bind("click", function ()
   {
      window.open(`/api/downloadOriginalImage.aspx?id=${_currentImage.id}`, "_blank");
   });

   _MTS_JQUERY(".whiteImgSrc").on("load", callback);
   _MTS_JQUERY(".whiteImgSrc").on("error", function ()
   {
      _MTS_JQUERY(this).attr("src", _MTS_MEDIAURL + "images/blockNoImg.png");
   });
}

function /*void*/PositionWhite(/*obj*/image)
{
   var windHeit = _MTS_JQUERY(window).height();
   var windScrlTop = _MTS_JQUERY(window).scrollTop();
   var witeHeit = _MTS_JQUERY(".white").outerHeight();

   var left = ((_MTS_JQUERY(window).width() / 2) - (_MTS_JQUERY(".white").outerWidth() / 2));
   var top = (witeHeit < windHeit) ? (((windHeit - witeHeit) / 2) + windScrlTop) : windScrlTop;

   if (top < 150) // Compensates for the MyTeamScoop header
      top = 150;

   _MTS_JQUERY(".white").css(
   {
      "left": left + "px",
      "top": top + "px"
   });
}

function /*obj*/GetNextImage(image)
{
   if (image == null)
      return null;

   var nextImage = GetImageByPosition(image.position + 1);
   if (nextImage == null)
      nextImage = _selectedAlbum.images[0];

   return nextImage;
}

function /*obj*/GetPreviousImage(image)
{
   if (image == null)
      return null;

   var nextImage = GetImageByPosition(image.position - 1);
   if (nextImage == null)
      nextImage = _selectedAlbum.images[_selectedAlbum.images.length - 1];

   return nextImage;
}

function /*object*/GetImageByPosition(/*int OR string*/position, parentId, parentMode)
{
   var pos = -1;

   if (typeof position === "string" && position != null)
   {
      pos = parseInt(position, 10);
   }
   else if (typeof position === "number" && position != null)
   {
      pos = position;
   }
   else
   {
      return null;
   }

   if (typeof (parentId) != "undefined" && typeof(parentMode) != "undefined" && typeof(_MTS_album) != "undefined")
   {
      for (var i = _MTS_album.length - 1; i >= 0; i--)
      {
         if (_MTS_album[i].id == parentId && _MTS_album[i].mode == parentMode)
         {
            if (_archivedAlbum.length == 0 && typeof(_selectedAlbum) !== "undefined")
               _archivedAlbum = _selectedAlbum;

            _selectedAlbum = _MTS_album[i];
            _reloadThumbnails = true;
            break;
         }
      }
   }

   if (typeof (_selectedAlbum) != "undefined")
   {
      for (var i = 0; i < _selectedAlbum.images.length; i++)
      {
         if (_selectedAlbum.images[i].position === pos)
         {
            return _selectedAlbum.images[i];
         }
      }
   }

   return null;
}

function /*void*/DeleteTag(/*json*/image, /*int*/tagId, /*function*/callback)
{
   var params = [];
   var newImages = [];

   if (typeof image !== "object" || image == null)
   {
      if (typeof callback === "function" && callback != null)
         callback(false);

      return;
   }

   params.push({ "name": "itemId", "value": image.id });

   if (typeof _teamId !== 'undefined')
      params.push({ "name": "teamId", "value": _teamId });

   params.push({ "name": "tagId", "value": tagId });
   params.push({ "name": "mode", "value": typeof _isPortal === "boolean" && _isPortal != null && _isPortal ? "portalImage" : "image" });

   _MTS_ajaxPending = true;
   _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/deleteTags.aspx", params, function (json)
   {
      if (typeof json !== "object" || json == null)
         callback(false);

      if (typeof json.ok !== "boolean" || json.ok == null)
         callback(false);

      if (typeof callback === "function" && callback != null)
         callback(json.ok);
   });
}

function /*void*/DeleteImage(/*json*/image, /*function*/callback)
{
   var params = [];
   var newImages = [];

   if (typeof image !== "object" || image == null)
   {
      if (typeof callback === "function" && callback != null)
         callback(false);

      return;
   }

   params.push({ "name": "imageId", "value": image.id });

   if (typeof _teamId !== 'undefined')
      params.push({ "name": "teamId", "value": _teamId });

   _MTS_ajaxPending = true;
   _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/deleteImage.aspx", params, function (json)
   {
      if (typeof json !== "object" || json == null)
         callback(false);

      if (typeof json.ok !== "boolean" || json.ok == null)
         callback(false);

      if (json.ok)
      {
         var loopControl = _selectedAlbum.images.length;
         var albumIndex = 0;
         for (var i = 0; i < loopControl; i++)
         {
            if (i === image.position)
            {
               albumIndex++;
               loopControl--;
            }

            if (albumIndex > loopControl)
               break;

            if (albumIndex > image.position)
               _selectedAlbum.images[albumIndex].position--;

            newImages[i] = _selectedAlbum.images[albumIndex];

            albumIndex++;
         }

         _selectedAlbum.images = null;
         _selectedAlbum.images = newImages;
      }

      if (typeof callback === "function" && callback != null)
         callback(json.ok);
   });
}

function /*void*/UpdateImageText(/*json*/image, /*string*/credit, /*string*/title, /*string*/summary, /*function*/callback)
{
   var hasCredit = credit != undefined && credit != null && credit.length > 0,
      hasTitle = title != undefined && title != null && title.length > 0,
      hasSummary = summary != undefined && summary != null && summary.length > 0;

   var p = [];
   if (hasTitle)
      p.param("title", title);
   if (hasSummary)
      p.param("summary", summary);
   if (hasCredit)
      p.param("credit", credit);
   
   p.param("teamId", typeof(_teamId) !== "undefined" ? _teamId : -1);
   p.param("imageId", image.id);

   _MTS_ajaxPending = true;
   _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/updateImage.aspx", p, function (o)
   {
      if (o.ok)
      {
         if (hasCredit)
         {
            image.credit = o.credit;
            _MTS_JQUERY("#whiteCredit").text(image.credit.length > 0 ? "Credit: " + image.credit : "");
         }

         if (hasTitle)
         {
            image.title = o.title;
            _MTS_JQUERY("#whiteTitle").text(image.title);
         }

         if (hasSummary)
         {
            image.summ = o.summary;
            _MTS_JQUERY("#whiteSummary").text(image.summ);
         }
      }

      if (typeof callback === "function" && callback != null)
         callback(json.ok);
   });
}

function /*void*/ToggleEdit(/*bool*/show)
{
   if (show)
   {
      _MTS_JQUERY(".editImgCtr").show();
   }
   else
   {
      _MTS_JQUERY(".editImgCtr").hide();
      _MTS_JQUERY(".imageInfoWrapper").show();
   }

   _MTS_JQUERY("#editCaptionWrap").css("display", $("#featureDate").css("display"));
}

function /*void*/ToggleTagBox(/*bool*/show)
{
   if (show)
   {
      var parentContainer = _MTS_JQUERY("#whiteTagButton").parent().parent();
      parentContainer.find(".chosen-container").show();
      parentContainer.find("#albumTag_chosen").hide();
      _MTS_JQUERY(".albumSelect").val(-1);
      _MTS_JQUERY(".scheduleEntrySelect").val(-1);
      _MTS_JQUERY("#scheduleEntryResultsSelectBox_chosen").hide();

      _MTS_JQUERY("#whiteTagButton").fadeTo(300, 0, function ()
      {
         _MTS_JQUERY("#whiteTagEditContainer").fadeTo(0, 0);
         _MTS_JQUERY("#whiteTagEditContainer").show();
         _MTS_JQUERY("#whiteTagEditContainer").fadeTo(300, 1);
      });
   }
   else
   {
      _MTS_JQUERY("#whiteTagEditContainer").fadeTo(300, 0, function ()
      {
         _MTS_JQUERY("#whiteTagEditContainer").hide();
         _MTS_JQUERY("#whiteTagButton").show();
         _MTS_JQUERY("#whiteTagButton").fadeTo(300, 1);
      });
   }
}

function /*void*/UpdateImageTag(/*json*/image, /*string*/seId, /*string*/rId, /*string*/nId, /*function*/callback)
{
   var params = [];

   if (typeof image !== "object" || image == null || typeof seId !== "string" && typeof rId !== "string" && nId !== "string" || seId == null && rId == null && nId == null)
   {
      if (typeof callback === "function" && callback != null)
         callback(false);

      return;
   }

   params.push({ "name": "itemId", "value": image.id });
   params.push({ "name": "teamId", "value": _teamId });
   params.push({ "name": "seId", "value": seId });
   params.push({ "name": "rId", "value": rId });
   params.push({ "name": "nId", "value": nId });
   params.push({ "name": "mode", "value": "image" });

   _MTS_ajaxPending = true;
   _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/updateTags.aspx", params, function (json)
   {
      if (typeof json !== "object" || json == null)
         callback(false);

      if (typeof json.ok !== "boolean" || json.ok == null)
         callback(false);

      var jsonTags = json.tags;

      if (json.ok && jsonTags.length > 0)
      {
         var newTagContainer = "";
         var id = -1;
         var scheduleId = -1;
         var tempTagName = "";
         var tagName = "";
         var newTag = null;
         var jTag = null;

         for (var i = 0; i < jsonTags.length; i++)
         {
            jTag = jsonTags[i];

            if (jTag.linkType == "ScheduleEvent")
            {
               newTagContainer = _MTS_JQUERY("#sE_" + seId);
               scheduleId = _MTS_JQUERY("#scheduleResult").val();
               tempTagName = _MTS_JQUERY("#scheduleEntryResultsSelectBox option[value=" + seId + "]").html();
               tagName = "";
               id = seId.toString();

               for (var j = 0; j < tempTagName.split(' ').length - 1; j++)
               {
                  tagName += tempTagName.split(' ')[j];
                  if (i < tempTagName.split(' ').length - 2)
                     tagName += " ";
               }
            }
            else if (jTag.linkType == "Roster")
            {
               id = rId.toString();
               scheduleId = -1;
               tagName = _MTS_JQUERY("#rE_" + rId).html();

               if (_MTS_JQUERY("#rP_" + rId).val() != null)
                  rCPhotoInsert(rId, json.tags[i].id, _currentImage.id);
            }
            else if (jTag.linkType == "NewsItem")
            {
               id = nId.toString();
               scheduleId = -1;
               tagName = _MTS_JQUERY("#nI_" + nId).html();
               _forceRefresh = true; //Used to refresh #home when selected from tabs
            }

            var tagId = jTag.id;
            var linkType = jTag.linkType;
            var writerId = jTag.writerId;
            var tagURL = jTag.href;

            newTag = {
               "linkId": id,
               "scheduleId": scheduleId,
               "tagId": tagId,
               "tagName": tagName,
               "tagType": linkType,
               "writerId": writerId,
               "href": tagURL
            };

            image.links.push(newTag);
            var tagHtml = InsertNewTag(id, tagId, linkType, scheduleId, tagName, false, 0, tagURL);

            if (_MTS_JQUERY("#currentTag").html() === null)
               _MTS_JQUERY("#tagContainer").append(tagHtml);
            else
               _MTS_JQUERY("#currentTag").append(tagHtml);
         }
      }

      if (typeof callback === "function" && callback != null)
         callback(json.ok);
   });
}

function StartImgCrop()
{
   $("#cropImgOpts").show();
   _MTS_previewImg = $(".whiteImgSrc");

   var coords = getInitCords();

        _MTS_previewImg.imgAreaSelect({
      x1: coords.x, y1: coords.y, x2: coords.x2, y2: coords.y2,
      instance: true,
      minWidth: 50, minHeight: 50,
      onSelectEnd: handleForm,
      persistent: true,
      handles: true
   });

   adjustMarks();
}

function getInitCords()
{
   var x = 0, y = 0, x2 = _MTS_previewImg.width(), y2 = _MTS_previewImg.height();

   var divFactor = calculateGCD(_imageSizes.SiteWideMxH, _imageSizes.SiteWideMxW);
   var setWidth = false;
   if (divFactor > 1)
   {
      var widthFactor = _imageSizes.SiteWideMxW / divFactor;
      var heightFactor = _imageSizes.SiteWideMxH / divFactor;
      var afterRatio = calculateAspectRatioFit(widthFactor, heightFactor, x2, y2);
      if (afterRatio.width > 50 && afterRatio.height > 50)
      {
         x2 = Math.floor(afterRatio.width);
         y2 = Math.floor(afterRatio.height);
         setWidth = true;
      }
   }

   if (!setWidth)
   {
      x2 = 50;
      y2 = 50;
   }

   return { "x": x, "y": y, "x2": x2, "y2": y2};
}

function calculateGCD(a, b)
{
   if (!b)
   {
      return a;
   }

   return calculateGCD(b, a % b);
}

function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight)
{
   var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

   return { width: srcWidth * ratio, height: srcHeight * ratio };
}

function adjustMarks()
{
   var cm = _MTS_JQUERY(".cropMarks");
   var wi = _MTS_JQUERY(".whiteImgSrc");

   cm.css({
      "width": wi.outerWidth() + "px",
      "height": wi.outerHeight(),
      "left": wi.position().left + "px",
      "top": wi.position().top + "px",
      "display": "block"
   });

}

function handleForm(img, selection)
{
   updateCoords(selection.x1, selection.x2, selection.y1, selection.y2);
}

function updateCoords(x1, x2, y1, y2)
{
   _MTS_JQUERY('input[id="prevX1"]').val(x1);
   _MTS_JQUERY('input[id="prevY1"]').val(y1);
   _MTS_JQUERY('input[id="prevX2"]').val(x2);
   _MTS_JQUERY('input[id="prevY2"]').val(y2);
}


function /*void*/ToggleNewTag()
{
   _beforeUpload = false;

   _MTS_JQUERY(".tagBtn").click();
   var tagWrap = _MTS_JQUERY(".uploadTagWrapper");
   tagWrap.addClass("showTagWrapper");

   if (!_MTS_sportsEnabled)
      _MTS_JQUERY(".filterColumn:not('#CategoryFilter,#SubcategoryFilter')").addClass("filterDisabled");
}

function /*void*/CenterElement(/*selector*/element)
{
   var dialog = _MTS_JQUERY(element);
   if (dialog.length === 0)
      return;

   if (dialog[0].parentNode !== document.body)
   {
      dialog[0].parentNode.removeChild(dialog[0]);
      document.body.appendChild(dialog[0]);
   }

   var wWidth = _MTS_JQUERY(window).width();
   var wHeight = _MTS_JQUERY(window).height();

   var dWidth = dialog.outerWidth();
   var dHeight = dialog.outerHeight();

   var top = (wHeight / 2) - (dHeight / 2);
   var left = (wWidth / 2) - (dWidth / 2);

   var sTop = _MTS_JQUERY(document).scrollTop();
   var sLeft = _MTS_JQUERY(document).scrollLeft();

   top += sTop;
   left += sLeft;

   if (top < 150)
      top = 150;

   dialog.css(
	{
	   left: left.toString() + "px",
	   top: top.toString() + "px"
	});
}

function /*void*/WireUpTag(/*string*/id, /*string*/link, /*string*/linkType)
{
   if (_beforeUpload)
   {
      _tags.push(id);
      _tagsLinkType.push(linkType);

      for (var i = 0; i < _wiredTags.length; i++)
      {
         if (_wiredTags[i] == id)
            return;
      }

      _wiredTags.push(id);

      _MTS_JQUERY("#tagAdd_" + id).hide();
   }
   else
   {
      setTimeout(function ()
      {
         if (_tags.length > 0)
            _MTS_JQUERY(".uploadContent .tagContainer").children().last().remove();
         else
            _MTS_JQUERY(".uploadContent .tagContainer").children().remove();
      }, 500);

      var curLinks = _currentImage.links;
      for (var i = curLinks.length - 1; i >= 0; i--)
      {
         if (curLinks[i].linkId == id && curLinks[i].tagType == linkType)
            return false;
      }

      var params = [];
      params.push({ "name": "itemId", "value": _currentImage.id });
      params.push({ "name": "linkType", "value": linkType });
      params.push({ "name": "linkId", "value": id });
      params.push({ "name": "mode", "value": "portalImage" });

      _MTS_ajaxPending = true;
      _MTS_JQUERY.getJSON(_MTS_SITEURL + "api/updateTags.aspx", params, function (json)
      {
         if (json.ok)
         {
            _MTS_JQUERY(".tagBlock").remove();
            _MTS_JQUERY(".portalText").remove();

            var tagId = json.tags[0].id;
            var writerId = json.tags[0].writerId;
            var tagURL = json.tags[0].href;
            var tagName = json.tags[0].title;

            newTag = {
               "linkId": id,
               "scheduleId": -1,
               "tagId": tagId,
               "tagName": tagName,
               "tagType": linkType,
               "writerId": writerId,
               "href": tagURL
            };

            _currentImage.links.push(newTag);
            var tagHtml = InsertNewTag(id, json.tags[0].id, linkType, -1, tagName, false, writerId, tagURL);

            var curTag = _MTS_JQUERY("#currentTag");

            if (curTag.length > 0)
            {
               curTag.append(tagHtml);
               return false;
            }

            _MTS_JQUERY("#tagContainer").html(tagHtml);
         }
      });
   }
}

function /*void*/DeleteImagePopup()
{
   var popper = new PopupDialog();
   popper.NewYesNoPrompt("Would you like to permanently delete this image?", "Are you sure?", null, function (response)
   {
      if (response === false)
         return;

      DeleteImage(_currentImage, function (deleted)
      {
         if (deleted)
         {
            _MTS_JQUERY("#photo_" + _currentImage.id).hide();

            CloseWiteBox();
         }
         else
         {
            popper.Hide();
            popper.NewOkayAlert("An unknown error prevented us from deleting this image at this time.", "Error!");
         }
      });
   });
}

function /*void*/StartSlideShow()
{
   _slideShowTimer = setTimeout(function ()
   {
      if (_currentImage == null || _MTS_JQUERY("#whiteBox").css("display") === "none")
         return;

      var image = GetNextImage(_currentImage);
      if (image == null)
         return;

      ChangeWhiteBoxImage(image);
      StartSlideShow();
   }, 10000);
}

function /*void*/PauseSlideShow()
{
   clearTimeout(_slideShowTimer);
}

function /*void*/ResumeSlideShow()
{
   clearTimeout(_slideShowTimer);
}

function /*void*/StopSlideShow()
{
   clearTimeout(_slideShowTimer);
}

function /*void*/ResetSlideShow()
{
   if (_slideShowTimer != null)
   {
      clearTimeout(_slideShowTimer);
      StartSlideShow();
   }
}

function /*void*/RewindSlideShow()
{
   var image = GetImageByPosition(0);
   if (image == null)
      return;

   ChangeWhiteBoxImage(image);
}

//Finds last selection that is not hidden by name
function /*int*/findSelectId(/*string*/id, /*string*/objClass, /*string*/objParent)
{
   var selectId = -1;

   objClass.each(function ()
   {
      if (this.id == id && this.parentNode.style.display != "none" && (this.parentNode.id == objParent || this.parentNode.className == objParent))
         selectId = this.value;
   });

   return selectId;
}

function /*string*/GetIdFromThis(/*this*/something, /*string*/prefix)
{
   var fullId = "";
   var id = "";

   if (typeof something !== "object" || something == null)
      return "";

   if (typeof prefix !== "string" || prefix == null)
      return "";

   fullId = something.getAttribute("id");
   if (typeof fullId !== "string" || fullId == null)
      return "";

   id = fullId.substring(prefix.length);
   if (typeof id !== "string" || id == null)
      return "";

   return id;
}

function /*object*/GetImageById(/*int OR string*/imageId, skipCheck)
{
   var id = -1;

   if (typeof imageId === "string" && imageId != null)
   {
      id = parseInt(imageId, 10);
   }
   else if (typeof imageId === "number" && imageId != null)
   {
      id = imageId;
   }
   else
   {
      return null;
   }

   //if (!skipCheck && typeof (_archivedAlbum.images) != "undefined" && _archivedAlbum.images.length > 0)
   //{
   //   _selectedAlbum = _archivedAlbum;
   //   _archivedAlbum = [];
   //   _reloadThumbnails = true;
   //}

   for (var i = 0; i < _selectedAlbum.images.length; i++)
   {
      if (_selectedAlbum.images[i].id === id)
      {
         return _selectedAlbum.images[i];
      }
   }

   return null;
}

function OverwriteUrl(url, haltUpdate)
{
    
    if (typeof haltUpdate === 'undefined')
      haltUpdate = false;
   
   if (typeof _MTS_allowUrlOverwrite === 'undefined' || !_MTS_allowUrlOverwrite
      || (history.state != null && history.state.haltUpdate))
      return;

   var val = 1;

   if (history.state != null && typeof history.state.linkBack !== 'undefined' && !isNaN(history.state.linkBack))
      val = history.state.linkBack + 1;


   history.pushState({ linkBack: val, haltUpdate: haltUpdate }, "", _MTS_SITEURL + url);
}

function ReplacePhotosAndContainer(album, container)
{
   if (typeof album !== 'undefined')
      _selectedAlbum = album;
   if (typeof container !== 'undefined')
      _activeContainer = container;

   _reloadThumbnails = true;
}

function highlightLightboxTags()
{
   _MTS_JQUERY(".whiteTagContainer:visible .imageTag").each(function ()
   {
      var id = _MTS_JQUERY(this).attr("id").split('_')[2];
      var type = _MTS_JQUERY(this).attr("id").split('_')[1];
      _MTS_JQUERY(".result[href$='" + id + ",\\'" + type + "\\')']").addClass("selectedTag");
   });
}

function sizePhoto()
{
   if (_MTS_JQUERY(".albumImageCtr").length > 0)
   {
      _MTS_JQUERY("#whiteImage").addClass("withAlbum");
   }   

   if (typeof (sizeWhiteBox) === "function")
      sizeWhiteBox();
}

function _MTS_CloseUploadFunc()
{
   _MTS_JQUERY.getJSON("/api/v1/portal/images/single?image_id=" + _currentImage.id, function (image)
   {
      _currentImage.credit = image.Credit;
      _currentImage.description = image.Description;
      _currentImage.title = image.Title;
      _currentImage.webActiveVersion = image.WebActiveVersion;

      _MTS_JQUERY(".whiteImgSrc").attr("src", getImageLink(_currentImage, 2));
      _MTS_JQUERY("#whiteTitle").html(image.Title + (image.Description && image.Description.length > 0 ? "<br><br>" + image.Description : ""));
      var credit = _MTS_JQUERY("#whiteCredit");
      if (image.Credit != "")
      {
         credit.html(" Credit: " + image.Credit);
         credit.show();
      }
      else
      {
         credit.hide();
      }
   });
}

﻿(function ()
{
   if (_MTS_JQUERY(".featured_news_panel_widget #featuredContent").css("display") != "none")
   {
      _MTS_JQUERY(document).on("widgetsloaded", function ()
      {
         setTimeout(begin_slider, 0);
      });
   }
   else
   {
      _MTS_JQUERY("#msNews").click(function ()
      {
         begin_slider();
      });
   }

   _MTS_JQUERY(document).on("resetSlider", function ()
   {
      begin_slider();
   });

   function begin_slider()
   {
      let swipeTarget = _MTS_JQUERY(".mts_widget #featuredContent .swiper:not(.swipeReady)");
      if (swipeTarget.length == 0)
         return;

      swipeTarget.each(i =>
      {
         let target = swipeTarget[i];
         let parent = _MTS_JQUERY(target).parents(".mts_widget");
         let modeId = parent.find(".photoModeId").val();
         let mode = parent.find(".photoMode").val();
         let usingImages = parent.find(".usePhotoBox").val() == "True" || parent.find(".bigSlide").length > 0;

         let swiper = new Swiper(target,
         {
            // Optional parameters
            loop: true,

            //Autoplay
            autoplay: {
               delay: 5000,
               pauseOnMouseEnter: true,
               disableOnInteraction: true
            },

            // If we need pagination
            pagination: {
               el: parent.find(".swiper-pagination")[0],
               type: "fraction"
            },

            // Navigation arrows
            navigation: {
               nextEl: parent.find(".swiper-button-next")[0],
               prevEl: parent.find(".swiper-button-prev")[0]
            }
         });

         swiper.on("click", function (s)
         {
            usingImages ? OpenWhiteBox(GetImageByPosition(s.activeIndex, modeId, mode)) : window.open(_MTS_JQUERY(s.slides[s.activeIndex]).find("img").data("link"), "_blank");;
         });

         parent.find("#featPrev").html(_MTS_JQUERY(swiper.slides[swiper.activeIndex]).find("img").data("title"));
         swiper.on("realIndexChange", function (s)
         {
            parent.find("#featPrev").html(_MTS_JQUERY(s.slides[s.activeIndex]).find("img").data("title"));
         });

         parent.find(".swiper").addClass("swipeReady");
      });

      _MTS_JQUERY("#featLink, .featSmall").dotdotdot();
   }
})();
﻿(function ()
{
   var _hoverState = -1;
   var _interval;
   var _slideVal = 100;

   var _rated = false;
   var _rating = 0;
   var _newRate = 0;
   var _commentType = "user";

   var _teamId = -1;
   var _featChange = false;

   var _articleId = -1;
   var _mts_adCount = 1;

   _MTS_JQUERY(document).ready(function ()
   {
      var pfs = $("#previousStoryTitle");
      $(window).scroll(function ()
      {
         var ni = $("#newsItem");
         if (ni.length > 0) {
            var mctb = ni.offset().bottom;
            if ($(window).scrollTop() > mctb) {
               var pfs = $("#previousStoryTitle");
               pfs.css({ "top": mctb + "px" });
            }
         }
      });

      _MTS_JQUERY(document).on("click", "#previousStoryTitle, .storyArrowRight, .storyArrowLeft, #nextStoryTitle", function ()
      {
         var id = _MTS_JQUERY(this).attr("class").split("_")[1];
         history.pushState({}, "", _MTS_SITEURL + _MTS_JQUERY("#nsUrl_" + id).val());
         getStory(id);
      });

      _MTS_JQUERY(document).on("click", ".ytThumb", function ()
      {
         var vp = _MTS_JQUERY("#vidPlayer");

         if (vp.css("display") == "none")
         {
            var bg = _MTS_JQUERY(".bg");
            bg.height(_MTS_JQUERY(document).height());
            bg.show();

            vp.center();
            vp.fadeTo(600, 1, function ()
            {
               vp.show();
               _MTS_JQUERY(".videoPlayer").show();
            });
         }

         var videoId = "";
         for (var i = 1, j = this.id.split('_').length; i < j; i++)
            videoId += (i > 1 ? "_" : "") + this.id.split('_')[i];

         var vidTitle = _MTS_JQUERY.trim(_MTS_JQUERY("#vidTitle_" + videoId).html()),
         vidDesc = _MTS_JQUERY.trim(_MTS_JQUERY("#vidDesc_" + videoId).html()),
         vidAuth = _MTS_JQUERY.trim(_MTS_JQUERY("#vidAuth_" + videoId).val());

         if (typeof chkPlayer === "function" && chkPlayer != null)
            chkPlayer();

         playVideo(videoId);

         _MTS_JQUERY("#vidTitle").html(vidTitle);
         _MTS_JQUERY("#vidDesc").html(vidDesc);
         _MTS_JQUERY("#vidAuth").html(vidAuth.length > 0 ? vidAuth : "Unknown");
      });

      _MTS_JQUERY(document).on("click", "#closePlayer", function ()
      {
         stopVideo();

         var vp = _MTS_JQUERY("#vidPlayer");
         vp.fadeTo(600, 0, function ()
         {
            vp.hide();
            _MTS_JQUERY(".bg").hide();
         });
      });

      _MTS_JQUERY(document).on("click", "#editFeatLink", function ()
      {
         var self = this;
         getMiniCalendar("select", "Date Range", function (m, d, y)
         {
            var newdate = m.toString() + "/" + d.toString() + "/" + y.toString() + " 12:00 AM";
            displayFeatureImageSelectBox(newdate);
         }, _MTS_JQUERY.trim(self.innerHTML));
      });

      _MTS_JQUERY(document).on("click", "#cancelFeatLink", function ()
      {
         _MTS_JQUERY("#editFeatLink").html("Not Featured");
         _MTS_JQUERY(this).hide();
         _MTS_JQUERY("#featApply").show();
         ajax("/api/editfeatured.aspx", [{ name: 'id', value: _articleId }], function (ret)
         {
            _MTS_JQUERY("#featApply").hide();
         });
      });

      _MTS_JQUERY(document).on("click", ".photoThumb", function ()
      {
         var image = GetImageById(GetIdFromThis(this, "photo_"));
         OpenWhiteBox(image);
      });

      _MTS_JQUERY(document).on("click", "#tweetBtn", function ()
      {
         var params = [];
         params.push({ name: 'mode', value: 'twittershare'})
         params.push({ name: 'id', value: _articleId });

         ajax("/api/updateNewsTracking.aspx", params, function (ret){});
      });
      
      _MTS_JQUERY(document).on("click", "#fbShare", function ()
      {
         var params = [];
         params.push({ name: 'mode', value: 'facebookshare' })
         params.push({ name: 'id', value: _articleId });

         ajax("/api/updateNewsTracking.aspx", params, function (ret) { });
      });

      _MTS_JQUERY(document).on("click", "#followBtn", function ()
      {
         var params = [];
         params.push({ name: 'id', value: _articleId });
         params.push({ name: 'type', value: 'newsitem' });
         if (_MTS_JQUERY(".followIcon").attr("title") == "Unfollow")
            params.push({ name: 'mode', value: 'deltag' });
         else
            params.push({ name: 'mode', value: 'addtag' });

         ajax("/api/updateNotificationSettings.aspx", params, function (ret)
         {
            if (_MTS_JQUERY(".followIcon").attr("title") == "Unfollow")
               _MTS_JQUERY(".followIcon").attr("title", "Follow").attr("class", "far fa-user-check followIcon unfollowed");
            else
               _MTS_JQUERY(".followIcon").attr("title", "Unfollow").attr("class", "fas fa-user-check followIcon followed");
         });
      });
   });
   
   _MTS_JQUERY(document).on("widgetsloaded", fireWidgetsLoaded);

   _MTS_JQUERY(document).one("widgetsloaded", function ()
   {
      addInfoBox();
      trackItem(_articleId, "PortalNews");
      getComments();
      if (typeof (FB) == "object")
      {
         var fb_embed_post_template = '<div class="fb-post" data-href="{embed_post_url}" data-width="{embed_post_width}"></div>';
         var embedPost = false;
         _MTS_JQUERY.each(_MTS_JQUERY('.FacebookEmbedPost'), function (index, value)
         {
            embedPost = fb_embed_post_template.replace("{embed_post_url}", _MTS_JQUERY(value).data('post')).replace("{embed_post_width}", _MTS_JQUERY(value).data('width'));
            _MTS_JQUERY(this).replaceWith(embedPost);
         });
         FB.XFBML.parse();
      }

      _cal.initialize();
      _cal.centerMiniCal();

      _MTS_JQUERY("#back").click(function ()
      {
         if (window.history.length > 1)
            BackAndRefresh();
         else
            window.close();
      });

      _MTS_JQUERY("#rater").mousemove(function (e)
      {
         _newRate = Math.ceil((e.pageX - (_MTS_JQUERY("#mainContent").offset().left + this.offsetLeft)) / 20);
         if (_newRate > 5)
            _newRate = 5;
         else if (_newRate < 1)
            _newRate = 1;

         _MTS_JQUERY(".gold_stars").css('width', '' + (_newRate * 20) + 'px');
      }).hover(function () { /* nothing */ }, function ()
      {
         _MTS_JQUERY(".gold_stars").css('width', '' + _rating + 'px');
      }).click(function ()
      {
         _rating = _newRate * 20;

         var params = [];
         params.push({ name: 'id', value: _articleId });
         params.push({ name: 'r', value: _newRate });

         ajax("/api/rateArticle.aspx", params, function (ret)
         {
            var o;
            eval("o = " + ret);

            if (o.rCount > 0)
            {
               _MTS_JQUERY("#user_score").html((o.rTotal / o.rCount).toFixed(2));
               _MTS_JQUERY(".count").html("(" + o.rCount + " ratings)");
            }
            _MTS_JQUERY(".user_rat").show();
         });
      });

      if (_rated)
         _MTS_JQUERY(".gold_stars").css('width', '' + _rating + 'px');

      _MTS_JQUERY("#vidPlayer, .bg").appendTo("body");

      _MTS_JQUERY("#thisButtonWillActivateVideoPlayer").click(function ()
      {
         var vp = _MTS_JQUERY("#vidPlayer");

         if (vp.css("display") == "none")
         {
            var bg = _MTS_JQUERY(".bg");
            bg.height(_MTS_JQUERY(document).height());
            bg.show();

            vp.center();
            vp.fadeTo(600, 1, function ()
            {
               vp.show();
               _MTS_JQUERY(".videoPlayer").show();
            });
         }
      });

      if (_MTS_JQUERY.slider)
      {
         _MTS_JQUERY("#vidScroller").slider(
         {
            create: vidMenu,
            orientation: "vertical",
            slide: vidMenu,
            min: 0, max: 100,
            value: 100
         });
      }

      _MTS_JQUERY(".vidHover").hover(function ()
      {
         var dir = this.id,
         _slideVal = _MTS_JQUERY("#vidScroller").slider("option", "value");

         if (_interval > 0)
            clearInterval(_interval);

         if (dir == "vidDown")
         {
            _hoverState = 0;

            _interval = setInterval(function ()
            {
               if (_hoverState == 0 && _slideVal > 0)
               {
                  _slideVal = _slideVal - 1;
                  VidHoverMenu(_slideVal);
               }
               else
                  clearInterval(_interval);
            }, 10);
         }
         else
         {
            _hoverState = 1;

            _interval = setInterval(function ()
            {
               if (_hoverState == 1 && _slideVal < 100)
               {
                  _slideVal = _slideVal + 1;
                  VidHoverMenu(_slideVal);
               }
               else
                  clearInterval(_interval);
            }, 10);
         }
      });

      _MTS_JQUERY(".vidHover").mouseout(function ()
      {
         _hoverState = -1;
         clearInterval(_interval);
      });

      _MTS_JQUERY(window).onresize = function ()
      {
         sirsz();
      };

      if (typeof (emailShare) != "function")
         _MTS_JQUERY(".mts_widget .shareBtn, .mts_widget .shareTitle").hide();
   });

   function runAd()
   {
      if (typeof (_MTS_PARA_AD) !== "undefined" && typeof googletag !== 'undefined')
      {
         var para_ad = parseInt(_MTS_PARA_AD);
         if (!isNaN(para_ad) && para_ad >= 0 && (_MTS_ITEM_ADS.length > 0 || _MTS_ITEM_ADS_MOBILE.length > 0))
         {
            var paragraphs = _MTS_JQUERY(".news_content_widget .body p");
            var paraAdIdx = -1;
            var paraAdPlace = -1;

            // if we find any tables in the story do not attempt to place ad
            if (paragraphs.parents("table").length > 0)
               return false;

            for (var i = 0, j = paragraphs.length - 1; i < j; i++)
            {
               var text = _MTS_JQUERY.trim(paragraphs[i].innerHTML);
               if (_MTS_JQUERY("<p/>").append(text).text().length > 20 || text.length > 100)
               {
                  paraAdIdx++;
                  paraAdPlace++;
                  if (paraAdPlace >= para_ad)
                     break;
               }
               else
                  paraAdIdx++;
            }

            if (paraAdPlace >= para_ad && paragraphs.length > paraAdIdx)
            {
               var id = "mts_ad_" + new Date().getTime(),
                  adBuilder = _MTS_JQUERY("<div id='" + id + "' class='borderedAd'></div>");

               var target = _MTS_JQUERY(paragraphs[paraAdIdx]);
               if (target.length > 0 && (!target.next() || !target.next().attr("id") || !target.next().attr("id").startsWith("mts_ad")))
               {
                  target.after(adBuilder);
                  ad = _MTS_ITEM_ADS[0] || { "width": 0, "height": 0 };
                  mobileAd = _MTS_ITEM_ADS_MOBILE[0] || { "width": 0, "height": 0 };

                  if (ad.location.indexOf("widget_") >= 0)
                  {
                     adBuilder.append("<div class='custom_widget'><input name='widgetName' type='hidden' value='" + ad.location.split('_')[1] + "' /></div></div>");
                  }
                  else
                  {
                     var mapping = googletag.sizeMapping().
                        addSize([0, 0], [mobileAd.width, mobileAd.height]).
                        addSize([1024, 768], [ad.width, ad.height]).
                        build();

                     var slot = googletag.defineSlot(ad.location, [ad.width ? ad.width : 300, ad.height ? ad.height : 250], id);
                     if (slot)
                     {
                        slot.defineSizeMapping(mapping)
                           .setTargeting(ad.target, ad.target2)
                           .setCollapseEmptyDiv(true)
                           .addService(googletag.pubads());
                        googletag.display(id);
                     }
                  }

                  _mts_adCount++;
               }
            }
         }
      }
   }

   function /*void*/vidMenu(event, ui)
   {
      var rp = _MTS_JQUERY(".videos"),
      height = rp[0].scrollHeight - rp[0].clientHeight;
      rp.scrollTop(height - (height * (ui.value / 100)));

      _slideVal = ui.value;
   }

   function getMiniCalendar(mode, title, callback, selected)
   {
      var dte = new Date();
      sDate = new Date(selected);

      if (sDate == "Invalid Date")
         sDate = new Date();

      _cal.clearRecycle();
      _cal.mode = mode;
      _cal.wndTitle = title;
      _cal.setContract(sDate.getFullYear(), 0, 0);
      _cal.maxYear = (_cal.startContractYear + 5);
      _cal.setCallback(callback);

      _cal.setSelection(sDate.getMonth() + 1, sDate.getDate(), sDate.getFullYear());
      _cal.show(100, 100);

      _MTS_JQUERY(".listingBg").css({ "height": _MTS_JQUERY(document).height(), "zIndex": 113 });
      _MTS_JQUERY(".listingBg").show();
   }

   function /*void*/getComments()
   {
      if (typeof (loadComments) != "function")
      {
         setTimeout(getComments, 250);
      }
      else
      {
         if (typeof _articleId === "undefined" || _articleId < 1)
            _articleId = _MTS_JQUERY("#MTS_STORY_ID").val();
         var prms = [];
         prms.push({ name: "newsId", value: _articleId });
         prms.push({ name: "currIdx", value: 0 });
         prms.push({ name: "commentType", value: _commentType });
         prms.push({ name: "type", value: 1 });
         loadComments(prms, _articleId, 0);
      }
   }

   function sirsz()
   {
      var img = _MTS_JQUERY("#story .body img");
      var sw = _MTS_JQUERY(".storyWrapper");
      if (sw.width() <= img.width())
      {
         img.css({ "width": "100%" });
      }
   }

   function fireWidgetsLoaded()
   {
      _articleId = _MTS_JQUERY("#MTS_STORY_ID").val();

      if (!_rated)
         _MTS_JQUERY(".user_rat").hide();
      else
         _MTS_JQUERY(".user_rat").show();

      sirsz();
      MTS_updateRegionCss();
      MTS_updateColumnCss();
      runAd();
   }

   function getStory(id)
   {
      var nextId = 0, prevId = 0;
      var currentTarget = _MTS_JQUERY("#delPN_" + id);
      if (currentTarget.length > 0)
      {
         // look at previous to find next story in succession
         var next = _MTS_JQUERY(currentTarget.parent().parent().prevAll(".item")[0]);
         if (next.length > 0)
         {
            nextId = next.find(".delPNBtn").attr("id").split('_')[1];
            if (currentTarget.parent().parent().next(".item").prevAll(".item").length == 0)
               next.parents(".news_panel_widget").find(".showMore").click();
         }

         // look at next to find previous story in succession
         var prev = _MTS_JQUERY(currentTarget.parent().parent().nextAll(".item")[0]);
         if (prev.length > 0)
            prevId = prev.find(".delPNBtn").attr("id").split('_')[1];
      }

      var params = [];
      params.push({ name: "id", value: id });
      params.push({ name: "nextId", value: nextId });
      params.push({ name: "prevId", value: prevId });

      ajax("/api/getPortalNewsContent.aspx", params, function (response)
      {
         _MTS_JQUERY(window).off("scroll");
         var target = _MTS_JQUERY("#newsItem");
         target.empty();
         target.html(response);

         _MTS_waitingOnLoad = [];
         _MTS_widgetsReady = false;
         _archivedAlbum = [];
         MTS_loadWidgets();
         if (typeof googletag !== 'undefined')
            googletag.pubads().refresh();

         if (typeof (adjustNoUserPrompt) !== 'undefined')
            adjustNoUserPrompt();

         if (nextId <= 0 && prevId <= 0)
            window.scrollTo(0, 0);

         trackItem(id, "PortalNews");

         _MTS_JQUERY(document).one("scroll", getComments);

         _MTS_JQUERY(document).one("widgetsloaded", function ()
         {
            _MTS_JQUERY(document).trigger("resetSlider");
            addInfoBox();
         });
      });
   }

   function addInfoBox()
   {
      if (typeof (_info_box) != "undefined" && _info_box != null && _info_box.DataValue != "undefined" && _info_box.DataValue.length > 0)
      {
         var paragraphs = _MTS_JQUERY(".storyWrapper p");
         var location = _info_box.WebParagraphLocation;
         var infoBox = _MTS_JQUERY("<div>");
         infoBox.attr("class", "mts_infoBox");

         var input = _info_box.DataValue;
         input = anchorme({
            input,
            options: {
               attributes: function (string)
               {
                  const attributes = {
                     target: "_blank"
                  };
                  return attributes;
               }
            }
         });

         infoBox.html(input);

         if (_info_box.WebBackgroundColor != null && _info_box.WebBackgroundColor.length > 0)
            infoBox.css("backgroundColor", "#" + _info_box.WebBackgroundColor);

         if (_info_box.WebFontColor != null && _info_box.WebFontColor.length > 0)
            infoBox.css("color", "#" + _info_box.WebFontColor);

         if (_info_box.WebFont != null && _info_box.WebFont.length > 0)
            infoBox.css("fontFamily", _info_box.WebFont);

         infoBox.css("float", _info_box.WebLocation > 0 ? _webLocation[_info_box.WebLocation] : "left");

         if (location <= 1)
            _MTS_JQUERY(paragraphs[0]).prepend(infoBox);
         else if (location - 1 < paragraphs.length)
            _MTS_JQUERY(paragraphs[location - 1]).prepend(infoBox);
         else
            _MTS_JQUERY(paragraphs[paragraphs.length - 1]).prepend(infoBox);
      }
   }

   function displayFeatureImageSelectBox(date)
   {
      var p = [];

      p.push({ name: "newsId", value: _articleId });

      var popup = new PopupDialog();
      popup.NewCustomDialog("", "Select an image to feature", function ()
      {
         var popupId = popup.GetPopupId();
         popup.AddElement("divWithClass", "", null, null, "featureImageCtr");
         popup.AddButton("Save", saveFeatureImage, date);

         popup.AddButton("Cancel", hidePopup);

         popup.Show();

         ajax("/api/getFeatureImageSelectBox.aspx", p, function (r)
         {
            _MTS_JQUERY(".featureImageCtr").html(r);

            if (_isFeatured)
               _MTS_JQUERY("#popUpDialog_" + popupId + " #image_" + _featureImageId).addClass("photoBlockSelected");

               _MTS_JQUERY("#popUpDialog_" + popupId + " .photoBlock").click(function ()
               {
                  _MTS_JQUERY(".photoBlock").removeClass("photoBlockSelected");
                  _MTS_JQUERY(this).addClass("photoBlockSelected");
               });

            var phb = _MTS_JQUERY("#popUpDialog_" + popupId + " .photoBlock");
            phb.css({ "height": phb.outerWidth() + "px" });
         });
      }, hidePopup, null);
   }

   function saveFeatureImage(popup, controlData, date)
   {
      var selectedImage = _MTS_JQUERY(".photoBlockSelected");

      if (selectedImage.length > 0)
      {
         _featureImageId = parseInt(selectedImage.attr("id").split('_')[1]);
         hidePopup(popup);

         featureNews(date);

         _isFeatured = true;
         _MTS_JQUERY("#selectFeatureImage").show();
      }
   }

   function featureNews(date)
   {
      var params = [];

      _MTS_JQUERY("#editFeatLink").html(date);

      params.push({ name: 'id', value: _articleId });
      params.push({ name: 'til', value: date });
      params.push({ name: 'featureImageId', value: _featureImageId });

      _MTS_JQUERY("#featApply").show();
      ajax("/api/editfeatured.aspx", params, function (ret)
      {
         _MTS_JQUERY("#featApply").hide();

         var cFL = _MTS_JQUERY("#cancelFeatLink")

         if (cFL.length == 0)
         {
            var cLink = "<a title='Cancel' id='cancelFeatLink' href='javascript:void(0);'>Cancel</a>";
            _MTS_JQUERY("#editFeatLink").parent().append(cLink);
         }
         else
            cFL.show();
      });
   }

   function hidePopup(popup)
   {
      popup.Hide();
   }
})();
﻿!function (A, u) { "object" == typeof exports && "undefined" != typeof module ? module.exports = u() : "function" == typeof define && define.amd ? define(u) : (A = A || self).anchorme = u() }(this, function () { "use strict"; var t = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {}; function A(A) { return A && A.__esModule && Object.prototype.hasOwnProperty.call(A, "default") ? A.default : A } function u(A, u) { return A(u = { exports: {} }, u.exports), u.exports } var N = u(function (A, u) { Object.defineProperty(u, "__esModule", { value: !0 }), u.TLDs = "(AAA|AARP|ABARTH|ABB|ABBOTT|ABBVIE|ABC|ABLE|ABOGADO|ABUDHABI|AC|ACADEMY|ACCENTURE|ACCOUNTANT|ACCOUNTANTS|ACO|ACTOR|AD|ADAC|ADS|ADULT|AE|AEG|AERO|AETNA|AF|AFAMILYCOMPANY|AFL|AFRICA|AG|AGAKHAN|AGENCY|AI|AIG|AIGO|AIRBUS|AIRFORCE|AIRTEL|AKDN|AL|ALFAROMEO|ALIBABA|ALIPAY|ALLFINANZ|ALLSTATE|ALLY|ALSACE|ALSTOM|AM|AMERICANEXPRESS|AMERICANFAMILY|AMEX|AMFAM|AMICA|AMSTERDAM|ANALYTICS|ANDROID|ANQUAN|ANZ|AO|AOL|APARTMENTS|APP|APPLE|AQ|AQUARELLE|AR|ARAB|ARAMCO|ARCHI|ARMY|ARPA|ART|ARTE|AS|ASDA|ASIA|ASSOCIATES|AT|ATHLETA|ATTORNEY|AU|AUCTION|AUDI|AUDIBLE|AUDIO|AUSPOST|AUTHOR|AUTO|AUTOS|AVIANCA|AW|AWS|AX|AXA|AZ|AZURE|BA|BABY|BAIDU|BANAMEX|BANANAREPUBLIC|BAND|BANK|BAR|BARCELONA|BARCLAYCARD|BARCLAYS|BAREFOOT|BARGAINS|BASEBALL|BASKETBALL|BAUHAUS|BAYERN|BB|BBC|BBT|BBVA|BCG|BCN|BD|BE|BEATS|BEAUTY|BEER|BENTLEY|BERLIN|BEST|BESTBUY|BET|BF|BG|BH|BHARTI|BI|BIBLE|BID|BIKE|BING|BINGO|BIO|BIZ|BJ|BLACK|BLACKFRIDAY|BLOCKBUSTER|BLOG|BLOOMBERG|BLUE|BM|BMS|BMW|BN|BNPPARIBAS|BO|BOATS|BOEHRINGER|BOFA|BOM|BOND|BOO|BOOK|BOOKING|BOSCH|BOSTIK|BOSTON|BOT|BOUTIQUE|BOX|BR|BRADESCO|BRIDGESTONE|BROADWAY|BROKER|BROTHER|BRUSSELS|BS|BT|BUDAPEST|BUGATTI|BUILD|BUILDERS|BUSINESS|BUY|BUZZ|BV|BW|BY|BZ|BZH|CA|CAB|CAFE|CAL|CALL|CALVINKLEIN|CAM|CAMERA|CAMP|CANCERRESEARCH|CANON|CAPETOWN|CAPITAL|CAPITALONE|CAR|CARAVAN|CARDS|CARE|CAREER|CAREERS|CARS|CASA|CASE|CASEIH|CASH|CASINO|CAT|CATERING|CATHOLIC|CBA|CBN|CBRE|CBS|CC|CD|CEB|CENTER|CEO|CERN|CF|CFA|CFD|CG|CH|CHANEL|CHANNEL|CHARITY|CHASE|CHAT|CHEAP|CHINTAI|CHRISTMAS|CHROME|CHURCH|CI|CIPRIANI|CIRCLE|CISCO|CITADEL|CITI|CITIC|CITY|CITYEATS|CK|CL|CLAIMS|CLEANING|CLICK|CLINIC|CLINIQUE|CLOTHING|CLOUD|CLUB|CLUBMED|CM|CN|CO|COACH|CODES|COFFEE|COLLEGE|COLOGNE|COM|COMCAST|COMMBANK|COMMUNITY|COMPANY|COMPARE|COMPUTER|COMSEC|CONDOS|CONSTRUCTION|CONSULTING|CONTACT|CONTRACTORS|COOKING|COOKINGCHANNEL|COOL|COOP|CORSICA|COUNTRY|COUPON|COUPONS|COURSES|CPA|CR|CREDIT|CREDITCARD|CREDITUNION|CRICKET|CROWN|CRS|CRUISE|CRUISES|CSC|CU|CUISINELLA|CV|CW|CX|CY|CYMRU|CYOU|CZ|DABUR|DAD|DANCE|DATA|DATE|DATING|DATSUN|DAY|DCLK|DDS|DE|DEAL|DEALER|DEALS|DEGREE|DELIVERY|DELL|DELOITTE|DELTA|DEMOCRAT|DENTAL|DENTIST|DESI|DESIGN|DEV|DHL|DIAMONDS|DIET|DIGITAL|DIRECT|DIRECTORY|DISCOUNT|DISCOVER|DISH|DIY|DJ|DK|DM|DNP|DO|DOCS|DOCTOR|DOG|DOMAINS|DOT|DOWNLOAD|DRIVE|DTV|DUBAI|DUCK|DUNLOP|DUPONT|DURBAN|DVAG|DVR|DZ|EARTH|EAT|EC|ECO|EDEKA|EDU|EDUCATION|EE|EG|EMAIL|EMERCK|ENERGY|ENGINEER|ENGINEERING|ENTERPRISES|EPSON|EQUIPMENT|ER|ERICSSON|ERNI|ES|ESQ|ESTATE|ESURANCE|ET|ETISALAT|EU|EUROVISION|EUS|EVENTS|EXCHANGE|EXPERT|EXPOSED|EXPRESS|EXTRASPACE|FAGE|FAIL|FAIRWINDS|FAITH|FAMILY|FAN|FANS|FARM|FARMERS|FASHION|FAST|FEDEX|FEEDBACK|FERRARI|FERRERO|FI|FIAT|FIDELITY|FIDO|FILM|FINAL|FINANCE|FINANCIAL|FIRE|FIRESTONE|FIRMDALE|FISH|FISHING|FIT|FITNESS|FJ|FK|FLICKR|FLIGHTS|FLIR|FLORIST|FLOWERS|FLY|FM|FO|FOO|FOOD|FOODNETWORK|FOOTBALL|FORD|FOREX|FORSALE|FORUM|FOUNDATION|FOX|FR|FREE|FRESENIUS|FRL|FROGANS|FRONTDOOR|FRONTIER|FTR|FUJITSU|FUJIXEROX|FUN|FUND|FURNITURE|FUTBOL|FYI|GA|GAL|GALLERY|GALLO|GALLUP|GAME|GAMES|GAP|GARDEN|GAY|GB|GBIZ|GD|GDN|GE|GEA|GENT|GENTING|GEORGE|GF|GG|GGEE|GH|GI|GIFT|GIFTS|GIVES|GIVING|GL|GLADE|GLASS|GLE|GLOBAL|GLOBO|GM|GMAIL|GMBH|GMO|GMX|GN|GODADDY|GOLD|GOLDPOINT|GOLF|GOO|GOODYEAR|GOOG|GOOGLE|GOP|GOT|GOV|GP|GQ|GR|GRAINGER|GRAPHICS|GRATIS|GREEN|GRIPE|GROCERY|GROUP|GS|GT|GU|GUARDIAN|GUCCI|GUGE|GUIDE|GUITARS|GURU|GW|GY|HAIR|HAMBURG|HANGOUT|HAUS|HBO|HDFC|HDFCBANK|HEALTH|HEALTHCARE|HELP|HELSINKI|HERE|HERMES|HGTV|HIPHOP|HISAMITSU|HITACHI|HIV|HK|HKT|HM|HN|HOCKEY|HOLDINGS|HOLIDAY|HOMEDEPOT|HOMEGOODS|HOMES|HOMESENSE|HONDA|HORSE|HOSPITAL|HOST|HOSTING|HOT|HOTELES|HOTELS|HOTMAIL|HOUSE|HOW|HR|HSBC|HT|HU|HUGHES|HYATT|HYUNDAI|IBM|ICBC|ICE|ICU|ID|IE|IEEE|IFM|IKANO|IL|IM|IMAMAT|IMDB|IMMO|IMMOBILIEN|IN|INC|INDUSTRIES|INFINITI|INFO|ING|INK|INSTITUTE|INSURANCE|INSURE|INT|INTEL|INTERNATIONAL|INTUIT|INVESTMENTS|IO|IPIRANGA|IQ|IR|IRISH|IS|ISMAILI|IST|ISTANBUL|IT|ITAU|ITV|IVECO|JAGUAR|JAVA|JCB|JCP|JE|JEEP|JETZT|JEWELRY|JIO|JLL|JM|JMP|JNJ|JO|JOBS|JOBURG|JOT|JOY|JP|JPMORGAN|JPRS|JUEGOS|JUNIPER|KAUFEN|KDDI|KE|KERRYHOTELS|KERRYLOGISTICS|KERRYPROPERTIES|KFH|KG|KH|KI|KIA|KIM|KINDER|KINDLE|KITCHEN|KIWI|KM|KN|KOELN|KOMATSU|KOSHER|KP|KPMG|KPN|KR|KRD|KRED|KUOKGROUP|KW|KY|KYOTO|KZ|LA|LACAIXA|LAMBORGHINI|LAMER|LANCASTER|LANCIA|LAND|LANDROVER|LANXESS|LASALLE|LAT|LATINO|LATROBE|LAW|LAWYER|LB|LC|LDS|LEASE|LECLERC|LEFRAK|LEGAL|LEGO|LEXUS|LGBT|LI|LIDL|LIFE|LIFEINSURANCE|LIFESTYLE|LIGHTING|LIKE|LILLY|LIMITED|LIMO|LINCOLN|LINDE|LINK|LIPSY|LIVE|LIVING|LIXIL|LK|LLC|LLP|LOAN|LOANS|LOCKER|LOCUS|LOFT|LOL|LONDON|LOTTE|LOTTO|LOVE|LPL|LPLFINANCIAL|LR|LS|LT|LTD|LTDA|LU|LUNDBECK|LUPIN|LUXE|LUXURY|LV|LY|MA|MACYS|MADRID|MAIF|MAISON|MAKEUP|MAN|MANAGEMENT|MANGO|MAP|MARKET|MARKETING|MARKETS|MARRIOTT|MARSHALLS|MASERATI|MATTEL|MBA|MC|MCKINSEY|MD|ME|MED|MEDIA|MEET|MELBOURNE|MEME|MEMORIAL|MEN|MENU|MERCKMSD|METLIFE|MG|MH|MIAMI|MICROSOFT|MIL|MINI|MINT|MIT|MITSUBISHI|MK|ML|MLB|MLS|MM|MMA|MN|MO|MOBI|MOBILE|MODA|MOE|MOI|MOM|MONASH|MONEY|MONSTER|MORMON|MORTGAGE|MOSCOW|MOTO|MOTORCYCLES|MOV|MOVIE|MP|MQ|MR|MS|MSD|MT|MTN|MTR|MU|MUSEUM|MUTUAL|MV|MW|MX|MY|MZ|NA|NAB|NAGOYA|NAME|NATIONWIDE|NATURA|NAVY|NBA|NC|NE|NEC|NET|NETBANK|NETFLIX|NETWORK|NEUSTAR|NEW|NEWHOLLAND|NEWS|NEXT|NEXTDIRECT|NEXUS|NF|NFL|NG|NGO|NHK|NI|NICO|NIKE|NIKON|NINJA|NISSAN|NISSAY|NL|NO|NOKIA|NORTHWESTERNMUTUAL|NORTON|NOW|NOWRUZ|NOWTV|NP|NR|NRA|NRW|NTT|NU|NYC|NZ|OBI|OBSERVER|OFF|OFFICE|OKINAWA|OLAYAN|OLAYANGROUP|OLDNAVY|OLLO|OM|OMEGA|ONE|ONG|ONL|ONLINE|ONYOURSIDE|OOO|OPEN|ORACLE|ORANGE|ORG|ORGANIC|ORIGINS|OSAKA|OTSUKA|OTT|OVH|PA|PAGE|PANASONIC|PARIS|PARS|PARTNERS|PARTS|PARTY|PASSAGENS|PAY|PCCW|PE|PET|PF|PFIZER|PG|PH|PHARMACY|PHD|PHILIPS|PHONE|PHOTO|PHOTOGRAPHY|PHOTOS|PHYSIO|PICS|PICTET|PICTURES|PID|PIN|PING|PINK|PIONEER|PIZZA|PK|PL|PLACE|PLAY|PLAYSTATION|PLUMBING|PLUS|PM|PN|PNC|POHL|POKER|POLITIE|PORN|POST|PR|PRAMERICA|PRAXI|PRESS|PRIME|PRO|PROD|PRODUCTIONS|PROF|PROGRESSIVE|PROMO|PROPERTIES|PROPERTY|PROTECTION|PRU|PRUDENTIAL|PS|PT|PUB|PW|PWC|PY|QA|QPON|QUEBEC|QUEST|QVC|RACING|RADIO|RAID|RE|READ|REALESTATE|REALTOR|REALTY|RECIPES|RED|REDSTONE|REDUMBRELLA|REHAB|REISE|REISEN|REIT|RELIANCE|REN|RENT|RENTALS|REPAIR|REPORT|REPUBLICAN|REST|RESTAURANT|REVIEW|REVIEWS|REXROTH|RICH|RICHARDLI|RICOH|RIGHTATHOME|RIL|RIO|RIP|RMIT|RO|ROCHER|ROCKS|RODEO|ROGERS|ROOM|RS|RSVP|RU|RUGBY|RUHR|RUN|RW|RWE|RYUKYU|SA|SAARLAND|SAFE|SAFETY|SAKURA|SALE|SALON|SAMSCLUB|SAMSUNG|SANDVIK|SANDVIKCOROMANT|SANOFI|SAP|SARL|SAS|SAVE|SAXO|SB|SBI|SBS|SC|SCA|SCB|SCHAEFFLER|SCHMIDT|SCHOLARSHIPS|SCHOOL|SCHULE|SCHWARZ|SCIENCE|SCJOHNSON|SCOR|SCOT|SD|SE|SEARCH|SEAT|SECURE|SECURITY|SEEK|SELECT|SENER|SERVICES|SES|SEVEN|SEW|SEX|SEXY|SFR|SG|SH|SHANGRILA|SHARP|SHAW|SHELL|SHIA|SHIKSHA|SHOES|SHOP|SHOPPING|SHOUJI|SHOW|SHOWTIME|SHRIRAM|SI|SILK|SINA|SINGLES|SITE|SJ|SK|SKI|SKIN|SKY|SKYPE|SL|SLING|SM|SMART|SMILE|SN|SNCF|SO|SOCCER|SOCIAL|SOFTBANK|SOFTWARE|SOHU|SOLAR|SOLUTIONS|SONG|SONY|SOY|SPACE|SPORT|SPOT|SPREADBETTING|SR|SRL|SS|ST|STADA|STAPLES|STAR|STATEBANK|STATEFARM|STC|STCGROUP|STOCKHOLM|STORAGE|STORE|STREAM|STUDIO|STUDY|STYLE|SU|SUCKS|SUPPLIES|SUPPLY|SUPPORT|SURF|SURGERY|SUZUKI|SV|SWATCH|SWIFTCOVER|SWISS|SX|SY|SYDNEY|SYMANTEC|SYSTEMS|SZ|TAB|TAIPEI|TALK|TAOBAO|TARGET|TATAMOTORS|TATAR|TATTOO|TAX|TAXI|TC|TCI|TD|TDK|TEAM|TECH|TECHNOLOGY|TEL|TEMASEK|TENNIS|TEVA|TF|TG|TH|THD|THEATER|THEATRE|TIAA|TICKETS|TIENDA|TIFFANY|TIPS|TIRES|TIROL|TJ|TJMAXX|TJX|TK|TKMAXX|TL|TM|TMALL|TN|TO|TODAY|TOKYO|TOOLS|TOP|TORAY|TOSHIBA|TOTAL|TOURS|TOWN|TOYOTA|TOYS|TR|TRADE|TRADING|TRAINING|TRAVEL|TRAVELCHANNEL|TRAVELERS|TRAVELERSINSURANCE|TRUST|TRV|TT|TUBE|TUI|TUNES|TUSHU|TV|TVS|TW|TZ|UA|UBANK|UBS|UG|UK|UNICOM|UNIVERSITY|UNO|UOL|UPS|US|UY|UZ|VA|VACATIONS|VANA|VANGUARD|VC|VE|VEGAS|VENTURES|VERISIGN|VERSICHERUNG|VET|VG|VI|VIAJES|VIDEO|VIG|VIKING|VILLAS|VIN|VIP|VIRGIN|VISA|VISION|VIVA|VIVO|VLAANDEREN|VN|VODKA|VOLKSWAGEN|VOLVO|VOTE|VOTING|VOTO|VOYAGE|VU|VUELOS|WALES|WALMART|WALTER|WANG|WANGGOU|WATCH|WATCHES|WEATHER|WEATHERCHANNEL|WEBCAM|WEBER|WEBSITE|WED|WEDDING|WEIBO|WEIR|WF|WHOSWHO|WIEN|WIKI|WILLIAMHILL|WIN|WINDOWS|WINE|WINNERS|WME|WOLTERSKLUWER|WOODSIDE|WORK|WORKS|WORLD|WOW|WS|WTC|WTF|XBOX|XEROX|XFINITY|XIHUAN|XIN|XN--11B4C3D|XN--1CK2E1B|XN--1QQW23A|XN--2SCRJ9C|XN--30RR7Y|XN--3BST00M|XN--3DS443G|XN--3E0B707E|XN--3HCRJ9C|XN--3OQ18VL8PN36A|XN--3PXU8K|XN--42C2D9A|XN--45BR5CYL|XN--45BRJ9C|XN--45Q11C|XN--4GBRIM|XN--54B7FTA0CC|XN--55QW42G|XN--55QX5D|XN--5SU34J936BGSG|XN--5TZM5G|XN--6FRZ82G|XN--6QQ986B3XL|XN--80ADXHKS|XN--80AO21A|XN--80AQECDR1A|XN--80ASEHDB|XN--80ASWG|XN--8Y0A063A|XN--90A3AC|XN--90AE|XN--90AIS|XN--9DBQ2A|XN--9ET52U|XN--9KRT00A|XN--B4W605FERD|XN--BCK1B9A5DRE4C|XN--C1AVG|XN--C2BR7G|XN--CCK2B3B|XN--CG4BKI|XN--CLCHC0EA0B2G2A9GCD|XN--CZR694B|XN--CZRS0T|XN--CZRU2D|XN--D1ACJ3B|XN--D1ALF|XN--E1A4C|XN--ECKVDTC9D|XN--EFVY88H|XN--FCT429K|XN--FHBEI|XN--FIQ228C5HS|XN--FIQ64B|XN--FIQS8S|XN--FIQZ9S|XN--FJQ720A|XN--FLW351E|XN--FPCRJ9C3D|XN--FZC2C9E2C|XN--FZYS8D69UVGM|XN--G2XX48C|XN--GCKR3F0F|XN--GECRJ9C|XN--GK3AT1E|XN--H2BREG3EVE|XN--H2BRJ9C|XN--H2BRJ9C8C|XN--HXT814E|XN--I1B6B1A6A2E|XN--IMR513N|XN--IO0A7I|XN--J1AEF|XN--J1AMH|XN--J6W193G|XN--JLQ61U9W7B|XN--JVR189M|XN--KCRX77D1X4A|XN--KPRW13D|XN--KPRY57D|XN--KPU716F|XN--KPUT3I|XN--L1ACC|XN--LGBBAT1AD8J|XN--MGB9AWBF|XN--MGBA3A3EJT|XN--MGBA3A4F16A|XN--MGBA7C0BBN0A|XN--MGBAAKC7DVF|XN--MGBAAM7A8H|XN--MGBAB2BD|XN--MGBAH1A3HJKRD|XN--MGBAI9AZGQP6J|XN--MGBAYH7GPA|XN--MGBBH1A|XN--MGBBH1A71E|XN--MGBC0A9AZCG|XN--MGBCA7DZDO|XN--MGBCPQ6GPA1A|XN--MGBERP4A5D4AR|XN--MGBGU82A|XN--MGBI4ECEXP|XN--MGBPL2FH|XN--MGBT3DHD|XN--MGBTX2B|XN--MGBX4CD0AB|XN--MIX891F|XN--MK1BU44C|XN--MXTQ1M|XN--NGBC5AZD|XN--NGBE9E0A|XN--NGBRX|XN--NODE|XN--NQV7F|XN--NQV7FS00EMA|XN--NYQY26A|XN--O3CW4H|XN--OGBPF8FL|XN--OTU796D|XN--P1ACF|XN--P1AI|XN--PBT977C|XN--PGBS0DH|XN--PSSY2U|XN--Q7CE6A|XN--Q9JYB4C|XN--QCKA1PMC|XN--QXA6A|XN--QXAM|XN--RHQV96G|XN--ROVU88B|XN--RVC1E0AM3E|XN--S9BRJ9C|XN--SES554G|XN--T60B56A|XN--TCKWE|XN--TIQ49XQYJ|XN--UNUP4Y|XN--VERMGENSBERATER-CTB|XN--VERMGENSBERATUNG-PWB|XN--VHQUV|XN--VUQ861B|XN--W4R85EL8FHU5DNRA|XN--W4RS40L|XN--WGBH1C|XN--WGBL6A|XN--XHQ521B|XN--XKC2AL3HYE2A|XN--XKC2DL3A5EE0H|XN--Y9A3AQ|XN--YFRO4I67O|XN--YGBI2AMMX|XN--ZFR164B|XXX|XYZ|YACHTS|YAHOO|YAMAXUN|YANDEX|YE|YODOBASHI|YOGA|YOKOHAMA|YOU|YOUTUBE|YT|YUN|ZA|ZAPPOS|ZARA|ZERO|ZIP|ZM|ZONE|ZUERICH|ZW|TEST)" }); A(N); N.TLDs; var L = u(function (A, E) { Object.defineProperty(E, "__esModule", { value: !0 }), E.openingParenthesis = "([\"'{", E.closingParenthesis = ")]\"'}", E.parenthesis = E.openingParenthesis.split("").map(function (A, u) { return "" + A + E.closingParenthesis.charAt(u) }), E.htmlAttributes = ["src", "data", "href", "cite", "formaction", "icon", "manifest", "poster", "codebase", "background", "profile", "usemap", "itemtype", "action", "longdesc", "classid", "archive"], E.nonLatinAlphabetRanges = "\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC", E.TLDs = N.TLDs }); A(L); L.openingParenthesis, L.closingParenthesis, L.parenthesis, L.htmlAttributes, L.nonLatinAlphabetRanges, L.TLDs; var B = u(function (A, u) { function S(A, u, E) { return "function" == typeof E ? E(A, u) : E } Object.defineProperty(u, "__esModule", { value: !0 }), u.transform = function (A, u) { var E = "", N = 1 / 0, C = {}, O = !1; if (u && u.specialTransform) for (var I = 0; I < u.specialTransform.length; I++) { var R = u.specialTransform[I]; if (R.test.test(A.string)) return R.transform(A.string, A) } return u && u.exclude && S(A.string, A, u.exclude) ? A.string : (u && u.protocol && (E = S(A.string, A, u.protocol)), E = A.protocol ? "" : E || (A.isEmail ? "mailto:" : A.isFile ? "file:///" : "http://"), u && u.truncate && (N = S(A.string, A, u.truncate)), u && u.middleTruncation && (O = S(A.string, A, u.middleTruncation)), u && u.attributes && (C = S(A.string, A, u.attributes)), "<a " + Object.keys(C).map(function (A) { return !0 === C[A] ? A : A + '="' + C[A] + '" ' }).join(" ") + 'href="' + E + A.string + '">' + (A.string.length > N ? O ? A.string.substring(0, Math.floor(N / 2)) + "�" + A.string.substring(A.string.length - Math.ceil(N / 2), A.string.length) : A.string.substring(0, N) + "�" : A.string) + "</a>") } }); A(B); B.transform; var e = u(function (A, u) { Object.defineProperty(u, "__esModule", { value: !0 }); var E = "([a-z0-9]+(-+[a-z0-9]+)*\\.)+(" + L.TLDs + ")", N = "a-zA-Z\\d\\-._~\\!$&*+,;=:@%'\"\\[\\]()", C = "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", O = "\\[(([a-f0-9:]+:+)+[a-f0-9]+)\\]", I = "(https?:|ftps?:)\\/\\/", R = "(((" + I + ")?(" + E + "|" + C + "|(" + I + ")(" + O + "|" + ("([a-z0-9]+(-+[a-z0-9]+)*\\.)+([a-z0-9][a-z0-9-]{0," + (Math.max.apply(t, L.TLDs.split("|").map(function (A) { return A.length })) - 2) + "}[a-z0-9])") + "))(?!@\\w)(:(\\d{1,5}))?)|(((https?:|ftps?:)\\/\\/)\\S+))", S = R + "((((\\/(([" + N + "]+(\\/[" + N + L.nonLatinAlphabetRanges + "]*)*))?)?)((\\?([" + N + "\\/?]*))?)((\\#([" + N + "\\/?]*))?))?\\b((([" + N + "\\/" + L.nonLatinAlphabetRanges + "][a-zA-Z\\d\\-_~+=\\/" + L.nonLatinAlphabetRanges + "]+)?))+)"; u.email = "\\b(mailto:)?([a-z0-9!#$%&'*+=?^_`{|}~-]+(\\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*)@(" + E + "|" + C + ")\\b", u.url = "(" + S + ")|(\\b" + R + "(((\\/(([a-zA-Z\\d\\-._~\\!$&*+,;=:@%'\"\\[\\]()]+(\\/[a-zA-Z\\d\\-._~\\!$&*+,;=:@%'\"\\[\\]()]*)*))?)?)((\\?([a-zA-Z\\d\\-._~\\!$&*+,;=:@%'\"\\[\\]()\\/?]*))?)((\\#([a-zA-Z\\d\\-._~\\!$&*+,;=:@%'\"\\[\\]()\\/?]*))?))?\\b(([\\/]?))+)", u.file = "(file:\\/\\/\\/)([a-z]+:(\\/|\\\\)+)?([\\w.]+([\\/\\\\]?)+)+", u.final = "(" + u.url + ")|(" + u.email + ")|(" + u.file + ")", u.finalRegex = new RegExp(u.final, "gi"), u.ipRegex = new RegExp("^(" + C + "|" + O + ")$", "i"), u.emailRegex = new RegExp("^(" + u.email + ")$", "i"), u.fileRegex = new RegExp("^(" + u.file + ")$", "i"), u.urlRegex = new RegExp("^(" + u.url + ")$", "i"); var T = { isURL: 0, isEmail: 0, isFile: 0, file: { fileName: 0, protocol: 0 }, email: { protocol: 0, local: 0, host: 0 }, url: { ipv4: 0, ipv6: 0, ipv4Confirmation: 0, byProtocol: 0, port: 0, protocol1: 0, protocol2: 0, protocol3: 0, protocolWithDomain: 0, path: 0, secondPartOfPath: 0, query: 0, fragment: 0 } }; u.iidxes = T; for (var B = ["file:///some/file/path/filename.pdf", "mailto:e+_mail.me@sub.domain.com", "http://sub.domain.co.uk:3000/p/a/t/h_(asd)/h?q=abc123#dfdf", "http://www.????.com", "http://127.0.0.1:3000/p/a/t_(asd)/h?q=abc123#dfdf", "http://[2a00:1450:4025:401::67]/k/something", "a.org/abc/?_??"].join(" "), e = null, D = 0; null !== (e = u.finalRegex.exec(B));)0 === D && (T.isFile = e.lastIndexOf(e[0]), T.file.fileName = e.indexOf("filename.pdf"), T.file.protocol = e.indexOf("file:///")), 1 === D && (T.isEmail = e.lastIndexOf(e[0]), T.email.protocol = e.indexOf("mailto:"), T.email.local = e.indexOf("e+_mail.me"), T.email.host = e.indexOf("sub.domain.com")), 2 === D && (T.isURL = e.lastIndexOf(e[0]), T.url.protocol1 = e.indexOf("http://"), T.url.protocolWithDomain = e.indexOf("http://sub.domain.co.uk:3000"), T.url.port = e.indexOf("3000"), T.url.path = e.indexOf("/p/a/t/h_(asd)/h"), T.url.query = e.indexOf("q=abc123"), T.url.fragment = e.indexOf("dfdf")), 3 === D && (T.url.byProtocol = e.lastIndexOf("http://www.????.com"), T.url.protocol2 = e.lastIndexOf("http://")), 4 === D && (T.url.ipv4 = e.indexOf("127.0.0.1"), T.url.ipv4Confirmation = e.indexOf("0.")), 5 === D && (T.url.ipv6 = e.indexOf("2a00:1450:4025:401::67"), T.url.protocol3 = e.lastIndexOf("http://")), 6 === D && (T.url.secondPartOfPath = e.indexOf("??")), D++ }); A(e); e.email, e.url, e.file, e.finalRegex, e.ipRegex, e.emailRegex, e.fileRegex, e.urlRegex, e.iidxes; var D = u(function (A, u) { Object.defineProperty(u, "__esModule", { value: !0 }), u.checkParenthesis = function (A, u, E, N) { return N === u && (E.split(A).length - E.split(u).length == 1 || A === u && E.split(A).length % 2 == 0 || void 0) }, u.maximumAttrLength = L.htmlAttributes.sort(function (A, u) { return u.length - A.length })[0].length, u.isInsideAttribute = function (A) { return /\s[a-z0-9-]+=('|")$/i.test(A) || /: ?url\(('|")?$/i.test(A) }, u.isInsideAnchorTag = function (A, u, E) { for (var N = A.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"), C = new RegExp("(?=(<a))(?!([\\s\\S]*)(<\\/a>)(" + N + "))[\\s\\S]*?(" + N + ")(?!\"|')", "gi"), O = null; null !== (O = C.exec(u));) { if (O.index + O[0].length === E) return !0 } return !1 } }); A(D); D.checkParenthesis, D.maximumAttrLength, D.isInsideAttribute, D.isInsideAnchorTag; return A(u(function (A, u) { Object.defineProperty(u, "__esModule", { value: !0 }); function T(I) { for (var R = [], S = null, A = function () { var A = S.index, N = A + S[0].length, C = S[0]; if ("/" === I.charAt(N) && (C += I.charAt(N), N++), -1 < L.closingParenthesis.indexOf(I.charAt(N)) && L.parenthesis.forEach(function (A) { var u = A.charAt(0), E = A.charAt(1); D.checkParenthesis(u, E, C, I.charAt(N)) && (C += I.charAt(N), N++) }), -1 !== ['""', "''", "()"].indexOf(I.charAt(A - 1) + I.charAt(N)) && D.isInsideAttribute(I.substring(A - D.maximumAttrLength - 15, A))) return "continue"; if (-1 < I.substring(N, I.length).indexOf("</a>") && -1 < I.substring(0, A).indexOf("<a") && D.isInsideAnchorTag(C, I, N)) return "continue"; if (S[e.iidxes.isURL]) { var u = (S[e.iidxes.url.path] || "") + (S[e.iidxes.url.secondPartOfPath] || "") || void 0, E = S[e.iidxes.url.protocol1] || S[e.iidxes.url.protocol2] || S[e.iidxes.url.protocol3]; R.push({ start: A, end: N, string: C, isURL: !0, protocol: E, port: S[e.iidxes.url.port], ipv4: S[e.iidxes.url.ipv4Confirmation] ? S[e.iidxes.url.ipv4] : void 0, ipv6: S[e.iidxes.url.ipv6], host: S[e.iidxes.url.byProtocol] ? void 0 : (S[e.iidxes.url.protocolWithDomain] || "").substr((E || "").length), confirmedByProtocol: !!S[e.iidxes.url.byProtocol], path: S[e.iidxes.url.byProtocol] ? void 0 : u, query: S[e.iidxes.url.query] || void 0, fragment: S[e.iidxes.url.fragment] || void 0 }) } else if (S[e.iidxes.isFile]) { var O = C.substr(8); R.push({ start: A, end: N, string: C, isFile: !0, protocol: S[e.iidxes.file.protocol], filename: S[e.iidxes.file.fileName], filePath: O, fileDirectory: O.substr(0, O.length - S[e.iidxes.file.fileName].length) }) } else S[e.iidxes.isEmail] ? R.push({ start: A, end: N, string: C, isEmail: !0, local: S[e.iidxes.email.local], protocol: S[e.iidxes.email.protocol], host: S[e.iidxes.email.host] }) : R.push({ start: A, end: N, string: C }) }; null !== (S = e.finalRegex.exec(I));)A(); return R } function E(A) { var u = "string" == typeof A ? { input: A, options: void 0, extensions: void 0 } : A, E = u.input, N = u.options, C = u.extensions; if (C) for (var O = 0; O < C.length; O++) { var I = C[O]; E = E.replace(I.test, I.transform) } var R = T(E), S = ""; for (O = 0; O < R.length; O++)S = (S || (0 === O ? E.substring(0, R[O].start) : "")) + B.transform(R[O], N) + (R[O + 1] ? E.substring(R[O].end, R[O + 1].start) : E.substring(R[O].end)); return S || E } E.list = function (A) { return T(A) }, E.validate = { ip: function (A) { return e.ipRegex.test(A) }, email: function (A) { return e.emailRegex.test(A) }, file: function (A) { return e.fileRegex.test(A) }, url: function (A) { return e.urlRegex.test(A) || e.ipRegex.test(A) } }, u.default = E })) });
﻿(function ()
{
   _MTS_JQUERY(document).one("widgetsloaded", function ()
   {
      if (_MTS_JQUERY("#loginBottom").length > 0)
      {
         var logbuttonsHereTarget = "";
         var currentButtonHref = _MTS_JQUERY("#loginBottom").attr("href");

         if (currentButtonHref.length > 0)
         {
            if (typeof _encodedPathAndQuery === "string" && _encodedPathAndQuery != null && _encodedPathAndQuery.length > 0)
               logbuttonsHereTarget = _encodedPathAndQuery;

            var portalString = "%2fPortal.aspx";
            _MTS_JQUERY(".lgBot").attr("href", currentButtonHref.replace(currentButtonHref.indexOf(portalString) >= 0 ? portalString : "%2f", logbuttonsHereTarget));
         }
      }

      if (typeof (ToggleCustomDropdowns) == "function")
         ToggleCustomDropdowns(80, "#searchType:visible");
   });
})();
