/*
   SiteComponents version:
   Id: offensivecomment.js,v 1.6 2009/03/27 07:54:02 kurt Exp 
   Name: SC_6_6_0 
   
   Disclaimer
   
   While we make every effort to ensure that this code is fit for its intended
   purpose, we make no guarantees as to its functionality. CoreTrek AS will
   accept no responsibility for the loss of data or any other damage or
   financial loss caused by use of this code.
   
   Copyright
   
   This programming code is copyright of CoreTrek AS. Permission to run this
   code is given to approved users of CoreTrek's publishing system CorePublish.
   
   This source code may not be copied, modified or otherwise repurposed for use
   by a third party without the written permission of CoreTrek AS.
   
   Contact webmaster@coretrek.com for information.
  
*/

/*

    ============================================================================
    IMPORTANT! This javascript is dependent on Prototype. If Scriptaculous is
               available the tooltip will use some nice effects.
    ============================================================================

    JavaScript enhancements for offensive comment link
    
*/

var OffensiveComment = Class.create({

    /**
     * Constructor rewrites the HTML to Ajax style
     */
    rewriteButtonToLink: function(element) {
        this.element = element;

        var form = element.down();

        this.ajaxifyForm(form);

        var button = element.select("button").first();

        this.link = element.update('<a href="#offensive">' + button.firstChild.nodeValue + '</a>').down();
        this.link.observe('click', this.submitListener.bindAsEventListener(this));
    },

    ajaxifyForm: function(form) {
        this.parameters = form.serialize();
        this.serviceUrl = form.readAttribute('action');

        this.tagOffensiveConfirmText = form.select("input[name=tag_offensive_confirm]")[0].value;
        this.taggedOffensiveText = form.select("input[name=tagged_offensive]")[0].value;

        this.button = form.select("button").first();
        this.button.observe('click', this.submitListener.bindAsEventListener(this));
    },

    // ========================================================================
    // Event listeners

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

        if(confirm(this.tagOffensiveConfirmText)) {
	        new Ajax.Request(this.serviceUrl, {
	            parameters: this.parameters,
	            onSuccess: this.successListener.bindAsEventListener(this)
	        });
        }
    },

    successListener: function(event) {
        if(typeof this.button == 'undefined') {
	        var updatedElement = this.element.update('<span>(' + this.taggedOffensiveText + ')</span>').down();

	        try {
	            new Effect.Highlight(updatedElement);
	        } catch (err) {
	            // Scriptaculous is not available, just ignore..
	        }
	    } else {
            this.button.disabled = true;
	    }
    }

})
