﻿var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
var keyPressedForUpButton = false;
var keyPressedForDownButton = false;
var divNum;
var currentTabIndex;
Global.load(function () {

    $(function () {
        $('.account-button-inner').each(function () {
            if ($(this).children().length == 0) {
                $(this).hide();
            }
        });
    });

    setTimeout(function () {
        if (BrowserDetect.browser == 'Explorer' && BrowserDetect.version == '7') {
            window.scrollTo(0, 0);
        }
    }, 1);

    // Listening for modern browser events and a bit extra for older versions of IE.
    var postMessageEvent = window.addEventListener ? "addEventListener" : "attachEvent",
        escapeHandler = window[postMessageEvent],
        messageEvent = postMessageEvent == "attachEvent" ? "onmessage" : "message";

    escapeHandler(messageEvent, function (e) {
        if (e.data == 'close the login box please') {
            closeLoginBox();
        }
    }, false);

    if ($('#ctl08 div.error').length > 0) {
        var name = $('#ctl08 div.error span').attr('class');
        $('input[name="' + name + '"]').focus();
    }

    getTweet();

    $('body').click(function (e) {
        var $this = $('.search-dropdown');
        var offset = $this.offset();
        if (e.pageX < offset.left || e.pageY < offset.top ||
            e.pageX > offset.left + $this.width() || e.pageY > offset.top + $this.height()) {
            $this.hide();
        }
    });

    $("#txtJoinEmail").focus(function () {
        if ($(this).val() == "Your Email Address") {
            $(this).val("");
        }
    });

    $("#txtJoinEmail").blur(function () {
        if ($(this).val() == "") {
            $(this).val("Your Email Address");
        }
    });

    // Navigation Active States
    if ($('body').hasClass('category')) {
        var pageTitle = $('.breadcrumbs li.active').text().split(' ')[0].toLowerCase();
        $('#header .' + pageTitle).parent('li:eq(0)').addClass('active');
    }

    //Email Signup
    $(".signin").click(function () {
        $(this).parent('li:eq(0)').toggleClass("active");
        $(".signup-drop").toggle();
        return false;
    });

    $('#email-signup').bind('click', function () {
        return false;
    });

    $(document).bind('click', function () {
        $(".dropdown").removeClass("active");
        $(".signup-drop").hide();
    });

    SignIn.attachCallback(function (response) {
        if (response.Error && response.MustChangePassword) {
            window.location.href = "signin.aspx?MustChangePassword=true&Email=" + response.Username + "&ReturnURL=" + window.location.href;
            return;
        }

        if (response.Error) {
            return;
        }

        closeLoginBox();

        if (window.location.href.indexOf("createaccount.aspx") != -1) {
            window.location.href = "account.aspx";
        }

        $(".cart-total").html(response.Customer.CartItemCount);
        var itemSuffix = response.Customer.CartItemCount == 1 ? "Item in <br /> your cart" : "Items in <br /> your cart";
        $(".cart-items").html(itemSuffix);

        $(".user-box").prepend('<span class="userinfo left">Hi, <a href="account.aspx">' + response.Customer.Name + '</a></span><span class="dotted-button small"><a href="signout.aspx" class="lightbox">Log Out</a></span>');
        $("span.loginbutton").remove();
        $("li.createaccountbutton").remove();
        $("li.emaildropdown").addClass("last");
    });

    $('.productName').each(function () {
        var $name = $(this);
        var productName = $name.text().split('  ');
        for (var string in productName) {
            var newProductName = productName[string].toLowerCase();
            if (newProductName.length > 1) {
                var giftCard = 'gift card';
                var matches = false;
                for (var i = 0; i < giftCard.length; i++) {
                    matches = newProductName[i] == giftCard[i] ? true : false;
                }
                if (matches) {
                    $name.parents('div.productDetails:eq(0)').addClass('giftCard');
                }
            }
        }
    });
});

function openLoginBox(info) {
    if ($("#loginbox").css("display") == "none") {
        // to help with focus
        var server = window.location.href.substring(0, window.location.href.lastIndexOf("?"));
        if (server.length < 1) {
            server = window.location.href;
        }
        server = server.substring(0, server.lastIndexOf("/"));
        server = server.replace('http:', 'https:');

        var infoQueryVar;
        if (info && info != "") {
            infoQueryVar = "&info=" + info;
        } else {
            infoQueryVar = "";
        }

        $("#secure").attr('src', server + '/MhmControls/LogInSecure.aspx?ParentUrl=' + window.location.href + infoQueryVar);
        // end focus
        var bodyHeight = $("body").height();
        var $fader = $("#fader").css({ height: bodyHeight + "px", width: "100%", top: "0", left: "0", "background": "url(skins/skin_1/images/lightbox-bg.png) repeat", position: "absolute", "z-index": "5000" });
        var loginWidth = 572;
        var loginHeight = 519;
        $(".pop-up-inner").height(313);
        $("#secure").height(300);
        var $login = $("#loginbox").width(loginWidth).height(loginHeight+500).show();
        var leftOffset = ($fader.width() / 2) - (loginWidth / 2);
        var topOffset = ($(window).height() / 2) - (loginHeight / 2);
        $login.css({ left: leftOffset, top: topOffset, position: "fixed" });
        if (info == 'You must be logged in to write a review.') { resize(15); }
        $fader.fadeIn(10);
        //var isFaderOpen = true;
    }
}

function closeLoginBox() {
    $("#fader").fadeOut(10);
    $("#loginbox").hide();
    //var isFaderOpen = false;
}
function resize(h) {
    var addedInHeight = h - 6;
    $(".pop-up-inner").height(303+addedInHeight +47);
    $("#secure").height(300+addedInHeight+50);
}
function submitLogin() {
    document.getElementById("loginbox").submit();
}
function submitEmail() {
    document.getElementById("email-signup").submit();
}

function submitDealerZip() {
    document.getElementById("find-retailer-form").submit();
}
function getTweet() {
//get the tweet, pasrse it and add it's text to .tweet p
    var sinceTweet = '';
    $.getJSON("//api.twitter.com/1/statuses/user_timeline/ISISFORWOMEN.json?count=1&callback=?", function (data) { //get tweets
        $.each(data, function (index, value) {
            var tweet = value.text;
            tweet = tweet.replace(/http:\/\/\S+/g, ' <a href="$&" target="_blank">$&</a>');
            tweet = tweet.replace(/(^|\s)@(\w+)/g, '$1<a href="http://www.twitter.com/$2" target="_blank">@$2</a>');
            tweet = tweet.replace(/(^|\s)#(\w+)/g, '$1<a href="http://www.twitter.com/$2" target="_blank">#$2</a>');
            $('.tweet p').html(tweet);

            //get the time since tweet and app to .tweetime span
            var tweetLapse = new Date().getTime() - Date.parse(value.created_at); ;

            var minutes = Math.round((tweetLapse / (1000 * 60)) % 60);
            var hours = Math.round((tweetLapse / (1000 * 60 * 60)) % 24);
            var days = Math.round(hours / 24);

            if (days >= 1) {
                sinceTweet = days + ' day';
            } else if (hours >= 1) {
                sinceTweet = hours + ' hour';
            } else {
                sinceTweet = minutes + 'minute';
            }
        });

        $('.tweettime span').html(sinceTweet);
       //pluralize if necessary
        if (sinceTweet > 1) {
            $('.tweettime span').append('s');
        }

    });
}

