// TinyMCE RichEdit Widget for Scriptaculous from http://dev.rubyonrails.org/ticket/5263

Ajax.InPlaceRichEditor = Class.create();

Object.extend(Ajax.InPlaceRichEditor.prototype, Ajax.InPlaceEditor.prototype);
Object.extend(Ajax.InPlaceRichEditor.prototype,
{
    enterEditMode: function(evt)
    {

        if (this.saving) return;
        if (this.editing) return;


        this.editing = true;
        this.onEnterEditMode();

        if (this.options.externalControl)
        {
            Element.hide(this.options.externalControl);
        }

        Element.hide(this.element);
        this.createForm();
        this.element.parentNode.insertBefore(this.form, this.element);
        Field.scrollFreeActivate(this.editField);

        if (this.options.textarea)
        {

            tinyMCE.addMCEControl(this.editField, 'value');
        }

        // stop the event to avoid a page refresh in Safari
        if (evt)
        {
            Event.stop(evt);
        }
        return false;
    },
    onclickCancel: function()
    {
        if (this.options.textarea)
        {
            tinyMCE.removeMCEControl('value');
        }

        this.onComplete();
        this.leaveEditMode();
        return false;
    },
    // added by Serg N. Kalachev <serg@kalachev.ru>
    convertHTMLLineBreaks: function(text) { return text; }, // fix to save </p>
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    onSubmit: function()
    {
        // onLoading resets these so we need to save them away for the Ajax call
        var form = this.form;

        if (this.options.textarea)
        {
            var tinyVal = tinyMCE.getContent('value');

            if (tinyVal)
                this.editField.value = tinyVal;

            tinyMCE.removeMCEControl('value');
        }

        var value = this.editField.value;

        // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
        // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
        // to be displayed indefinitely
        this.onLoading();

        if (this.options.evalScripts)
        {
            new Ajax.Request(
                this.url, Object.extend(
                {
                    parameters: this.options.callback(form, value),
                    onComplete: this.onComplete.bind(this),
                    onFailure: this.onFailure.bind(this),
                    asynchronous:true,
                    evalScripts:true
                }, this.options.ajaxOptions));
        }
        else
        {
            new Ajax.Updater(
                {
                    success: this.element,
                    // don't update on failure (this could be an option)
                    failure: null
                },
                this.url, Object.extend(
                {
                    parameters: this.options.callback(form, value),
                    onComplete: this.onComplete.bind(this),
                    onFailure: this.onFailure.bind(this)
                }, this.options.ajaxOptions));
        }
        // stop the event to avoid a page refresh in Safari
        if (arguments.length > 1)
        {
            Event.stop(arguments[0]);
        }
        return false;
    }
});

//--------------------------------------------------------------------------------------------------------------
// original from http://dev.rubyonrails.org/ticket/5264
// modified by Serg N. Kalachev <serg@kalachev.ru>

Ajax.InPlaceCalendarEditor = Class.create();
Object.extend(Ajax.InPlaceCalendarEditor.prototype, Ajax.InPlaceEditor.prototype);
Object.extend(Ajax.InPlaceCalendarEditor.prototype,
{
	createSelectBox: function(collection, value)
	{
		var selectTag = document.createElement("select");

		collection.each(function(e, i)
		{
			optionTag = document.createElement("option");
			optionTag.value = (e instanceof Array) ? e[0] : e;

			var optionName = (e instanceof Array) ? e[1] : e;

			if (value == optionTag.value)
				optionTag.selected = true;

			optionTag.appendChild(document.createTextNode(optionName));
			selectTag.appendChild(optionTag);
		}.bind(this));

		return selectTag;
	},
	createCheckBox: function(value)
	{
		var labelTag = document.createElement("label");

		checkTag = document.createElement("input");
		checkTag.type = "checkbox";
		checkTag.id = "valueCheck";
		if( value )	checkTag.checked = 'checked';
		labelTag.appendChild(checkTag);
		labelTag.appendChild(document.createTextNode(this.options.publishedText));

		return labelTag;
	},
	createEditField: function()
	{
		if (!this.cached_Div)
		{
      var main_parts = this.options.value.split(' ');
			var parts = main_parts[0].split('-');
			var times = main_parts[1].split(':');
			var is_published = main_parts[2];

      var months = this.options.monthNames;

			var theDiv = document.createElement("div");

			var days = new Array();

			for (var i = 1; i <= 31; i++)
				days[days.length] = [(i < 10) ? '0' + i : i, i];

			theDiv.appendChild(this.createSelectBox(days, parts[2]));

			theDiv.appendChild(this.createSelectBox(months, parts[1]));

			var years = new Array();

			for (var i = this.options.start_year; i <= this.options.end_year; i++)
				years[years.length] = [(i < 10) ? '0' + i : i, i];

			theDiv.appendChild(this.createSelectBox(years, parts[0]));

			theDiv.appendChild(document.createElement("br"));

			var hours = new Array();
			for (var i = 0; i <= 23; i++)
				hours[hours.length] = [(i < 10) ? '0' + i : i, (i < 10) ? '0' + i : i];
			theDiv.appendChild(this.createSelectBox(hours, times[0]));

			var minutes = new Array();
			for (var i = 0; i <= 59; i++)
				minutes[minutes.length] = [(i < 10) ? '0' + i : i, (i < 10) ? '0' + i : i];
			theDiv.appendChild(this.createSelectBox(minutes, times[1]));
			theDiv.appendChild(this.createSelectBox(minutes, times[2]));

			theDiv.appendChild(document.createElement("br"));

      theDiv.appendChild(this.createCheckBox(parseInt(parseInt(is_published)) ? true : false));

			this.cached_Div = theDiv;
		}

		this.editField = this.cached_Div;

		if (this.options.loadTextURL)
			this.loadExternalText();

		this.form.appendChild(this.editField);

		this.options.callback = function(form, value)
		{
			return "value=" + encodeURIComponent(value);
		}
	},
	onSubmit: function()
	{
		// onLoading resets these so we need to save them away for the Ajax call
		var form = this.form;
//		var value = this.editField.value;

		var controls = this.editField.getElementsByTagName('select');

    var published = this.editField.getElementsByTagName('input')[0];
    
		var value = controls[2].value + '-' + controls[1].value + '-' + controls[0].value +
      ' ' + controls[3].value + ':' + controls[4].value + ':' + controls[5].value +
      ' ' + ( published.checked ? '1' : '0' );

		// do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
		// which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
		// to be displayed indefinitely
		this.onLoading();

		if (this.options.evalScripts)
		{
			new Ajax.Request(
				this.url, Object.extend(
				{
					parameters: this.options.callback(form, value),
					onComplete: this.onComplete.bind(this),
					onFailure: this.onFailure.bind(this),
					asynchronous:true,
					evalScripts:true
				}, this.options.ajaxOptions));
		}
		else
		{
			new Ajax.Updater(
				{
					success: this.element,
				// don't update on failure (this could be an option)
					failure: null
				}, this.url, Object.extend(
				{
					parameters: this.options.callback(form, value),
					onComplete: this.onComplete.bind(this),
					onFailure: this.onFailure.bind(this)
				}, this.options.ajaxOptions));
		}
		// stop the event to avoid a page refresh in Safari
		if (arguments.length > 1)
		{
			Event.stop(arguments[0]);
		}

		return false;
	}
});

//--------------------------------------------------------------------------------------------------------------
// Ajax.InPlaceCategoryEditor
// Serg N. Kalachev <serg@kalachev.ru>

Element.addAutocompleter = function (field,upd,url) {
  setTimeout(function()
  {
    new Ajax.Autocompleter(field, upd, url, {});
  }, 3);
}

Ajax.InPlaceCategoryEditor = Class.create();
Object.extend(Ajax.InPlaceCategoryEditor.prototype, Ajax.InPlaceEditor.prototype);
Object.extend(Ajax.InPlaceCategoryEditor.prototype,
{
  createForm: function() {
    this.form = document.createElement("form");
    this.form.id = this.options.formId;
    Element.addClassName(this.form, this.options.formClassName)
    this.form.onsubmit = this.onSubmit.bind(this);

    this.createEditField();

    var div = document.createElement("div")
    div.id = 'auto-category';
    div.className = 'auto_complete';
    div.style.display = 'none';
    this.form.appendChild(div);
    this.form.appendChild(document.createElement("br"));
    this.form.appendChild(this.createCheckBox(false));
    this.form.appendChild(document.createElement("br"));

    if (this.options.okButton) {
      okButton = document.createElement("input");
      okButton.type = "submit";
      okButton.value = this.options.okText;
      okButton.className = 'editor_ok_button';
      this.form.appendChild(okButton);
    }

    if (this.options.cancelLink) {
      cancelLink = document.createElement("a");
      cancelLink.href = "#";
      cancelLink.appendChild(document.createTextNode(this.options.cancelText));
      cancelLink.onclick = this.onclickCancel.bind(this);
      cancelLink.className = 'editor_cancel';
      this.form.appendChild(cancelLink);
    }
    
    this.editField.autocomplete = 'on';
    Element.addAutocompleter( this.editField, 'auto-category', this.options.fecthUrl )
  },
	createCheckBox: function(value)
	{
		var labelTag = document.createElement("label");

		checkTag = document.createElement("input");
		checkTag.type = "checkbox";
		checkTag.id = "rename-check";
		if( value )	checkTag.checked = 'checked';
		labelTag.appendChild(checkTag);
		labelTag.appendChild(document.createTextNode(this.options.renameText));

		return labelTag;
	},
  onSubmit: function() {
    // onLoading resets these so we need to save them away for the Ajax call
    var form = this.form;
    var value = this.editField.value;
    var rename = form.getElementsByTagName('input')[1];

    if( $('rename-check').checked )
    {
      value = '>>>' + value;
      this.editField.value = value;
    }

    // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
    // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
    // to be displayed indefinitely
    this.onLoading();

    if (this.options.evalScripts) {
      new Ajax.Request(
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this),
          asynchronous:true,
          evalScripts:true
        }, this.options.ajaxOptions));
    } else  {
      new Ajax.Updater(
        { success: this.element,
          // don't update on failure (this could be an option)
          failure: null },
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this)
        }, this.options.ajaxOptions));
    }
    // stop the event to avoid a page refresh in Safari
    if (arguments.length > 1) {
      Event.stop(arguments[0]);
    }
    return false;
  }
});

