// JavaScript Document
(function($) {
 
    var plugin = Echo.createPlugin({
        "name": "ShowCharactersLeft",
        // plugin is written for the Submit application
        "applications": ["Submit"],
        "init": function(plugin, application) {
            // extend renderers and place some new HTML into template
            plugin.extendRenderer("Submit", "text", plugin.textRenderer);
            plugin.extendRenderer("Submit", "typedCharsCounter", plugin.typedCharsCounterRenderer);
            plugin.extendTemplate("Submit", plugin.counterTemplate, "insertAfter", "echo-submit-content");
            // create plugin specific variable typed with the value 0
			var fieldlength = parseInt(application.config.get("characterLimit"));
			if (isNaN(fieldlength)) fieldlength = 5000;
            plugin.set(application, "typed", fieldlength + plugin.label("charactersLeft"));
        }
    });
 
    plugin.addLabels({
        "numCharsTyped": "Number of characters typed: ",
		"charactersLeft": " characters left",
		"characterLeft": " character left",
		"reachedLimit": "Character limit exceeded!"
    });
 

    // HTML which will be inserted to the template to add counter element
    plugin.counterTemplate =
        '<div class="echo-submit-textCounter echo-primaryFont">' +
            '<span class="echo-submit-typedCharsCounter"></span>' +
        '</div>';
 
    // extend existing text renderer of the Submit application
    plugin.textRenderer = function(element, dom) {
        var application = this;
        // we should call existing renderer so as not to break things
        application.parentRenderer("text", arguments);
        // add onkeyup/onkeypress event handlers to count typed characters in real time
        element.bind("keyup keypress blur", function(event) {
			var fieldlength = parseInt(application.config.get("characterLimit"));
			if (isNaN(fieldlength)) fieldlength = 5000;
			var cleft = fieldlength - element.val().length;
			if (cleft < 0) {
				plugin.set(application, "typed", plugin.label("reachedLimit"));
				element.val(element.val().substring(0,(fieldlength - 1)));
			} else
				plugin.set(application, "typed", cleft + plugin.label((cleft == 1) ? "characterLeft" : "charactersLeft"));
            // counter was updated so we should update its appearance
        	application.rerender("typedCharsCounter");
        });
    };
	
    // add new typedCharsCounter renderer
    plugin.typedCharsCounterRenderer = function(element, dom) {
        var application = this;
        // just return plugin specific variable
        // (it will be inserted into HTML automatically)
        return plugin.get(application, "typed");
    };
 
})(jQuery);

