var msgHandler;
Event.observe(window, 'load', function() {
    
    messageHandler = new FlashMsg();


    // listen for input fields that have dummy text
    var formhelpers = new FormHelpers();
    fieldDummyText = new Array(
    		'ThingSearch',
    		'ThingTitleLike',
    		'ThingTitleDiss',
    		'InvitationEmailQuick'
	);
    for(var i=0; i<fieldDummyText.length; i++) {
	    if($(fieldDummyText[i])) {
	        formhelpers.actionBoxSetValue(fieldDummyText[i]);
	        Event.observe(fieldDummyText[i], 'focus', function(e){formhelpers.actionBoxUpdate(e)});
	        Event.observe(fieldDummyText[i], 'blur', function(e){formhelpers.actionBoxUpdate(e)});
	    }
    }
});

var Likediss = Class.create();
Likediss.Util = {

	generateId: function(prefix) {
		var unique_id = false;
		while (!unique_id) {
			var id = prefix + '_' + Math.floor(Math.random() * Math.pow(10,10));
			if (!$(id)) {
				unique_id = true;
			}
		}
		return id;
	}
}


var FlashMsg = Class.create();
FlashMsg.prototype = {

	containerId: 'flashMessage',

    initialize: function() {
        // create msg box if not there
		if(!($(this.containerId))) {
			Element.insert($('masthead'),{after:'<div id="'+this.containerId+'" class="message" style="display:none;"> </div>'});
		}

		// Hide server rendered message box after a while?
		// this.timer();
    },
	
	show: function(msg) {
		this.timer(this);

    	$(this.containerId).innerHTML = msg;

    	if(!Element.visible(this.containerId)) {
	    	Effect.Appear(this.containerId, { duration:0.5});
    	}
		else {
            this.highlight();
    	}
	},
	
	hide: function() {
		Effect.Fade(this.containerId);
	},

	highlight: function() {
    	new Effect.Highlight(this.containerId, { duration:1.5,startcolor:'#ffd000'});
	},

	timer: function() {
	    var self = this;
		if (this.t) {
			window.clearTimeout(this.t);
		}
		this.t = window.setTimeout(function() {self.hide();},10000);
	}
}
/**
 * Ajax editor for for tags, comments etc.
 * 
 */
Likediss.Editor = Class.create();
Likediss.Editor.prototype = {

    /** 
     * Constructor
     * 
	 * @param  activator_id    Id for the element that trigggers the editor
	 * @param  submitor_id     Id for submit element
	 * @param  cancelator_id   Id for cancel element
	 * @param  url             Url to send XHR to
	 * @param  editor_id       Id for the form
	 * @param  input_field     Id for the input field
	 * @param  update_block    Id for block to render new tags to
	 * @param  temp_id_holder  Id for hidden form controller that holds the temp_id
	 * 
     */
    initialize: function(activator_id, submitor_id, cancelator_id, url, editor_id, input_field_id,
                update_block_id, temp_id_holder_id, insertBefore) {
    	this.activator = $(activator_id);
    	this.submitor = $(submitor_id);
    	this.cancelator = $(cancelator_id);
    	this.url = url;
    	this.editor = $(editor_id);
    	this.input_field = $(input_field_id);
    	this.update_block_id = update_block_id;
    	this.temp_id_holder = $(temp_id_holder_id);
    	this.insertBefore = insertBefore;
    	
    	this.temp_id = Likediss.Util.generateId('id');

    	this.disableEditor();
    	var main = this;

        Event.observe(this.activator, 'click', function(e){main.activateEditor();Event.stop(e);});
        Event.observe(this.cancelator, 'click', function(e){main.disableEditor();Event.stop(e);});
		Event.observe(this.editor, 'submit', function(e) {main.submit(e);return false;});
		Event.observe(this.submitor, 'click', function(e) {main.submit(e);Event.stop(e);});
		
    	this.temp_id_holder.setAttribute('value', this.temp_id);

	},
	
	/**
	 * Submit new comment with XHR
	 * 
	 */
	submit: function() {
    	var main = this;
       
		new Ajax.Request(this.url, {
			asynchronous:true, 
			evalScripts:true, 
			method: 'post',
			onSuccess: function(transport) {
				main.updatePage(transport);
				main.finished();
			},
			onFailure: function() {
				alert('Oops, something bad happend.');
				main.finished();
			},
			onLoading: function(request){
				main.loading();
			}, 
			parameters: $(main.editor).serialize(true)
			
		});
	},
	

    /**
     * Update comments with new from response
     * 
     * param new_tags HTMLObject New tags ready to render
     * 
     */
     updatePage: function(new_tags) {
         if (this.insertBefore) {
    		new Insertion.Before(this.insertBefore, new_tags.responseText);
         } else {
            $(this.update_block_id).cleanWhitespace();
    		new Insertion.Bottom(this.update_block_id, new_tags.responseText);
         }
     },
    
    /**
     * Call when waiting for XHR respons
     * 
     */
    loading: function() {
    	this.toggleFormFields(true);
		this.input_field.className = 'ajax_loading';
    },

    /**
     * Disable/enable form controls in the form
     * 
     * @param disabled boolean
     * 
     */
     toggleFormFields: function(dis) {

		var input_fields = this.editor.getElementsByTagName('input');
    	for(var i=0; i<input_fields.length; i++) {
    		input_fields[i].disabled = dis;
    	}
    	var textarea;
    	if (textarea = this.editor.getElementsByTagName('textarea')[0]) {
    	     textarea.disabled = dis;
    	}
    },

    /**
     * Call when XHR respons returned
     * 
     */
    finished: function() {
		this.input_field.className = '';
    	this.disableEditor();
    	this.toggleFormFields(false);
    	
    	if ($(this.temp_id)) {
	    	new Effect.Highlight(this.temp_id, {startcolor: '#fff060', duration: 2});
    	}
    },
    
    /**
     * Activate the comments editor
     */
    activateEditor: function() {
        
    	this.activator.toggle();
    	this.editor.toggle();
    	this.input_field.activate();

    	// Generate new id for next comment to add
    	// and set temp id to hidden input value to pass to controller
    	this.temp_id = Likediss.Util.generateId('id');
    	this.temp_id_holder.setAttribute('value', this.temp_id);
    	
    },

    /**
     * Disable the editor, call on cancel or after update action
     */
    disableEditor: function() {
    	this.activator.style.display = '';
    	this.editor.toggle();
    	this.editor.reset();
    }
}


var FormHelpers = Class.create();
FormHelpers.prototype = {

    initialize: function() {
        
    },

    actionBoxGetString: function(id) {
        switch (id) {
            case 'ThingSearch':
                defaultStr = 'Search for stuff';
                break;
            case 'ThingTitleLike':
                defaultStr = 'What do you like?';
                break;
            case 'ThingTitleDiss':
                defaultStr = 'What do you diss?';
                break;
            case 'InvitationEmailQuick':
                defaultStr = 'Enter email address';
                break;
        }
        return defaultStr;
    },

    actionBoxSetValue: function(id) {
        var defaultStr = this.actionBoxGetString(id);;
        $(id).value = defaultStr;
    },

    actionBoxUpdate: function(ev) {
        var el = '';
        if (ev.type == undefined) {
            el.id = ev;
            ev.type = 'load';
        } else {
            el = Event.element(ev);
        }
        
        var defaultStr = this.actionBoxGetString(el.id);;
 
        if (ev.type == 'blur') {
            if (el.value.length == 0) {
                el.className = 'no-text';
                el.value = defaultStr;
            }
        }

        if (ev.type == 'focus') {
            if (el.value == defaultStr) {
                el.value = '';
                el.className = 'text';
            }
        }
    }
}

var Voting = Class.create();
Voting = {

    vote: function(value, id, users_own_page) {

        if (value == 'like') {
            $('like_' + id).className = 'like active';
            $('diss_' + id).className = 'diss inactive';
            
            // Fade post-box if user diss on her own like list
            if (users_own_page == 'diss') {
                Effect.Fade($('comment_' + id));
            }
            
        } else {
            if (value == 'diss') {
                $('like_' + id).className = 'like inactive';
                $('diss_' + id).className = 'diss active';

                // Fade post-box if user likes on her own diss list
                if (users_own_page == 'like') {
                    Effect.Fade($('comment_' + id));
                }

            }
        }
    },
    waiting: function(id) {
        $(id).className = $(id).className + ' waiting';
        $(id).blur();
    }
}

var Follow = Class.create();
Follow = {

    waiting: function(id) {
        $(id).className = $(id).className + ' waiting';
        $(id).blur();
    },

    complete: function(update_field, reset_style, username) {

        $(reset_style).className = '';
        if ($(update_field).textContent.strip() == 'Unfollow') {
            messageHandler.show('You are now following ' + username + '.');
        } else {
            messageHandler.show('You are not following ' + username + ' anymore' + '.');
        }
    }
}

/**
 * Extend Script.aculo.us Ajax.InPlaceEditor object with cancel button
 */
Ajax.InPlaceEditor.prototype.__createForm = Ajax.InPlaceEditor.prototype.createForm;
Ajax.InPlaceEditor.prototype = Object.extend(Ajax.InPlaceEditor.prototype, {
    createForm: function() {
        var cancelButton = document.createElement("input");
        cancelButton.type = "button";
        cancelButton.value = 'Cancel';
        cancelButton.onclick = this.onclickCancel.bind(this);
        cancelButton.className = 'editor_ok_button';
        this.__createForm();
        this.form.appendChild(cancelButton);
    }
});

/**
 * Create a combination of an autocompleter and an inplaceeditor
 * 
 * @param {edit_field}     Id of the link/input field
 * @param suggest_list   Id of the suggest list container
 * @param url_suggest    Url for fetching suggestions
 * @param url_post       Url for posting the results
 * @return nothing
 * 
 */
var InPlaceEditor_AutoCompleter = Class.create();
InPlaceEditor_AutoCompleter = function(edit_field, suggest_list, url_suggest, url_post) {
	$(suggest_list).style.display = 'none';
    var editor = new Ajax.InPlaceEditor(edit_field, url_suggest, {
	    okButton: true,
	    submitOnBlur: false,
	    size: 40,
	    okText: 'Add',
	    cancelLink: false,
	    highlightcolor: '#FFFFFF',
        cancelButton: false,
	    callback: function(form,value) {
			return 'data[Tag][name]=' + escape(value);
		},
		onCreate: function() { $(edit_field).value = ''; }
	});
	Object.extend(editor, {
		_createEditField: editor.createEditField,
	    createEditField: function() {
		    this._createEditField();
		    new Ajax.Autocompleter(this.editField, suggest_list, url_post, {
                frequency:0.1
            });
		}
	});
}
