//В плагин вносились изменения. Не обновлять!!!

(function (jQuery) {
    jQuery.fn.multipleSelect = function(o) {
        return this.each(function() {
            new jQuery.multipleSelect(this, o);
        });
    };

    jQuery.multipleSelect = function(e, o) {
        if (!jQuery.multipleSelect.bodyClickBound) {
            $('body').click(function () { if (!jQuery.multipleSelect.active) { $('.multipleselectpopup').hide(); $('.autocomplete-suggestions').hide(); } });
            if (jQuery.multipleSelect.hasOwnProperty("active")) jQuery.multipleSelect.bodyClickBound = true;
        }

        this.options = o || {};
        this.name = e.name;
        this.width = this.options.width;
        this.select = jQuery(e);
        this.autoCompleteUrl = this.select.attr('acurl');
        this.autoCompleteParams = this.select.attr('acparams');
        this.selectUrl = this.select.attr('selurl');
        this.selectDialogFn = this.select.attr('seldialogfn');
        this.holder = this.select.parent();
        this.maxitems = this.options.maxitems ? this.options.maxitems : 12;
        this.maxwidth = this.options.maxwidth ? this.options.maxwidth : 'auto';
        this.filteritems = this.options.filteritems ? this.options.filteritems : 10;
        this.select.hide();
        this.tree = this.select.hasClass('multitree');
        this.treeIndenter = String.fromCharCode(160) + String.fromCharCode(160) + String.fromCharCode(160) + String.fromCharCode(160); // черта - String.fromCharCode(8212), а теперь 4 &nbsp;

        var div = this.select.parent();
        var self = this;
        if (this.options.init) self.init(true);

        $('a:first', div).click(function() { self.init(); return false; });

        if (!jQuery.multipleSelects) jQuery.multipleSelects = new Array();
        jQuery.multipleSelects[this.name] = this;
        return self;
    };

    jQuery.multipleSelect.initByClassName = function(className, o) {
        if ($(className).length > 0) $(className).multipleSelect(o);
    };

    jQuery.multipleSelect.fn = jQuery.multipleSelect.prototype = {
        multipleSelect: '1.0.0'
    };

    jQuery.multipleSelect.fn.extend = jQuery.multipleSelect.extend = jQuery.extend;

    jQuery.multipleSelect.fn.extend({

        init: function (skip) {
            var self = this;
            var sel = self.select;
            
            if (sel.hasClass("radio"))
                $(sel).siblings("input").click();

            if (sel.hasClass('processed')) {
                if (sel.parent().hasClass('isdisabled'))
                    return false;
                self.toggle();
                if (self.ac && $(self.ac).is(':visible')) self.ac.focus();
                return self;
            }
            //для input устанавливается дополнительное поле path
            var isDisableChild = sel.hasClass('set-path');
            
            var name = sel.attr('name');
            var id = sel.attr('id');
            var div = sel.parent();
            var checklisttitleclasses = "";
            if (sel.hasClass('inline-block')) {
                checklisttitleclasses += " inline";
            }
            
            if ($('a:first', div).length == 0) {
                if (div.hasClass('isdisabled'))
                    div.append('<div class="checklisttitledisable' + checklisttitleclasses + '"><a data-target-id="'+id+'" href="#" onclick="return false;">' + MultipleSelectResources.Choose + '</a></div>');
                else
                    div.append('<div class="checklisttitle' + checklisttitleclasses + '"><a data-target-id="' + id + '" href="#">' + MultipleSelectResources.Choose + '</a></div>');
            }
            div.append('<div class="popupwrapper multipleselectpopup"><div class="msitems popup"></div></div>');
            self.popup = $('div.popupwrapper', div);

            if (self.width)
                $(self.popup).width(self.width + 18);

            self.popup.bind('mouseover', function () { jQuery.multipleSelect.active = true; }).bind('mouseout', function () { if (jQuery.multipleSelect.hasOwnProperty("active")) jQuery.multipleSelect.active = false; });
            self.itemscontainer = $('div.msitems', div);

            self.link = $('a:first', div);

            if (self.autoCompleteUrl) {
                self.itemscontainer.append('<nobr><input class="autocomplete" />&nbsp;');
                if (!self.selectDialogFn)
                    self.itemscontainer.append('<a href="#" onclick="return selectFilter(\'' + self.selectUrl + '\',\'' + self.name + '\')"><img src="img/buttons/browsedialog.gif" class="middle"/></a></nobr>');
                else
                    self.itemscontainer.append('<a href="#" onclick="return ' + self.selectDialogFn + '(\'' + self.selectUrl + '\',\'' + self.name + '\')"><img src="img/buttons/browsedialog.gif" class="middle"/></a></nobr>');
                self.ac = $('input.autocomplete', this.itemscontainer);
                if (self.width)
                    $(self.ac).width(self.width - 75);

                

                self.ac.devbridgeAutocomplete({
                    serviceUrl: base + self.autoCompleteUrl,
                    minChars: 1,
                    triggerselectItemResult: true,
                    params: function () {
                        var acParams = {};
                        if (self.autoCompleteParams) {
                            acParams =  $.extend({}, acParams, typeof window[self.autoCompleteParams] === "function" ? window[self.autoCompleteParams]() : self.autoCompleteParams);
                        }
                        return acParams;
                    }
                }).bind('selectItemResult', function (e, suggestion) { self.acResult(e, suggestion); if (jQuery.multipleSelect.hasOwnProperty("active")) jQuery.multipleSelect.active = true; });
            }

            var cbhtml = '<ul' + (self.width ? ' style="width: ' + self.width + 'px;"' : '') + ' id="cbblock" class="checklist" selectid="' + div.find('select').attr("id") + '">';

            //галочка выбрать все
            if (sel.hasClass('check-all')) {
                var select = div.find('select');
                var isAll = select.attr("id").indexOf("Service") != -1 ? $("#isAllService").val() : $("#isAll").val();
                var addAttr = isAll == "True" ? 'checked="true"' : '';
                cbhtml += '<li' + (self.width ? ' style="width: ' + self.width + 'px;"' : '') + '><label for="checkAll" class="radio"><input type="checkbox" value="0"  id="checkAll_' + select.attr("id") + '" selectid="' + select.attr("id") + '" ' + addAttr + '/>' + MultipleSelectResources.ChooseAll + '</label></li>';
            }
            
            var tree_regex = /(\s\/\s)/g;
            var currentPath = new Array();

            $('option', sel).each(function(i, el) {
                var val = el.value;
                var txt = el.text;
                var cbid = name + '_' + val;
                var listyle = '';
                var isChild = false;

               if (self.tree) {
                    var m = txt.match(tree_regex);
                    if (m) {
                        isChild = true;
                        var cc = el.text.split(tree_regex);
                        var level = (cc.length - 1) / 2;

                        if (isDisableChild) {
                            while (currentPath.length != level)
                                currentPath.pop();

                            currentPath.push(val);
                        }

                        txt = cc[cc.length - 1];
                        el.text = txt;
                        for (var i = 0; i < level; i++) el.text = self.treeIndenter + el.text;
                        listyle = 'style="margin-left:' + level * 18 + 'px;';
                        listyle += (self.width ? ' width: ' + self.width + 'px;"' : '"')
                    }
               }

               var txtTitle = txt.replace(/<[^>]+>/ig, "").trim();

               //txt = shortenComplexName(txt);

                if (isDisableChild) {
                    var isDisabled = false;
                    if (!isChild) {
                        currentPath = [val];
                    } else {
                        if (currentPath.length > 1) {
                            var value = currentPath[0];
                            var element = sel.find("option[value='" + value + "']");
                            isDisabled = element.attr("selected") == "selected";
                        }
                    }                    					

                    cbhtml += '<li ' + listyle + '><label' + (self.width ? ' style="width: ' + self.width + 'px;"' : '') + ' title="' + txtTitle + '" for="' + cbid + '" class="radio"><input type="checkbox" value="' + val + '" id="' + cbid + '" ' + (isDisabled || el.selected ? ' checked="true"' : '') + (isDisabled ? ' disabled="disabled"' : '') + 'path ="' + currentPath.join("|") + '"/>' + txt + '</label></li>';
                } else {
                    cbhtml += '<li ' + listyle + '><label' + (self.width ? ' style="width: ' + self.width + 'px;"' : '') + ' title="' + txtTitle + '" for="' + cbid + '" class="radio"><input type="checkbox" value="' + val + '" id="' + cbid + '" ' + (el.selected ? ' checked="true"' : '') + '/>' + txt + '</label></li>';

                }
            });
            cbhtml += '</ul>';
            cbhtml += '<a href="#" class="mshidelink"><img src="img/close.gif" /></a>';
            self.itemscontainer.append(cbhtml);
            $('a.mshidelink', self.itemscontainer).click(function () { self.popup.hide(); $('.autocomplete-suggestions').hide(); return false; });
            self.list = $('ul.checklist', self.itemscontainer);
            $('input[type="checkbox"]', self.list).bind('change', function () { self.itemClicked(this); });
            self.optionsToString();

            self.setHeight();
            sel.trigger('hideChecked', [self]);
            sel.on("change", function() { self.optionsToString(); });

            sel.addClass('processed').hide();

            if (!skip) self.toggle();
            jQuery.data(self.select.get(0), 'multipleselect', self);
            return self;
        },

        setHeight: function() {
            var self = this;
            var itemcount = $('option', self.select).length;
            if (itemcount > self.maxitems) itemcount = self.maxitems;
            var height = itemcount * 20 + 2;
            self.list.css('height', height);
        },

        toggle: function() {
            var self = this;
            var div = self.popup;
            if (div != null) {
                var hide = div.is(':visible');
                var left = self.link.position().left;
                self.popup.css('position', 'absolute').css('left', left);
                self.popup.bgiframe();
                $('.autocomplete-suggestions').hide();
                $('div.multipleselectpopup').hide();
                if (!hide) div.show();
            };
        },

        addOption: function(id, name, selected) {
            var self = this;
            var cbid = self.select.attr('name') + '_' + id;

            cbid = cbid.replace(/(:|\.|\[|\]|,|\|)/g, "\\$1");

            var nameTitle = name.replace(/<[^>]+>/ig, "").trim();

            //name = shortenComplexName(name);

            if (this.options.single) {
                var alreadyInList = self.list.find("input#" + cbid);

                if (alreadyInList.length > 0) {
                    alreadyInList.each(function (id, e) {
                        $(e).attr("checked", selected);
                    });
                    return;
                }
            }

            self.list.append('<li' + (self.width ? ' style="width: ' + self.width + 'px;"' : '') + '><label' + (self.width ? ' style="width: ' + self.width + 'px;"' : '') + ' for="' + cbid + '" title="' + nameTitle + '" class="radio"><input type="checkbox" value="' + id + '" id="' + cbid + '" ' + (selected ? ' checked="true"' : '') + '/>' + name + '</label></li>');
            $(document.getElementById(cbid), self.list).bind('click', function () { self.itemClicked(this) });
            self.setHeight();
        },

        uncheckAll: function() {
            var self = this;
            self.list.find("input").each(function (id, e) {
                $(e).attr("checked", false);
            });
        },

        uncheckOther: function (cbid) {
            var self = this;
            cbid = cbid.replace(/(:|\.|\[|\]|,|\|)/g, "\\$1");
            self.list.find("input").not("input[value='" + cbid + "']").each(function (id, e) {
                $(e).attr("checked", false);
            });
        },

        optionsToString: function() {
            var self = this;
            var sel = self.select;
            var text = '';
            var trim_tree_re = new RegExp('^([' + self.treeIndenter + '])*');
            if ($('option:selected', sel).length > 0)
                $('option:selected', sel).each(function(i, el) { var el_text = self.tree ? el.text.replace(trim_tree_re, '') : el.text; text += ((i > 0) ? ', ' : '') + el_text; });
            else
                text = MultipleSelectResources.Choose;
            if (text.length > 90) text = text.substring(0, 90) + '...';
            self.link.attr('title', text).html(text);
            self.select.trigger('linkTextChanged', [self.link]);
        },

        filterItems: function(str) {
            var self = this;
            if (str.length == 0) {
                $('li', self.list).show();
            }
            else {
                $('li', self.list).hide();
                $("li label", self.list).each(function(i, el) { el = $(el); if (el.text().toLowerCase().indexOf(str) >= 0) el.parent().show(); });
            }
        },        

        acResult: function(e, suggestion) {
            var self = this;           
            var name = suggestion.value;
            var id = suggestion.data.id;

            if (self.options.single) {
                self.uncheckOther(id);

                var alreadyInList = self.list.find("input[value='" + id + "']");

                if (alreadyInList.length > 0) {
                    alreadyInList.each(function (id, e) {
                        $(e).attr("checked", true);
                    });
                    return;
                }
            }

            //for (var i = 2; i < d.length; i++)
            //    id += '|' + d[i];

            $(e.target).val('');
            if ($('option[value="' + id + '"]', self.select).length > 0) return;
            self.select.append('<option selected value="' + id + '">' + name + '</option>');
            self.addOption(id, name, true);
            self.optionsToString();
            self.select.trigger('change');
            $(e.target).focus();
        },

        itemClicked: function (cb) {
            var self = this;
            if (this.options.single)
                self.uncheckOther($(cb).val());
            var sel = this.select;
            var $sel = $(sel);
            if (cb.id != "checkAll_" + $(cb).attr("selectid")) {
                if (!$sel.is('[child-autoselect-cond]')
                       || (typeof window[$sel.attr('child-autoselect-cond')] == "function" && window[$sel.attr('child-autoselect-cond')]())) {
                    $('option[value="' + cb.value + '"]', sel).attr('selected', cb.checked);
                    sel.trigger('change');
                    if (self.options.onchange) self.options.onchange(self);
                    self.select.trigger('addStatus', [cb, self]);

                    if ($(sel).hasClass('child-autoselect')) {
                        self.itemscontainer.find('input[type=checkbox]').each(function () {
                            if (this.value != null && this.value != cb.value && this.value.substring(0, cb.value.length) == cb.value) {
                                this.checked = cb.checked;
                                self.itemClicked(this);
                            }
                        });
                    }
                }
                
            } else {
                //"Выбрать все"
                //console.log('xxxxxxxxxxx')
                var id = $(cb).attr("selectid");
                var objs = $('input[id^=' + id + ']');
                var s = $('select#' + id).find("option");
                
                if ($(cb).prop("checked")) {
                    objs.attr("checked", "checked");
                    s.attr("selected", "selected");
                } else {
                    objs.removeAttr("checked");
                    s.removeAttr("selected");
                }
              }
            self.optionsToString();
        },

        unwrapControl: function(o) {
            var self = this;
            self.select.show();
            $('div', self.holder).hide();
            $('.autocomplete-suggestions').hide();
        },

        unwrapClearControl: function(o) { // метод сбрасывает фильтр если выбрано пустое поле
            var self = this;
            $('option:selected', self.select).removeAttr('selected');
            $('.radio input[type="checkbox"]:checked', self.list).attr('checked', false);
            text = MultipleSelectResources.Choose;
            self.link.attr('title', text).html(text);
        },

        wrapControl: function(skip) {
            var self = this;
            self.select.hide();
            $('div', self.holder).show();
            if (skip) self.popup.hide();
        }
    });

})(jQuery);

//$(function() {
//    jQuery.multipleSelect.initByClassName('.multipleselect', { maxwidth: '300px', init: true });
//});



