
var cartTimer = null;
var checkoutPage = null;

$(document).ready(function()
{
    // The product selector area
    attachToolTip();
    initItemAdd();
    initColorLinks();
    initSizeLinks();
    initItemThumbs();

    // The cart on each page
    initCartToggle();
    initCartUpdate();
    updateCartTimer();

    // The final checkout page	
    initCheckout();
    initTOSValidation();
});

function initCartUpdate()
{
    $('input.cart_update').unbind('click').click(function(e){
        e.stopPropagation();

        $('.popup_cart_inner').addClass('progress');
        $('.checkout_flag').val('0');

        $.ajax({
            type: 		"post",
            url: 		'/popup-shop/update-cart/',
            dataType: 	"html",
            context:	$('.popup_cart_content'),
            data: 		$(this).parents('form').serialize(),
            error: function(request, error)
            {
                $('.popup_cart_inner').removeClass('progress');
                alert('Oops, there was an error while trying to update your cart.\nPlease try again later.');
            },
            success: function(data)
            {
                $('.popup_cart_inner').removeClass('progress');
                $(this).html(data);
                initCartToggle();
                initCartUpdate();
            }
        });

        return false;
    });

    $('a.cart_remove').unbind('click').click(function(e){
        e.stopPropagation();
        $(this).parents('tr').find('.quantity_flag').val('0');
        $('input.cart_update').click();

        return false;
    });
}

function zPad(number, length)
{
    var str = '' + number;

    while (str.length < length) {
        str = '0' + str;
    }

    return str;
}

function updateCartTimer()
{
    if(typeof(ps_timeleft) != 'undefined')
    {
        if(ps_timeleft < 0)
        {
            $('.cart_counter div').text('Your cart is empty.');
            $('.cart_tab_number').text('0');
            if(checkoutPage)
                document.location = '/popup-shop';
            else
                $('.cart_table .item_row, .cart_table .subtotal_row, .popup_cart_content .cart_checkout, .popup_cart_content .cart_update').remove();
        }

        else
        {
            if (ps_timeleft <= 0)
            {
                $('.cart_counter div').text('Sorry, your cart has expired');
                $('.cart_tab_number').text('0');
                if(checkoutPage)
                    document.location = '/popup-shop';
                else
                   $('.cart_table .item_row, .cart_table .subtotal_row, .popup_cart_content .cart_checkout, .popup_cart_content .cart_update').remove();
            }

            else
            {
                ps_timeleft--;
                $('.cart_counter .cart_counter_num').text(Math.floor(ps_timeleft/60) + ':' + zPad(ps_timeleft % 60, 2));

                clearTimeout(cartTimer);
                cartTimer =	setTimeout('updateCartTimer()', 1000);
            }
        }
    }
}



function initCheckout()
{
    if ($('#popupCheckoutForm').length)
    {
        $('select.bstate, select.sstate').change(function(e){
            $('input.cart_update').click();
        });
        $('select.bstate, select.sstate').change();

        $('select.bcountry, select.scountry').change(function(e){
            if ($(this).val() != '' && $(this).val() != 'US')
            {
                $(this).parents('.fieldset_pad').find('.bstate, .sstate').parents('div.input').hide();
                $(this).parents('.fieldset_pad').find('.bstate2, .sstate2').parents('div.input').show();
            }

            else
            {
                $(this).parents('.fieldset_pad').find('.bstate, .sstate').parents('div.input').show();
                $(this).parents('.fieldset_pad').find('.bstate2, .sstate2').parents('div.input').hide();
            }

            $('input.cart_update').click();
        });
        $('select.bcountry, select.scountry').change();

        $('#FlashOrderUseBillingAddress').change(function(e){
            if ($(this).attr('checked'))
            {
                var leftColItems = $('.bill_address_wrap').find('input, select');

                $(this).parents('.fieldset_pad').find('input, select').not('input:checkbox, input[type="hidden"]').each(function(index){
                    $(this).val(leftColItems.eq(index).val());
                });

                $(this).parents('.fieldset_pad').find('.error-message').remove();

                $('select.bcountry, select.scountry').change();
            }

            else
            {
                $(this).parents('.fieldset_pad').find('input, select').not('input:checkbox, input[type="hidden"]').val('');
            }

            $('input.cart_update').click();
        });
        
        
        //cart timer on checkout
        if ($('#popupCheckoutForm .time_left').length)
        {
            ps_timeleft = parseInt($('#popupCheckoutForm .time_left').text());
            $('#popupCheckoutForm .time_left').remove();
            checkoutPage = true;
            updateCartTimer();
        }
    }
}

function initItemAdd()
{
    if ($('.add_item_to_cart').length)
    {
        $('#optionSize, #optionColor').val('');

        $('form.add_item_to_cart').submit(function(e){

            if ($.trim($('#itemType').val()) == 'Product') {
                // If item type is product, validate optionSize and optionColor
                if ($.trim($('#optionSize').val()) == '' || $.trim($('#optionColor').val()) == '')
                {
                    alert('Please select a size/color combination.');
                }  
            }
			
            if ($(this).hasClass('progress'))
            {
                alert('Just one second while your previous request completes.');
            }

            else
            {
                window.scrollTo(0, 0);

                $(this).addClass('progress');

                $('a.cart_toggle').click();

                $('.popup_cart_inner').addClass('progress');

                $.ajax({
                    type: 		"post",
                    url: 		$(this).attr('action'),
                    dataType: 	"json",
                    context:	$(this),
                    data: 		$(this).serialize(),
                    error: function(request, error)
                    {
                        $('.popup_cart_inner').removeClass('progress');

                        $(this).removeClass('progress');
                        alert('Oops, there was an error while trying to add this item to your cart.\nPlease try again later.');
                    },
                    success: function(data)
                    {
                        $(this).removeClass('progress');

                        if (data.success == 1)
                        {
                            $.ajax({
                                type: 		"post",
                                url: 		'/popup-shop/update-cart/page/',
                                dataType: 	"html",
                                context:	$('.popup_cart_content'),
                                data: 		{},
                                error: function(request, error)
                                {
                                    $('.popup_cart_inner').removeClass('progress');
                                    alert('Oops, there was an error while trying to update your cart.\nPlease try again later.');
                                },
                                success: function(data)
                                {
                                    $('.popup_cart_inner').removeClass('progress');
                                    $(this).html(data);
                                    initCartToggle();
                                    initCartUpdate();
                                }
                            });
                        }

                        else
                        {
                            $('.popup_cart_inner').removeClass('progress');
                            alert(data.msg);
                        }
                    }
                });
            }

            return false;
        });
    }
}

function initItemThumbs()
{
    if ($('.add_item_to_cart').length)
    {
        $('.imageNav .item_thumb').unbind('click').click(function(e){
            e.stopPropagation();

            var img = $('.imageInner img');

            img.parents('a').attr('rel', $(this).attr('rel'));
            img.attr('src', img.attr('src').replace(/\/[0-9]+\.jpg/, '/' + $(this).attr('rel') + '.jpg'));

            return false;
        });


        $('.imageInner .item_img').unbind('click').click(function(e){
            e.stopPropagation();

            //alert('Open Image Popup Here');

            return false;
        });
    }
}

function initColorLinks()
{
    if ($('.add_item_to_cart').length)
    {
        $('.add_item_to_cart a.optionColor').unbind('click').bind('click', function(e){
            e.stopPropagation();

            $('a.optionColor span').removeClass('selected');
            $(this).find('span').addClass('selected');
            $('#optionColor').val($(this).attr('rel'));

            return false;
        });
    }
}

function initTOSValidation() {
    $('#popupCheckoutForm').submit(function(e){ 
        var ret = true;
        $('.tos').each(function(index) {
           if(!this.checked)
               ret = false;
        });
        
        if(!ret) {
            alert("Please accept the terms of service associated with each sale");
        }
        
        return ret;
    });
}

function initSizeLinks()
{
    if ($('.add_item_to_cart').length)
    {
        $('.add_item_to_cart a.optionSize').unbind('click').bind('click', function(e){
            e.stopPropagation();

            if (!$(this).find('.sizebox').is('.sold-out, .not-available'))
            {
                var sizes = $('.add_item_to_cart a.optionSize');
                sizes.removeClass('selected');
                $(this).addClass('selected');
                $('#optionSize').val($(this).attr('rel'));
                $('#optionColor').val('');
                $('a.optionColor span').removeClass('selected');
                $('.add_item_to_cart .itemInfo .no_colors').remove();
                $('.add_item_to_cart .itemInfo .clist').addClass('hidden').eq(sizes.index($(this))).removeClass('hidden');

                var colors = $('.add_item_to_cart .itemInfo .clist').eq(sizes.index($(this)));

                if (colors.find('a.optionColor').length == 1)
                {
                    colors.find('a.optionColor').click();
                }
            }

            return false;
        });

        if ($('.add_item_to_cart a.optionSize').length == 1)
        {
            $('.add_item_to_cart a.optionSize').click();
        }
    }
}

function initCartToggle()
{
    if ($('a.cart_toggle').length)
    {
        $('a.cart_toggle, a.cart_keepshopping, a.cart_close').unbind('click').bind('click', function(e){
            e.stopPropagation();

            var theCart = $('.popup_cart_wrapper');
            var theOverlay = $('.popup_cart_overlay');

            if(theCart.length)
            {
                if(theOverlay.length)
                {
                    theCart.slideToggle('fast');
                    theOverlay.fadeOut('slow',function()
                    {
                        $(this).remove();
                    });
                }

                else
                {
                    var theOverlayMarkup = '<div class="popup_cart_overlay"></div>';
                    $('body').append(theOverlayMarkup);
                    theOverlay.fadeIn('fast');
                    theCart.slideToggle('fast');
                }
            }

            return false;
        });

        if ($('.popup_cart_content .time_left').length)
        {
            ps_timeleft = parseInt($('.popup_cart_content .time_left').text());
            $('.popup_cart_content .time_left').remove();
            updateCartTimer();
        }

        var total = 0;

        $('.popup_cart_content .item_row select').each(function(i){
            total += parseInt($(this).val());
        });
        
        $('.popup_cart_content .item_row input').each(function(i){
            total += parseInt($(this).val());
        });

        $('.cart_tab_number').text(total);
    }
}
function cart_removeItem(removeItemReq,thisButton){
    if(removeItemReq!='' && removeItemReq!=null){
        $.ajax({
            url: removeItemReq,
            context: $('.cart_table').find(thisButton),
            success: function(){
                $(this).parents('item_row').remove();
            }
        });
    }
}
function checkout_removeItem(removeItemReq,thisButton){
    if(removeItemReq!='' && removeItemReq!=null){
        $.ajax({
            url: removeItemReq,
            context: $('.confirm_table').find(thisButton),
            success: function(){
                $(this).parents('item_row_confirm').remove();
            }
        });
    }
}
function cart_update(){
    if($('.popup_cart_wrapper form').length){
        $('.popup_cart_wrapper form').submit();
    }
}
function attachToolTip(){
    var sizeboxes = $('.sizebox');

    if (sizeboxes.length)
    {
        var tooltipShell = '<div class="tooltipWrap" style="position:absolute;left:-50000px;top:-50000px;"><div class="tooltipInner">++replace++</div></div>';
        $.each(sizeboxes,function(){
            $(this).hover(
                function () {
                    var offset = $(this).offset();
                    var tiptext = $(this).attr('rel');
                    if(tiptext){
                        thisTip = tooltipShell.replace('++replace++',tiptext);
                        $('body').append(thisTip);
                        $('.tooltipWrap').css('top',offset.top+35);
                        $('.tooltipWrap').css('left',offset.left);
                    }
                },
                function () {
                    $('.tooltipWrap').remove();
                }
                );
        });
    }
}

function showView(currImg) {
    if((currImg.src).search(/_thumb/i)>0){
        var bigImage = (currImg.src).replace('_thumb','_lg');
        $('.imageInner img').attr('src',bigImage);
    }
}
function toggleMoreViews(url){
    if(url!='' || url!='undefined'){
        window.open(url,'More Views','width=580,height=580,toolbar=no,location=no,menubar=no')
    }
}
