<?php
/*
Plugin Name: Character Counter
Description: Add a character counter to textbox fields
Version: 1.00
Requires at least: 2.10
Author: The CMS Builder Cookbook
Author URI: http://thecmsbcookbook.com/
*/

// DON'T UPDATE ANYTHING BELOW THIS LINE

addAction('admin_head',       'charcounter_loadJavascriptPlugin', null, 0);
addFilter('edit_fieldSchema', 'charcounter_addFieldJavascript', null, 2);

//
function charcounter_loadJavascriptPlugin() {
  $skippedMenus = array('', 'admin');
  if (in_array(@$GLOBALS['menu'], $skippedMenus)) { return; }

  // get javascript plugin url
  list(,$jsUrl) = getPluginPathAndUrl('jquery_textarea_v2/jquery.textareaCounter.plugin.js');

  // get html
  ob_start();
  ?>
    <script src='<?php echo $jsUrl ?>' type='text/javascript'></script>
    <script type="text/javascript">
      // hide default div that gets added by the jquery plugin
      $(window).load(function(){ // use window.load instead of document.ready so we run this code _after_ .charleft is added by document.ready in above plugin
        $('.charleft').next('br').remove();
        $('.charleft').hide();
      });

      // function for updating textarea counters
      function updateTextareaCounter(data, fieldname) {
        if (data.max) { var output = sprintf("%s Characters | %s Characters Left | %s Words | Character Limit:%s", data.input, data.left, data.words, data.max); }
        else          { var output = sprintf("%s Characters | %s Words", data.input, data.words); }

        var jselector = '#' +fieldname+ '_textareaCounterOutput';
        $(jselector).text(output);
      }
    </script>
  <?php
  $html = ob_get_clean();

  //
  echo $html;
}

//
function charcounter_addFieldJavascript($fieldSchema, $tableName) {
  if (@$fieldSchema['type'] != 'textbox') { return $fieldSchema; }
  $fieldname = $fieldSchema['name'];

  // get javascript
  ob_start();
  ?>
    <script type="text/javascript">
      $(document).ready(function(){
        var jselector = '[name=<?php echo $fieldname ?>]';
        var options   = { 'maxCharacterSize': <?php echo intval(@$fieldSchema['maxLength']) ?>, 'displayFormat' : '' };
        var callback  = function(data){ updateTextareaCounter(data, '<?php echo $fieldname ?>') };
        $(jselector).textareaCount(options, callback);
      });
    </script>
  <?php
  $jsCode = ob_get_clean();

  // add javascript and output div to field description
  $outputDiv = "<div id='{$fieldname}_textareaCounterOutput' style='float: right; padding: 0px 10px;'></div>";
  $fieldSchema['description'] = $jsCode . $outputDiv . $fieldSchema['description'];

  //
  return $fieldSchema;
}


?>
