/** reactor class **/

var reaction = function(selector) {
	this.target = selector;
  
	this.delegates = [];
	for(var f in this) {
		if (typeof(this[f]) == 'function')
			this.delegates[f] = this.createDelegate(this, this[f]);
	}
	
	$('#post-comments').css('min-height', $('.atom-body').height() + $('#comment-form').height());
}

reaction.prototype.createDelegate = function(target, handler) {
	var delegate = function() {
		return handler.apply(target, Array.prototype.slice.call(arguments));
	};

	return delegate;
};

reaction.prototype.react = function() {
	var o = jQuery.forms.toDataStructure( jQuery(this.target) );
	var parameters = JSON.stringify(o);

	jQuery.ajax({
		type: 'POST',
		url: '/api/crutils/react',
		data: { parameters: parameters },
		dataType: 'json',
		success: this.delegates.onReact,
		error: this.delegates.onError
	}); 
  
	return false;
};


reaction.prototype.onReact = function(result) {
	if(result.type == 1) {
    	jQuery(this.target).find('input [type=text]').val('');
    	jQuery(this.target).find('textarea').val('');
    
    	var display = jQuery(this.target).find('#reactions_errors');
    	display.css({color: 'green'});
    	display.html( heap.translate('reactions_success'));

    	setTimeout(function(){
			location.hash = "#post-comments";
			location.reload();
		},2500);
  	} else {
    	this.showErrors(result);
	}

	return false;
}

reaction.prototype.onError = function(result) {
	this.showErrors();
}

reaction.prototype.showErrors = function(result) {
  if(result && result.code == 'ERR_VALIDATION_FAILED') {
    var error_phrase = '';
    for(field in result.data) {
		var token = result.data[field];
		var errstr = heap.translate(token);
		var fieldname = heap.translate('validation_'+field);
		errstr = errstr.replace(/\%field/, fieldname);
		error_phrase += '<li>'+errstr+"</li>";
	}

    jQuery(this.target).find('#reactions_errors').html(error_phrase);
    
   	jQuery(this.target).find('#reactions_errors').fadeIn();    

	} else {
		jQuery(this.target).find('#reactions_errors').text(heap.translate('reactions_error'));
		jQuery(this.target).find('#reactions_errors').fadeIn();
	}
}

