/*
 * 
 * Textarea Word Count Jquery Plugin 
 * Version 1.0
 * 
 * Copyright (c) 2008 Roshan Bhattarai
 * website : http://roshanbh.com.np
 * 
  * Added progressbar code
  * 2010 Gary Leeming
  *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
*/

jQuery.fn.wordCount = function (params) {
    var p = {
        counterElement: "display_count",
        maxWords: 300,
        progressBarElement: ""

    };
    var total_words = 0;

    if (params) {
        jQuery.extend(p, params);
    }

    //for each keypress function on text areas
    this.keypress(function () {
        doCalc(this);
    });

    //run this when started to set current word count
    //in case page refreshed
    doCalc(this);


    function doCalc(obj) {

        //total_words = $(obj).val().split(/[\s\.\?]+/).length;
        if ($(obj).val().length > 0) {
            //total_words = $(obj).val().split(/[\s\.\?]+/).length;
            total_words = $(obj).val().match(/[A-Za-z\'\-\d]+/g).length;
        } else {
            total_words = 0;
        }

        if (p.progressBarElement != "") {
            percentage = (total_words / p.maxWords) * 100;

            $('#' + p.progressBarElement).progressbar("option", "value", percentage);

            //Change colour of progress bar depending on whether complete or not
            $('#' + p.progressBarElement).addClass('progress-bar-empty');
            $('#' + p.progressBarElement).removeClass('ui-widget-content');
            $('#' + p.progressBarElement + ' div').removeClass('ui-widget-header');

            if (percentage >= 100) {
                $('#' + p.progressBarElement + ' div').removeClass("progress-bar-unfinished");
                $('#' + p.progressBarElement + ' div').addClass("progress-bar-finished");
            } else {
                $('#' + p.progressBarElement + ' div').addClass("progress-bar-unfinished");
                $('#' + p.progressBarElement + ' div').removeClass("progress-bar-finished");
            }
        }
        $('#' + p.counterElement).html(total_words);
    }
};

