var toggler = Behavior.create({
    onclick: function(){
      var el = this.element; 
      Effect.toggle(el.next(), 'blind');
      el.toggleClassName('expanded');
    }
});

Event.addBehavior({
  '#monitor_submit': function() { this.hide(); },
  '#qod:click': function() { 
    this.up('form').getElements().select(function(el) { return /_qod_/.test(el.id); } ).invoke('toggleDisability'); 
  },
  'a.popup': function() { 
    this.writeAttribute('target', '_blank').writeAttribute('rel', 'external');
  },
  '.trigger': function() {
    this.next().hide();
    toggler.attach(this);
  },
  '.expanded': function() {
    this.addClassName('trigger');
    toggler.attach(this);
  },
  '.resizable': function(){
    new ResizingTextArea(this);
  }
});

// you must ensure that control status is in sync with this
Element.Methods.toggleDisability = function(el) { el.disabled = !el.disabled; }

// TODO: account for the margins of element el (have to strip "px" convert to integer)
function doPosition(el)
{
  var x = getCookie(el + "_x");
  var y = getCookie(el + "_y");
  if (x != "" && y != "") {
    x = x + "px";
    y = y + "px";
    Element.setStyle(el, {'left':x, 'top':y});
  }
}

function positionSaver(el) {
  positionSaver.prototype.onEnd = function () {
    document.cookie = $(el).id + "_y=" + $(el).offsetTop;
    document.cookie = $(el).id + "_x=" + $(el).offsetLeft;
  }
}

function getCookie(name) {
  var search = name + "="
  var return_value = "";
  if (document.cookie.length > 0) {
    var offset = document.cookie.indexOf(search)
    // if cookie exists
    if (offset != -1) { 
      offset += search.length
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1) end = document.cookie.length;
      return_value=unescape(document.cookie.substring(offset, end))
      }
   }
  return return_value;
}

// Peter-Paul Kock http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

var TopicForm = {
  editNewTitle: function(txtField) {
    $('new_topic').innerHTML = (txtField.value.length > 5) ? txtField.value : 'New Topic';
  }
}

var EditForm = {
  // show the form
  init: function(postId) {
    $('edit-post-' + postId + '_spinner').show();
    this.clearForm();
  },

  clearForm: function() {
    this.loadData('');
    $('post_body').fire('resizing:do');
  },
  
  loadData: function(post) {
    var fields = ['body', 'id', 'user_id'];
    // TODO: handle QOD
    //var qod_fields = ['qod_l1', 'qod_l2', 'qod_l3']; 
    //// Add QOD fields to them iff QOD is true
    //if(data != '' && post['qod_id'] != null) {
    //  // QUESTION: can Event.addBehaviour handle multiple events, of which one is a custom event? Then we could fire a checked to handle toggling
    //  $('qod').checked = true;
    //  $('qod').up('form').getElements().select(function(el) { return /_qod_/.test(el.id); } ).each(function(el) { el.disabled = false; });
    //  fields.concat(qod_fields);
    //} else {
    //  console.log("here");
    //  $('qod').checked = false;
    //  console.log("here");
    //  $('qod').up('form').getElements().select(function(el) { return /_qod_/.test(el.id); } ).each(function(el) { el.disabled = true; });
    //}
    fields.each(function(name){
      var el = $('post_' + name);
      el.value = post == '' ? post : post[name];
    });
  },
  
  currentPostId: function() {
    return $('post_id').value;
  },
  
  isEditing: function(postId) {
    return (this.currentPostId() == postId.toString());
  },
  
  startEditing: function(escapedUrl) {
    url = escapedUrl.unescapeHTML();
    this.ajaxSubmit = Event.observe('post_form', 'submit', function(e) {
      new Ajax.Request(url, {
        method: 'put', 
        asynchronous: true, 
        parameters: Form.serialize(this)
      });
      Event.stop(e);
    });
  },
  
  stopEditing: function(){
    Event.stopObserving('post_form', 'submit', this.ajaxSubmit);
  },
  
  edit: function(post, url) {
    this.loadData(post); 
    this.startEditing(url);
    setTimeout(function(){
        // Chaining's a bit broken with these fellas
        $('post_body').fire('resizing:do');
        new Effect.ScrollTo('post_body', {offset: -100 });
        $('post_body').focus();
        new Effect.Highlight('post_body', {queue: 'end' });
    }, 250);
  },

  cancel: function(e) {
    var post_id = this.currentPostId();
    if(post_id != '') {
      this.stopEditing();
      setTimeout(function(){
        new Effect.ScrollTo('post-body-' + post_id, {offset: -30 });
      }, 250);
    }
    this.clearForm();
  }
}

var ResizingTextArea = Class.create();
ResizingTextArea.prototype = {
    defaultRows: 8,

    initialize: function(field)
    {
        this.defaultRows = Math.max(field.rows, 1);
        this.resizeNeeded = this.resizeNeeded.bindAsEventListener(this);
        Event.observe(field, "click", this.resizeNeeded);
        Event.observe(field, "keyup", this.resizeNeeded);
        Event.observe(field, "resizing:do", this.resizeNeeded);
    },

    resizeNeeded: function(event)
    {
        var t = Event.element(event);
        var lines = t.value.split('\n');
        var newRows = lines.length + 1;
        var oldRows = t.rows;
        for (var i = 0; i < lines.length; i++)
        {
            var line = lines[i];
            if (line.length >= t.cols) newRows += Math.floor(line.length / t.cols);
        }
        if (newRows > t.rows) t.rows = newRows;
        if (newRows < t.rows) t.rows = Math.max(this.defaultRows, newRows);
    }
}
Element.addMethods();
