(function($) {
  function getViewportZoom() {
    var zoom = 1.0;
    if ($.browser.msie && parseInt($.browser.version) == 7 && document.body.getBoundingClientRect) {
      var rect = document.body.getBoundingClientRect();
      var physicalW = rect.right - rect.left;
      var logicalW = document.body.offsetWidth;
      zoom = physicalW / logicalW;
    }
    return zoom;
  }
  function getViewportWidth() {
    var width;
    if(typeof window.innerWidth != 'undefined') {
      width = parseInt(window.innerWidth);
    } else if(typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
      width = parseInt(document.documentElement.clientWidth);
    } else {
      width = parseInt(document.getElementsByTagName('body')[0].clientWidth);
    }
    width = width * (1 / getViewportZoom());
    return width;
  }
  function getViewportHeight() {
    var height;
    if(typeof window.innerHeight != 'undefined') {
      height = parseInt(window.innerHeight);
    } else if(typeof document.documentElement != 'undefined' && typeof document.documentElement.clientHeight != 'undefined' && document.documentElement.clientHeight != 0) {
      height = parseInt(document.documentElement.clientHeight);
    } else {
      height = parseInt(document.getElementsByTagName('body')[0].clientHeight);
    }
    height = height * (1 / getViewportZoom());
    return height;
  }

  var keyContainerClass = function() {
    var obj = {},
        container = [],
        lastKeyDown,
        dummyClass = function(){};

    dummyClass.prototype = keyContainerClass.prototype;
    obj = new dummyClass;

    document.onkeydown = function(e) {
      if (((e == null) ? event.keyCode : e.which) == 27 && window.ajax > 0) {
        return false; // by Fx nie przerywal wywolan AJAX
      }
      lastKeyDown = (e == null) ? event.keyCode : e.which;
      if (container.length) {
        if (typeof container[container.length-1][lastKeyDown] != "undefined") {
          $(container[container.length-1][lastKeyDown]).click();
        }
      }
      if (((e == null) ? event.keyCode : e.which) == 27) {
        return false; // by Fx nie przerywal wywolan AJAX
      }
    }
    obj.getLastKeyDown = function() {
      return lastKeyDown;
    }
    obj.removeLast = function() {
      container.pop();
    }
    obj.removeAll = function() {
      container = [];
    }
    obj.add = function(action) {
      container.push(action);
    }
    return obj;
  };

  var keyContainer = new keyContainerClass;

  var ajax = 0;
  $(function() {
    $("body").ajaxStart(function() {
      window.ajax++;
    });

    $("body").ajaxStop(function() {
      window.ajax--;
    });
  });

  var overflow_default = null;
  $.alerts = {
    _hide: function(id, hideOverlay) {
      var p = {};
      if (id !== undefined) {
        p.id = id;
      }
      if (hideOverlay === undefined) {
        p.hideOverlay = true;
      } else {
        p.hideOverlay = hideOverlay;
      }
      $.alerts2._hide(p);
    },
    _hide_all : function() {
      $.alerts2._hide_all();
    }
  }
  $.alerts2 = {
    verticalOffset: 0,
    horizontalOffset: 0,
    overlayColor : "#fff",
    scrollHeight: 0,
    overlayOpacity : .80,
    maxZIndex : 90000,
    defaultShowParameters : {
      id : 'popup_container',
      showOverlay : true,
      title : false,
      buttons : [{label : 'zamknij', isDefault : true, keys : [13,27]}],
      prompText : false,
      prompTextDefault : '',
      prompTextMaxLen : false
    },
    defaultHideParameters : {
      hideOverlay : true,
      id          : 'popup_container'
    },
    defaultKeys : {
      esc   : 27,
      enter : 13
    },
    _overlay : function(action) {
      if(action == 'status') {
        return ($("#popup_overlay").length >= 1);
      }
      var $body = $("body");
      if(action == 'show') {
        $("#popup_overlay").remove();
        var css = {
          position  : "fixed",
          zIndex    : 90000,
          top       : 0,
          left      : 0,
          right     : 0,
          bottom    : 0,
          background: $.alerts2.overlayColor,
          opacity   : $.alerts2.overlayOpacity
        };

        if($.browser.msie && parseInt($.browser.version) < 7) {
          css = $.extend(css, {
            position : "absolute",
            width    : '100%'
          });
        }
        var $overlay = $("<div/>", {
          id : "popup_overlay",
          css : css
        }).appendTo($body);
        if($.browser.msie && parseInt($.browser.version) < 7) {
          /**
           * IE6 select list hack
           */
          var html =
              "<iframe style=\"position: absolute; display: block; " +
              "z-index: -1; width: 100%; height: 100%; top: 0; left: 0;" +
              "filter: mask(); background-color: #ffffff; \"></iframe>";
           $overlay.append(html);
           // force refresh of div
           var olddisplay = $overlay.css('display');
           $overlay.css('display', 'none');
           $overlay.css('display', olddisplay);
        }
        var scrollTop = $('html').scrollTop();
        $('html').css('overflow', 'hidden');
        $('html').animate({'scrollTop' : scrollTop}, 0);
        return;
      }

      var $alerts = $('.popup_container');
      if($alerts.length == 0) {
        $('#popup_overlay').remove();
        var scrollTop = $('html').scrollTop();
        $('html').css('overflow', 'auto');
        $('html').animate({'scrollTop' : scrollTop}, 0);
      } else {
        if($('#popup_overlay').length == 0) {
          $.alerts2._overlay('show');
        }
        var maxZIndex = 0;
        $alerts.each(function () {
          maxZIndex = Math.max(maxZIndex, parseInt($(this).css('zIndex')));
        });
        $('#popup_overlay').css('zIndex', maxZIndex-1);
      }
    },
    _getRandId : function() {
      var randID = false;

      while(!randID) {
        var rand = 'jA'+Math.random().toString().replace('.', '').substr(1, 7);
        if (0 == $("#"+rand).length) {
          randID = rand;
        }
      }
      return randID;
    },
    _show : function(p) {
      if (this.maxZIndex < 90000) this.maxZIndex = 90000;

      this.scrollHeight = this.scrollbarWidth();
      p = $.extend({},this.defaultShowParameters, p);
      p.overlayExists = this._overlay('status');

      if(false === p.id) {
        p.id = this._getRandId();
      }
      // na wypadek uruchomienia div'ow z tym samym ID, dzieje sie tak czesto, kiedy nie podaje sie wlasnego ID i leci standard z configa
      if($("#"+p.id).length) {
        p.id = this._getRandId();
      }

      if(undefined !== p.content) {
        p.message = $.ajax({
          url : '/'+default_language+'/'+( 'https:' == document.location.protocol ? '_ajax_ssl' : '_ajax' )+'/HTMLContents/Alert.html',
          data : {
            message : p.content
          },
          async: false
        }).responseText
      }

      if(true === p.prompText) {
        p.message += '<br /><input type="text" name="promptText" id="prompt_input_'+p.id+'" value="'+p.prompTextDefault+'" maxlength="'+((p.prompTextMaxLen)?p.prompTextMaxLen+'" style="width:'+p.prompTextMaxLen+'ex;"':'" width="100%')+'"/><br/><br/>';
      }

      var $container = $("<div></div>", {
        'id' : p.id,
        'class' : "popup_container",
        "css" : {
          position : ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed',
          zIndex : this.maxZIndex +2,
          left : -10000
        }
      }).appendTo('body');

      $('<h1 class="popup_title"></h1>' +
        '<div class="popup_content">' +
          '<div class="popup_message" style="overflow:auto;"></div>' +
          '<div class="popup_panel_helper" style="text-align:center;zoom:1;border:1px solid #fff;"><div class="popup_panel" style="position:relative;text-align:center;zoom:1;"></div></div>' +
        '</div>').appendTo($container);

      if(undefined !== p.className && false !== p.className) {
        $(".popup_content", $container).addClass(p.className);
      }

      if(p.title) {
        $(".popup_title", $container).text(p.title).show();
      }
      $(".popup_message", $container).html(p.message);

      $container.css({
        minWidth: $container.outerWidth() + this.scrollbarWidth(),
        maxWidth: $container.outerWidth() + this.scrollHeight
      });

      if ('undefined' !== typeof p.fnAfterLoad ) {
        eval(p.fnAfterLoad);
      }

      $.alerts2._overlay();
      $container.show();

      this.maxZIndex = this.maxZIndex + 2;

      if(!$.isArray(p.buttons) || 0 == p.buttons.length) {
        if(typeof p.buttons == 'string') {
          $('#'+p.id+' .popup_panel').html(p.buttons);
        }
        this._resize(p.id);
        this._reposition();
        return false;
      }
      var keys = [];
      if ($.isArray(p.buttons)) {
        $.each(p.buttons, function(i, button) {
          if ('object' != typeof button) {
            return;
          }
          if(typeof button.result === "boolean" && !$.isArray(button.keys)) {
            button.keys = [ button.result ? 13 : 27 ];
          }
          if($.isArray(button.keys)) {
            keys[i] = button.keys;
          }
        });
        $.each(p.buttons, function(_, button) {
          if ('object' != typeof button) {
            return;
          }
          var $button = $('<a href="javascript:void(0);" class="button"'+(button.id ? ' id="'+button.id+'"' : '')+'>'+button.label+'</a>');

          if(button.hide) {
            $button.attr('style', 'display:none;');
          }

          if($.isFunction(button.click)) {
            if(true == button.isDefault && p.id !== $.alerts2.defaultShowParameters.id) {
              $button.click(function() {
                $.alerts2._hide({id : p.id, 'hideOverlay' : !p.overlayExists});
              });
            } else {
              $button.click(function() {
                button.click();
              });
            }
          } else if(false == button.click) {
            $button.click(function() {
              return false;
            });
          } else if($.isFunction(p.callback)) {
            $button.click(function() {
              p.callback(button.result, $("input[name='promptText']", $container).val());
            });
          } else {
            $button.click(function() {
              if(p.id != $.alerts2.defaultShowParameters.id) {
                $.alerts2._hide({id : p.id, 'hideOverlay' : !p.overlayExists});
              } else {
                $.alerts2._hide({'hideOverlay' : !p.overlayExists});
              }
            });
          }
          $button.appendTo($(".popup_panel", $container));
        });
      }
      $('<br style="clear:both;"/>').appendTo($(".popup_panel", $container));

      $("input.hidden").remove();
      $('<input type="button" class="hidden" />').hide().appendTo("body").focus();

      this._resize(p.id);

      var tmp = {};
      if(keys.length) {
        $.each(keys, function(i, keysy) {
          for(var j in keysy) {
            tmp[keysy[j]] = "#"+p.id+" .popup_panel a:eq("+i+")";
          }
        });
      }
      keyContainer.add(tmp);

      setTimeout('$.alerts2._reposition();', 25);

      if(p.afterShow) {
        setTimeout(p.afterShow, 100);
      }
      // set focus on first button
      setTimeout('$("#'+p.id+' .popup_panel a:eq(0)").focus();', 25);
      // datepicker hide - fix na scroll w katalogu (!!)
      $('#ui-datepicker-div').hide();

      // autocomplete = off
      $('#'+p.id+' input[type=text]').attr('autocomplete', 'off');

    },
    _resize : function(id) {

      var sizes = {
        heightWindow : getViewportHeight()-this.scrollHeight - 20,
        heightAlert  : parseInt($("#"+id).outerHeight()),
        widthWindow  : getViewportWidth()-this.scrollHeight - 20,
        widthAlert   : parseInt($("#"+id).outerWidth())
      }

      var resizeValue;
      if(sizes.heightAlert > sizes.heightWindow) {
        resizeValue = (sizes.heightAlert-sizes.heightWindow);
        $("#"+id).height(parseInt($("#"+id).outerHeight())-resizeValue);
        $("#"+id+" div.popup_message").height(parseInt($("#"+id).innerHeight()) - parseInt($('#'+id+' .popup_title').outerHeight(true)) - 1.75 * parseInt($('#'+id+' .popup_panel_helper').outerHeight(true)) - 2*5);
      } else {
        $("#"+id).height('auto');
      }

      if(sizes.widthAlert > sizes.widthWindow) {
        resizeValue = (sizes.widthAlert-sizes.widthWindow);
        $("#"+id).css({
          width    : (sizes.widthAlert - resizeValue-10)+'px',
          minWidth : (sizes.widthAlert - resizeValue-10)+'px'
        });
      }
      $('#'+id+' .popup_panel_helper').width($('#'+id+' .popup_content').outerWidth());

    },
    _hide : function(p) {

      if($('.popup_container').length <= 1 && overflow_default != null) {
        $('body').css({overflow:overflow_default});
        overflow_default = null;
      }
      if(!$.isPlainObject(p)) p = {};
      p = $.extend({}, this.defaultHideParameters, p);

      $("#"+p.id).remove();
      keyContainer.removeLast();

      this.maxZIndex = this.maxZIndex-2;

      this._overlay('hide');

    },
    scrollbarWidth: function() {
        var $div = $('<div style="width:50px;height:50px;overflow:auto;position:absolute;top:-200px;left:-200px;"><div style="width:100%;">--</div></div>').appendTo('body');
        var w1 = $('div', $div).innerWidth();
        $('div', $div).height(100);
        var w2 = $('div', $div).innerWidth();
        $div.remove();
        return ((w1 - w2) > 0 ? (w1 - w2) : 15);
    },
    _hide_all : function(p) {
      if(overflow_default != null) {
        $('body').css({overflow:overflow_default});
        overflow_default = null;
      }
      if(!$.isPlainObject(p)) p = {};
      p = $.extend({}, this.defaultHideParameters, p);

      $('body > .popup_container').remove();
      keyContainer.removeAll();

      if(true === p.hideOverlay) {
        this._overlay('hide');
      }

    },
    _reposition : function() {
      $("body > .popup_container").each(function () {
        var $this = $(this);

        var top  = ((getViewportHeight()/ 2) - ($this.outerHeight() / 2)) + $.alerts2.verticalOffset + (( $.browser.msie && parseInt($.browser.version) <= 6 ) ? $(window).scrollTop() : 0),
            left = ((getViewportWidth() / 2) - ($this.outerWidth() / 2)) + $.alerts2.horizontalOffset;
        if (top < 0)  top = 0;
        if (left < 0) left = 0;
        $this.css({
          top : top+"px",
          left: left+"px"
        }).show();
        $("#popup_overlay").css({height : $(document).height()});
      });
    }
  }

  jAlert2 = function(parameters) {
    $.alerts2._show(parameters);
  }

  jAlert = function(message, title, classAlert, showOverlay, id, callback) {
    $.alerts2._show({
      'message' : message,
      'title'   : title,
      'className' : classAlert,
      'showOverlay' : showOverlay,
      'id' : id,
      'callback' : callback
    });
  }

  jConfirm = function(message, title, classAlert, callback, id) {
    $.alerts2._show({
      'message' : message,
      'title' : title,
      'className' : classAlert,
      'id' : id,
      'buttons' : [
        {'label' : 'anuluj', 'result' : false,keys : [27]},
        {'label' : 'ok'    , 'result' : true, keys : [13]}
      ],
      'callback' : callback
    });
  }

  jInfo = function(message, title, type, showOverlay, id, callback) {
    $.alerts2._show({
      content : message,
      title : title,
      showOverlay : showOverlay,
      id : id,
      callback : callback
    });
  }

  showAlert = function(title, message, w, h, c, pButtonOk, pCrossExit) {
    $.alerts2._show({
      title : title,
      message : message
    });
  }

  showInfo = function(message) {
    jAlert2({
      id : "jApreloader",
      showOverlay : true,
      message : message,
      buttons : []
    });
  }

  jPreloader = function(parameters) {
    if (!$.isPlainObject(parameters)) parameters = {};

    $('#jApreloader').remove();
    if (!$("div.popup_container").length) {
      $("#popup_overlay").remove();
    }

    if(parameters.action === 'hide') {
      $.alerts2._hide({
        id          : "jApreloader",
        hideOverlay : (parameters.hideOverlay === false ? false : true)
      });
    }
    else {
      jAlert2({
        id          : "jApreloader",
        showOverlay : true,
        message     : parameters.message,
        buttons     : []
      });
    }
  }

  jPreloaderShow = function(sMessage) {
    jPreloader({message: sMessage ? sMessage : 'Wczytywanie danych...'});
  }

  jPreloaderHide = function(bHideOverlay) {
    if($("#jApreloader").length == 0) {
      return;
    }
    jPreloader({action: 'hide', hideOverlay: (bHideOverlay === false ? false : true)});
  }

  /**
   * reposition dialog window on window resize
   */
  $(window).resize(function () {
    var $popups = $('.popup_container').each(function () {
      var $this = $(this);
      var $message = $('.popup_message', $this);
      $this.width($message.innerWidth());
      var h = $message.outerHeight(false);
      $message.height('auto');
      $message.height($message.outerHeight());
      h = $message.outerHeight(false) - h;
      $this.height($this.outerHeight(false) + h);
      $.alerts2._resize(this.id);
    });
    if ($popups.length > 0) {
      $.alerts2._reposition();
    }
  });

})(jQuery)

