﻿/***************************************************************
Javascript Library for Search API
    
Library Dependencies:
- jQuery Core v1.3.2
- ivory.core.js
- ivory.search.js
***************************************************************/

$.bind = (function () {

    function parse_and_validate(result) {
        var data = JSON.parse(result);
        // do validation if result is real optionitem class
        return data;
    }

    return {

        /*
        * Sender: jquery control that trigger this event
        * Target: jquery control that acts as the output dumper
        * Result: data in JSON format retruned from the server
        */
        list: function (sender, target, result) {
            var data = JSON.parse(result),
                itemCount = data ? data.length : 0,
                item, html = ['<ul class="more">'],
                lessList = target.children("ul:first").addClass("less"), moreList,
                toggleList = function () {
                    moreList.toggle();
                    lessList.toggle();
                };

            for (var i = 0; i < itemCount; i++) {
                item = data[i];

                html.push('<li class="refine-item">');
                html.push('<a href="' + item.Attributes.RefineUrl + '">' + item.Text + '</a><span class="count">(' + item.Attributes.Count + ')</span>');
                html.push('</li>');
            }

            html.push('<li class="refine-item"><a href="#">(less...)</a></li></ul>');

            // Change "more" link
            lessList.hide().children("li:last").children("a").unbind("click").click(toggleList);
            lessList.children(".loading").remove();

            // Add new HTML and attach event to "less" link
            moreList = $(html.join("")).appendTo(target);
            moreList.children("li:last").children("a").click(toggleList);
        },

        /*
        * Sender: jquery control that trigger this event
        * Target: jquery control that acts as the output dumper
        * Result: data in JSON format retruned from the server
        */
        select: function (sender, target, result) {

            var data = parse_and_validate(result);

            var options = "";

            var desc = (target.attr("data-desc") == 'true');

            for (var i = 0; i < data.length; i++) {
                var isSelectableOptGroup = false;
                var item = desc ? data[data.length - i - 1] : data[i];

                var attr = " ";
                if (!$.isEmpty(item.Attributes)) {
                    $.each(item.Attributes, function (key, val) {
                        if (key != "RefineUrl") {
                            var tempKey = key;
                            if (key == "Count")
                                tempKey = "data-" + key;
                            attr += tempKey + "='" + val + "' ";
                            isSelectableOptGroup = (key == "class" && (" " + val + " ").indexOf(" selectable-optgroup ") > -1);
                        }
                    });
                }

                var text = item.Text;
                options += '<option value="' + item.Value + '" ' + $.trim(attr) + '>' + text + '</option>';
            }

            // dump the content
            target.html(options);

            // if OptGroup is set, add padding to the non-group
            var hasOptGroup = (target.find("option[class=selectable-optgroup]").length > 0);
            if (hasOptGroup) {
                $.each(target.find("option[class!=selectable-optgroup]"), function () {
                    var text = $(this).html();
                    $(this).html("&nbsp;&nbsp;&nbsp;&nbsp;" + text);
                });
            }

            // insert default value if available
            var defaultValue = $.form.defaultValue(target);
            if (!$.isEmpty(defaultValue)) {

                if (sender != null) {
                    var senderText = sender
                        .find("option[value='" + sender.val() + "']")
                        .text();

                    if (senderText.indexOf("(") > -1)
                        senderText = senderText.substring(0, senderText.indexOf("("));

                    defaultValue = defaultValue.replace(/\{0\}/g, $.trim(senderText));
                }

                target.children().first().before('<option value="">' + defaultValue + '</option>');
                target[0].selectedIndex = 0;

            }
        }

    };

})();
