(function($){
  var newWin = null;
  var ss_popUpScreenTop = 50;
  var ss_popUpScreenLeft = 50;
  var pageDomain = location.protocol + '//' + location.hostname;
  // Global ss_popUp function
  window.ss_popUp = function(popURL, popName, popWidth, popHeight){
    // Get the popURL from the Link object, if necessary
    var popTitle = popURL;
    if (popURL.constructor != String) {
      popURL = popURL.href;
      var titleAttr = $(popURL).attr('title');
      if (titleAttr === '') {
        titleAttr = $(popURL).text();
      }
      popTitle = (titleAttr) ? titleAttr : popURL;
    }
    // Determine when to use old-school pop-up
    if (((arguments.length > 4) && !arguments[4]) || ((location.protocol == 'https:') && /^http:/i.test(popURL)) || ($('.ss_popup_window_wrapper').length == 0)) { // If false was passed as 5th parameter, or if were' on a secure page but requesting non-secure link, or if the necessary divs don't exist; fall back to old-school pop-up
      if (newWin && !newWin.closed) {
        newWin.close();
      }
      newWin = self.open(popURL, popName, 'width='+popWidth+',height='+popHeight+',resizable=yes,status=yes,screenX='+ss_popUpScreenLeft+',screenY='+ss_popUpScreenTop+',top='+ss_popUpScreenTop+',left='+ss_popUpScreenLeft+',scrollbars=yes');
    }
    else { // Show the "ss_popUp" in an overlay/iframe
      var ie6 = ($.browser.msie && ($.browser.version <= 6));
      var modalOptions = (arguments.length > 4) && arguments[4]; // Modal overlay options are passed as the 5th parameter to ss_popUp
      var startingZindex = (modalOptions && $.fn.overlay) ? 10003 : 1003;
      window.ss_popUp.zIndex = (window.ss_popUp.zIndex) ? window.ss_popUp.zIndex+1 : startingZindex;
      // Width/Height settings for wrapper div
      var titleBarWidth = popWidth;
      var wrapperWidth = popWidth + 52;
      var wrapperHeight = popHeight + 71;
      var sideShadowHeight = popHeight + 6;
      var bottomShadowWidth = popWidth - 10;
      var contentWidth = popWidth;
      var contentHeight = popHeight;
      // IE6 width adjustments
      if (ie6) {
        wrapperWidth += 6;
        titleBarWidth += 4;
        sideShadowHeight += 4;
        bottomShadowWidth += 4;
        contentWidth += 4;
        contentHeight += 4;
      }
      var ss_popUpId = 'ss_popUp_'+popName;
      // Called by the close button and window.close
      var ss_closePopUp = function(){
        window.ss_popUp[popName] = false;
        $('#'+ss_popUpId).slideUp('fast', function(){
          if (modalOptions && $.fn.overlay) {
            $(this).hideOverlay(function(bgOverlay){
              $(bgOverlay).remove();
            });
          }
          $(this).remove(); // Remove it from the DOM
        });
      };
      if (window.ss_popUp[popName]) { // This popName is already showing
        var ss_popUpWrapper = $('#'+ss_popUpId)[0];
        var $existingIframe = $('.ss_popup_content_iframe', ss_popUpWrapper);
        var $iframeCopy = $('div.ss_popup_window_wrapper:not([id]) .ss_popup_content_iframe').clone();
        $iframeCopy.attr({
          width: $existingIframe.attr('width'),
          height: $existingIframe.attr('height')
        });
        $existingIframe.replaceWith($iframeCopy[0]);
      }
      else { // Create a new overaly for this ss_popUp
        // Resize the overlay
        var ss_popUpWrapper = $('div.ss_popup_window_wrapper:not([id])').clone().attr('id', ss_popUpId).css({
          width: wrapperWidth+'px',
          height: wrapperHeight+'px',
          top: ss_popUpScreenTop+'px',
          left: ss_popUpScreenLeft+'px'
        })[0];
        // Make sure the ss_popUp gets focus when clicked
        $('.ss_popup_title_bar', ss_popUpWrapper).width(titleBarWidth).find('.ss_popup_title_header').width(popWidth).mousedown(function(){
          $('#'+ss_popUpId).css('z-index', ++window.ss_popUp.zIndex);
          return true;
        });
        // Close button
        $('a.ss_popup_close_button_link', ss_popUpWrapper).one('click', function(){
          ss_closePopUp();
          return false;
        });
        // Shadows
        $('.ss_popup_shadow2,.ss_popup_shadow8', ss_popUpWrapper).height(sideShadowHeight);
        $('.ss_popup_shadow5', ss_popUpWrapper).width(bottomShadowWidth);
        // Iframe
        $('.ss_popup_content_wrapper', ss_popUpWrapper).css({
          width: contentWidth+'px',
          height: contentHeight+'px'
        });
        var loadingMessage = $('iframe.ss_popup_content_iframe', ss_popUpWrapper).attr({
          width: popWidth,
          height: popHeight
        }).text(); // The loading message is sitting between the open/close <iframe> tags
        // Enable dragging
        var dragOptions = {
          handle: '.ss_popup_title_header',
          opacity: ($.browser.msie) ? 1 : 0.85 /* Don't use transparent drag for IE */
        };
        if ($.fn.draggable) {
          $('.ss_popup_title_header', ss_popUpWrapper).css('cursor', 'move');
        }
        $(ss_popUpWrapper).prependTo('body');
        // Use an overlay for IE6, or when the 5th parameter is passed
        if ($.fn.overlay && (ie6 || modalOptions)) { // Only enable modal version if the plugin exists
          if (modalOptions && modalOptions.constructor == Boolean) { // If only true was passed in, use the default overlay settings
            modalOptions = {
              css: {
                backgroundColor: '#FFFFFF',
                opacity: 0.6
              }
            };
          }
          var overlayOptions = $.extend(true, {drag: dragOptions}, {modal: modalOptions});
          $(ss_popUpWrapper).overlay(overlayOptions).showOverlay();
        }
        else {
          // When modal, but plugin doesn't exist, throw up a warning for Firebug users
          if (modalOptions && !$.fn.overlay && window.console) {
            console.warn('ss_popUp in modal mode requires the jQuery overlay plugin.');
          }
          // Only include dragging if the plugin exists
          if ($.fn.draggable) {
            $(ss_popUpWrapper).draggable(dragOptions);
          }
          $(ss_popUpWrapper).show();
        }
        window.ss_popUp[popName] = true;
      }
      // Make sure the user can see the ss_popUp overlay
      self.scrollTo(0,0);
      // Display the loading message in the iframe
      var iframeWin = $('.ss_popup_content_iframe', ss_popUpWrapper)[0].contentWindow;
      iframeWin.document.open();
      iframeWin.document.write(loadingMessage);
      iframeWin.document.close();
      // Extra features if we're on the same domain
      if ((popURL.substr(0,pageDomain.length) == pageDomain) || !/^https?:/i.test(popURL)) {
        $('.ss_popup_content_iframe', ss_popUpWrapper).one('load', function(){
          // Set the page's <title> into the overlay's title bar
          try {
            var iframePageTitle = this.contentWindow.document.title;
            if (iframePageTitle !== '') {
              $('.ss_popup_title_header', ss_popUpWrapper).text(iframePageTitle);
            }
            // Override the window.close() method
            this.contentWindow.close = function(){
              ss_closePopUp();
            };
          }
          catch(e) {} // If the page redirects to a different protocol, this would generate an error!
        });
      }
      // Load the URL into the iframe, bypassing the browser history
      iframeWin.location.replace(popURL);
      // Change the title bar
      $(ss_popUpWrapper).css('z-index', window.ss_popUp.zIndex).find('.ss_popup_title_header').text(popTitle).attr('title', popURL);
    }
  };
})(jQuery);