/**
 * @version		$Id: comments.js 716 2010-06-25 21:43:03Z robs $
 * @package		JXtended.Comments
 * @subpackage	com_comments
 * @copyright	Copyright (C) 2008 - 2010 JXtended, LLC. All rights reserved.
 * @license		GNU General Public License <http://www.gnu.org/copyleft/gpl.html>
 * @link		http://jxtended.com
 */

/**
 * JXtended Comments behavior class
 *
 * @package		JXtended.Comments
 * @subpackage	JavaScript
 * @version		1.0
 */
var JXComments = new Class({

	getOptions: function(){
		return {};
	},

	initialize: function(options) {
		// handle the options
		this.setOptions(this.getOptions(), options);
		if (this.options.initialize) this.options.initialize.call(this);
        
		this.respondTrigger = $E('#leave-response a');
		if ($chk(this.respondTrigger)) {
			this.respondTrigger.addEvent('click', function(e){
				// prevent the click event
				new Event(e).stop();

				// evaluate a JSON object in the rel attribute
				data = Json.evaluate(this.rel.match(/{[^}]*}/)[0]);
				Comments.getform(data);
			});
		} else {
			if ($chk($('respond-form'))) {
				this.decorateform();
			}
		}
    },
    
	getcomments: function() {
		
	},
    
	getform: function(data) {
		
		// Check if the form has been loaded.
		if ($chk(this.formSlide)) {
			// Form already exists, show it.
			this.formSlide.toggle();
			return true;
		}

		// Load the form via AJAX.
		var url	= data.base+'index.php?option=com_comments&task=comment.getForm&protocol=ajax&thread_id='+data.thread_id;
		var request	= new Ajax(url, { method: 'get', update: $('respond-container'), onComplete: function(r){
			if ($chk($('respond-form'))) {
				this.decorateform();
			}
		}.bind(this) }).request();
	},
    
    decorateform: function() {
		this.formContainer = $('respond-container');
		this.formSlide = new Fx.Slide(this.formContainer);
		this.form = $('respond-form');

		// Convert the action to a JSON request.		
		var query	= 'protocol=json&tmpl=component&format=raw';
		var action	= this.form.getProperty('action');
		this.form.setProperty('action', action.contains('?') ? action+'&'+query : action+'?'+query);

		refresher = $E('a.captcha-image-refresh', this.form);
		if ($chk(refresher)) {
			refresher.addEvent('click', function(e){
				// prevent the click event
				new Event(e).stop();
				Comments.refreshcaptcha();
			});
		}

		// handle reCAPTCHA if it is available
		if ((window.Recaptcha != undefined)) {
			Recaptcha.create(cOptions.reCaptchaPubKey,
			'recaptchaContainer', {
			   theme: 'clean'
			});
		}

		// create a new JXHighlighter if the class exists
		if ((window.JXBBCodeEditor != undefined)) {
			new JXBBCodeEditor();
		}

		// create a new postEditor if the class exists
		if ((window.postEditor != undefined)) {
			new postEditor.create('comment_body', 'captcha', postlanguage.DEFAULT);
		}

		// handle the onsubmit event
		this.form.addEvent('submit', function(e) {
			// prevent the submit event
			new Event(e).stop();
	
			// handle form validation
			var valid = document.formvalidator.isValid(this);
			if (valid == false) {
				// do field validation
				if (this.name && this.name.hasClass('invalid')) {
					alert(JXLang.INVALID_NAME_TXT);
				} else if (this.email && this.email.hasClass('invalid')) {
					alert(JXLang.INVALID_EMAIL_TXT);
				} else if (this.body.hasClass('invalid')) {
					alert(JXLang.INVALID_BODY_TXT);
				}
				return false;
			}

			// This empties the log and shows the spinning indicator
			var log = $('respond-container').addClass('ajax-loading');

			// send takes care of encoding and returns the Ajax instance.
			// onComplete removes the spinner from the log.
			this.send({
				onComplete: function(responseText) {
					log.removeClass('ajax-loading');

					response = Json.evaluate(responseText);
					
					replaceTokens(response.token);
					
					if (response.error == true) {
						alert(response.message);
					} else {
						// Get the current number of comments
						n = $('commentlist').getElements('li').length;

						comment = new Element('li').setProperty('id', 'comment-'+response.id);
						comment.addClass('comment');

						// Check if the comment goes at the top or the bottom.
						if (response.position == 'top') {
							// Set the comment row class.
							if ($chk($('commentlist').getFirst())) {
								comment.addClass($('commentlist').getFirst().hasClass('odd') ? 'even' : 'odd');
							} else {
								comment.addClass('odd');
							}
	
							// Build up your comment list element's body
							comment.setHTML(response.body);
							
							// Add the comment to the list.
							comment.injectTop($('commentlist'));
						}
						else {
							// Set the comment row class.
							comment.addClass(((n % 2) == 0) ? 'odd' : 'even');
	
							// Build up your comment list element's body
							comment.setHTML(response.body);
							
							// Add the comment to the list.
							comment.injectInside($('commentlist'));
						}

						// Clear out the form
						$('respond-form').reset();

						// Also, we need to refresh the captcha stuff
						Comments.refreshcaptcha();

						// Show the comment.
						comment.setOpacity(0);
						new Fx.Style(comment, 'opacity', {duration: 1500}).start(0,1);

						// Increase the number of comments
						$('comments-num').setHTML(response.num_text);
					}
				},
				
				onFailure: function(x) {
					// Remove the loading graphic.
					log.removeClass('ajax-loading');
					
					// Decode the JSON response.
					r = Json.evaluate(x.responseText);
					replaceTokens(r.token);
					alert(r.message);
				}
			});
		});

	},
    
	refreshcaptcha: function() {
		if (window.Recaptcha != undefined) {
			Recaptcha.reload();
		} else if (window.cOptions != undefined && cOptions.captcha) {
			img = $E('img.captcha-image', this.form);
			img.src = img.src+'#';
		}
	},
    
	submit: function() {
		
	}
});
	
// bind the Events and Options objects to the JXHighlighter class
JXComments.implement(new Events);
JXComments.implement(new Options);

function replaceTokens(n)
{
	$(document).getElements('input').each(function(e){
		if (e.getProperty('name') && e.getProperty('name').length == 32 && e.getProperty('value') == '1' && e.getProperty('type') == 'hidden') {
			e.setProperty('name', n);
		}
	});
}

window.addEvent('domready', function(){
	Comments = new JXComments();
});
