﻿(function ($) {
    $.widget("entities.localisation", {
        options: {
            serviceUrl: '/Services/ServiceLocalisation.svc/ProposerLocalisations?maxPays=0',
            hfId: '',
            errorCssClass: '',
            clientValidationFunction: null,
            rechercheEtrangere: false
        },

        hf: null,
        firstItemValue: null,
        firstItemText: null,
        previousVal: null,

        isOpen: false,

        _create: function () {
            var self = this;

            self.hf = $('#' + self.options.hfId);
            self.previousVal = self.getValue();

            self.element.change(function () {
                if ($(this).val() == '') {
                    self.setValue('');
                }
            }).focus(function () {
                self.unHighLight();
            }).focusout(function (e) {
                setTimeout(function () {
                    if (self.firstItemValue) {
                        self.element.val(self.firstItemText)
                        self.setValue(self.firstItemValue);
                        self.isOpen = false;
                    }
                }, 100);
            }).autocomplete({

                source: function (req, resp) {
                    $.ajax({
                        url: self.options.serviceUrl,
                        dataType: 'json',
                        data: {
                            q: req.term
                        },
                        success: function (data) {
                            var prop = (data && data.d && data.d[0] && data.d[0].PropositionsLocalisation && data.d[0].PropositionsLocalisation[0]) ? data.d[0].PropositionsLocalisation[0] : null;

                            //Réinitialise la valeur
                            self.setValue('');

                            //Sauvegarde la première proposition
                            self.firstItemText = prop ? prop.Nom : null;
                            self.firstItemValue = prop ? prop.Valeur : null;

                            resp($.map(data.d, function (item) {
                                return item; /* PropositionLocalisationGroupe.*/
                            }))
                        }
                    });
                },

                select: function (event, ui) {
                    self.setValue(ui.item.serverId);
                    self.isOpen = false;
                },

                open: function (event, ui) {
                    self.isOpen = true;
                    self.element.focus();
                    /* TODO Incorporer dans le monkey patch. */
                    $(this).data('autocomplete')._move('next', event);

                    /*var active = $(this).autocomplete('widget').data('menu').active,
                    item = (typeof active != 'undefined' && active != null) ? active.data('item.autocomplete') : null;*/
                },

                delay: 300

            }).data('autocomplete')._renderItem = self.renderItem;
            if (this.options.rechercheEtrangere)
                this.setupEtrangere(false);
        },

        getValue: function () {
            return this.hf.val();
        },

        setValue: function (v) {
            var self = this;

            self.firstItemText = null;
            self.firstItemValue = null;

            if (!v && !self.previousVal)
                return;

            if (v != self.previousVal) {
                self.hf.val(v);

                self.unHighLight();

                self.element.trigger('selected', [v || null]);
            }
            self.previousVal = v;
        },

        renderItem: function (ul, item) {
            var parent = $("<ul></ul>").append("<li>" + item.LibelleGroupe + "</li>").appendTo(ul);
            $.each(item.PropositionsLocalisation, function (index, item) {
                $("<li></li>").data("item.autocomplete", {
                    label: item.Nom,
                    value: item.Nom,
                    serverId: item.Valeur
                }).append("<a>" + item.Nom + "</a>").appendTo(parent);
            });
            return parent;
        },

        destroy: function () {
        },

        _setOption: function (option, value) {
        },

        highLight: function () {
            if (this.options.errorCssClass != '')
                $(this.element).addClass(this.options.errorCssClass);
        },

        unHighLight: function () {
            if (this.options.errorCssClass != '')
                $(this.element).removeClass(this.options.errorCssClass);
        },

        setupEtrangere: function (etrangereActive) {
            if (etrangereActive) {
                // Disactive recherche etrangere -> active tb.
                this.setValue('');
                this.element.val('');
                this.element.attr('disabled', false);

                // TODO Clean up: The direct parent of the localisation textbox (this.element)
                // is the watermark span.
                this.element.prev().show();
            }
            else {
                // Enable.
                this.unHighLight();
                this.setValue('p:2');
                this.element.val('Maroc');
                this.element.attr('disabled', true);
                this.element.prev().hide();
            }
        },

        toggleEtrangere: function () {
            this.setupEtrangere(this.element.attr('disabled'));
        },

        validate: function () {
            var val = this.getValue();
            var isValid = (typeof val != 'undefined') && val != '';
            if (!isValid) {
                this.highLight();

                if (this.options.clientValidationFunction && this.options.clientValidationFunction != '')
                    eval(this.options.clientValidationFunction + "(this.element)");
            }

            return isValid;
        }
    });
} (jQuery));
