$(document).ready(function() {
    //purely design issue
    var winHeight = $(window).height(); // get window height
    var offset = $('#footer').offset(); //where is the footer on the page?
    var wheresFooter = offset.top; //is it at the bottom? 
    var footerHeight = $('#footer').height(); //how tall is the footer
    var minOffset = winHeight - footerHeight; //footer should not be any further up than this position
    if (wheresFooter < minOffset) {
        var footerMargin = minOffset - wheresFooter + 10; //set margin to this 10 pixels added for some reason for FireFox
        $('#footer').css('top', footerMargin);
    }

    // AB Testing Search Bar
    $('.sbox3').keypress(function() {
        $('.sbox3').css('background-position', '0 -30px');
    });
    $('.sbox3').blur(function() {
        if ($('.sbox3').val() === "") {
            $('.sbox3').css('background-position', '0 0');
        }
    });

    if ($('.sbox3').val() !== "") {
        $('.sbox3').css('background-position', '0 -30px');
    }

    // remove "s" if hours are only 1
    $('.hours').each(function() {
        if ($(this).html() === "1 hours") {
            $(this).html("1 hour");
        }
    })

    //Password issue in IE
    $('.passfocus').hide();
    $('input.passblur').focus(function() {
        $(this).hide().next('.passfocus').show().focus();
    });
    $('input.passfocus').blur(function() {
        if ($(this).val() == "") {
            $(this).hide().prev('.passblur').show();
        }
    });

    //sign in section
    $('.signin').toggle(
		function() {
		    var myWidth = $(window).width();
		    $(this).addClass("toggle");
		    if (myWidth < "800") {
		        $('#login').animate({ top: "67px" });
		    } else {
		        $('#login').animate({ top: "30px" });
		    }
		},
      	function() {
      	    $(this).removeClass("toggle");
      	    $('#login').animate({ top: "-50px" });
      	}
    	);
    //billboard content
    $('.section', this).hide();
    $('.expanded', this).show();
    $('.link').click(function(e) {
        e.preventDefault();
        var theElement = $(this).next();
        if (theElement.hasClass('section') && !theElement.is(':visible')) {
            $('.section:visible').prev('.link').removeClass('active');
            $(this).addClass('active');
            $('.section:visible').animate({
                width: ['toggle', 'swing']
            });
            $(this).next('.section').animate({
                width: ['toggle', 'swing']
            });
        }
    });


    //lightbox
    $(".ilcshort").attr("href", "#ilc");
    $(".badpasscode").attr("href", "#badpasscode");
    $(".anypasscodemsg").attr("href", "#anypasscodemsg");
    $(".passcodecourseincart").attr("href", "#passcodecourseincart");
    $(".passcodeexpired").attr("href", "#passcodeexpired");
    $(".passcodeinvalid").attr("href", "#passcodeinvalid");
    $(".passcodeusedincart").attr("href", "#passcodeusedincart");
    $(".whatsthis").attr("href", "#whatsthis");
    $(".special").attr("href", "#special");
    $(".sptshort").attr("href", "#spt");
    $(".aspshort").attr("href", "#asp");
    $(".ctpshort").attr("href", "#ctp");
    $(".newsletter").attr("href", "#newsletter");
    $(".unverified").attr("href", "#unverified");
    $(".forgot").attr("href", "#forgotpass");
    $(".add2cart").attr("href", "#startdate");
    $(".alreadysignedin").attr("href", "#alreadysignedin");
    $(".supportform").attr("href", "#supportform");
    $(".aspnotready").attr("href", "#aspnotready");

    $(".lightbox").fancybox();

    // var menuHeight = $('.menu').height();
    function menuBGheight(tiers, parentHeight) {
        var menuHeight = $('.navigation').height() + 42;
        var nextHeight = tiers.height() + 40; // next tier (2nd or 3rd)
        if (parentHeight > nextHeight) {
            if (parentHeight > menuHeight) {
                parentHeight = parentHeight + 40;
                $('.pullout, .menu').height(parentHeight);
            } else {
                $('.pullout, .menu').height(menuHeight);
            }
        } else {
            if (parentHeight > menuHeight) {
                $('.pullout, .menu').height(nextHeight);
            } else {
                if (menuHeight > nextHeight) {
                    $('.pullout, .menu').height(menuHeight);
                } else {
                    $('.pullout, .menu').height(nextHeight);
                }
            }
        }
    }

    //Left Nav (or, navigation, if I need to search for it later)
    var theBackground = $('.pullout');
    var ready = true;
    $('.tier1').click(function(e) {
        e.preventDefault();
        var theElement = $(this).next('ul');
        var backWidth = theBackground.width(); //variable for pullout column width
        if (theElement.is(':visible')) {
            var visible = true;
        } else {
            $('.tier1').removeClass('selected');
        }
        if (ready) {
            $(this).toggleClass('selected');
            ready = false;
            $('.navigation ul').hide(); //hide all 2nd tier
            if (visible) {
                theElement.show();
            }
            $(theElement).animate({
                width: ['toggle', 'swing']
            }, 300, function() {
                ready = true;
            });
            if (!theBackground.is(':visible')) {
                theBackground.css('width', '250px');
                $(theBackground).animate({
                    width: ['toggle', 'swing']
                }, 300);
            } else if (backWidth == '500' && !visible) {
                $(theBackground).animate({
                    width: ['250', 'swing']
                }, 300);
            } else if (visible) {
                $(theBackground).animate({
                    width: ['toggle', 'swing']
                }, 300);
            }
            var menuHeight = $('.navigation').height() + 42;
            menuBGheight(theElement, menuHeight);
            $('.tier2').removeClass('selected');
        }
    });

    //user clicks second tier 
    $('.tier2').click(function(e) {
        e.preventDefault();
        var backWidth = theBackground.width(); //variable for pullout column width
        var theElement = $(this).next('ul');
        if (theElement.is(':visible')) {
            var visible = true;
        } else {
            $('.tier2').removeClass('selected');
        }
        if (ready) {
            $(this).toggleClass('selected');
            ready = false;
            $('.navigation ul ul').hide(); //hide all 3nd tier
            if (visible) {
                theElement.show();
                var closeBg = true;
            }
            $(theElement).animate({
                width: ['toggle', 'swing']
            }, 300, function() {
                ready = true;
            });
            if (closeBg) {
                $(theBackground).animate({
                    width: ['250px', 'swing']
                }, 300);
            }
            if (backWidth < '300') {
                $(theBackground).animate({
                    width: ['500px', 'swing']
                }, 300);

            }
            var tier2Height = $(this).parent().parent().height();
            menuBGheight(theElement, tier2Height);
        }
    });



    //Hash Tags for Menu
    $('.menu .label').attr('href', '#openbrowsecatalog');
    $('.expanded .label').attr('href', '#closebrowsecatalog');

    //user clicks top label
    $('.menu .label').click(function(e) {
        e.preventDefault(); // don't go anywhere
        var tierOne = $(this).next('ul'); //nested list
        if (!tierOne.is(':visible')) {
            $('#leftnav').removeClass("navbg"); //get rid of "sticky note" background
            $('.menu ul:visible').animate({ //hide visible menu
                height: ['toggle', 'swing']
            });
            $(this).next('ul').animate({ // show or hide nested list
                height: ['toggle', 'swing']
            });
            $('.menu li:visible').parents('li').removeClass('expanded');
            $(this).parent('li').addClass('expanded');
            $(this).attr('href', '#closebrowsecatalog'); //hash tags for google analyitics
        } else if (tierOne.is(':visible')) {
            $('#leftnav').addClass("navbg"); //add "sticky note" background
            $('.menu ul:visible').animate({ //hide visible menu
                height: ['toggle', 'swing']
            });
            $(this).parent('li').removeClass('expanded');
            $(this).attr('href', '#openbrowsecatalog'); //hash tags for google analyitics
        }
        $('.tier1').removeClass('selected'); // remove background on tier 1 links
        $('.tier2').removeClass('selected'); // remove background on tier 2 links
        $('.menu ul ul:visible').hide(); // lose tier 2 links

        if (theBackground.is(':visible')) { // hide background if we are closing main menu
            $('.pullout').animate({
                width: ['toggle', 'swing']
            });
        }
    });

    // If user clicks off the menu
    var mouse_is_inside = false;
    //var OGmenuHeight = $('.menu').height();
    $('.menu').hover(function() {
        mouse_is_inside = true;
    }, function() {
        mouse_is_inside = false;
    });
    $(document).mouseup(function() {
        if (!mouse_is_inside && theBackground.is(':visible')) {
            $('.pullout').animate({
                width: ['toggle', 'swing']
            });
            $('.menu ul ul:visible').animate({
                width: ['toggle', 'swing']
            });
            $('.tier1').removeClass('selected');
            $('.tier2').removeClass('selected');

            //$('.menu').delay(300).animate({ height: OGmenuHeight });
        }

    });

    //view more on table
    $('.menu .more .viewmore').toggle(
      function() {
          $(this).prev('ul').animate({
              height: ['toggle', 'swing']
          });
          $(this).text('View Less');
      },
      function() {
          $(this).prev('ul').animate({
              height: ['toggle', 'swing']
          });
          $(this).text('View More');
      }
    );
    //for IE, Make leftnav div height the same size as content height
    var bodHeight = $('#content').height();
    $('#leftnav').css('min-height', bodHeight);

    //table
    $('.table tr:odd').addClass('alt');

    //Shopping Cart: Credit Card Magic 
    //Tip o' Hat to Panic.com. You guys are awesome.
    $(".ccard").keyup(function() {
        var value = $(this).val();
        if (value == 6) {
            $(".creditcards").addClass("discover");
            $(".creditcards").removeClass("amex visa mastercard");
            $(".cvc").removeClass("amexcvc");
        } else if (value == 5) {
            $(".creditcards").addClass("mastercard");
            $(".creditcards").removeClass("amex visa discover");
            $(".cvc").removeClass("amexcvc");
        } else if (value == 4) {
            $(".creditcards").addClass("visa");
            $(".creditcards").removeClass("amex discover mastercard");
            $(".cvc").removeClass("amexcvc");
        } else if (value == 3 || value == 7) {
            $(".creditcards").addClass("amex");
            $(".creditcards").removeClass("visa mastercard discover");
            $(".cvc").addClass("amexcvc");
        } else if (value == "") {
            $(".creditcards").removeClass("visa mastercard discover amex");
            $(".cvc").removeClass("amexcvc");
        }
    });

    // Help Content
    $('.localscroll a').click(function(e) {
        e.preventDefault();
        var wherewego = $(this).attr('href');
        $(window).scrollTo(wherewego, 800);
    });

    /* This code is licensed under Creative Commons Attribution 3.0    *
    * You may share and remix the script so long as you attribute the *
    * original author, Andrew January.                                *
    * http://creativecommons.org/licenses/by/3.0/                     */


    // Check to see if the browser already supports placeholder text (introduced in HTML5). If it does,
    // then we don't need to do anything.
    var i = document.createElement('input');
    if ('placeholder' in i) {
        return;
    }

    var isPassword = function(input) {
        return $(input).attr('realType') == 'password';
    }

    var valueIsPlaceholder = function(input) {
        return input.value == $(input).attr('placeholder');
    }

    var showPlaceholder = function(input, loading) {
        // FF and IE save values when you refresh the page. If the user refreshes the page
        // with the placeholders showing they will be the default values and the input fields won't
        // be empty. Using loading && valueIsPlaceholder is a hack to get around this and highlight
        // the placeholders properly on refresh.
        if (input.value == '' || (loading && valueIsPlaceholder(input))) {
            if (isPassword(input)) {
                // Must use setAttribute rather than jQuery as jQuery throws an exception
                // when changing type to maintain compatability with IE.
                // We use our own "compatability" method by simply swallowing the error.
                try {
                    input.setAttribute('type', 'input');
                } catch (e) { }
            }
            input.value = $(input).attr('placeholder');
            $(input).addClass('placeholder');
        }
    }

    var hidePlaceholder = function(input) {
        if (valueIsPlaceholder(input) && $(input).hasClass('placeholder')) {
            if (isPassword(input)) {
                try {
                    input.setAttribute('type', 'password');
                    // Opera loses focus when you change the type, so we have to refocus it.
                    input.focus();
                } catch (e) { }
            }

            input.value = '';
            $(input).removeClass('placeholder');
        }
    }

    $(':text[placeholder],:password[placeholder]').each(function(index) {
        // We change the type of password fields to text so their placeholder shows.
        // We need to store somewhere that they are actually password fields so we can convert
        // back when the users types something in.
        if ($(this).attr('type') == 'password') {
            $(this).attr('realType', 'password');
        }

        showPlaceholder(this, true);

        $(this).focus(function() { hidePlaceholder(this) });
        $(this).blur(function() { showPlaceholder(this, false) });
    });
});
