var RS = RS || {};

RS.word_count_fields = [];

RS.init_word_counter = function(counter, field, limit_type, limit, count_type) {
	var
		error,
		direction = arguments[4] || (limit_type == 'max' ? 'down' : 'up');
		count_type = count_type || 'words'
	
	counter = $(counter);
	field = $(field);
	
	var get_count = function(body) {
	  var count = count_type == 'words' ? RS.count_words(body) : body.length;
	  
	  if (limit_type == 'max') {
	    var count_max = limit - count;
	    if (count_max < 0) {
        field.addClass('word-count-over');
        error = true;
	    }
	    else if (error) {
      	field.removeClass('word-count-over');
      	error = false;
      }
	  }
	  
	  return count;
	}
	
  var non_fck_count = function() {
  	if (field.is('.default-text-js.gray')) {
  		counter.html('0');
  	}
  	else {
			counter.html(get_count(field.val()));
  	}
	}
	
	RS.word_count_fields.push({ field: field, counter: counter, get_count: get_count });
	field.keyup(non_fck_count).trigger('keyup');
}

RS.count_words = function(text) {
	if (RS.fck_enabled) {
		text = text.replace(/<[^<]+>/g, ' ');
	}
	
	text = $.trim(text);
	
	if (text.length) {
		return text.replace(/\s+/g, ' ').split(' ').length;
	}
	return 0;
}

function wc_FCKeditor_OnComplete(instance) {
	RS.fck_enabled = true;
	
	$(RS.word_count_fields).each(function() {
		var obj = this;
		if (typeof obj != 'function' && 'edit-' + obj.field.attr('name') == instance.Name) {
			obj.field.addClass('word_counter_fck').unbind('keyup');
			
			instance.Events.AttachEvent('OnSelectionChange', function() {
			  obj.counter.html(obj.get_count(instance.EditorDocument.body.innerHTML));
			});
		}
	});
	
	if (typeof fck_FCKeditor_OnComplete == 'function') {
	  fck_FCKeditor_OnComplete(instance);
	}
}