/*
* jQuery Proposals 1.0.1
*
* Copyright (c) 2009 Igor Shakhov
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
*/

(function($) {
    $.fn.proposals = function(options) {
        var defaults = {
            title: 'Results',
            position: 'center',
            oneWordUrl: '/ajax_link',
            oneWordMethod: 'GET',
            fullTextUrl: '/ajax_block',
            fullTextMethod: 'POST',
            relative: 'none'
        }

        var options = $.extend(defaults, options);

        return this.each(function() {
            var o = options;

            var $this = this.$this = $(this);
            popup = ($this.popup = $('<div title="' + o.title + '"></div>')).hide();
            $this.after(popup);

            if ($.inArray(o.relative, ['top', 'right', 'bottom', 'left']) < 0) {
                o.relative = 'none';
            }

            if (o.relative != 'none') {
                if (o.position.constructor != Array || o.position[0].constructor != Number) {
                    o.position = [0, 0];
                }
            }

            $this.popup.dialog({
                autoOpen: false,
                relative: o.relative
            });

            $this.lastValue = '';

            $this.keypress(function(e) {
                $this.popup.dialog('close');

                if (e.which == 32) {
                    var word = $.trim($this.val());
                    if (word.length > 0) {
                        getProposals($this, o.oneWordUrl, false, o.oneWordMethod, o.position, o.relative);
                        this.focus();
                    }
                }
            });

            var btn = $("#" + this.$this.attr('btn'));
            btn[0].txt = this;
            btn.click(function() {
                $this.popup.dialog('close');
                this.txt.$this.lastValue = '';
                getProposals(this.txt.$this, o.fullTextUrl, true, o.fullTextMethod, o.position, o.relative);
            });
        });

        $.ui.dialog.defaults.bgiframe = true;
    };

    function getProposals(txt, url, fullSearch, method, position, relative) {
        if (fullSearch) {
            var value = $.trim(txt.val());
        } else {
            var values = $.trim(txt.val()).split(" ");
            var value = values[values.length - 1];
        }
        if (value.length > 0/* && txt.lastValue != value*/) {
            txt.lastValue = value;

            $.ajax({
                type: method,
                url: url,
                data: fullSearch ? { sn_msgbody: value} : { sn_key: value },
                dataType: "json",
                success: function(data) {
                    var newText = "<div class='ac_results'><ul style='overflow: auto; max-height: 300px;'>";
                    var success = false;
                    $.each(data, function(i, item) {
                        success = true;
                        var styleName;
                        if (i % 2 > 0) {
                            styleName = "ac_odd";
                        } else {
                            styleName = "ac_even";
                        }
                        newText += "<li class='" + styleName + "'>" +
                                       "<b>" + item.Key + "</b>&nbsp;<a href='#' onclick='$.fn.proposals.insertLink(\"" + txt[0].id + "\",\"" + item.Key + "\",\"" + item.Link + "\"," + fullSearch + ");$(this).remove();return false;'>[Link in Text einf&uuml;gen]</a><br />" +
                                       item.Comment + "<br />" +
                                       "<a href='" + item.Link + "' onclick='$.fn.proposals.openLink(\"" + item.Link + "\");return false;'>" + item.Link + "</a><br />" +
                                       "</li>";
                    });
                    if (!success) {
                        newText += "<li class='ac_even'><b>Nothing was found</b></li>";
                    } else {
                        newText += "</ul></div>";
                        txt.popup.html("<p>" + newText + "</p>");

                        if (!txt.popup.dialog('isOpen')) {
                            if (relative != 'none') {
                                var offset = txt.offset();
                                var top = offset.top - $(document).scrollTop() + position[1];
                                var left = offset.left - $(document).scrollLeft() + position[0];
                                if (relative == 'right') {
                                    position = [left + txt.outerWidth(), top];
                                } else if (relative == 'bottom') {
                                    position = [left, top + txt.outerHeight()];
                                } else if (relative == 'left' || relative == 'top') {
                                    position = [left, top];
                                }
                            }
                            txt.popup.dialog('option', 'position', position);
                        }
                        txt.popup.dialog('open');
                        txt.focus();
                    }
                }
            });
        } else {
            txt.focus();
        }
    }

    $.fn.proposals.openLink = function(link) {
        link += "";
        if ((link.indexOf("http://") < 0) && (link.indexOf("https://") < 0)) {
            link = "http://" + link;
        }
        window.open(link, "_blank");
    }

    $.fn.proposals.insertLink = function(txtId, key, link, onlyFirst) {
        var txt = $("#" + txtId);
        var linkMatch = "link";
        var textMatch = "text";
        var formatString = "[url=" + linkMatch + "]" + textMatch + "[/url]";
        var currentValue = txt.val();
        var newValue = formatString.replace(linkMatch, link).replace(textMatch, key);

        var re;
        if (onlyFirst) {
            re = new RegExp("(^|[^\\S])" + key + "((?=[^\\S])|$)", "i");
        } else {
            re = new RegExp("(^|[^\\S])" + key + "((?=[^\\S])|$)(?!.*(^|[^\\S])" + key + "((?=[^\\S])|$).*)", "i");
        }

        newValue = currentValue.replace(re, "$1" + newValue);
        txt.val(newValue);
        txt.focus();
    }
})(jQuery);