// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// Console log debuggix fix for ie
// try { console.log('init console... done'); } catch(e) { console = { log: function() {} } }

var MessageForm = Class.create({

	//initialize: function(message, removable_link, focused, is_reply) {
	initialize: function(form_target, options, language) {
		/*this.options = options || { }*/
//		this.options = { is_public: false, is_reply: true, focused: false, target_id: false, target_insertion: 'before' }
		this.options = { type: 'new_msg', focused: false, target_id: false, target_insertion: 'before',
      removable_link: false, target_action: false }

    this.language = { reply: 'Kirjoita oma vastauksesi...', new_msg: 'Kirjoita uusi viesti...',
      priv: 'Näytä vain sisäänkirjautuneille', submit: 'L&auml;het&auml; viesti',
      email: 'Viesti s&auml;hk&ouml;postina joukkueelle',
      comment: 'Kirjoita kommenttisi', comment_submit: "Kommentoi"}

		Object.extend(this.options, options || { });
    Object.extend(this.language, language || { });

		//this.form_target = $(form_target);
    if(this.options.removable_link) {
      link = $(this.options.removable_link);
      link.hide();
      if (link.nodeName != 'A'){ link = link.select('A')[0]; }
      this.url = link.href
    }
    
    if(this.options.target_action){
//    } else {
      this.url = this.options.target_action
    }

    this.submit_text = this.language.submit
    switch (this.options.type) {
      case 'reply': this.label_text = this.language.reply; break;
      case 'new_msg': this.label_text = this.language.new_msg; break;
      case 'comment':
        this.label_text = this.language.comment;
        this.submit_text = this.language.comment_submit;
        break;
    }
		form_target = $(form_target)
		this.id_base = form_target.id
	
		this.text_area_blur_listener = this.text_area_blur.bindAsEventListener(this);
		this.reply_form = this.reply_form();
		form_target.insert({ 'bottom': this.reply_form });

		this.target = this.options.target_id || this.form_element;
		if (this.options.focused){
			this.text_area.focus();	this.text_area_focus();
			distance_from_bottom = document.viewport.getHeight()-(this.text_area.cumulativeOffset()[1]-document.viewport.getScrollOffsets()[1]);
			if (distance_from_bottom < 150){ // area distance from top
				Effect.ScrollTo(this.text_area, {offset: -300, duration: 0.5});
			}
		}
		this.update_location();

//		if (this.options.is_public) {	this.msg_public.checked = true } // ie6, needs after insert

	},

	form_input_disable: function(disabled){
		this.text_area.disabled = disabled;
		this.msg_email_input.disabled = disabled;
		this.button_send.disabled = disabled;
		this.ajax_indicator.style.display = ( disabled ? 'block' : 'none' );
//		if (this.options.is_reply) {this.msg_public = disabled; }
		if (this.options.type == 'reply') {this.msg_private = disabled; }
	},

	form_submit_success: function(){
		this.text_area.value = "";
//		this.form_input_disable(false);
		this.text_area_blur_manual();
	},

	form_submit_failure: function(){
		this.form_element.insert({'top' : "<div>Problem sending the message, try again.</div>"});
	},

	form_submit_complete: function(){
		this.form_input_disable(false);
	},

	form_submit_start: function(event){
		//new Ajax.Updater(this.form_element, this.url, {
		new Ajax.Updater(this.target, this.url, {
				asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form_element),
				onSuccess: this.form_submit_success.bindAsEventListener(this),
				onFailure: this.form_submit_failure.bindAsEventListener(this),
				onComplete:  this.form_submit_complete.bindAsEventListener(this),
				insertion: this.options.target_insertion} );
		this.form_input_disable(true);

		Event.stop(event); // Do not submit by traditional way
	},

	text_area_focus: function(){
		this.reply_form.addClassName('focused');
		new ResizingTextArea(this.text_area, {maxLength : 6000, emptyRows : 1});
		if(!this.document_observe){
			this.document_observe = true;
			document.observe('click', this.text_area_blur_listener);
		}
	},

	text_area_blur_manual: function(really_blur){
		if (this.text_area.value.empty()){
				this.reply_form.removeClassName('focused');
				this.text_area.rows = 1;
		}
		if (really_blur){	this.text_area.blur(); }
	},

	text_area_blur: function(event){
		if (!event.findElement('#'+this.form_element.id) && !event.findElement('a')){
			document.stopObserving('click', this.text_area_blur_listener);
			this.document_observe = false;
			this.text_area_blur_manual(true);
		}
	},

	update_location: function(){ // This is needed for ie
		left = this.text_area.positionedOffset()[0] + "px";
		//console.log("left: " + left);
		this.ajax_indicator.style.left = left;
		this.reply_label.style.left = left;
	},

	reply_form: function(){
//		css_class = 'clearfix message_form ajax' + (this.options.is_reply ? ' reply' : '');
		css_class = 'clearfix message_form ajax ' + this.options.type;
		this.form_element = new Element('form', { 'class': css_class, 'method' : 'post',
			'id' : (this.id_base+'_form')	});
		this.ajax_indicator = new Element('div', { 'class': 'indicator_ajax'}).update("Saving/Loading ...");
		this.text_area = new Element('textarea', {'id':(this.id_base+'_textarea'), 'cols':'70', 'rows':'2', 'name':'message[message]'});
		this.text_area.observe("focus", this.text_area_focus.bindAsEventListener(this));

		//this.text_area.observe("blur", this.text_area_blur.bindAsEventListener(this));
		text_area_holder = new Element('span').insert(this.text_area); // this is ie fix, form margin inherit bug
		this.reply_label = new Element('label', {'class':'overlabel_custom','for':this.text_area.id}
			).update(this.label_text);
//			).update((this.options.is_reply ? this.language.reply : this.language.new_msg));
			//).update((this.options.is_reply ? 'Kirjoita oma vastauksesi...' : 'Kirjoita uusi viesti...'));


    this.msg_email_input = new Element('input', {
			'id':(this.id_base+'_email'), 'name':'message[force_notify]', 'type':'checkbox', 'value':'true'});
		msg_email_input_label = new Element('label', {'class': 'email', 'for':this.msg_email_input.id}).
			update(' '+this.language.email).insert({'top' : this.msg_email_input});
		control = new Element('div', {'class':'control'}).insert(msg_email_input_label); 

//    control = new Element('div', {'class':'control'});

//		if (!this.options.is_reply) {
		if (this.options.type == 'new_msg' ) {
			this.msg_private_false = new Element('input', {'type':"hidden", 'value':"false", 'name':"message[private]"});
			this.msg_private = new Element('input', {
				'id':(this.id_base+'_private'), 'name':'message[private]', 'type':'checkbox', 'value':'true', 'checked':false});
				//'id':(this.id_base+'_public'), 'name':'message[public]', 'type':'checkbox', 'value':'true', 'checked':this.options.is_public});
			p_label = new Element('label', {'for':this.msg_private.id}).
				update(' '+this.language.priv).insert({'top' : this.msg_private}).insert({'top' : this.msg_private_false});
//				update(' Näytä vain sisäänkirjautuneille').insert({'top' : this.msg_private}).insert({'top' : this.msg_private_false});
			control.insert(p_label)
		}

		this.button_send = new Element('button', {'class':'submit','type':'submit'}).update(this.submit_text);
//		this.button_send = new Element('button', {'class':'submit','type':'submit'}).update('L&auml;het&auml; viesti'); //.update('Lähetä viesti');
		this.button_send.observe("click", this.form_submit_start.bindAsEventListener(this))
		control.insert(this.button_send);

		this.form_element.insert(this.ajax_indicator).insert(this.reply_label).insert(text_area_holder).insert(control);
		return this.form_element;
	}
});


// Automatically resizable textbox, prototype enabled
// usage <%= text_area_tag ..., :onFocus => "new ResizingTextArea(this);" %>
//var ResizingTextArea = Class.create();
// http://jasonmoser.com/ajax/
// http://jroller.com/rmcmahon/entry/resizingtextarea_with_prototype
// one better way is to create a hidden div with similar attributes set the div's
// contents to be the same as that of the textarea: http://www.maclife.com/forums/topic/104178

// Container for references to all those ResizingTextArea objects, removes double observings
var ResizingTextAreas = {
	list: [],
	includes: function(id){
		if ( id != null && this.list.indexOf(id) != -1 ){ return true; }
		return false;
	},
	add: function(id){ if (id!=null){this.list.push(id)} }
};

ResizingTextArea = Class.create({
	defaultRows: 1,
	initialize: function(field, options) {
		field = $(field)
		if (!ResizingTextAreas.includes(field.identify())){
			this.options = options || { };
			this.maxLength = parseInt(this.options.maxLength || '10000');
			this.maxRows = parseInt(this.options.maxRows || '25');
			this.emptyRows = parseInt(this.options.emptyRows || '1');

			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, "focus", this.resizeNeeded);

			this.resizeElement(field);
			ResizingTextAreas.add(field.identify());
		}
	},
	resizeNeeded: function(event){
		var t = Event.element(event);

		if (t.value.length > this.maxLength) { // check maxLength
			t.value = t.value.substring(0, this.maxLength);
		}// else {
		this.resizeElement(t)
		//}
	},
	resizeElement: function(t){
		var lines = t.value.split('\n');

		var newRows = lines.length + this.emptyRows; //1; // This tells how many empty rows there are
		for (var i = 0; i < lines.length; i++){ // check overlonge lines
			var line = lines[i];
			if (line.length >= t.cols){ newRows += Math.floor(line.length / t.cols); }
		}
		if(Prototype.Browser.IE){
			newRows += 1;
			newRows += Math.floor(newRows/5); // ie somehow needs more space
		}
		if (newRows > t.rows && newRows < this.maxRows) {	t.rows = newRows; }
		if (newRows < t.rows) {t.rows = Math.max(this.defaultRows, newRows); }
	}
});
