(function($) {

    jQuery.fn.fundometer = function(options) {
        // Set the options.
        options = jQuery.extend({}, jQuery.fn.fundometer.defaults, options);

        // Go through the matched elements and return the jQuery object.
        return this.each(function() {
            var o = options;
            // Add class fundometer to the main div
            $(this).addClass('fundometer')
                .append("<div class='value'></div>")
                .append("<div class='objective'></div>");
            // Add the image
            $('<img>')
                .attr('src', o.maskImage)
                .appendTo($(this));
            // Place the objective
            var temp = getHeight($(this));
            var percentHeight = temp[1];
            bottomObjective = percentHeight + temp[0];
           
            $(this).find('div.objective').css('bottom', bottomObjective + 'px');
            // Set the value
            _setValue($(this), o.rateValue);
            
        });
    };

    // Public defaults values
    $.fn.fundometer.defaults = {
        rateValue   : 0,                 // Rate value of the fundometer (per cent of the objective)
        //effect      : ["scale", "slow"],   // Effect when the value increment
        maskImage   : "/recykids/images/content/fund-frame.png"
        //hiddenField : "valueFundometer"
    };

    function getHeight(obj)
    {
            var totalHeight = parseInt(obj.css('height').replace(/px/, ''), 10);
            bottomValueString = obj.find('div.value').css('bottom').replace(/px/, '');
            bottomValueInt = parseInt(bottomValueString, 10);
            return [bottomValueInt, Math.ceil((totalHeight - bottomValueInt) * 0.75)];
    }
    
    // Private functions.
    /**
     * Set the value of the fundometer and animate it
     */
    function _setValue(obj, value) {
        obj.find("div.value").animate(
                                    {height : Math.ceil((getHeight(obj)[1] * value / 100) + 3) + "px"},
                                    "slow",
                                    "linear"
                                );
       // return value;
    };

    /**
    * Set the value of the fundometer and animate it
    */
    function _getValue(obj) {
        cssHeight = obj.find("div.value").css("height");
        value =  cssHeight.replace(/^\s\s*/, '').replace(/\s\s*$/, '').replace(/%/, '');
        return value;
    };

    // Public functions.

    $.fn.fundometer.setValue = function(fundometerElement, value) {
        _setValue(fundometerElement, value);
        return value;
    };


    $.fn.fundometer.getValue = function(fundometerElement) {
        return _getValue(fundometerElement);
    };

})(jQuery);
