﻿function checkHeaderKey(e, hsbox, type) {
    if (e.keyCode == 13) {
        return callHeaderSearch(hsbox, type);
    }
    return true;
}

function callHeaderSearch(sbox, type) {
    if (sbox.value == "Search this Site") {
        sbox.value = "";
    }

    var url = "http://search.astd.org/Search.aspx?csquery=" + sbox.value;
    if (type != undefined && type != "All Topics") {
        url += "&f=" + encodeURIComponent("type:" + type);
    }

    window.location = url;
    return false;
}

function clearSearchText(el) {
    if (el.defaultValue == el.value) el.value = ""
}

// Begin lookahead

var search_option = false;

lookaheadParams = {
    workflows: "autocomplete",
    highlight: "true",
    fields: "title,teaser(text,numfragments=2) as text,uri,table,img,thumb",
    "q.type": "simple",
    "join.rollup": "children",
    hits: 5,
    output: "full",
    facet: "concepts(maxnumbuckets=2)"
};

function renderMedia(media) {
    html = '<div class="lookahead_result_img_wrap"><img src="http://store.astd.org/Products/ProductImages/' + media.thumb + '" alt="photo" border="0" class="lookahead_result_img lookahead_result_media" onclick="window.location = \'' + media.uri + '\'; return true;"/></div>';
    html += '<div class="tooltip"><div class="tooltip_content"><img src="http://store.astd.org/Products/ProductImages/' + media.img + '" onclick="window.location = \'' + media.uri + '\'; return true;" alt="photo" border="0" class="lookahead_tooltip_img"/></div></div>';
    return html;
};

var didYouMeanType = "did_you_mean";
var typeOrderMap = { 
    'ASTD.org': 1,
    'ASTD Store': 2
};
typeOrderMap[didYouMeanType] = 0;

function handleLookaheadResponse(data, queryTerm, responseCallback) {
    // handle "did you mean" results
    var i = 0;
    // make sure the query term is at least 3 characters long or the results won't be useful
    if (queryTerm != undefined && queryTerm.length > 2 && data.facets.length > 0 && data.facets[0].buckets.length > 0) {
        var label = data.facets[0].buckets[0].label;

        // if the suggestion is the same as the query term, then use the second suggestion (if there is one)
        if (label.toLowerCase() == queryTerm.toLowerCase()) {
            if (data.facets[0].buckets.length > 1) {
                label = data.facets[0].buckets[1].label;
            } else {
                // ignore the suggestion
                label = '';
            }
        }

        if (label != '') {
            var obj = new Object;
            obj.table = didYouMeanType;
            obj.label = suggestResult([label]);

            // add in the did you mean item and ensure we don't process it in the loop below
            data.documents.unshift(obj);
            i++;
        }
    }

    for (; i < data.documents.length; i++) {
        data.documents[i].label = '';
        if (data.documents[i].thumb != undefined) {
            data.documents[i].label += renderMedia(data.documents[i]);
        }
        data.documents[i].label += '<div><div class="lookahead_result_title">' + data.documents[i].title + '</div>';
        if (data.documents[i].text != undefined) {
            content_text = data.documents[i].text
        } else {
            content_text = ''
        }
        data.documents[i].label += '<div class="lookahead_result_content">' + content_text + '</div><div style="clear:both;"></div></div>';
        data.documents[i].value = data.documents[i].uri;
    }

    responseCallback(data.documents);
}

function gotoResults(keyword, type) {
    window.location = 'http://search.astd.org/Search.aspx?csquery=' + encodeURIComponent(keyword) + (type == undefined ? '' : ('&f=' + encodeURIComponent('table:' + type)));
    return true;
}


function suggestResult(keywords) {

    html = '<li class="ui-menu-item-suggest"><div class="did_you_mean_right"><span onclick="return gotoResults($(\'#header_search_input\').val());">See All</span></div><span class="lookahead_result_title">DID YOU MEAN: </span>';
    for (var i = 0, len = keywords.length; i < len; ++i) {
        html += '<span class="did_you_mean" onclick="return gotoResults(\'' + keywords[i] + '\');">' + keywords[i] + '</span>';
        if (i + 1 != len) {
            html += ', ';
        } else {
            html += '?';
        }
    }
    html += '</li>';
    return html;
}

$.widget("custom.groupedcomplete", $.ui.autocomplete, {
    mediaTypes: ["Photos & Videos"],

    _init: function () {
        var self = this;
        // unbind the default handler and bind one with our tweaks for the enter key
        this.element.unbind("keydown.autocomplete");
        this.element.bind("keydown.autocomplete", function (event) {
            var keyCode = $.ui.keyCode;
            switch (event.keyCode) {
                case keyCode.PAGE_UP:
                    self._move("previousPage", event);
                    break;
                case keyCode.PAGE_DOWN:
                    self._move("nextPage", event);
                    break;
                case keyCode.UP:
                    self._move("previous", event);
                    // prevent moving cursor to beginning of text field in some browsers
                    event.preventDefault();
                    break;
                case keyCode.DOWN:
                    self._move("next", event);
                    // prevent moving cursor to end of text field in some browsers
                    event.preventDefault();
                    break;
                case keyCode.ENTER:
                    // when menu is open or has focus
                    if (self.menu.active) {
                        event.preventDefault();
                    } else {
                        callHeaderSearch($("#header_search_input")[0]);
                        event.preventDefault();
                        break;
                    }
                    //passthrough - ENTER and TAB both select the current element
                case keyCode.TAB:
                    if (!self.menu.active) {
                        return;
                    }
                    self.menu.select(event);
                    break;
                case keyCode.ESCAPE:
                    self.element.val(self.term);
                    self.close(event);
                    break;
                case keyCode.LEFT:
                case keyCode.RIGHT:
                case keyCode.SHIFT:
                case keyCode.CONTROL:
                case keyCode.ALT:
                    // ignore metakeys (shift, ctrl, alt)
                    break;
                default:
                    // keypress is triggered before the input value is changed
                    clearTimeout(self.searching);
                    self.searching = setTimeout(function () {
                        self.search(null, event);
                    }, self.options.delay);
                    break;
            }
        });
    },

    _renderMenu: function (ul, items) {
        var self = this;

        // preserve the relative ordering, but group the results by type
        var typeArray = [];
        var types = {};
        var media = {};
        var numRows = 0;
        for (var i = 0; i < items.length; i++) {
            var type = items[i].table.toString();

            // handle did you mean
            if (type == didYouMeanType) {
                typeArray.push(didYouMeanType);
                types[didYouMeanType] = [items[i]];
                continue;
            }

            var typeList = types[type];
            if (typeList == undefined) {
                typeList = [];
                types[type] = typeList;
                typeArray.push(type);
            }

            // return a max of 3 results per type unless this is media in which case we'll return 5
            // per type
            if ($.inArray(type, self.mediaTypes) != -1) {
                // if this is the first item of this media type, add it to the type list and reconfigure
                // the label for the horizontal media layout
                items[i].isMedia = true;
                if (typeList.length == 0) {
                    typeList.push(items[i]);
                    numRows++;
                    items[i].label = '';
                    items[i].mediaCount = 0;
                }

                if (++typeList[0].mediaCount <= 5) {
                    typeList[0].label += renderMedia(items[i]);
                }
            } else if (typeList.length < 3 && (type == didYouMeanType || type == "ASTD.org" || type == "ASTD Store")) {
                typeList.push(items[i]);
                numRows++;
            }
        }

        // if we have more than 6 rows, take items off of each non-media type until we're down to 6 results
        var maxRows = 6;
        while (numRows > maxRows) {
            for (i = typeArray.length - 1; numRows > maxRows && i >= 0; i--) {
                typeList = types[typeArray[i]];
                // keep at least 1 result in each.  this will automatically handle the media types
                if (typeList.length > 1) {
                    typeList.pop();
                    numRows--;
                }
            }
        }

        // put the types in a predetermined order
        typeArray.sort(function (a, b) {
            var idx1 = a in typeOrderMap ? typeOrderMap[a] : Number.MAX_VALUE;
            var idx2 = b in typeOrderMap ? typeOrderMap[b] : Number.MAX_VALUE;
            return idx1 - idx2;
        });

        i = 0;
        keyword = $('#header_search_input').val();
        for (i = 0; i < typeArray.length; i++) {
            type = typeArray[i];
            if (type == didYouMeanType || type == "ASTD.org" || type == "ASTD Store") {
                typeList = types[type];

                // handle did you mean
                if (type == didYouMeanType) {
                    ul.append(typeList[0].label);
                    continue;
                }

                ul.append("<li class='lookahead_type_group lookahead_heading' onclick='return gotoResults(\"" + keyword + "\", \"" + type + "\");'><div class='left'>" + type + "</div><div class='seeall right'>See All Results</div></li>");
                for (var j in typeList) {
                    if (typeList[j].isMedia != undefined && typeList[j].isMedia) {
                        typeList[j].label += '<div class="clear"></div>';
                    }
                    self._renderItem(ul, typeList[j]);
                }
            }
        }
        ul.append("<li class='lookahead_footer ui-corner-bottom'><div class='lookahead_heading' style='color:white' onclick='return gotoResults(\"" + keyword + "\");'>See All Results <img src='/ASTD/Images/right-arrow.gif' alt='See All Results'/></div></li>");

    },

    _positionAC: function (el, menuEl) {
        // workaround for FF bug
        var leftOffset = -7;
        var box = $(el).offset();
        if (parseInt(box.left) != box.left) {
            leftOffset = -6;
        }

        $(menuEl).show().position({
            my: "left top",
            at: "left bottom",
            of: this.element,
            offset: leftOffset + " 10",
            collision: "none"
        });
    },

    _suggest: function (items) {
        var ul = this.menu.element
                .empty()
                .zIndex(this.element.zIndex() - 1),
            menuWidth,
            textWidth;
        this._renderMenu(ul, items);
        // TODO refresh should check if the active item is still in the dom, removing the need for a manual deactivate
        this.menu.deactivate();
        this.menu.refresh();

        this._positionAC(this.element, this.menu.element);

        menuWidth = ul.width("").width();
        textWidth = this.element.width();
        ul.width(Math.max(menuWidth, textWidth));
        ul.css('position', 'absolute');

        // if the window is resized, ensure the autocomplete is positioned correctly
        var self = this;
        $(window).bind('resize.autocomplete', function () {
            self._positionAC(self.element, self.menu.element);
        });
    }
});

function insertCarrot(trigger, tip) {
    var parent_padding = parseInt(trigger.parent().css('padding-left'));
    var x_pos = trigger.position().left + (trigger.width() / 2) - parent_padding;
    var y_pos = trigger.position().top + trigger.outerHeight() - 10;
    var carrot = $('<div class="carrot"></div>');
    carrot.css({ position: 'absolute', top: y_pos, left: x_pos, zindex: 20001 });
    tip.before(carrot);
    carrot.css('z-index', 10001); //ie7 hack
}

$(document).ready(function () {
    $("#header_search_input").groupedcomplete({
        source: function (request, response) {
            json = $.ajax({
                url: "http://search.astd.org:17000/autocomplete/json",
                data: $.extend(lookaheadParams, { query: request.term, jsoncallback: '?' }),
                dataType: 'jsonp',
                username: 'attivio',
                password: 'astd',
                success: function (data) {
                    handleLookaheadResponse(data, request.term, response);
                }
            });
        },

        open: function () {
            $('.lookahead_result_img_wrap').each(function () {
                $(this).tooltip({
                    position: 'bottom right',
                    predelay: 1000,
                    relative: true,
                    onShow: function () {
                        var trigger = this.getTrigger();
                        var tip = this.getTip();
                        insertCarrot(trigger, tip);
                        var horizontal_adjustment = trigger.parent().position().left + ((trigger.parent().outerWidth() - tip.outerWidth()) / 2) - 2;
                        var vertical_adjustment = trigger.position().top + trigger.outerHeight() + 1;
                        tip.css({ position: 'absolute', top: vertical_adjustment, left: horizontal_adjustment });
                    },
                    onHide: function () {
                        $('.carrot').remove();
                    }

                });

            });
            $('.lookahead_type_group').hover(
                function () {
                    $('.seeall', this).fadeIn();
                },
                function () {
                    $('.seeall', this).fadeOut();
                }
            );
            $('#header_search_input_wrap').addClass('header_search_trigger');
        },

        focus: function (event, ui) {
            search_option = ui.item.uri;
            return false;
        },

        select: function (event, ui) {
            if (ui.item.isMedia == undefined || !ui.item.isMedia) {
                window.location = ui.item.uri;
            }
            return false;
        },

        close: function () {
            $('#header_search_input_wrap').removeClass('header_search_trigger');

            // remove the window resize handler for autocomplete
            $(window).unbind('resize.autocomplete');
        }
    });
});
