function trim(str)
{ var start_pos=0;
  var end_pos=str.length;
  
  for(start_pos=0;start_pos<end_pos;start_pos++)
    if(str.charAt(start_pos)!=' ') break;
 
 
  for(end_pos=end_pos-1;end_pos>0;end_pos--)
    if(str.charAt(end_pos)!=' ') break;
  
  if((start_pos==str.length)&&(end_pos==0)) return "";
  
  return str.substring(start_pos, end_pos+1);
}

function space_count(str)
{ var sc=0;
  for(i=0;i<str.length;i++)
    { if(str.charAt(i)=='\r' && str.charAt(i)=='\n')
	  { sc++;
	    i++;
		continue;
	  }
	  if(str.charAt(i)==' ' || str.charAt(i)=='\n') sc++;
	}
  return sc;
}


function delete_spare_words(str)
{ str=trim(str);
  var space_count=0;
  for(last_space_pos=0;space_count!=word_count;)
  	{ if(str.charAt(last_space_pos)=='\r'&&str.charAt(last_space_pos+1)=='\n')
	  { space_count++;
	    last_space_pos=last_space_pos+2;
		continue;
	  }
	  if(str.charAt(last_space_pos)==' ' || str.charAt(last_space_pos)=='\n')
	  { space_count++;
	  }
	  last_space_pos++;
	}
  
  if(str.charAt(last_space_pos-1)=='\n'&&str.charAt(last_space_pos-2)=='\r') last_space_pos--;
  str=str.substring(0,last_space_pos-1);
  return str;
}

function wc()
{ 
  var form_content = document.getElementById('form_content');
  var sc=space_count(trim(form_content.value));
  if(sc==0) word_input=0;
  else word_input=sc+1;
	
  var word_remain=word_count-word_input;
  if(word_remain<0){ 
      form_content.value=delete_spare_words(document.getElementById('form_content').value);
  }
  else{ 
      document.getElementById('span_word_count_input').innerHTML=word_input;
  	  document.getElementById('span_word_count_remain').innerHTML=word_count-word_input;
  }
}
