(function($) {

  function overlayStyles() {
    return {
      'display': 'block',
      'position': 'absolute',
      'top': '0',
      'left': '0',
      'width': '100%',
      'height': $(document).height(),
      'z-index': '15000'
    }
  }

  function popupObject(elements, handler) {
    return {
      'elements': elements,
      'handler': handler,
      'close': function() { 
          $(window).unbind('scroll', this.handler);
          $(window).unbind('resize', this.handler);
          this.elements.remove();
        }
    }
  }

  $.popup = function(element, containerClass) {
    if (typeof(containerClass) == 'undefined') { containerClass = 'default'; }

    var elements = $('<div class="' + containerClass + '"></div>')
    var overlay = $('<div class="mask"></div>').css(overlayStyles()).appendTo(elements);
    $(element).css({
      'z-index': '15001',
      'position': 'absolute'
    });
    elements.appendTo('body');
    element.addClass('popup').appendTo(elements).center();

    var resizeHandler = function() { element.center(); };
    $(window).scroll(resizeHandler);
    $(window).resize(resizeHandler);

    return popupObject(elements, resizeHandler);
  }

  $.fn.center = function() {
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
  }



  $.peace_popup = function(element, width) {
    var root = $(
      '<div>' +
        '<div class="top"><div class="ppinner"></div></div>' +
        '<div class="middle"><div class="ppinner ppcontent"></div></div>' +
        '<div class="bottom"><div class="ppinner"></div></div>' +
      '</div>'
    );

    $('.ppcontent', root).append(element);
    return $.popup(root, 'peace_popup');
  }

  $.fn.addInnerDivs = function(count) {
    for (var ix = 0; ix < count; ++ix) {
      this.wrapInner('<div class="inner-' + (count - ix) + '"></div>');
    }
    return this;
  }

  $(function() {
    $(".with_default").focus(function() {
      if(this.value == this.defaultValue) {
        this.select();
      }
    });

    if ($.cookie('age_check') != 'ok' && window.skip_login != 'yes') {
      var elements = $(
        '<div style="width: 320px; text-align: left;">' +
        '<h2 class="welcome"><span>Välkommen, eller?</span></h2>' + 
        '<p>Den här webbsajten är till för oss som är under 20&nbsp;år' +
          ' och som vill diskutera våld och hur det påverkar oss.' + 
          ' Om du är äldre finns det säkert något annat ställe.</p>' +
        '<p class="checkbox"><input type="checkbox" name="age" id="agecheck" class="checkbox" /> ' +
          '<label for="agecheck">Jag är under 20 år</label></p>' +
        '<button type="button" class="continue"><span>Fortsätt till Peacepower</span></button></div>'
      );
      var pap = $.peace_popup(elements, 330);
      $('button', pap.elements).click(function() {
        $.cookie('age_check', 'ok');
        pap.close();
      });
    }

    if ($.cookie('ppadmin') == 'yes') {
      $(".forum .show li.topic").each(function() {
        var message_id = this.id;
        $(".title strong", this).append(" <a href='javascript: void 0;' class='delete' data-message='" + message_id + "'>[Ta bort hela tråden]</a>");
      });
      $(".forum .show li.post").each(function() {
        var message_id = this.id;
        $(".content", this).append("<p><a href='javascript: void 0;' class='delete' data-message='" + message_id + "'>&raquo; Ta bort det här meddelandet</a></p>");
      });

      $("a.delete").click(function() {
        var msg = $(this).attr('data-message');

        var type = (msg.indexOf('topic') == 0) ? 'topic' : 'message';
        var type_str = (msg.indexOf('topic') == 0) ? 'tråden?' : 'meddelandet?';

        if (confirm("Är du säker på att du vill ta bort " + type_str, "Ja", "Nej")) {
          var id = msg.substring(msg.indexOf("_") + 1);
          $.post('/admin/remove_' + type, { 'id': id }, function (msg) {
            alert("Servern svarade: " + msg);
          }, 'text');
        }
      });
    }
  });

})(jQuery);

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


