/* Image popuper
 *
 * @require dimensions
 * @require yyModal
 */

$(function()
{
  yyModalInit();
});

/* {{{ yyModalInit()
 *
 * Tą funkcję można wiele razy - funkcja automatycznie sprawdza które linki
 * zostały już wcześniej przez nią przerobione na popupy
 */

  var yyModalInit = function()
  {
    $('div.album ul').css({float:'left',display:'inline'}).each(function()
    {
      $(this).css('marginLeft', Math.round(($(this.parentNode).width()-$(this).width())/2)+'px');
    });

    $('a.popup').not('.popup-ready').click(function()
    {
      var match = this.className.match(/([0-9]+)x([0-9]+)/);

      if (match)
      {
        var imgWidth  = match[1];
        var imgHeight = match[2];
        var imgAlt    = $('img', this).attr('alt');
        var imgTitle  = $('img', this).attr('title');

        var Modal = new yyModal(
        {
          css: {
            background: '#fff',
            padding: '6px'
          },
          contentCss: {
            width:  imgWidth+'px',
            height: imgHeight+'px'
          },
          close: 'zamknij'
        });

        Modal.setContent('<img src="'+this.href+'" width="'+imgWidth+'" height="'+imgHeight+'" alt="'+imgAlt+'" title="'+imgTitle+'" />');
        Modal.open();
      }

      return false;
    })
    .addClass('popup-ready');
  }

/* }}} */

/* {{{ yyModal
 *
 * @require dimensions.js
 */

yyModal = function(cfg)
{
  this.cfg        = {};
  this.css        = {};
  this.contentCss = {};
  this.closeCss   = {position:'absolute', 'background-color': '#fff' };
  this.created    = false;
  this.opened     = false;
  this.background = null;
  this.viewer     = null;
  this.contentDiv = null;
  this.closeDiv   = null;

  /* {{{ setCfg()
   */

    this.setCfg = function(cfg)
    {
      if (cfg)
      {
        this.cfg = cfg;

        if (cfg.css)
        {
          this.css = cfg.css;
        }

        if (cfg.contentCss)
        {
          this.contentCss = cfg.contentCss;
        }

        if (cfg.closeCss)
        {
          this.closeCss = cfg.closeCss;
        }

        if (cfg.width)
        {
          this.css.width = cfg.width+'px';
        }

        if (cfg.height)
        {
          this.css.height = cfg.height+'px';
        }
      }
    };

  /* }}} */
  /* {{{ initBg()
   */

    this.initBg = function()
    {
      if (this.background === null)
      {
        this.background = $('#yyModal-background');

        if (this.background.length === 0)
        {
          if (!window.totalHeight)
          {
            var docH  = $(document).height()
            var pageH = $('body>:first-child').height();

            /*
            var pageH = 0;
            $('body>*').each(function()
            {
              pageH += $(this).height();
            });
            */

            window.totalHeight = pageH > docH ? pageH : docH;
          }

          this.background = $('<div id="yyModal-background"></div>');
          this.background.appendTo('body')
          .css({opacity: '0', background: '#000', position: 'absolute', zIndex: '500', left: '0', top: '0', width: '' +$(document).width() +'px', height: '' +window.totalHeight +'px'})
          .hide();
        }
      }
    };

  /* }}} */
  /* {{{ init()
   */

    this.init = function()
    {
      var closeTxt = 'close';

      if (!this.created)
      {
        this.initBg();

        if (this.cfg.close)
        {
          closeTxt = this.cfg.close;
        }

        $('#yyModal').remove();

        this.contentDiv  = $('<div id="yyModal-content"></div>').css(this.contentCss);
        this.closeDiv    = $('<div id="yyModal-close" title="'+closeTxt+'"><a href="#">'+closeTxt+'</a></div>');

        this.viewer  = $('<div id="yyModal"></div>').css(this.css);
        this.viewer.append(this.contentDiv);
        this.viewer.append(this.closeDiv);

        this.viewer[0].yyModal = this;

        this.contentDiv.css(this.contentCss);
        this.closeDiv.css(this.closeCss).addClass('hidden');

        this.addEvents();

        this.created = true;
      }
    };

  /* }}} */
  /* {{{ addEvents()
   */

    this.addEvents = function()
    {
      var self = this;

      if (this.viewer)
      {
        if (this.closeDiv)
        {
          this.viewer.hover(function()
          {
            self.closeDiv.removeClass('hidden');
          }, function()
          {
            self.closeDiv.addClass('hidden');
          });

          this.closeDiv.click(function(){ self.close(); });
        }

        this.viewer.click(function()
        {
          if (!self.closeDiv || self.closeDiv.css('display') == 'none')
          {
            self.close();
          }

          return false;
        });

        this.viewer.bind('dblclick', function()
        {
          self.close();
          return false;
        });
      }

      $(document).bind('keypress', this.onKeyPress);

      if (this.background)
      {
        this.background.click(function()
        {
          self.close();
          return false;
        });
      }
    };

  /* }}} */
  /* {{{ onKeyPress()
   */

    this.onKeyPress = function(e)
    {
      if (e.keyCode == 27)
      {
        var el = $('#yyModal');

        if (el.length > 0)
        {
          var Modal = el[0].yyModal;

          Modal.close();

          return false;
        }
      }
    };

  /* }}} */
  /* {{{ setContent()
   */

    this.setContent = function(content)
    {
      this.init();

      if (this.contentDiv)
      {
        this.contentDiv.empty().append(content);
      }
    };

  /* }}} */

  /* {{{ open()
   */

    this.open = function()
    {
      this.init();

      if (this.viewer)
      {
        var self = this;

        self.viewer.appendTo('body').center().hide();

        self.opened = true;

        if (this.background)
        {
          this.background.fadeTo(300, 0.8, function()
          {
            self.viewer.slideDown(500);
          });
        }
        else
        {
          self.viewer.slideDown(500);
        }
      }
    };

  /* }}} */
  /* {{{ close()
   */

    this.close = function()
    {
      var self = this;

      $(document).unbind('keypress', this.onKeyPress);

      if (this.viewer)
      {
        if (!this.opened)
        {
          self.viewer.remove();
          self.viewer     = null;
          self.contentDiv = null;
          self.closeDiv   = null;
          self.created    = false;
        }
        else
        {
          this.viewer.slideUp(300, function()
          {
            self.viewer.remove();
            self.viewer      = null;
            self.contentDiv  = null;
            self.closeDiv    = null;
            self.created     = false;
            self.opened      = false;

            if (self.background)
            {
              self.background.fadeOut(300, function()
              {
                self.background.remove();
                self.background = null;
              });
            }
          });
        }
      }
    };

  /* }}} */

  if (cfg){ this.setCfg(cfg); };
}

/* }}} */
/* {{{ dimensions.js
 */

  jQuery.fn._height=jQuery.fn.height;jQuery.fn._width=jQuery.fn.width;jQuery.fn.height=function(){if(this[0]==window)return self.innerHeight||jQuery.boxModel&&document.documentElement.clientHeight||document.body.clientHeight;if(this[0]==document)return Math.max(document.body.scrollHeight,document.body.offsetHeight);return this._height(arguments[0])};jQuery.fn.width=function(){if(this[0]==window)return self.innerWidth||jQuery.boxModel&&document.documentElement.clientWidth||document.body.clientWidth;if(this[0]==document)return Math.max(document.body.scrollWidth,document.body.offsetWidth);return this._width(arguments[0])};jQuery.fn.innerHeight=function(){return this[0]==window||this[0]==document?this.height():this.css('display')!='none'?this[0].offsetHeight-(parseInt(this.css("borderTopWidth"))||0)-(parseInt(this.css("borderBottomWidth"))||0):this.height()+(parseInt(this.css("paddingTop"))||0)+(parseInt(this.css("paddingBottom"))||0)};jQuery.fn.innerWidth=function(){return this[0]==window||this[0]==document?this.width():this.css('display')!='none'?this[0].offsetWidth-(parseInt(this.css("borderLeftWidth"))||0)-(parseInt(this.css("borderRightWidth"))||0):this.height()+(parseInt(this.css("paddingLeft"))||0)+(parseInt(this.css("paddingRight"))||0)};jQuery.fn.outerHeight=function(){return this[0]==window||this[0]==document?this.height():this.css('display')!='none'?this[0].offsetHeight:this.height()+(parseInt(this.css("borderTopWidth"))||0)+(parseInt(this.css("borderBottomWidth"))||0)+(parseInt(this.css("paddingTop"))||0)+(parseInt(this.css("paddingBottom"))||0)};jQuery.fn.outerWidth=function(){return this[0]==window||this[0]==document?this.width():this.css('display')!='none'?this[0].offsetWidth:this.height()+(parseInt(this.css("borderLeftWidth"))||0)+(parseInt(this.css("borderRightWidth"))||0)+(parseInt(this.css("paddingLeft"))||0)+(parseInt(this.css("paddingRight"))||0)};jQuery.fn.scrollLeft=function(){if(this[0]==window||this[0]==document)return self.pageXOffset||jQuery.boxModel&&document.documentElement.scrollLeft||document.body.scrollLeft;return this[0].scrollLeft};jQuery.fn.scrollTop=function(){if(this[0]==window||this[0]==document)return self.pageYOffset||jQuery.boxModel&&document.documentElement.scrollTop||document.body.scrollTop;return this[0].scrollTop};jQuery.fn.offset=function(options,returnObject){var x=0,y=0,elem=this[0],parent=this[0],op,sl=0,st=0,options=jQuery.extend({margin:true,border:true,padding:false,scroll:true},options||{});do{x+=parent.offsetLeft||0;y+=parent.offsetTop||0;if(jQuery.browser.mozilla||jQuery.browser.msie){var bt=parseInt(jQuery.css(parent,'borderTopWidth'))||0;var bl=parseInt(jQuery.css(parent,'borderLeftWidth'))||0;x+=bl;y+=bt;if(jQuery.browser.mozilla&&parent!=elem&&jQuery.css(parent,'overflow')!='visible'){x+=bl;y+=bt}}if(options.scroll){op=parent.offsetParent;do{sl+=parent.scrollLeft||0;st+=parent.scrollTop||0;parent=parent.parentNode;if(jQuery.browser.mozilla&&parent!=elem&&parent!=op&&jQuery.css(parent,'overflow')!='visible'){y+=parseInt(jQuery.css(parent,'borderTopWidth'))||0;x+=parseInt(jQuery.css(parent,'borderLeftWidth'))||0}}while(parent!=op)}else parent=parent.offsetParent;if(parent&&(parent.tagName.toLowerCase()=='body'||parent.tagName.toLowerCase()=='html')){if(jQuery.browser.safari&&jQuery.css(parent,'position')!='absolute'){x+=parseInt(jQuery.css(op,'marginLeft'))||0;y+=parseInt(jQuery.css(op,'marginTop'))||0}break}}while(parent);if(!options.margin){x-=parseInt(jQuery.css(elem,'marginLeft'))||0;y-=parseInt(jQuery.css(elem,'marginTop'))||0}if(options.border&&(jQuery.browser.safari||jQuery.browser.opera)){x+=parseInt(jQuery.css(elem,'borderLeftWidth'))||0;y+=parseInt(jQuery.css(elem,'borderTopWidth'))||0}else if(!options.border&&!(jQuery.browser.safari||jQuery.browser.opera)){x-=parseInt(jQuery.css(elem,'borderLeftWidth'))||0;y-=parseInt(jQuery.css(elem,'borderTopWidth'))||0}if(options.padding){x+=parseInt(jQuery.css(elem,'paddingLeft'))||0;y+=parseInt(jQuery.css(elem,'paddingTop'))||0}if(options.scroll&&jQuery.browser.opera&&jQuery.css(elem,'display')=='inline'){sl-=elem.scrollLeft||0;st-=elem.scrollTop||0}var returnValue=options.scroll?{top:y-st,left:x-sl,scrollTop:st,scrollLeft:sl}:{top:y,left:x};if(returnObject){jQuery.extend(returnObject,returnValue);return this}else{return returnValue}};

/* }}} */
/* {{{ $.center()
 */

  // Created by Andreas Lagerkvist http://exscale.se
  // A center-function (uses dimensions plugin)
  $.fn.center = function(show_info)
  {
    return this.each(function()
    {
      /*
      if (typeof document.body.style.maxHeight == "undefined")
      {
        // IE<=6
        $(this).css({position: 'absolute'});
      } else {
        $(this).css({position: 'fixed'});
      }
      */

      $(this).css({position: 'absolute'});

      var leftPos = ($(window).width() - $(this).outerWidth()) / 2 + $(window).scrollLeft();
      var topPos = ($(window).height() - $(this).outerHeight()) / 2 + $(window).scrollTop();

      if(topPos < 0) topPos = 0;
      if(leftPos < 0) leftPos = 0;

      $(this).css({left: leftPos +'px', top: topPos +'px', zIndex: '1000'});
    });
  }

/* }}} */
