var CookiesDisclaimer = Class.create({
  initialize : function(settings) {
    this.settings = settings;
    //this.clearCookie('cookiesDisclaimer'); // for debugging

    if(!this.getCookie('cookiesDisclaimer')){
      this.showDisclaimer();
    }
  },

  getCookie : function(key)
  {
    var keyEquals = key + "=";
    var value     = false;

    document.cookie.split(';').invoke('strip').each(function(s){
      if (s.startsWith(keyEquals)) {
        value = unescape(s.substring(keyEquals.length, s.length));
      }
    });

    return value;
  },

  setCookie : function(key, value, days) {
    var setValue      = key + '=' + escape(new String(value));
    var setExpiration = "";
    
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      var setExpiration = "; expires=" + date.toGMTString();
    }

    var cookieString = setValue + setExpiration + ";path=/";
    document.cookie  = cookieString;
  },

  clearCookie : function(key) {
    this.setCookie(key,'',-1);
  },

  animation : function(event, element) {
    switch(this.settings.animation)
    {
      case 'none': 
        event == 'show' ? $(element).show() : $(element).hide(); break;
      case 'slide': 
        event == 'show' ? Effect.BlindDown(element, { duration : 1 }) : Effect.BlindUp(element, { duration : 1 }); break;
      case 'fade':
        event == 'show' ? Effect.Appear(element, { duration : 1 }) : Effect.Fade(element, { duration : 1 }); break;
    }
  },

  showDisclaimer : function() {
    var html = '<div id="cookiesDisclaimer" style="display: none;">'
             + this.settings.disclaimer
             + '<a href="#" name="cookiesDisclaimerHide" id="cookiesDisclaimerHide">'
             + (this.settings.buttonType == 'close' ? '&times;' : this.settings.buttonText)
             + '</a>'
             + '</div>';

    $('xwikimaincontainerinner').insert( {before : html } );
    $("cookiesDisclaimerHide").observe('click', this.hideDisclaimer.bind(this));

    this.animation('show', 'cookiesDisclaimer');  
  },

  hideDisclaimer : function() {
    this.setCookie('cookiesDisclaimer', 'hide', 365);
    this.animation('hide', 'cookiesDisclaimer');
  }
});
document.observe("dom:loaded", function() {
  var settings =
  {
    'type'       : "bar",
    'position'   : "bottom",
    'animation'  : "slide",
    'buttonType' : "text",
    'buttonText' : "<p>[Agree and Proceed]<\/p>",
    'disclaimer' : "<p>This site uses cookies to improve your experience, to provide secure log-in and to optimise site functionality. By clicking \'Agree and Proceed\' you agree to accept cookies.<\/p>"
  };  
  var cookieDisclaimer = new CookiesDisclaimer(settings);
});

