(function(){
  var Portal = {
    initialize: function(){
      this.carousel_height = $("carousel") ? $("carousel").getHeight() : 0;
      this.body = $$("body")[0];
      this.portal = $("portal");
      this.columns = $$(".column");
      this.page_title = this.portal.readAttribute("data-title");
      this.bindEvents();
      this.createSortables();
      this.timer = null;
      this.parameters = {
        columns: [],
        column_ids: []
      };

    },

    bindEvents: function(){
      this.portal.on("click", "a.icon.delete", this.deleteWidgetEvent.bind(this));
      this.portal.on("click", ".widget_page.reset", this.resetPageEvent.bind(this));
      this.portal.on("click", "a.setAsHomepage", this.setAsHomepage);
    },

    setAsHomepage: function(){
      this.style.behavior='url(#default#homepage)';
      this.setHomePage(document.URL);
      //window.setHomePage(document.URL);
    },

    resetPageEvent: function(event){
      event.stop();
      if (!confirm("Deze pagina herstellen?")) { return; }

      var url = "/portals/reset_page";
      var request = new Ajax.Request(url, {
        method: "post",
        parameters: {
          authenticity_token: $$("meta[name='csrf-token']").first().content,
          widget_page_title: this.page_title
        },
        onSuccess: function(){ window.location.reload(); }
      }, this);
    },

    deleteWidgetEvent: function(event){
      event.stop();

      if(!confirm("Deze widget verwijderen?")){ return; }

      var widget = event.element().up(".widget");
      var column = widget.up(".column");

      widget.blindUp({
        duration: 0.5,
        afterFinish: function(){ 
          widget.remove();
          this.sortingChange(column);
        }.bind(this)
      }, this);
    },

    syncColumns: function(extra){
      extra = extra || 0;

      this.columns.each(function(c){ c.setStyle({ height: "auto" }); });
      var max = this.columns.collect(function(c){ 
        if (c.id == "col_2") {
          return c.getHeight() - this.carousel_height; 
        } else {
          return c.getHeight(); 
        }
      }, this).max();

      this.columns.each(function(c){ 
        new_height = max + extra + (c.id == "col_2" ? this.carousel_height : 0);
        c.setStyle({ height: new_height + "px"});
      }, this);
    },

    createSortables: function(){
      this.columns.each(function(column){
        Sortable.create(column, {
          tag: "div",
          handle: "widget_handler",
          constraint: '',
          dropOnEmpty: true,
          containment: this.columns,
          scroll: window,
          onUpdate: this.sortingChange.bind(this),
          starteffect: this.syncColumns.bind(this, 40),
          endeffect: function() {}
        });
      }, this);
    },

    serialize: function(parameters){
      var prm = this.parameters.columns.join("&") + "&page_title=" + this.page_title + 
                "&col_ids[]=" + this.parameters.column_ids.join("&col_ids[]=");
      return prm + "&authenticity_token=" + $$("meta[name='csrf-token']").first().content;
    },

    sortingChange: function(column){
      this.syncColumns();
      this.parameters.columns.push(Sortable.serialize(column.id));
      this.parameters.column_ids.push(column.id);

      clearTimeout(this.timer);
      this.timer = setTimeout(this.sendSortUpdate.bind(this), 200);
    },

    sendSortUpdate: function(){
      var url = "/portals/update_positions";

      var request = new Ajax.Request(url, {
        method: "post",
        parameters: this.serialize(this.parameters)
      });

      this.parameters = {columns: [], column_ids: []};
    }
  
    //sortingChange: function(column){
    //  this.syncColumns();
    //  var url = "/portals/update_positions",
    //      parameters = Sortable.serialize(column.id) + 
    //                      "&col_number=" + column.id.replace("col_", "") +
    //                      "&page_title=" + this.page_title;
    //                      //"&authenticity_token=" + csrf_token;

    //  var request = new Ajax.Request(url, {
    //    method: "post",
    //    parameters: parameters
    //  });
    //}
  };


  document.observe("dom:loaded", function(){ 
    if($("portal")){ 
      Portal.initialize(); 
    } else {
      $$(".widget a.icon.delete").invoke("hide");
    }
  });
})();

