/*
 * Extension of Autocomplete that is able to display additional
 * textfields triggered by '+/-' button. 
 */
(function($){

    var bttnId = 0;
    /**
     * Init function
     *
     * @param {Object} url
     * @param {Object} options
     */
    $.fn.multicomplete = function(url, options){
        var $this = $(this);
        // save options for further reuse
        $this.opts = $.extend({}, options, $this.opts, $.Autocompleter.defaults);
        try {
            addFormatting($this).autocomplete(url, options).result(function(event, item){
                // simply set inbox title to id
                $(this).attr('var', item[1] ? item[1] : item[0]);
			
				if(this.id=="destination"){
					$('#country_id').val(item[1]);
					$('#state').val(item[2]);
					$('#county').val(item[3]);
					$('#city').val(item[4]);
				}
				if(this.id=="treatment"){
					if(item[1]>0 && item[2]>-1)
						$('#treatment').removeClass("error");
					else 
						$('#treatment').addClass("error");
					$('#cat_id').val(item[1]);
					$('#cat_root').val(item[2]);
					$('#root').val(item[3]);
					}
            });
        } 
        catch (err) {
            log(err);
        }
        $this.url = url;
        extend($this);
        return $this;
    };
    
    /**
     * In browsers with console will log the message
     * @param {Object} msg message to log
     */
    function log(msg){
        if (window.console) {
            window.console.log(msg);
        }
    }
    
    /**
     * Adds some functions to the multicomplete control
     * @param {Object} $this the wrapped control
     */
    function extend($this){
        $this.reset = function(){
            reset($this);
        };
        $this.getSelected = function(){
            return getSelected($this);
        };
    }
    
    /**
     * Collect titles (id) from all input fields and return as an array
     */
    function getSelected($this){
        var selected = [];
        $this.opts.container.find('.' + $this.opts.inputClass).each(function(){
            var id = $(this).attr('var');
            if (id) {
				selected.push(id);
			}
        });
        return selected;
    }
    
    /**
     * Remove all previously added text fields and reset selection to nothing
     */
    function reset($this){
        // remove formatting
        $this.opts.container.html('');
        $this.opts.container.append($this.get(0));
        try {
            addFormatting($this).autocomplete($this.url, $this.opts).result(function(event, item){
                // simply set inbox title to id
                $(this).attr('title', item[1] ? item[1] : item[0]);
            });
        } 
        catch (err) {
            // alert(err);
        }
    }
    
    /**
     * Wraps supplied text box into div and appends "+/-" button
     */
    function addFormatting($this){
        var div = $('<div class="big_field_holder" id="multicompleteContainer_' + bttnId + '">');
        if (!$this.opts.container) {
            $this.opts.container = $this.parent();
        }
        $this.parent().append(div);
        $this.remove();
        div.append($this);
        if ($this.opts.title) {
            $this.val($this.opts.title);
            $this.addClass('multiTitle');
        }
        // bind some events
        $this.bind('click', function(){
            if ($this.val() == $this.opts.title) {
                $this.val('').removeClass('multiTitle');
            }
        });
        $this.blur(function(event){
            // see if we need to mark newly added SELECT
			var clazz = '.' + $this.opts.resultsClass;
            var results = $(clazz);
            var select = $(clazz + '[@id=select_' + $this.attr('id') + ']')
            if (results.length > 0 && select.length == 0) {
                var res = $(results[results.length - 1]);
                if (!res.attr('id')) {
                    res.attr('id', 'select_' + $this.attr('id'));
                }
            }
            if (!$this.val() && $this.opts.title) {
                $this.val($this.opts.title).addClass('multiTitle');
                event.preventDefault();
                return false;
            }
        });
        
        return $this;
    }
    
    /**
     * Handles click on 'add/remove' button
     * @param {Object} bttn
     * @param {Object} $this
     * @param {Object} div
     */
    function onButtonClick(bttn, $this, div){
/*        var opts = $this.opts;
        // see if we are adding or removing
        var adding = bttn.attr('title') == '+';
        if (adding) {
            var input = $('<input type="text" id="' + $this.attr('id') + '_' +
            bttnId++ +
            '" class="' +
            $this.attr('class') +
            '"/>');
            div.after(input);
            // change button class to remove
            bttn.attr('title', '-').removeClass('addFilter').addClass('removeFilter').html('-');
            return input.multicomplete($this.url, $this.opts).result(function(event, item){
                // simply set inbox title to id
                $(this).attr('title', item[1] ? item[1] : item[0]);
            });
        }
        else {
            div.remove();
            // also remove hidden selection list
            $('#select_' + $this.attr('id')).remove();
        }*/
    }
    
})(jQuery);
