;(function($) {
    $.widget("ui.dropdownchecklist", {
        _appendDropContainer: function() {
            var wrapper = $("<div/>");
            wrapper.addClass("ui-dropdownchecklist-dropcontainer-wrapper");
            wrapper.css({
                position: 'absolute',
                left: "-3300",
                top: "-3300px",
                width: '3000px',
                height: '3000px'
            });
            var container = $("<div/>"); // the actual container
            container.addClass("ui-dropdownchecklist-dropcontainer")
                .css("overflow-y", "auto");
            wrapper.append(container);
            $(document.body).append(wrapper);
            wrapper.drop = false;
            return wrapper;
        },
        _appendControl: function() {
            var self = this, options = this.options, sourceSelect = this.sourceSelect;
            var wrapper = $("<span/>");
            wrapper.addClass("ui-dropdownchecklist-wrapper");
            wrapper.css({
                display: "inline-block",
                cursor: "default"
            });

            var control = $("<span/>");
            control.addClass("ui-dropdownchecklist");
            control.css({
                display: "inline-block"
            });
            
            wrapper.append(control);

            var textContainer = $("<span/>");
            textContainer.addClass("ui-dropdownchecklist-text")
            textContainer.css({
                display: "inline-block",
                overflow: "hidden"
            });
            control.append(textContainer);

            wrapper.hover(function() {
                if (!self.disabled) {
                    control.toggleClass("ui-dropdownchecklist-hover")
                }
            }, function() {
                if (!self.disabled) {
                    control.toggleClass("ui-dropdownchecklist-hover")
                }
            });

            wrapper.click(function(event) {
                if (!self.disabled) {
                    event.stopPropagation();
                    self._toggleDropContainer();
                }
            })

            wrapper.insertAfter(sourceSelect);

            return wrapper;
        },
        _createDropItem: function(index, value, text, checked, indent) {
            var self = this;
            var item = $("<div/>");
            item.addClass("ui-dropdownchecklist-item");
            item.css({whiteSpace: "nowrap"});
            var checkedString = checked ? ' checked="checked"' : '';
            var checkBox = $('<input type="checkbox"' + checkedString + '/>')
                .attr("index", index)
                .val(value);
            item.append(checkBox);
            var label = $("<span/>");
            label.addClass("ui-dropdownchecklist-text")
                .css({
                    cursor: "default",
                    width: "100%"
                })
                .text(text);
			if (indent) {
				item.addClass("ui-dropdownchecklist-indent");
			}
            item.append(label);
            item.hover(function() {
                item.addClass("ui-dropdownchecklist-item-hover")
            }, function() {
                item.removeClass("ui-dropdownchecklist-item-hover")
            });
            checkBox.click(function(event) {
                event.stopPropagation();
                self._syncSelected($(this));
                
                self.sourceSelect.trigger("change");
                
            });
            var checkItem = function(event) {            	
                event.stopPropagation();
                var checked = checkBox.attr("checked");
                checkBox.attr("checked", !checked)
                self._syncSelected(checkBox);
                self.sourceSelect.trigger("change");
                if(self.sourceSelect.attr('name') == 'FILTER_SECTIONS') {
                	var  filterTest = '';         	
                	$('#filter-sections option').each(function (i) {
                		if((i>0) && ($(this).attr('selected'))) {
                			           			
                		}
                	});

                }
            }
            label.click(checkItem);
            item.click(checkItem);
            return item;
        },
		_createGroupItem: function(text) {
			var self = this;
			var group = $("<div />")
			group.addClass("ui-dropdownchecklist-group");
			group.css({whiteSpace: "nowrap"});
            var label = $("<span/>");
            label.addClass("ui-dropdownchecklist-text")
                .css({
                    cursor: "default",
                    width: "100%"
                })
                .text(text);
			group.append(label);
			return group;
		},
        _appendItems: function() {
            var self = this, sourceSelect = this.sourceSelect, controlWrapper = this.controlWrapper, dropWrapper = this.dropWrapper;
            var dropContainerDiv = dropWrapper.find(".ui-dropdownchecklist-dropcontainer");
            dropContainerDiv.css({ "float": "left" }); // to allow getting the actual width of the container
			sourceSelect.children().each(function(index) { // when the select has groups
				var opt = $(this);
                if (opt.is("option")) {
                    self._appendOption(opt, dropContainerDiv, index, false);
                } else {
                    var text = opt.attr("label");
                    var group = self._createGroupItem(text);
                    dropContainerDiv.append(group);
                    self._appendOptions(opt, dropContainerDiv, index, true);
                }
			});
            var divWidth = dropContainerDiv.outerWidth();
            var divHeight = dropContainerDiv.outerHeight();
            dropContainerDiv.css({ "float": "" }); // set it back
            return { width: divWidth, height: divHeight };
        },
		_appendOptions: function(parent, container, parentIndex, indent) {
			var self = this;
			parent.children("option").each(function(index) {
                var option = $(this);
                var childIndex = (parentIndex + "." + index);
                self._appendOption(option, container, childIndex, indent);
            })
		},
        _appendOption: function(option, container, index, indent) {
            var self = this;
            var text = option.text();
            var value = option.val();
            var selected = option.attr("selected");
            var item = self._createDropItem(index, value, text, selected, indent);
            container.append(item);
        },
        _syncSelected: function(senderCheckbox) {
            var self = this, options = this.options, sourceSelect = this.sourceSelect, controlWrapper = this.controlWrapper, dropWrapper = this.dropWrapper;
            var allCheckboxes = dropWrapper.find("input");
            if (options.firstItemChecksAll) {
                if (senderCheckbox.attr("index") == 0) {
                    allCheckboxes.attr("checked", senderCheckbox.attr("checked"));
                } else {
                    var allChecked;
                    allChecked = true;
                    allCheckboxes.each(function(index) {
                        if (index > 0) {
                            var checked = $(this).attr("checked");
                            if (!checked) allChecked = false;
                        }
                    });
                    var firstCheckbox = allCheckboxes.filter(":first");
                    firstCheckbox.attr("checked", false);
                    if (allChecked) {
                        firstCheckbox.attr("checked", true);
                    }
                }
            }

            var selectOptions = sourceSelect.get(0).options;
            allCheckboxes.each(function(index) {
                $(selectOptions[index]).attr("selected", $(this).attr("checked"));
            });

            self._updateControlText();
        },
        _updateControlText: function() {
            var self = this, sourceSelect = this.sourceSelect, options = this.options, controlWrapper = this.controlWrapper, dropWrapper = this.dropWrapper;
            var firstSelect = sourceSelect.find("option:first");
            var allSelected = null != firstSelect && firstSelect.attr("selected");
            var selectOptions = sourceSelect.find("option");
            var text = self._formatText(selectOptions, options.firstItemChecksAll, allSelected);
            var controlLabel = controlWrapper.find(".ui-dropdownchecklist-text");
            if(text == '') {
            	controlLabel.text($(sourceSelect).attr('title')).css('color','#373635').css('font-size','9pt').css('font-weight','bold');	
            } else {
            	controlLabel.text($(sourceSelect).attr('title')+' ('+text+')').css('color','green').css('font-size','8pt').css('font-weight','normal');	
            	/*$(sourceSelect).attr('title')+' (выбрано)'*/
            }
            
            controlLabel.attr("title", text);
        },
        _formatText: function(selectOptions, firstItemChecksAll, allSelected) {
            var text;
            if (firstItemChecksAll && allSelected) {
                text = selectOptions.filter(":first").text();
            } else {
                text = "";
                selectOptions.each(function() {
                    if ($(this).attr("selected")) {
                        text += $(this).text() + ", ";
                    }
                });
                if (text.length > 0) {
                    text = text.substring(0, text.length - 2);
                }
            }
            return text;
        },
        _toggleDropContainer: function() {
            var self = this, dropWrapper = this.dropWrapper, controlWrapper = this.controlWrapper;
            var hide = function() {
                var instance = $.ui.dropdownchecklist.drop;
                if (null != instance) {
                    instance.dropWrapper.css({
                        top: "-3300px",
                        left: "-3300px"
                    });
                    instance.controlWrapper.find(".ui-dropdownchecklist").toggleClass("ui-dropdownchecklist-active");
                    instance.dropWrapper.drop = false;
                    $.ui.dropdownchecklist.drop = null;
                    $(document).unbind("click", hide);
					self.sourceSelect.trigger("blur");
                }
            }
            var show = function(instance) {
                if (null != $.ui.dropdownchecklist.drop) {
                    hide();
                }
                instance.dropWrapper.css({
                    top: instance.controlWrapper.offset().top + instance.controlWrapper.outerHeight() + "px",
                    left: instance.controlWrapper.offset().left + "px"
                })
                instance.controlWrapper.find(".ui-dropdownchecklist").toggleClass("ui-dropdownchecklist-active");
                instance.dropWrapper.drop = true;
                $.ui.dropdownchecklist.drop = instance;
                $(document).bind("click", hide);
				self.sourceSelect.trigger("focus");
            }
            if (dropWrapper.drop) {
                hide(self);
            } else {
                show(self);
            }
        },
        _setSize: function(dropCalculatedSize) {
            var options = this.options, dropWrapper = this.dropWrapper, controlWrapper = this.controlWrapper;

            var controlWidth;
            if (options.width) {
                controlWidth = parseInt(options.width);
            } else {
                controlWidth = dropCalculatedSize.width;
                var minWidth = options.minWidth;
                if (controlWidth < minWidth) {
                    controlWidth = minWidth;
                }
            }
            controlWrapper.find(".ui-dropdownchecklist-text").css({
                width: controlWidth + "px"
            });

            var controlOuterWidth = controlWrapper.outerWidth();
            var dropHeight = options.maxDropHeight ? parseInt(options.maxDropHeight) : dropCalculatedSize.height;
            var dropWidth = dropCalculatedSize.width < controlOuterWidth ? controlOuterWidth : dropCalculatedSize.width;

            $(dropWrapper).css({
                width: dropWidth + "px",
                height: dropHeight + "px"
            });

            dropWrapper.find(".ui-dropdownchecklist-dropcontainer").css({
                height: dropHeight + "px"
            });
        },
        _init: function() {
            var self = this, options = this.options;

            var sourceSelect = self.element;
            self.initialDisplay = sourceSelect.css("display");
            sourceSelect.css("display", "none");
            self.initialMultiple = sourceSelect.attr("multiple");
            sourceSelect.attr("multiple", "multiple");
            self.sourceSelect = sourceSelect;

            var dropWrapper = self._appendDropContainer();
            self.dropWrapper = dropWrapper;
            var dropCalculatedSize = self._appendItems();
            var controlWrapper = self._appendControl();
            self.controlWrapper = controlWrapper;
            self._updateControlText(controlWrapper, dropWrapper, sourceSelect);
            self._setSize(dropCalculatedSize);
        },
        enable: function() {
            this.controlWrapper.find(".ui-dropdownchecklist").removeClass("ui-dropdownchecklist-disabled");
            this.disabled = false;
        },
        disable: function() {
            this.controlWrapper.find(".ui-dropdownchecklist").addClass("ui-dropdownchecklist-disabled");
            this.disabled = true;
        },
        destroy: function() {
            $.widget.prototype.destroy.apply(this, arguments);
            this.sourceSelect.css("display", this.initialDisplay);
            this.sourceSelect.attr("multiple", this.initialMultiple);
            this.controlWrapper.unbind().remove();
            this.dropWrapper.remove();
        }
    });

    $.extend($.ui.dropdownchecklist, {
        defaults: {
            width: null,
            maxDropHeight: null,
            firstItemChecksAll: false,
            minWidth: 50
        }
    });
})(jQuery);