$(document).ready(function()
{    
    //print hidden print-friendly version of the receipt
    $('#printer_friendly').click(function() {        
        $('#wstarWrapper_wrapper').append('<div id = "wstarWrapper">');
        $('#cart_content_top').clone().appendTo('#wstarWrapper');
        
        //remove some things not requred on the print        
        $('#wstarWrapper').find('#bottom_left').remove();
        $('#wstarWrapper').find('#printer_friendly').remove();
        $('#wstarWrapper').find('#proceed_to_checkout').remove();
        
        $('#wstarWrapper').jqprint();
    });
    
    
    //toggle checkboxes
    $('.not_in_list').live('click', function() {
        var other = '#' + $(this).attr('id').replace('_wrapper', '_other');
        $(other).parent().slideToggle('fast');
    });
    $('.checkbox_wrapper').live('click', function() {
        var id = '#' + $(this).attr('id').replace('_wrapper', '');
        var box = id + '_box';
        var proxy = id + '_hidden';

        if ($(proxy).val() == 1) {
            $(box).css('backgroundImage', box_off);
            $(proxy).val(0);
        } else {
            $(box).css('backgroundImage', box_on);
            $(proxy).val(1);
        }
    });
    $('#set_shipping select').live('change', function() {
        var id = '#' + $(this).attr('id');
        var box = id + '_box';
        var proxy = id + '_hidden';
        var other = id + '_other';

        if ($(proxy).val() == 1) {
            $(proxy).val(0);
            $(box).css('backgroundImage', box_off);
            $(other).parent().slideToggle('fast');
        }
    });
    $('.other').livequery(function() {
        var id = $(this).attr('id');
        var proxy = '#' + id.replace('_other', '_hidden');

        if ($(proxy).val() != 1) {
            $(this).parent().hide();
        }
    });
    $('.box_proxy').livequery(function() {
        var id = $(this).attr('id');
        var box = '#' + id.replace('_hidden', '_box');

        if ($(this).val() == 1) {
            $(box).css('backgroundImage', box_on);
        }
    });

    //toggle shipping
    $('#change_shipping').live('click', function() {
        $('#set_shipping').slideToggle('slow');
    });
    $('#set_shipping_close').live('click', function() {
        $('#set_shipping').slideUp('slow');
    });
    $('#set_shipping_submit').live('click', function() {
        $.post('/cart/shipping', $('#form-ship').formSerialize(), function(data) {
            $('#ajax1').html(data);
        });
    });
    $('#set_shipping #errorState').livequery(function() {
        if ($(this).val() == 1) {
            $('#set_shipping').show();
        }
    });
    $('#set_shipping #province, #set_shipping #province_other, #set_shipping #country, #set_shipping #country_other').live('change', function() {
        cartUpdateShippingMethod();
    });
    $('#set_shipping .checkbox_wrapper').live('click', function() {
        cartUpdateShippingMethod();
    });
    $('.cart_recommend_item').live('hover', function() {
        $(this).css('border', '1px solid #D3D4D6');
    }, function() {
        $(this).css('border', '1px solid white');
    });
    $('table#cart tr').live('hover', function() {
        $(this).css('background-color', '#F0EEEC');
    }, function() {
        $(this).css('background-color', 'white');
    });
    
    //country -> province listing
    $('#country').live('change', function() {
        var country = $(this).val();
        var menu = $('#province');
        var other = $('#province_other');
        var box = $('#province_box');
        var hidden = $('#province_hidden');

        if (country == 'united_states') {
            other.parent().slideUp();
            box.css('backgroundImage', box_off);
            hidden.val(0);
            menu.val('montana');
        } else if (country == 'canada') {
            other.parent().slideUp();
            box.css('backgroundImage', box_off);
            hidden.val(0);
            menu.val('alberta');
        } else {
            other.parent().slideDown();
            box.css('backgroundImage', box_on);
            hidden.val(1);
            menu.val('none');
            other.focus();
        }
    });

    //continue shopping
    $('#continue_link').live('click', function() {
        history.back();
    });

    //toggle checkboxes
    $('.cart_remove_box').live('click', function() {
        var id = $(this).attr('id').replace('box_', 'remove_');
        var sel = document.getElementById(id) ||
            document.getElementById(id.replace( /\:/, '\\:' ));
        var current_row = $(this).parent().parent();
        var next_row = current_row.next();
        var prev_row = current_row.prev();
        
        if ($(sel).val() == '1') {
            $(this).find('img').attr('src', box_off_src);
            $(sel).val(0);
        } else {
          $(this).find('img').attr('src', box_on_src);
            $(sel).val(1);
        }
        
        // free product rows must be removed when the parent product is removed
        if (next_row.hasClass('free')) {
            next_row.find('.cart_remove_box').click();
        }
    });
    $('.cart_update_box').live('change', function() {
        var id = $(this).attr('name');
        var qty = $(this).val();
        var min = parseInt($(this).attr('min'));
        var b = id.replace('quantity_', 'box_');
        var r = id.replace('quantity_', 'remove_');
        var m = id.replace('quantity_', 'min_');
        var box = document.getElementById(b) ||
            document.getElementById(b.replace( /\:/, '\\:' ));
        var rem = document.getElementById(r) ||
            document.getElementById(r.replace( /\:/, '\\:' ));
        var emin = document.getElementById(m) ||
            document.getElementById(r.replace( /\:/, '\\:' ));

        qty = qty.replace( /[^0-9]/g, '');
        if ((qty == 0) || (qty == '')) {
            qty = 0;
            if ($(rem).val() == 0) {
                $(box).css('backgroundImage', box_on);
                $(rem).val(1);
            }
        } else {
            if ($(rem).val() == 1) {
                $(box).css('backgroundImage', box_off);
                $(rem).val(0);
            }
            if (qty < min) {
                qty = min;
                if (min > 1) {
                    $(emin).show();
                }
            }
        }
        $(this).val(qty);
    });

    //client filters
    $('.add_qty').live('change', function() {
        var qty = $(this).val();

        qty = qty.replace( /[^0-9]/g, '');
        if (qty < 1) {
            qty = 1;
        }
        $(this).val(qty);
    });
    $('.add_code').live('change', function() {
        var code = $(this).val();

        code = code.replace( /[\s]/g, '');
        $(this).val(code);
    });

    //add to tote button
    $('#cart_addtotote').live('click', function() {
        cartAddToTote();
    });
    $('#cart_additems input').live('keyup', function(e) {
        switch (e.keyCode) {
            case 13:
                cartAddToTote();
            default:
                break;
        }
    });

    //clear tote
    $('#clear_tote').live('click', function() {
        confirmationDialog('Are you sure you want to clear your tote?', function() {
            setupPopup('please wait while we clear your bag...');

            $.post('/cart/clearcart', null, function(data)
            {
                $('#ajaxclear').html(data);
                $('#tote_quantity').html('0 items');
                $('#tote_price').html($('#price_clear').val());
                destroyPopup();
            });
        });
    });
    
    //save changes
    $('#save_changes').live('click', function() {
        $(this).css('visibility', 'hidden');
        setupPopup('please wait while we update your bag...');

        $.post('/cart/savechanges', $('#cart_review').formSerialize(), function(json)
        {
            $('#ajaxclear').html(json.content);
            toteRefresh(json.tote);
            destroyPopup();
        }, 'json');
    });

    //proceed to checkout
    $('#proceed_to_checkout').live('click', function() {
        $(this).css('visibility', 'hidden');
        setupPopup('please wait...');
        top.location = '/checkout?site=' + $('#site').val();
    });

    //init focus
    $('#code_1').livequery(function() {
        if ($('#tote_quantity').html().substr(0, 1) == '0') {
            $(this).focus();
        }
    });

    // remove personalization - old personalization system
    $('div#cart .removePersonalization').live('click', function() {
        var row = $(this).parent().parent().parent().parent();
        var ptext = $(this).parent().parent();
        var code = $(this).attr('id').replace('rp_', '');
        row.slideUp('slow');
        $.post('/cart/personalizeremove', {code: code}, function(json) {
            var newCode = 'row_' + json.newCode;
            var newRow = document.getElementById(newCode) || document.getElementById(newCode.replace( /\:/g, '\\:' ));
            if ((newRow != null) && ($(newRow).length != 0)) {
                $(newRow).slideUp('slow', function() {
                    row.html(json.newContent);
                    row.attr('id', newCode);
                    row.slideDown('slow');
                });
            } else {
                row.html(json.newContent);
                row.attr('id', newCode);
                row.slideDown('slow');
            }

            //refresh shipping
            $('#ajax1').fadeOut('fast').html(json.shipping).fadeIn('fast');
        }, 'json');
    });

    //select all button
    $('#select_all').live('click', function() {
        $('.cart_remove_box').each(function() {
            $(this).css('backgroundImage', box_on);
            $(this).next('input').val(1);
        });
    });

    // display design studio popup when edit personalization is clicked
    $('a.edit_personalization.new-system').live('click', function(event) {
        var row_id = $(this).attr('id');
        var id_parts = row_id.split('_');
        var product_lookup = id_parts[1];
        var loading_img = $(this).parent().find('img');
        var modify_links = $(this).parent().find('a');

        // personalized goodie bags/ merchandise bags require a minimum qty of 2 so don't proceed if qty is less
        var lookup_parts = product_lookup.split(':');
        var product_id = lookup_parts[2];
        if(product_id == '3388' || product_id == '3389') {
            var qty = parseInt($('input[name="quantity_' + product_lookup + '"]').val());
            if(qty < 2) {
                return;
            }
        }
        event.preventDefault();
        
        $.displayDesignStudio(product_lookup, loading_img, modify_links);
    });
    
    /*
     * do not allow showcase binder supplmenet item to be able to be ordered
     * by itself.
     */
    $('#cart').livequery(function()
    {
        var productRows = $("#cart div[id^=row_]");
        var supplementItem = $("#cart div[id^=row_1150-1]");
        
        // show continue shopping button if no more items require personalization
        if ($(productRows).length > 1) {
            $(supplementItem).find('div.personalization_header').hide();
        }
    });
});

function cartAddToTote()
{
    var max = $('#add_qty').val();
    var hasProduct = false;

    for (var i = 1; i < max; i++) {
        var code = '#code_' + i;
        if ($(code).val() != '')
            hasProduct = true;
    }

    if (hasProduct) {
        $('#cart_addtotote').css('visibility', 'hidden');
        setupPopup('please wait while we add these items to your shopping bag...');

        $.post('/cart/manualadd', $('#form_additems').formSerialize(), function(json) {
            if (json.overMax.valueOf()){
                alert('Were sorry, but due to limited quantities of magazines, a maximum quantity of 2 is allowed. \n If you require more than this please contact customer service.');
            }
            if ($(json.content).find('#update_cart_add_max').val() > 1) {
                $('#cart_additems').html(json.content);
                $('#add_qty').val($('#update_cart_add_max').val());
                $('#cart_addtotote').show();
            } else {
                $('#content').html(json.content);
            }
            toteRefresh(json.tote);
            destroyPopup();
        }, 'json');
    } else {
        $('#code_1').focus();
    }
}

function cartUpdateShippingMethod()
{
    $.post('/cart/shippingmethod', $('#form-ship').formSerialize(), function(data) {
        $('#ajax2').html(data);
    });
}

