/*
Класс для подсчета количества слов в texarea
для пользования:
1) на странице где испоьзуется создать обьект классса
   в конструктор обьекта передаютмя параметры сразу
   Пример:
   var Qwords = new wordClass("question","CountQWords","FreeQWords",21);
   где:
   "question" - Id текстрарии
   "CountQWords" - ID span, в кторый будет выводится количество введенных слов, если не нужен то null
   "FreeQWords" - ID span, в кторый будет выводится количество оставшихся слов, если не нужен то null
   21 - максимально допустимое количество слов
3)юзать)))
*/
function wordClass(inputId,countSpanId,remainderSpanId,maxWords,dontBlock)
{
  this.input = document.getElementById(inputId);
  this.countSpan = document.getElementById(countSpanId);
  this.remainderSpan = document.getElementById(remainderSpanId);
  this.dontBlock = dontBlock;
  
  $(this.input).keyup(
  
    function (q){return function(){q.calculateWords()}} (this)
    );
    if(maxWords)
      this.maxWords = maxWords;
    else 
      this.maxWords = 1000;
  this.countWords = 0;
  this.curText = "";
}



wordClass.prototype.trim = function(str)
{
  return this.ltrim(this.rtrim(str));
}

wordClass.prototype.rtrim = function(str)
{
  return str.replace(new RegExp("[\\s\\n]+$", "g"), "");
}

wordClass.prototype.ltrim = function(str)
{
	return str.replace(new RegExp("^[\\s\\n]+", "g"), "");
}


wordClass.prototype.calculateWords = function()
{
  if (this.input!=null)
  {
  
    if(this.dontBlock!=null && this.dontBlock!=0)
      this.dontBlock = 1;
    else
      this.dontBlock = 0;
      
    var text = this.input.value;
    
    
    var carPos;
    try { 
      carPos = this.getCaretPos(this.input);
    } catch(e) {
      carPos = 0;
    }
    
    //var carPos = this.getCaretPos(this.input);
    
    text = this.trim(text);
    if(text.length)
    {
      var z=0;
      if(this.countWords != this.getCountWords(this.input,0))
      {
        if(this.onChange)
          this.onChange();
      }
      
      
      this.countWords = this.getCountWords(this.input,0);
  
      if(this.countWords>this.maxWords && !this.dontBlock)
      {
        if(this.trim(this.curText))
          this.input.value = this.curText;
        this.countWords = this.getCountWords(this.input,0);
        
        if (this.input.ownerDocument.selection) //ie
          var r = this.input.createTextRange();
        else
          this.input.setSelectionRange(carPos,carPos-1);
      }
      else
        this.curText = text;
    }else
      this.countWords = 0;
      
    if(this.countSpan!=null)
     this.countSpan.innerHTML = this.countWords;
  
    if(this.remainderSpan!=null  )
      this.remainderSpan.innerHTML = (this.maxWords - this.countWords);
  }
}

wordClass.prototype.getCaretPos =  function(obj)
{
  obj.focus();
  if(obj.selectionStart) return obj.selectionStart;//Gecko
  else if (document.selection)//IE
  {
    var sel = document.selection.createRange();
    var clone = sel.duplicate();
    sel.collapse(true);
    clone.moveToElementText(obj);
    clone.setEndPoint('EndToEnd', sel);
    return clone.text.length;
  }
  return 0;
}

wordClass.prototype.getCountWords =  function(input,word)
{
  sText = this.trim(input.value);
  var aWords = sText.split(/\s+/);
  var iWordsCount = aWords.length
  if( (iWordsCount == 1) && (aWords[0] == '') ) {
    iWordsCount = 0;      
  }
    if(word!=null && word == 0)
     return iWordsCount;
    else
     return iWordsCount + ' words';
}