﻿$(function () {
    $('#dfarea').click(function () {
        location.href = '/Customize?df=true';
    });
    $('#ysarea').click(function () {
        var iid = $('#ysarea').attr('data-iid');
        if (iid && iid != 0) {
            location.href = '/Store?iid=' + iid;
        } else {
            location.href = '/Store/SearchResults';
        }
    });
    $('a#login').toggle(function () {
        var $lp = $('div#loginPopup').fadeIn(300, function () {
            $(this).find('input.loginEmail').focus();
        });
    }, function () {
        $('div#loginPopup').fadeOut(500);
    });
    /* institution lookup */
    $('table.instLkpItems td').live('click', function () {
        instPopupSelect($(this).parents('tr:first'));
    });
    var populateInstLookup = function ($t) {
        $t.siblings('input[type=hidden]').val('');
        var q = $t.val();
        if ($t.val().length >= 3) {
            $.ajax({
                url: '/Search/InstitutionLookup',
                type: 'POST',
                data: 'q=' + q,
                dataType: 'html',
                complete: function () {
                    $t.removeClass('instLkpPending');
                },
                success: function (data, status, req) {
                    var $pop = $t.siblings('div.instLkpPop').html(data).show();
                    $pop.wrapText(q, 'highlight');
                }
            });
        }
    }
    $('input.instLkp').keyup(function (e) {
        var $t = $(this);
        $t.addClass('instLkpPending');
        if (document.instLkpTimeout) clearTimeout(document.instLkpTimeout);
        document.instLkpTimeout = $.delay(200, function () {
            populateInstLookup($t);
        });
    }).blur(function () {
        var $pop = $(this).siblings('div.instLkpPop');
        $.delay(300, function () { $pop.hide(); });
        $(this).data('focused', false);
    }).focus(function () {
        var $t = $(this).data('focused', true);
        $.delay(200, function () {
            if ($t.siblings('input[type=hidden]').val() == '') {
                populateInstLookup($t);
            }
        });
    })

    /* menu */
    $('ul#menu > li').hasMenuPopup('div:first');
    $('ul#menu > li li').click(function () {
        var $a = $(this).children('a:first');
        var h = $a.attr('href');
        document.location = h;
    });
    /* minicart */
    var $mc = $('div#minicart').click(function () {
        location.href = '/Cart';
    });
    var mcw = $mc.width();
    var $mcc = $('div#minicartcontents').css('left', mcw + 'px');
    $mc.hasMenuPopup($mcc);
    var $caltip;
    $('div#calendarwidgetarea').hoverDelay(400, function ($t) {
        $caltip = $('div#calendarWidgetTip').showTip($t, {
            src: '/Tip/ShippedByGuarantee.htm'
        });
    }, function ($t) {
        $caltip.hideTip();
    });
    var $emailtip;
    $('input#esemail').focus(function () {
        $emailtip = $('#esemailtip').showTip($(this));
    }).blur(function () {
        $emailtip.hideTip();
    }).keydown(function () {
        $emailtip.hideTip();
    });

    $('input.numeric, input.currency').keydown(function (e) {
        var $t = $(this);
        var allowDecimal = $t.hasClass('decimal') || $t.hasClass('currency');
        var allowNegative = $t.hasClass('negative');
        if (window.event) e = window.event;
        var keynum = (e.keyCode) ? e.keyCode : e.which;
        if (e.ctrlKey)
            return true;
        switch (keynum) {
            case 9: //tab
            case 13: //enter
            case 17: //ctrl
            case 18: //alt
            case 19: //pause/break
            case 20: //capslock
            case 27: //escape
            case 33: //page up
            case 34: //page down
            case 35: //end
            case 36: //home
            case 37: //left arrow
            case 38: //up arrow
            case 39: //right arrow
            case 40: //down arrow
            case 8: //backspace
            case 45: //insert
            case 46: //delete
                return true;
            case 96: //0 numpad
            case 97: //1 numpad
            case 98: //2 numpad
            case 99: //3 numpad
            case 100: //4 numpad
            case 101: //5 numpad
            case 102: //6 numpad
            case 103: //7 numpad
            case 104: //8 numpad
            case 105: //9 numpad
            case 49: //1
            case 50: //2
            case 51: //3
            case 52: //4
            case 53: //5
            case 54: //6
            case 55: //7
            case 56: //8
            case 57: //9
            case 48: //0
                return !e.shiftKey;
                break;
            //NUMPAD                                                       
            case 110: //. numpad
            case 190: //.
                return !e.shiftKey && allowDecimal;
                break;
            case 109: //- numpad
            case 189: //-
                return !e.shiftKey && allowNegative;
                break;
            default:
                return false;
        };
    }).change(function () {
        var $t = $(this);
        if ($t.hasClass('string')) {
            if (isNaN($t.val())) $t.val('');
            return;
        }
        if (isNaN($t.val())) {
            $t.val(0);
        } else {
            if (!$t.hasClass('negative')) {
                if ($t.val() < 0) $t.val(0);
            }
            if ($t.hasClass('decimal')) {
                $t.val(parseFloat($t.val()));
            } else if ($t.hasClass('currency')) {
                $t.val(parseFloat($t.val()).toFixed(2));
            } else {
                $t.val(parseInt($t.val() || 0));
            }
        }
    });
});

$.ajaxSetup({
    error: function (req, data, ex) {
        if (req.responseText.indexOf('SessionTimeoutException') > -1) {
            location.href = '/Error/SessionTimeout';
        }
        alert('An error occurred processing your request, please try again. If the problem persists, please contact Customer Service.');
    }
});
$.ajaxJson = function (ajaxObj) {
    var requestId = (new Date()).valueOf();
    if (!document.requestIds) document.requestIds = {};
    document.requestIds[ajaxObj.url] = requestId;
    if (ajaxObj.form) {
        ajaxObj.data = ajaxObj.form.serialize() + '&reqId=' + requestId;
    } else {
        if (!ajaxObj.data) ajaxObj.data = {};
        ajaxObj.data.reqId = requestId;
    }
    $.ajax({
        url: ajaxObj.url,
        type: 'POST',
        data: ajaxObj.data,
        dataType: 'json',
        success: function (data, req, status) {
            if (data.RequestId == document.requestIds[ajaxObj.url]) {
                if (data.Error) {
                    if (ajaxObj.error) {
                        ajaxObj.error(data.ErrorCode, data.Error);
                    } else {
                        alert(data.Error);
                    }
                    if (data.Exception) alert(data.Exception);
                } else {
                    if (ajaxObj.success) ajaxObj.success(data.Data, req, status);
                }
            }
        }
    });
}
$.delay = function (ms, func) {
    return setTimeout(func, ms);
}
$.fn.filmstrip = function (o) {
    $(this).each(function () {
        var $fs = $(this);
        $fs.data('index', 0);
        $fs.data('pageSize', o.pageSize || 5);
        var $btnL = $fs.children('button.left');
        var $btnR = $fs.children('button.right');
        var $ul = $fs.children('ul');
        var ulw = $ul.outerWidth(true);
        var fsw = $fs.innerWidth();
        var ulpos = $ul.position();
        var doMove = function () {
            var index = $fs.data('index');
            var itemIndex = $fs.data('pageSize') * index;
            var $to = $($fs.find('ul li').get(itemIndex || 0));
            if ($to.length > 0) {
                var off = $to.position();
                $fs.children('ul').animate({ left: -off.left + 'px' }, 500);
            } else {
                if (index > 0) {
                    $fs.data('index', index - 1);
                }
            }
        }
        $btnL.click(function () {
            var index = $fs.data('index');
            if (index > 0) {
                $fs.data('index', $fs.data('index') - 1);
            }
            doMove();
        });
        $btnR.click(function () {
            $fs.data('index', $fs.data('index') + 1);
            o.load($fs);
            doMove();
        });
    });
};
$.fn.outerHTML = function (html) {
    var $t = $(this);
    if ($t.length == 0) {
        return null;
    }
    if (html) {
        $t[0].outerHTML = html;
    }
    return $(this)[0].outerHTML;
};
$.fn.hoverDelay = function (ms, funcIn, funcOut) {
    var $t = $(this);
    if ($t.length == 0) {
        return null;
    }
    $t.hover(function () {
        $t.data('hd-over', true);
        $.delay(ms, function () {
            var stillOver = $t.data('hd-over');
            $t.data('hd-met', stillOver);
            if (stillOver) {
                funcIn($t);
            }
        });
    }, function () {
        $t.data('hd-over', false);
        if ($t.data('hd-met')) {
            funcOut($t);
        }
        $t.data('hd-met', false);
    });
};
String.prototype.format = function () {
    var result = this;
    if (arguments.length == 0)
        return result;
    for (var i = 0; i < arguments.length; i++) {
        result = result.replace('{' + i + '}', arguments[i]);
    }
    return result;
};
function logInOutSuccess($wrap, hideMsg) {
    if (!hideMsg) loginWorking('Successfully logged in!');
    $wrap.find('div.customerSelect').hide();
    $.delay(500, function () {
        var sendTo = $wrap.find('input[name=sendTo]').val();
        if (sendTo) {
            location.href = sendTo;
        } else {
            location.reload(true);
        }
    });
}
function showCart(o) {
    if (!o) o = {};
    var $d = $('div#minicartcontents');
    var $mc = $('div#minicart');
    $mc.unbind('mouseenter mouseleave');
    if (o.showingCart) o.showingCart($mc, $d);
    showMenu($d);
    $(document).not($d).click(function (e) {
        hideMenu($d);
        $mc.hasMenuPopup($d);
        if (o.cartHidden) o.cartHidden($mc, $d);
    });
    if (o.cartShown) o.cartShown($mc, $d);
    return $d;
}
function showMenu($div) {
    $div.data('s', true);
    $div.css('z-index', '1000');
    $div.data('w');
    var l = $div.data('l');
    if (!l) {
        l = $div.css('left');
        l = l ? parseInt(l) : 0;
        $div.data('l', l);
    }
    var w = $div.data('w');
    if (!w) {
        w = $div.width();
        $div.data('w', w);
    }
    var h = $div.data('h');
    if (!h) {
        h = $div.height();
        $div.data('h', h);
    }
    var sl = 0;
    if (isNaN(l)) l = 0;
    if (!isNaN(l) && l > 0) sl = l;
    $div.width(0).height(0).css('left', sl + 'px').children().css('opacity', '0');
    $div.show().animate({
        width: w + 'px',
        height: h + 'px',
        left: l + 'px'
    },
        {
            duration: 300,
            queue: false,
            complete: function () {
                $div.children().animate({
                    opacity: '1'
                }, {
                    queue: false,
                    duration: 300
                });
            }
        });
};
function hideMenu($div) {
    var s = $div.data('s');
    $div.data('s', false);
    if (!s) return;
    var l = $div.data('l');
    var sl = 0;
    if (!isNaN(l) && l > 0) sl = l;
    $div.css('z-index', '1');
    $div.children().animate({
        opacity: '0'
    },
        {
            queue: false,
            duration: 200,
            complete: function () {
                $div.animate({
                    width: '0px',
                    height: '0px',
                    left: sl + 'px'
                }, {
                    queue: false,
                    duration: 200,
                    complete: function () {
                        $div.hide();
                    }
                });
            }
        });
};
$.fn.hasMenuPopup = function (popup) {
    this.each(function () {
        var $t = $(this);
        var to = null;
        $t.hover(function () {
            to = $.delay(270, function () {
                var $div = (typeof popup == 'string') ? $t.children(popup) : popup;
                if ($div)
                    showMenu($div);
            });
        },
        function () {
            if (to) clearTimeout(to);
            var $div = (typeof popup == 'string') ? $t.children(popup) : popup;
            if ($div)
                hideMenu($div);
        });
    });
}
$.fn.showTip = function ($target, options) {
    options = options || {};
    var $tip = $(this);
    $tip.data('s', true);
    var $content = $tip.find('.content');
    if ($content.length == 0) {
        $tip.css('display', 'inline-block');
        $content = $('<div class="content"/>').html($tip.html());
        $tip.html('').prependTo($('body'));
        var $arrowCont = $('<div class="arrowCont" />');
        var $arrow = $('<div class="arrow" />').appendTo($arrowCont);
        var targetOffset = $target.offset();
        $tip.refresh = function () {
            if ($tip.hasClass('up')) {
                $tip.append($content);
                $tip.append($arrowCont);
                $tip.css({
                    left: targetOffset.left + (($target.outerWidth(true) - $tip.outerWidth(true)) / 2) + 'px',
                    top: targetOffset.top + -1 * $tip.outerHeight() + 'px'
                });
            } else if ($tip.hasClass('down')) {
                $tip.append($arrowCont);
                $tip.append($content);
                $tip.css({
                    left: targetOffset.left + (($target.outerWidth(true) - $tip.outerWidth(true)) / 2) + 'px',
                    top: targetOffset.top + $target.outerHeight() + 'px'
                });
            } else if ($tip.hasClass('left')) {
                $tip.append($arrowCont);
                $arrowCont.prepend($content);
                var arrh = parseInt($arrow.css('height'));
                var arrw = parseInt($arrow.css('width'));
                $tip.css({
                    width: arrw + $content.outerWidth() + 'px',
                    height: $content.outerHeight() + 'px'
                });
                $arrowCont.css({
                    height: $content.outerHeight() + 'px',
                    position: 'relative'
                });
                $arrow.css({
                    position: 'absolute',
                    top: '50%',
                    right: '0',
                    marginTop: arrh / -2 + 'px'
                });
                $content.css({
                    position: 'absolute',
                    top: '0',
                    right: arrw + 'px'
                });
                $tip.css({
                    top: targetOffset.top + (($target.outerHeight() - $tip.outerHeight()) / 2) + 'px',
                    left: targetOffset.left - $tip.outerWidth() + 'px'
                });
            } else if ($tip.hasClass('right')) {
                $tip.append($arrowCont);
                $arrowCont.append($content);
                $content.css({
                    position: 'absolute',
                    top: '0',
                    left: $arrow.outerWidth() + 'px'
                });
                $tip.css({
                    width: $arrow.outerWidth() + $content.outerWidth() + 'px',
                    height: $content.outerHeight() + 'px'
                });
                $arrowCont.css({
                    height: $content.outerHeight() + 'px',
                    position: 'relative'
                });
                $arrow.css({
                    position: 'absolute',
                    top: '50%',
                    left: '0',
                    marginTop: $arrow.outerHeight(true) / -2 + 'px'
                });
                $tip.css({
                    top: targetOffset.top + (($target.outerHeight() - $tip.outerHeight()) / 2) + 'px',
                    left: targetOffset.left + $target.outerWidth() + 'px'
                });
            };
        };
        $tip.refresh();
    }
    if (!$tip.hideTip) {
        $tip.hideTip = function () {
            if ($content.data('loadstatus') == 'loading') {
                $.delay(1000, function () { $tip.hideTip(); });
                return;
            }
            if ($tip.data('s')) {
                $tip.data('s', false);
                $tip.fadeOut('slow');
            }
        };
    }
    $tip.hide().fadeIn('slow', function () {
        if (options.src && $content.data('loadstatus') != 'loaded') {
            $content.html('Loading...');
            $content.data('loadstatus', 'loading');
            $content.load(options.src, function (res, status, req) {
                if (status == 'error') {
                    $content.data('loadstatus', 'error');
                    $content.html('An error occured loading this tip. Please try again.');
                }
                $content.data('loadstatus', 'loaded');
                $tip.refresh();
            });
        }
        if (options.shown) options.shown($tip);
    });
    return $tip;
};
$.fn.hideModal = function (complete) {
    var $m = $(this).data('modal');
    if ($m) {
        $m.data('visible', false);
        $m.fadeOut(400, function () {
            $('div#modalbg').fadeOut(400, function () {
                if (complete) complete();
            });
        });
    }
};
$.fn.modalVisible = function () {
    var $m = $(this).data('modal');
    if ($m) {
        return $m.data('visible');
    }
    return false;
}
$.fn.showModal = function (o) {
    var $t = $(this).first();
    var $bg = $('div#modalbg');
    var $b = $('body');
    if ($bg.length == 0) {
        $bg = $('<div id="modalbg" />').appendTo($b);
    }
    var $m = $t.data('modal');
    if (!$m) {
        $m = $('<div class="modal"><button class="closeBtn" type="button"><span class="sprite darkx"/></span></button>');
        $t.data('modal', $m);
        $m.append($t.show()).appendTo($b).css({
            left: ($bg.width() - $m.outerWidth(false)) / 2 + 'px',
            top: ($bg.height() - $m.outerHeight(false)) / 2 + 'px'
        }).hide();
    }
    $m.data('visible', true);
    $m.children('button.closeBtn').click(function () {
        $t.hideModal();
    })
    $bg.hide().fadeIn(400, function () {
        $m.fadeIn(400);
    });
    $bg.click(function () {
        $t.hideModal();
    });
    return $t;
}
$.fn.updateModal = function () {
    var $bg = $('div#modalbg');
    var $m = $(this).data('modal');
    if ($m) {
        $m.css({
            left: ($bg.width() - $m.outerWidth(false)) / 2 + 'px',
            top: ($bg.height() - $m.outerHeight(false)) / 2 + 'px'
        })
    }
}
$.fn.showGallery = function (o) {
    var $source = $(this).first();
    if ($source.length == 1) {
        var $items = $source.children();
        var $ig = $('#imageGallery');
        var $thumbs = $ig.children('div.igthumbs:first');
        var $title = $ig.children('div.igtitle:first');
        var $display = $ig.children('img:first');
        if ($ig.length == 0) {
            $thumbs = $('<div class="igthumbs"/>');
            $display = $('<img />');
            $title = $('<div class="igtitle"/>');
            $ig = $('<div id="imageGallery"></div>').append($title).append($display).append($thumbs).appendTo($('body')).hide();
        }
        $thumbs.children().remove();
        if ($items.length > 1) {
            $items.each(function () {
                var $i = $(this);
                var thumbSrc = $i.find('img:first').attr('src');
                var $a = $i.children('a:first');
                var fullSrc = $a.attr('href');
                var title = $a.attr('title');
                var $thumb = $('<img src="' + thumbSrc + '"/>').appendTo($thumbs).data('fullSrc', fullSrc).data('title', title).click(function () {
                    $('#imageGallery img:first').attr('src', $(this).data('fullSrc'));
                    $('#imageGallery div.igtitle:first').text($(this).data('title'));
                    $('#imageGallery').updateModal();
                });
            });
        }
        var $firstA = $items.first().children('a:first')
        $display.attr('src', $firstA.attr('href')).load(function () {
            $('#imageGallery').updateModal();
        }).click(function () {
            var $ts = $('#imageGallery div.igthumbs:first img');

        });
        $title.text($firstA.attr('title'));
        $ig.show().showModal();
    }
}
function loginWorking(msg) {
    $('form#loginForm').hide();
    $('div#loginWorking').show().children('span').text(msg);
}
function instPopupSelect($tr) {
    var $p = $tr.parents('div.instLkp:first');
    $p.find('input[type=hidden]:first').val($tr.attr('data-id'));
    $p.find('input.instLkp:first').val($tr.attr('data-name'));
    $tr.parents('div.instLkpPop').hide();
    $p.find('input.instLkp:first').focus();
}
$.fn.wrapText = function (pattern, className) {
    function innerWrapText(node, pattern, className) {
        var skip = 0;
        if (node.nodeType == 3) {
            var pos = node.data.toUpperCase().indexOf(pattern);
            if (pos >= 0) {
                var span = document.createElement('span');
                span.className = className;
                var mdl = node.splitText(pos);
                var end = mdl.splitText(pattern.length);
                var mdlClone = mdl.cloneNode(true);
                span.appendChild(mdlClone);
                mdl.parentNode.replaceChild(span, mdl);
                skip = 1;
            }
        }
        else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
            for (var i = 0; i < node.childNodes.length; ++i) {
                i += innerWrapText(node.childNodes[i], pattern, className);
            }
        }
        return skip;
    }
    return this.each(function () {
        innerWrapText(this, pattern.toUpperCase(), className);
    });
};

$.fn.removeWrapText = function (className) {
    return this.find("span." + className).each(function () {
        //this.parentNode.firstChild.nodeName;
        with (this.parentNode) {
            replaceChild(this.firstChild, this);
            normalize();
        }
    }).end();
};
