/**
 *
 * Developer:  Roman Strelenko
 *             Magento PHP Developer
 * Email:      strelenko.roman@gmail.com
 * Web:        http://strelldev.com
 *
 * Date:       09.10.11
 * Time:       21:39
 */

/**
 * package: Jh_AjaxSuggest
 */

if (typeof Jh == 'undefined') {
    Jh = new Object();
}

Jh.suggestForm = Class.create();
Jh.suggestForm.prototype = {
    form: null,
    field: null,
    emptyText: null,
    hasValue: false,
    initialize: function (form, field, emptyText) {
        this.form = $(form);
        this.field = $(field);
        this.emptyText = emptyText;

        Event.observe(this.form,  'submit', this.onSubmit.bind(this));
        Event.observe(this.field, 'blur', this.onBlur.bind(this));
        Event.observe(this.field, 'focus', this.onFocus.bind(this));
        var searchFormInstance = this;
        this.onBlur(
            {
                element: function () {
                    return searchFormInstance.field;
                }
            }
        );
    },
    onBlur: function (event) {
        this.hasValue = event.element().value != '';
        if (!this.hasValue) {
            event.element().value = this.emptyText;
        } 
        return false;
    },
    onFocus: function (event) {
        if (!this.hasValue) {
            event.element().value = '';
        }
        return false;
    },
    onSubmit: function (event) {
        if (!this.hasValue) {
            Event.stop(event);
            return false;
        }
        return true;
    },
    initAutocomplete: function (url, destinationElement, minChars) {
        new Ajax.Autocompleter(
            this.field,
            destinationElement,
            url,
            {
                paramName: this.field.name,
                method: 'get',
                minChars: minChars,
                updateElement: this.onSearchTitleSelect.bind(this),
                onShow : function(element, update) {
                    if(!update.style.position || update.style.position=='absolute') {
                        update.style.position = 'absolute';
                        Position.clone(element, update, {
                            setHeight: false,
                            offsetTop: element.offsetHeight
                        });
                    }
                    Effect.Appear(update,{duration:0});
                }

            }
        );
    },
    onSearchTitleSelect: function (element) {
        element.select('a').each(function (element){
            setLocation(element.getAttribute('href'));
            return false;
        });
        return false;
    }
}

