function toToggle(divId, hrefId, labelOpen, labelClose ){
 
  var d = document.getElementById(divId);
  var l = document.getElementById(hrefId);
  if( d.style.display == 'none' ) {
    d.style.display = 'block';
    l.innerHTML = labelClose;
  }else{
    d.style.display = 'none';
    l.innerHTML = labelOpen;
  }

}

function count_words(text) {
    var count = 0;
    
    text = text.replace(/<br \/>/ig, " "); // kind of ugly, but it works
    text = text.replace(/(<([^>]+)>)/ig, ""); // kind of ugly, but it works
    
    var str = text.replace(/\s+/g, ' '); // replace all whitespace with single space
    str = str.replace(/\s+$/g, ''); // replace all whitespace with single space
    str = str.split(' '); // split on single spaces
    count = str.length;
    if( str[0].length <= 0) { count--; } 
    return count;
}

var allEditor = new Array();

function registerEditor( editor ) {

	var limit     = 500;
    if( document.getElementById("max_" + editor.name) ) {
       limit     = document.getElementById("max_" + editor.name).value;
    }
    word_count( editor.getData(), editor.name );
    
	editor.on( 'key', function( evt ){
   		word_count( evt.editor.getData(), editor.name );
	}, editor.element.$ );
	
	allEditor[allEditor.length] = editor;

}


function word_count(xhtml, elname) {

    var count     = count_words(xhtml);
    var count_obj =  document.getElementById("count_" + elname);
    var limit     = 500;
    if( document.getElementById("max_" + elname) ) {
     limit     = document.getElementById("max_" + elname).value;
    }

    var color = 'blue';
    if (count > limit) { 
        color = "red";
    }

    var count_msg = "You have used <span style='color:"+color+";font-weight:bold'>" + count + "</span> of <strong>" + limit + "</strong>";
    if( count_obj ) {
      count_obj.innerHTML = count_msg; // update live counter on the page
    }

    return count;
}

function doWordCountEnforce(editorInstance) {
    if( document.getElementById("max_" + editorInstance.name) ) {
 	   var count = word_count(editorInstance.getData());
	   var limit  = document.getElementById("max_" + editorInstance.name).value;
	   var error_msg = "You have exceeded the " + limit + " word limit.\nPlease revise your response.\n";
	   if (count > limit) {
  	         alert(error_msg);
        	   return false;
	   }
     }
     return true;
}

function doSave() {

	for(i=0; i < allEditor.length; i++ ){
	    if( !doWordCountEnforce(allEditor[i]) ) {
	       return false;
	    }
	}
    return true;
}


