/**
 *
 *
 * Created by: Becklyn GmbH, Jannik Zschiesche <jz@becklyn.com>
 * Date: 20.07.2011
 * Time: 11:30 AM
 */


/**
 *
 * Configuration data values:
 *  # rowSelector: the jQuery selection string to the rows inside the $wrap
 *  # elementSelector: the jQuery selection string to the elements inside the rows
 *
 * @param configData object the configuration data.
 * @param $wrap jQuery the wrapping element
 * @class Height_Adjuster
 * @constructor
 * @constructs Height_Adjuster
 */
function Height_Adjuster (configData, $wrap)
{

    /**
     * The handler for the content block rows
     *
     * @type jQuery
     */
    var $rows = $wrap.find( configData.rowSelector );



    /**
     * Adjusts the height of all matched elements
     *
     * @type void
     */
    this.adjustHeightOfAllRows = function ()
    {
        if (!configDataIsValid())
        {
            return;
        }

        $rows.each(
            function (index, element) {
                _adjustHeightOfRow( $(element) );
            }
        );
    };



    /**
     * Returns, whether the config data is valid
     *
     * @type Boolean
     */
    function configDataIsValid ()
    {
        return (typeof configData == "object") && (typeof configData.rowSelector == "string")
                && (typeof configData.elementSelector == "string");
    }



    /**
     * Adjusts the height of a single row
     *
     * @param $row jQuery
     */
    function _adjustHeightOfRow ($row)
    {
        var maximumHeight = _getMaximumHeightOfRow($row);
        $row.find( configData.elementSelector ).css("height", maximumHeight);
    }


    
    /**
     * Returns the maximum height of a row
     *
     * @param $row int
     */
    function _getMaximumHeightOfRow ($row)
    {

        var maximumHeight = 0;

        $row.find( configData.elementSelector ).each(
            function (index, element) {
                maximumHeight = Math.max(maximumHeight, $(element).height());
            }
        );

        return maximumHeight;
    }
}


/**
 * Register the function to the jQuery framework
 */
(function ($)
{
    $.fn.adjustHeight = function (configData)
    {
        var adjuster = new Height_Adjuster(configData, this);
        adjuster.adjustHeightOfAllRows();

        // provide the jQuery conventional fluent interface
        return this;
    };
})(jQuery);
