﻿$(function () {
    var container = $('#layout-container'),
            header = $('#header'),
            outerLeft = $('#OuterLeft'),
            outerRight = $('#OuterRight'),
            inter = null;

    function fixBorder() {
        var outerWidth = Math.ceil((container.innerWidth() - header.width()) / 2);
        outerLeft.width(outerWidth).position({
            my: 'right top',
            of: header,
            at: 'left top',
            collision: 'none'
        });
        outerRight.width(outerWidth).position({
            my: 'left top',
            of: header,
            at: 'right top',
            collision: 'none'
        });
    }

    $(window).bind({
        resize: fixBorder,
        focus: function () {
            if (!inter)
                inter = setInterval(fixBorder, 50);
        },
        blur: function () {
            if (inter) {
                clearInterval(inter);
                inter = null;
            }
        }
    }).focus();
});

// correct height for layout 02
$(window).load(function () {
    // set height
    if (_CLIENT_LAYOUT == '01' || _CLIENT_LAYOUT == '02' || _CLIENT_LAYOUT == '06') {
        var top = $('div#left-content-top').outerHeight();
        var mid = $('div#left-content-middle').outerHeight();
        var bot = $('div#left-content-bottom').outerHeight();
        var tot = top + mid + bot;
        var mh = $('div#page').css('min-height');
        var mhi = parseInt(mh.replace('px', ''));
        if (mhi == NaN)
            mhi = 0;
        //$('div#page').height(tot);
        if (tot > mhi)
            $('div#page').css('min-height', tot);
    }
});


(function ($) {
    $.widget("ari.searchbox", {

        options: {
            cssClass: 'search-hints',
            searchUrl: '/KeywordProducts/Search',
            searchAllUrl: '/SearchAll',
            autoCompleteURL: '/KeywordProducts/Autocomplete',
            templateId: 'auto-complete-result-tmpl',
            watermarkText: 'Search for product or part number...',
            minLength: 2,
            delay: 300
        },

        close: function () {
            this.autoSuggestBox.hide();
            this._clearSelection();
        },

        _create: function () {
            var self = this,
                suppressKeyPress;

            this.autoSuggestBox = $('<div/>', { 'class': this.options.cssClass, 'style': 'z-index:9999;width:370px' }).appendTo(document.body);
            this.selectedItem = null;
            this.template = $('#' + this.options.templateId);
            this.element
                .attr('autocomplete', 'off')
                .bind('keydown.searchbox', function (e) {
                    suppressKeyPress = false;
                    var keyCode = $.ui.keyCode;

                    switch (e.keyCode) {
                        case keyCode.UP:
                            if (self.selectedItem != null) {
                                var prev = self.selectedItem.prev();
                                if (prev.length == 0) {
                                    prev = self.selectedItem.closest('.hint-group').prev('.hint-group');
                                    if (prev.length !== 0)
                                        prev = prev.find('li:last');
                                    else
                                        prev = null;
                                }
                                if (prev) {
                                    self.selectedItem.removeClass('ui-state-hover');
                                    self.selectedItem = prev;
                                }
                            }
                            if (self.selectedItem)
                                self.selectedItem.addClass('ui-state-hover');
                            break;
                        case keyCode.DOWN:
                            if (self.selectedItem == null)
                                self.selectedItem = self.autoSuggestBox.find('li:first');
                            else {
                                var next = self.selectedItem.next();
                                if (next.length == 0) {
                                    next = self.selectedItem.closest('.hint-group').next('.hint-group');
                                    if (next.length !== 0)
                                        next = next.find('li:first');
                                    else
                                        next = null;
                                }
                                if (next) {
                                    self.selectedItem.removeClass('ui-state-hover');
                                    self.selectedItem = next;
                                }
                            }
                            if (self.selectedItem)
                                self.selectedItem.addClass('ui-state-hover');
                            break;
                        case keyCode.ENTER:
                        case keyCode.NUMPAD_ENTER:
                            suppressKeyPress = true;
                            if (self.selectedItem && self.selectedItem.length > 0)
                                location = self.selectedItem.find('a').attr('href');
                            else
                                $('#SearchButton').click();
                            break;
                        case keyCode.ESCAPE:
                            self.autoSuggestBox.hide();
                            //self.element.val( self.term );
                            //self.close( event );
                            break;
                        default:
                            clearTimeout(self.searching);
                            self.searching = setTimeout(function () {
                                self._search(self.element.val());
                            }, self.options.delay);
                            break;
                    }
                })
                .bind('keypress.searchbox', function (e) {
                    if (suppressKeyPress) {
                        suppressKeyPress = false;
                        e.preventDefault();
                    }
                })
                .bind('focus.searchbox', function (e) {
                    self._clearSelection();
                    if (self.element.val() === self.options.watermarkText) {
                        self.element.removeClass('watermarkOn').val('');
                    }
                })
                .bind('blur.searchbox', function (e) {
                    e.stopPropagation();
                    setTimeout(function() {
                        clearInterval(self.searching);
                        self._clearSelection();
                        self.autoSuggestBox.hide();
                        self.element.val($.trim(self.element.val()));
                        if (self.element.val() === '') {
                            self.element.addClass('watermarkOn').val(self.options.watermarkText);
                        }
                    }, 250);
                })
                .blur();
        },

        _cache: {},

        _search: function (term) {
            var self = this,
                key = $.trim(term.toLowerCase());

            if (term.length >= self.options.minLength) {
                if (self._cache[key] === undefined)
                    $.getJSON(self.options.autoCompleteURL, { criteria: term }, function (data) {
                        for (var i = 0; i < data.length; ++i) {
                            data[i].ViewAllLink = self.options.searchAllUrl + '?criteria=' + encodeURIComponent(term) + '&ProductType=' + data[i].ProductType;
                        }
                        self._cache[key] = data;
                        self._showResult(term, key, data);
                    });
                else
                    self._showResult(term, key, self._cache[key]);
            }
        },

        _showResult: function (term, key, data) {
            this.autoSuggestBox.hide();
            if (data.length > 0 || /\s+$/.test(term)) {
                if (this.autoSuggestBox.data('term') !== key) {
                    this.selectedItem = null;
                    this.autoSuggestBox
                        .data('term', key)
                        .empty()
                        .append(this.template.tmpl(data))
                        .append($('<p/>').append(
                            $('<a/>', {
                                text: 'See all results for "' + term + '" »',
                                href: this.options.searchUrl + '?criteria=' + encodeURIComponent(term)
                            })));
                }
            }
            this.autoSuggestBox.show().position({ my: 'left top', at: 'left bottom', of: '#SearchBox', collision: 'none' });
        },

        _clearSelection: function () {
            if (this.selectedItem !== null) {
                this.selectedItem.removeClass('ui-state-hover');
                this.selectedItem = null;
            }
        }
    });
})(jQuery);

function initSearchBox(ctx) {
    $(function () {
        var $searchDiv = $('#SearchDiv'),
            $searchBox = $('#SearchBox'),
            $searchResult = $('#auto-complete-result');

        $searchBox.searchbox({ searchUrl: ctx.urlPrefix + ctx.searchUrl, searchAllUrl: ctx.urlPrefix + ctx.searchAllUrl, autoCompleteURL: ctx.autoCompleteURL, delay: 150 });

        $('#SearchButton').click(function (e) {
            location = ctx.urlPrefix + ctx.searchUrl + '?' + $.param({ criteria: $searchBox.val() });
        });

        $searchDiv.show();

        // reposition on resize
        $(window).resize(function () {
            var offset = searchOffset();
            var posElement = $('div#header').find('table');
            //var posElement = $('div#noFindIt');
            if (posElement.length == 0)
                posElement = $('div#header');
            if (posElement.length > 0) {
                $searchDiv.position({
                    of: posElement,
                    my: 'right top',
                    at: 'right top',
                    collision: 'fit',
                    offset: offset
                });
            }
        }).resize();

        function searchOffset() {
            var pos = $searchDiv.find('#SearchPos');
            pos.show();
            var right = pos.css('right');
            var top = pos.css('top');

            if (right == undefined)
                right = 0;
            if (top == undefined)
                top = 0;
            pos.hide();

            // if we haven't moved it we will move it based on the div#header padding
            if ((top == 0 || top == '0px' || top == 'auto') && $('div#header').length > 0 && _CLIENT_LAYOUT) {
                var topPad = "0";
                switch (_CLIENT_LAYOUT) {
                    case "01":
                    case "02":
                    case "04":
                        topPad = $('div#header').css('margin-top');
                        break;
                }
                top = "-" + topPad;
            }

            return right + ' ' + top;
        }
    });
}

function initNav(data) {
    $(function () {
        var isHorizontal = data.isHorizontal;
        var navImgUrl = data.navImgUrl;

        function makeLinkButton($a) {
            $a.addClass('ui-state-default')
            .hover(function () {
                $(this).toggleClass('ui-state-hover');
            }, function () {
                $(this).toggleClass('ui-state-hover');
            }).css({ display: 'block', 'white-space': 'nowrap' });
        }

        $('#MainNav').css({ margin: '0', padding: '0' }).children('li').each(function () {
            var $self = $(this).css({ margin: '0', padding: '0', float: 'left' });
            var isDivider = $self.is('.divider');
            if (!isDivider)
                $self.width(isHorizontal ? 'auto' : '160px');
            /*if ($.browser.msie && isHorizontal && !isDivider)
            $self.css({ width: 0 });*/

            makeLinkButton($self.children('a'));
            var html = $('<div/>').append($('ul:first', this)).html();
            if (html !== '') {
                $self.fgmenu({
                    content: html,
                    positionOpts: {
                        posX: isHorizontal ? 'left' : 'right',
                        posY: isHorizontal ? 'bottom' : 'top',
                        detectH: false,
                        detectV: false
                    },
                    showSpeed: 0,
                    callerOnState: '',
                    crossSpeed: 0,
                    flyOut: true
                });

                $self.mouseover(function () {
                    $(this).data('menu').showMenu();
                }).unbind('click').click(function () {
                    var href = $(this).children('a').attr('href');
                    if (href !== '#')
                        location.href = href;
                });
            }
            else
                $self.mouseover(function () {
                    $.each(allUIMenus, function () {
                        if (this.menuOpen)
                            this.kill();
                    });
                });
        });

        $('.fg-menu-container').live('mouseleave', function (e) {
            if ($(e.relatedTarget).closest('#MainNav').length == 0) {
                var $ele = $(this);
                $ele.data('leaving', setTimeout(function () {
                    $ele.hide();
                }, 200));
            }
        }).live('mouseenter', function (e) {
            var $ele = $(this);
            if ($ele.data('leaving')) {
                clearTimeout($ele.data('leaving'));
                $ele.removeData('leaving');
            }
        });

        $('#MainNav').show();
    });
}

// The following 2 methods are extract from /common/js/menu.js. They are temporarily moved here so we don't have to include /common/js/menu.js. They should be replaced with the jquery keyfilter.
function KeyFilter(e, RegEx) {
    var keynum;
    var keychar = new String("");
    var re = new RegExp(RegEx);

    if (window.event) {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    if (keychar.match(re) || keynum == 8 || String(keynum) == "undefined")
        return true;
    else
        return false;
}

function KeyFilterRemove(searchChar, replaceChar, obj) {
    obj.value = obj.value.replace(searchChar, replaceChar);
}

