﻿// JScript File
var tooltip = function() {
    var id = 'ToolTip';
    var top = 3;
    var left = 3;
    var maxw = 300;
    var speed = 10;
    var timer = 10;
    var endalpha = 85;
    var alpha = 0;
    var tt, t, c, b, h;
    var ie = document.all ? true : false;
    return {
        show: function(v, w) {
            if (tt == null) {
                tt = document.createElement('div');
                tt.setAttribute('id', id);
                t = document.createElement('div');
                t.setAttribute('id', id + 'Top');
                c = document.createElement('div');
                c.setAttribute('id', id + 'Cont');
                b = document.createElement('div');
                b.setAttribute('id', id + 'Bot');
                tt.appendChild(t);
                tt.appendChild(c);
                tt.appendChild(b);
                document.body.appendChild(tt);
                tt.style.opacity = 0;
                tt.style.filter = 'alpha(opacity=0)';
                document.onmousemove = this.pos;
            }
            tt.style.display = 'block';
            c.innerHTML = v;
            tt.style.width = w ? w + 'px' : 'auto';
            if (!w && ie) {
                t.style.display = 'none';
                b.style.display = 'none';
                tt.style.width = tt.offsetWidth;
                t.style.display = 'block';
                b.style.display = 'block';
            }
            if (tt.offsetWidth > maxw) { tt.style.width = maxw + 'px' }
            h = parseInt(tt.offsetHeight) + top;
            clearInterval(tt.timer);
            tt.timer = setInterval(function() { tooltip.fade(1) }, timer);
        },

        pos: function(e) {
            // For IE6 compatibity - nick 22/08/2008 11:32
            var u = 0, l = 0;
            if (typeof (window.pageYOffset) == 'number') {
                //Netscape compliant
                u = window.pageYOffset;
                l = window.pageXOffset;
            } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
                //DOM compliant
                u = document.body.scrollTop;
                l = document.body.scrollLeft;
            } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
                //IE6 standards compliant mode
                u = document.documentElement.scrollTop;
                l = document.documentElement.scrollLeft;
            }

            u = ie ? event.clientY + u : e.pageY;
            l = ie ? event.clientX + l : e.pageX;
            tt.style.top = (u - h) + 'px';
            tt.style.left = (l + left) + 'px';
            tt.style.position = 'absolute';
        },

        fade: function(d) {
            var a = alpha;
            if ((a != endalpha && d == 1) || (a != 0 && d == -1)) {
                var i = speed;
                if (endalpha - a < speed && d == 1) {
                    i = endalpha - a;
                } else if (alpha < speed && d == -1) {
                    i = a;
                }
                alpha = a + (i * d);
                tt.style.opacity = alpha * .01;
                tt.style.filter = 'alpha(opacity=' + alpha + ')';
            } else {
                clearInterval(tt.timer);
                if (d == -1) { tt.style.display = 'none' }
            }
        },
        hide: function() {
            clearInterval(tt.timer);
            tt.timer = setInterval(function() { tooltip.fade(-1) }, timer);
        }
    };
} ();


function openLW(LWHref, LWWidth, LWHeight, Title) {

    $('a#FancyBoxClick').remove();
    $('body').prepend("<a id='FancyBoxClick' class='iframe2' title='" + Title + "' href='" + LWHref + "'></a> ");
    //LWWidth, LWHeight can be used as passed if required
    LWWidth = parseInt(stripAlphaChars(LWWidth));
    LWHeight = parseInt(stripAlphaChars(LWHeight));
    $(".iframe2").fancybox({
        'hideOnContentClick': false,
        'overlayColor': '#000',
        'overlayOpacity': '.8',
        'frameHeight': LWHeight,
        'frameWidth': LWWidth
    });
    $('a#FancyBoxClick').click();
    $('#fancy_overlay').css('opacity', 0.5);
}

function openFB(LWHref, title, fbOpts) {

    var fbOpts = $.extend({
        onStart: function () { },
        onClosed: function () { },
        onComplete: function () { },
        enableEscapeButton: true,
        showCloseButton: true,
        overlayOpacity: 0.3,
        overlayColor: '#666',
        hideOnOverlayClick: true,
        hideOnContentClick: true,
        width: 400,
        height: 400,
        padding: 15,
        title: title,
        href: LWHref,
        autoScale: false,
        transitionIn: 'none',
        transitionOut: 'none',
        type: 'iframe'

    }, fbOpts || {});

    $.fancybox(fbOpts);

}

function stripAlphaChars(str) {
    str = str.replace(/\D/g, '');
    return str;
}

function stripHTML(str) {
    var re = /(<([^>]+)>)/gi;
    str = str.replace(re, '');
    return str;
}
   
function closeLW() {
    $.fancybox.close();
}

function UpdateSideCarts() {
    if (window.updateMiniCart) { updateMiniCart(''); }
    if (window.updateCart) { updateCart(); }
    if (window.updateRollDownCart) { updateRollDownCart(); }
   
    siteCustom();
    //if(window.jAddSlideDown){jAddSlideDown();}
}

/*side cart code*/
var moveBy, mouseInHeader, mouseInSlider, itemsInCart;
//on dom ready
$(function() {
    sliderUp();
    if (!$("#SideCart").hasClass("stayDown")) {
        setPositionOfSlider();
        cartAnimation();
    } else {
        $("#SlideCart").removeClass('hidden');
    }
    itemsInCart = $('#SlideCart div.item').size();

});

//called when the ajax request is complete
function cartUpdatedCallback() {
    setPositionOfSlider(); //reposition the cart slider
    cartAnimation();
    sliderDown();

    if ($('#SlideCart div.item').size() != itemsInCart) {
        setTimeout(function() { sliderUp(); }, 4000);
    }
}


//move the sidecart drop down up the value of it's new height
function setPositionOfSlider() {
    moveBy = $('#SlideCart').height();
    $('#SlideCartLiner').css('top', moveBy * -1).css('display', 'block');
}

//determines when to call slideup and slidedown  
function cartAnimation() {
    mouseInHeader = mouseInSlider = false;
    $('#SideCart').mouseenter(function() { mouseInHeader = true; sliderDown(); }).mouseleave(function() { mouseInHeader = false; sliderUp(); });
    $('#SlideCartLiner').mouseenter(function() { mouseInSlider = true; sliderDown(); }).mouseleave(function() { mouseInSlider = false; setTimeout(function() { if (mouseInHeader == false) { sliderUp(); } }, 1); });
}

//slides the cart up
function sliderUp() {
    setTimeout(function() {
        if (mouseInSlider == false) {
            $("#SlideCart").animate({ 'height': '0px' }, { duration: 1000, queue: false, complete: function() { } });
            $('#SlideCartLiner').animate({ 'top': moveBy * -1 }, { duration: 1000, queue: false, complete: function() { } });
        }
    }, 1);
}

//slides the cart down
function sliderDown() {
    if (!$("#SideCart > div").hasClass('emptyCart')) {
        $("#SlideCart").css('width', $('#SideCart').width()).animate({ 'height': moveBy + 'px' }, { duration: 1000, queue: false }); $('#SlideCartLiner').animate({ 'top': 0 }, { duration: 1000, queue: false, complete: function() { } });
    }
}
/* end side cart code*/

//will clear text of textbox on focus and reset value to original if left empty
function resetTextValue(selector) {
    var txtVal = $(selector).val();
    $(selector).focus(function() {
        if ($(this).val() == txtVal) { $(this).val(''); }
    }).blur(function() {
        if ($(this).val() == '') { $(this).val(txtVal); }
    });
}

//DOM ready
$(function() {
    resetTextValue('#SearchBox input[type=text]');
    resetTextValue('#SendToFriend textarea');
    //DD_roundies.addRule('.validationSummary, #AddToCart, *', '5px', true);

    $('body').removeClass($('body').attr('class'));

    //add title attribute to match text to drop lists
    $('select option').each(function() {
        $(this).attr('title', $(this).text());
    });

    //Change Breadcrumb html
    if ($('#BreadCrumb a.breadcrumb').size() > 1) {
        var breadCrumbText = $('#BreadCrumb a.breadcrumb:last').text();
        $('#BreadCrumb a.breadcrumb:last').replaceWith('<span class="breadcrumb last">' + breadCrumbText + '</span>');
    }

    //make the enter key hit the submit button in the right place
    $('.form input').live('keypress', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { //Enter keycode
            $(this).closest('.form').find('input.submit').click();
            e.preventDefault();
        }
    });


    //hide existing validation errors on submit clicks
    $('a.btnAction').live('click', function() { $(this).closest('.form').find('.validationSummary > ul').hide(); });

    $('input[type=text]').addClass('text');
    $('input[type=password]').addClass('password text');
    //    $('tr').filter(':odd').addClass('odd');
    //    $('tr').filter(':even').addClass('even');
    $('.items .item').filter(':even').addClass('even');
    $('.items .item:first').addClass('first');
    helpFAQ();

    $('.skuSelection a.addToCart').click(function(e) {
        alert('');
        e.preventDefault();

    });

    //replace cms created form buttons with stylable trixy 
//    $('input.replace').each(function(e) {
//        var temp = $(this);
//        temp.hide();
//        $(this).after("<a id=Dynamic_" + $(this).index() + " href='/' class='btnAction dynamic'><span></span></a>");
//        $('#Dynamic_' + $(this).index()).attr('title', $(this).attr('title')).find('span').text(temp.val());
//        $(this).siblings().click(function(e) {
//            e.preventDefault();
//            temp.click();
//        });
//    });



    $('#Navigation ul.rootGroup > li a').each(function() {
        if (document.location.href.indexOf($(this).attr('href')) != -1) {
            $(this).closest('li.item').addClass('selected')
            .parent().closest('li.item').addClass('selected');
        }
    });

    siteCustom();
    setUpTabs();
    validationHelpers();

});



function addRowClasses() {
    $('tr').filter(':odd').addClass('odd');
    $('tr').filter(':even').addClass('even');
}

//called by on product display page on update
function swatchHelper() {
    $('.swatchItem img').siblings().addClass('sibling');
    $('.swatch img').siblings('span').addClass('sibling');
}

/* faq type expanding list*/
function helpFAQ() {
    $('div.faq div.wrap').hide();
    $('div.faq a').click(function(e) {
        e.preventDefault();
        $(this).parents('div.faq').find('div.wrap').slideUp();
        if ($(this).siblings().hasClass('down')) {
            $(this).css('background-position', '-279px 3px').siblings().slideUp().removeClass('down');
        } else {
            $(this).parents('div.faq').find('div.wrap').removeClass('down').siblings().css('background-position', '-279px 3px');
            $(this).css('background-position', '0px 3px').siblings().slideDown().addClass('down');
        }
    });
}



function setUpTabs() {
    //Setup the client side tab menu control
    $("#TabSystem #Menu a").live('click',  function() { var index = $("#TabSystem #Menu a").removeClass("active").index($(this).addClass('active'));  $("#TabSystem .tab").hide().eq(index).show();
        if ($(this).attr('href') == "") { return false; }
    });    
     $("#TabSystem a:first").click();
     //$("#TabSystem a.active").click();
}

//search pages calls then when after ajax call from pager index change
function selectTab() {
    var location = window.location.toString();
    if (location.indexOf("#Info") > 0) {
        setTimeout(function() { $("#TabSystem a.information").click(); }, 1);//seems to need a timeout or it won't select the tab
    }
    else
    {
        setTimeout(function() { $("#TabSystem a.products").click(); }, 1);
    }
}

function validationHelpers() {
    //$('.ValidateError br,.ValidateError img').remove();

//    $('#Content .form table tr:not(#CheckoutAddressDetails tr)').each(function() {
//        if ($(this).find('td').size() < 3) {
//            $(this).append('<td class="validator"></td>');
//        }
//    });

    $('#Content .form .text').blur(function() {
        var theTR = $(this).closest('tr');
        theTR.find('.valid, .invalid').remove();
        theTR.find('span.error,span.ValidateError').each(function() {
            var id = document.getElementById($(this).attr('id'));
            ValidatorValidate(id);
            if (id.isvalid) {
                theTR.find('.valid').remove();
                theTR.find('td.validator').append('<span class="valid validator"></span>');
            } else {
                theTR.find('span.error,span.ValidateError').hide();
                theTR.find('td.validator').append('<span class="invalid validator" onclick="$(this).closest(\'tr\').find(\'.text\').focus()" onmouseover="tooltip.show(\'' + stripHTML(id.errormessage) + '\');" onmouseout="tooltip.hide();"></span>');

            }
        });

        if (theTR.find('span.validator').size() > 1) {
            theTR.find('span.valid').remove();
            if (theTR.find('span.validator').size() > 1) {
                theTR.find('span.validator').not('span.validator:first').remove();
            }
        }
    });

    $('#Content .form a.btnAction').click(function(e) {
        $(this).closest('.form').find('input.text').each(function() {
            $(this).blur();
        });
    });

}

function LoginError() {

    $('#Login .loggedOut').show();
    $('#LoginIncorrect').fadeIn();
    $('body, #LoginIncorrect .close').one('click',function(e) {
        e.preventDefault();
        $('#LoginIncorrect').fadeOut();
    });
    
    $('#LoginIncorrect').click(function(e) {
        e.stopPropagation();
    });

}
function ResetPWD() {

    $('#Login .loggedOut').show();
    $('#ResetError').fadeIn();
    $('body, #ResetError .close').one('click', function(e) {
        e.preventDefault();
        $('#ResetError').fadeOut();
    });

    $('#ResetError').click(function(e) {
        e.stopPropagation();
    });

}




function positionFooter() {
    var docHeight = $('#Header').outerHeight() - $("#Spacer").height();
    var docHeight2 = $('#Content').outerHeight() - $("#Spacer2").height();
    //      $('#DocH').text('d h:' +docHeight);
    //      $('#WinH').text('w h:' + $(window).height());


    if ($(window).height() > docHeight) {
        var diff = (docHeight - $(window).height()) * -1;
        var diff2 = (docHeight2 - $(window).height()) * -1;
        $("#Spacer").height(diff);
        $("#Spacer2").height(diff2);
    }
}

//Custom Stuff
function siteCustom() {

    ProductListAnimation();
    
//    $(document).hover(function() {
//        $('#ToolTip').animate({ 'opacity': 0 }, { queue: false, duration: 100, complete: function() { } });
//    }, function() {

//    });
//    
//    $('a').hover(function(e) {
//        if ($('#ToolTip').size() < 1) {
//            $('body').append('<div id="ToolTip" style=""><div id="ToolTipTop"></div><div id="ToolTipCont"></div><div id="ToolTipBot"></div></div>');
//        }
//        $('#ToolTipCont').text($(this).text());
//        $('#ToolTip').show().animate({ 'opacity': .85 }, { queue: false, complete: function() { } });
//        $(document).unbind('mousemove').bind('mousemove', function(e) {
//            $("#ToolTip").css({ 'left': e.pageX + 3, 'top': e.pageY - $('#ToolTip').height() - 3 });
//        });
//    }, function() {
//        $('#ToolTip').remove().animate({ 'opacity': 0 }, { queue: false, duration: 100, complete: function() { } });
//    });

    $('#CatNav ul > li.active > a').each(function(e) {
        if ($(this).siblings().size() > 0) {
            $(this).addClass('noClick');
        }
    });

    $('a.noClick').live('click', function(e) {
        e.preventDefault();
    });
    


    positionFooter();
    //$(window).scroll(positionFooter).resize(positionFooter);



    $('.btnLoyalty').live('click', function(e) {
        if (typeof (window.memberId) == 'undefined') {
            window.memberId = -1;
        }
        e.preventDefault();
        openLW('/controls/mipiaci/loyaltystatus.aspx?memberId=' + window.memberId, '520', '350', 'rewards');
    });

    
    
    $('#Login a.btnLogin').fadeIn().live('click', function(e) {
        e.preventDefault();
        if ($('#Login').hasClass('out')) {
            //$(this).siblings('.message').slideUp();
            $('#Login .loggedOut').slideDown(function() { $(this).css('zoom', 1) });
        } else {
            //alert("$('.btnLogout').trigger('click');");
            $('.btnLogout').trigger('click');
        }
    });   
   
}

function ProductListAnimation() {
    $('#FeaturedProducts tr').each(function() {
        $(this).find('td:last').addClass('last');
    });

    //these class settings were just for page load, and need to be removed
    $("td.item .subsequent").removeClass("subsequent").css('opacity', '0');
    //function for changing the picture according to hovering over the swatch

    $("#FeaturedProducts .item .swatch a").mouseenter(function() {
        var id = $(this).attr("id").substr(2, $(this).attr("id").length);
        var imgID = "#I_" + id;
        var prcID = "#P_" + id;
        $(this).closest("td.item").find(".img div").not(imgID).css('z-index', 1).animate({ 'opacity': 0 }, { queue: false, duration: 1000, complete: function() { $(this).removeClass("active"); } });
        $(this).closest("td.item").find(imgID).css('z-index', 2).animate({ 'opacity': 1 }, { queue: false, duration: 1000 }).addClass("active");
        $(this).closest("td.item").find(".price div").not(prcID).css('z-index', 1).animate({ 'opacity': 0 }, { queue: false, duration: 1000, complete: function() { $(this).removeClass("active"); } });
        $(this).closest("td.item").find(prcID).css('z-index', 2).animate({ 'opacity': 1 }, { queue: false, duration: 1000 }).addClass("active");
    });
} 


function ProductDisplayCallback() {
    UpdateSideCarts();
    setTimeout(function () {
        MagicZoom.refresh();
    }, 150);
    CycleMe();
}

function startCycler() {

    CycleMe();
}


$("#ProductDisplay #Thumbnails a").live('click', function (e) {
    e.preventDefault();
    $("#Thumbnails li").removeClass('active');
    $(this).parent().addClass('active');

    var zoomedImage = $(this).attr('href');
    var regularImage = $(this).attr('rel');
    var rel = $('#ProductDisplay .mainImage a').attr('rel');
    var zoomElement = $('#ProductDisplay .mainImage a')[0];
        
    MagicZoom.update(zoomElement, zoomedImage, regularImage, rel);

    //MagicZoom.update($('#ProductDisplay .mainImage a')[0], $(this).attr('href'), $(this).attr('rel'), $('#ProductDisplay .mainImage a').attr('rel'));
});


function CycleMe() {
    window.count = $('#Cycler .item').size() -1;
    $('#Cycler .firstItem').addClass('current');

    $('#Next').click(function() {
        showNext();
    });

    $('#Prev').click(function() {
        showPrev();
    });

}

function showNext() {

    if ($('.current').index() < window.count) {
        $('.current').removeClass('current').next().addClass('current');
    } else {
        $('.current').removeClass('current');
        $('#Cycler .item:eq(0)').addClass('current');
    }
}
function showPrev() {
    if ($('.current').index() > 0) {
        $('.current').removeClass('current').prev().addClass('current');
    } else {
        $('.current').removeClass('current');
        $('#Cycler .item:eq('+ window.count+ ')').addClass('current');
    }
}







