/**
 * Widget catcomplete
 * @version     1.0.0
 * @since       1.0.0
 * @package     contrexx
 * @subpackage  lib
 * @copyright   CONTREXX CMS - COMVATION AG
 * @author      Michael Ritter <michael.ritter@comvation.com>
 * @todo        Fix "'c.width("").width' is not a function" bug in Opera (11.50) (Opera only)
 */

var $jq = jQuery.noConflict();

/**
 * Code mostly copied from http://jqueryui.com/demos/autocomplete/
 * JSON Parsing:
 * array {
 *      {
 *          label:          Formatted String
 *          value:          String for the input field
 *          [category:      String]
 *          [any key:       any value] <-- creates a hidden field
 *      }
 * }
 */
$jq.widget( "custom.catcomplete", $jq.ui.autocomplete, {
    _renderMenu: function( ul, items ) {
        var self = this,
            currentCategory = "";
        $jq.each( items, function( index, item ) {
            if ( item.category != undefined && item.category != currentCategory && item.category != "") {
                    ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
                    currentCategory = item.category;
            }
            self._renderItem( ul, item );
        });
    }
});

/**
 * Configuration options
 * 
 * If you set url, its value will be used as source
 * 
 * For each entry in the response array that is not 'label', 'value' or 'category'
 * a hidden field will be created
 * @param id string value for the id attribute
 * @param url string AJAX request url
 * @param min int Minimum count of chars before a request is sent
 */
function registerCatcompleteWidget(id, url, min) {

    $jq(document).ready(function(){
        $jq("#" + id).catcomplete({
            minLength: min,
            source: function(request, response) {
                $jq.getJSON(url, { term: request.term }, response);
            },
            select: function (event, ui) {
                $jq(this).val(ui.item.value);
                $jq.each(ui.item, function(index,value) {
                    // if index is not internal
                    if (index != "label" && index != "value" && index != "category" && value != undefined) {
                        // if hidden field does not exist
                        if ($jq("#"+index).length == 0) {
                            $jq("#" + id).after($jq("<input type='hidden' name='"+index+"' id='"+index+"' />"));
                        }
                        $jq("#"+index).val(value);
                        $jq("#"+index).change();
                    }
                });
            }
        });
    });
}
