var storeClosed = false;

var $ = jQuery;

//if (document.body)
    //document.body.style.background = '#ff0';

/*
Using Multiple JavaScript Onload Functions
www.webreference.com/programming/javascript/onloads/index.html
*/
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

var countdown_el,
    countdown_el_offset,
    countdown_el_offset_top;

$(document).ready(function () {

    $(document).ajaxStop(function() {
        $('.tax:eq(0)').text('Estimated Tax:');
    });

    if ($('.error .no-results-message').length) {
        $('.error .no-results-message').remove();
    }

    if ($('.masthead').length) {
        $('html').addClass('home');
    }
    if ($('.closed').length == 0) {
        $('#mainContentWrapper').prepend('<div class="countdown a hidden"><div class="countdown b"><div class="note">Note: Only the items added to your cart prior to the store closing will be available for checkout.</div><div class="msg">Store Closes in:</div><div class="value days"></div><div class="label">Days</div><div class="value hours"></div><div class="label">Hours</div><div class="value minutes"></div><div class="label">Minutes</div><div class="value seconds"></div><div class="label">Seconds</div></div></div>');
    }
    if ($('.countdown').length) {
        //var end = new Date('November 29, 2011 03:00:00');
        var end = new Date('January 7, 2012 3:00:00');
        var _second = 1000;
        var _minute = _second * 60;
        var _hour = _minute * 60;
        var _day = _hour * 24
        var timer;
        function update_countdown() {
            var now = new Date();
            var distance = end - now;
            if (distance < 0) {
                // handle expiry here..
                storeClosed == true;
                clearInterval(timer); // stop the timer from continuing ..
                $('.countdown .days').text('0');
                $('.countdown .hours').text('0');
                $('.countdown .minutes').text('0');
                $('.countdown .seconds').text('0');
                if ($('.closed').length == 0 && $('.cart').length == 0 && $('.info').length == 0) {
                    window.location.href = '/info/closed';
                } else {
                    if ($('.cart').length == 0) {
                        $('.searchButton button,.navigationLinks a,#header-1 .imageWidget a').addClass('disabled').attr('href', '/info/closed');
                        if ($('.info').length == 0) {
                            $('#mainContentWrapper a,#mainContentWrapper button').addClass('disabled').attr('href', '/info/closed');
                        }
                    } else {
                        $('.searchButton button,.navigationLinks a,#header-1 .imageWidget a').addClass('disabled').attr('href', '/info/closed');
                        $('.productDetails a').addClass('disabled').attr('href', '#');
                        $('.productImage').parent().addClass('disabled').attr('href', '#');
                    }
                    $('.countdown .value,.countdown .label,.countdown .note').remove();
                    $('.countdown .msg').css('font-size', '20px').css('margin-top', '10px').html('The store is now closed, however you may <a href="/cart">complete your checkout</a> with the items currently in your cart.');
                }
            } else {
                var days = Math.floor(distance / _day);
                var hours = Math.floor((distance % _day) / _hour);
                var minutes = Math.floor((distance % _hour) / _minute);
                var seconds = Math.floor((distance % _minute) / _second);
                $('.countdown .days').text(days);
                $('.countdown .hours').text(hours);
                $('.countdown .minutes').text(minutes);
                $('.countdown .seconds').text(seconds);
            }
            if ($('.countdown.a').hasClass('hidden')) {
                $('.countdown.a').removeClass('hidden');
                countdown_el = $('.countdown');
                countdown_el_offset = countdown_el.offset();
                countdown_el_offset_top = countdown_el_offset.top;
            }
        }
        timer = setInterval(update_countdown, 1000);
        if ($('.closed').length == 0) {
            $(window).scroll(function () {
                if (($(window).scrollTop() > countdown_el_offset_top)) {
                    $('.countdown.a').addClass('fixed');
                    if ($('.countdown-placeholder').length == 0) {
                        $('#mainContentWrapper').prepend('<div class="countdown-placeholder"></div>');
                    }
                } else if (($(window).scrollTop() < countdown_el_offset_top)) {
                    $('.countdown.a').removeClass('fixed');
                    $('#mainContentWrapper .countdown-placeholder').remove();
                }
            });
        }
    } else if ($('.closed').length) {
        $('#header-1 .imageWidget a,.searchButton button,.navigationLinks a,#mainContentWrapper button').addClass('disabled').attr('href', '/info/closed');
    }
    $('a.disabled,button.disabled').live('click', function () {
        if ($(this).attr('href') != '#') {
            window.location.href = $(this).attr('href');
        }
        return false;
    });


    //$('body').addClass('bg');
    //$('#wrapper').css('display','block');
    // add ie class to html tag if internet explorer
    if ($.browser.msie) {
        $('html').addClass('ie');
    } else {
        $('html').addClass('not-ie');
    }
    // hijack quantity select menu and change to text input field
    if ($('.detail #buyboxQuantity').length) {
        var orig_price = $('.attr-value:contains("Original Retail Price")').text();
        $('#right-11').remove();
        $('#right-5').append('<div class="original-price">' + orig_price + '</div>');
        var qty_par = $('#buyboxQuantity').parent();
        var qty_name = $('#buyboxQuantity').attr('name');
        $('#buyboxQuantity,.itemOnSale,.attr-title').remove();
        var qty_replacer_html = '<input id="buyboxQuantity" name="' + qty_name + '" type="text" size="3" />';
        $(qty_par).append(qty_replacer_html);
        $('ul.productInfo').prepend('<li><em>'+$('.attr-value').text()+'</em></li>');
        $('.product-ext-attr-widget').remove();
        // $10.00 (50%)
        // allow integers only
        /*$('#buyboxQuantity').live('keypress',function(e) {
        var code;
        if (!e) var e = window.event;
        if (e.keyCode) {
        code = e.keyCode;
        } else if (e.which) {
        code = e.which;
        }
        if (/[^0-9]/.test(String.fromCharCode(code))) {
        return false;
        }
        if (parseFloat($(this).val()) > 50) {
        $(this).val('50');
        return false;
        }
        if ($(this).val().length == 2) {
        return false;
        }
        });*/
        // allow integers only
        $('#buyboxQuantity').live('keyup', function (e) {
            $(this).val($(this).val().replace(/\D/g, ''));
            if (parseFloat($(this).val()) > 50) {
                $(this).val('50');
            }
        });
        /*var selectValues = {"11":"11","12":"12","13":"13","14":"14","15":"15","16":"16","17":"17","18":"18","19":"19","20":"20","21":"21","22":"22","23":"23","24":"24","25":"25","26":"26","27":"27"};
        $.each(selectValues,function(key,value){
        $('#buyboxQuantity').append($("<option></option>").attr("value",key).text(value));
        });*/
    }
    // force disable on all quick view options
    $('.productQuickView').remove();
    if ($('.browseRefinements .binName').length == 0) {
        $('.browseRefinements').remove();
    }
    // on home page (via check if masthead is present), remove default columns
    if ($('.masthead').length) {
        $('#columns').remove();
    }
    // hijack search query/results elements and move to left sidebar
    if ($('body.search').length) {
        $('h1:contains("Search")').remove();
        var search_count = $('.searchCount').html();
        $('.searchCount').remove();
        $('.browseRefinements').prepend('<div class="browseLadder">Search</div><div class="searchQuery">' + search_count + '</div>');
    }
    // remove availability reference from product view page
    if ($('.productAvailabilityMessage').length) {
        $('.productAvailabilityMessage').remove();
    }
    // actions for cart page
    if ($('.is-cart').length) {
        $('#leftColumn,#centerColumn,.productListWidget').remove();
        $('#rightColumn').attr('id', '');
    }
    if ($('.cart').length) {
        $('#center-6,.saveForLater').remove();
        $('.quantity input[type="text"]').live('keyup', function (e) {
            $(this).val($(this).val().replace(/\D/g, ''));
            if (parseFloat($(this).val()) > 50) {
                $(this).val('50');
            }
        });
    }
    if ($('.addToAUWL').length) {
        $('.addToAUWL').remove();
    }
    // no search results
    if ($('.is-no-results').length) {
        $('#columns').html('<div class="no-results-message">We\'re sorry, but we can\'t find the product you\'re looking for. You can use the search feature above or the product categories to get to the right place.</div>');
    }
    // no search results
    if ($('.is-404').length) {
        $('#columns').html('<div class="no-results-message">We\'re sorry, but we can\'t find the page you\'re looking for. You can use the search feature above or the product categories to get to the right place.</div>');
    }

    /*

    CONSULTANT ID CHECK / CAPTURE

        */
    
    if (!storeClosed) {

        var cookieName = "ThirtyOneOutlet";
        var cookieValue = null;
        var logInPath = "/info/login"
        var curPath = getPathName();
        //alert("cid querystring value= " + consultantId);
        //alert("curPath= " + curPath);

        // Do nothing if already on login page
        if (curPath != logInPath) {

            // see if they already have a valid cookie
            cookieValue = getCookie(cookieName);

            // set or override cookie value IF they're coming in with a consultant id on the querystring (override cuz could be a new cid)
            var consultantId = parseInt(getParamValue("cid"));
            if (typeof consultantId !== "undefined" && consultantId != null && consultantId != "" && !isNaN(consultantId)) {
                setCookie(cookieName, consultantId, 10000);
                cookieValue = consultantId;
                //console.log('passed');
            } else {
                //console.log('failed');
            }

            // Added  || cookieValue == "null"   JJH 12/04/2012 @ 4:15PM EST
            if ((typeof cookieValue === "undefined") || cookieValue == null || cookieValue == "" || cookieValue == "null") {
                window.location.href = logInPath;
            }
            else {
                //Everything is verified & good
                if (document.getElementById("wrapper")) {
                    document.getElementById("wrapper").style.display = "block";
                }
            }
        }
        else {
            // they're on the "log in" page, display the wrapper, background, etc.
            if (document.getElementById("wrapper")) {
                document.getElementById("wrapper").style.display = "block";
            }
        }

    }

});

/*

FUNCTIONS FOR CONSULTANT ID CHECK / CAPTURE

    */

function getPathName() {
    var currentPath = null;
    var strHref = window.location.href;
    //alert("strHref= " + strHref);
    var mypage_array = strHref.split("/");

    if (mypage_array.length > 3) {
        currentPath = "/" + mypage_array[mypage_array.length - 2] + "/" + mypage_array[mypage_array.length - 1];
    }
    //alert("currentPath= " + currentPath);
    return currentPath;
}

function getCookie(c_name) {
    var i, x, y;
    var ARRcookies = document.cookie.split(";");
    if (ARRcookies.length > 0) {
        for (i = 0; i < ARRcookies.length; i++) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x == c_name) {
                return unescape(y);
            }
        }
    }
    return null;
}

function setCookie(c_name, value, pMinutes) {
    // give it an expiration date in GMT format
    var currdate = new Date();
    var expirationdate = new Date(currdate.getTime() + (pMinutes * 60 * 1000));  // 10000 = 10 seconds  formula = pMinutes*60*1000

    //var exdate = new Date();
    //exdate.setDate(exdate.getDate() + pMinutes);
    var c_value = escape(value) + ((pMinutes == null) ? "" : "; expires=" + expirationdate.toUTCString() + "; path=/");  //exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getParamValue(param) {
    var loc = location.search.substring(1, location.search.length);
    var paramValue;
    var params = loc.split('&')
    for (i = 0; i < params.length; i++) {
        paramName = params[i].substring(0, params[i].indexOf('='));
        if (paramName == param) {
            paramValue = params[i].substring(params[i].indexOf('=') + 1);
        }
    }
    return paramValue;
}
