$(document).ready(function() {
    if(typeof original_pricing != 'undefined') {
        $('#quantity').change(update_price);
        $('.options').change(update_pricing);
        $('.ball select').change(update_image);
        $('.print').click(update_type);
        update_pricing();
    }
    $('form:has(.artwork_agree)').submit(validate_artwork);

    $('#rush').change(function() {
        if($(this).attr('checked')) {
            $('#rush_needby').show();
            $('#rush_price').show();
        }
        else {
            $('#rush_needby').hide();
            $('#rush_price').hide();
        }
        update_total_price();
    });

    $('#address_id').change(update_address);
    $('#country').change(show_states);
    show_states();
    $('#billing_form .address').change(update_shipping);
    $('form:has(#country)').submit(validate_address);

    $('#billing_form').submit(function() {
        if(!$('.shipping_option:checked').length) {
            var option = $('#shipping_options');
            option.html('<span class="error">' + option.html() + '</span>');
            return false;
        }
        return true;
    });

    $('.answer').hide();
    $('.question').click(function() {
        $('#' + this.id + '_answer').slideToggle();
    });
});

// Checkout Pages

function update_address(e) {
    if(typeof addresses == 'undefined' || typeof current_address == 'undefined') {
        return;
    }

    var id = $('#address_id').val();
    var address = addresses[id];
    if(!address) {
        return;
    }

    var first_name = $('form [name=address[first_name]]');
    var last_name  = $('form [name=address[last_name]]');
    var address_1  = $('form [name=address[address_1]]');
    var address_2  = $('form [name=address[address_2]]');
    var phone      = $('form [name=address[phone]]');

    var country = $('#country').val();
    addresses[id] = {
        id: id,
        first_name: first_name.val(),
        last_name:  last_name.val(),
        address_1:  address_1.val(),
        address_2:  address_2.val(),
        phone:      phone.val(),
        city: $('#city').val(),
        state: $('#state_' + country).val(),
        zip: $('#zip').val(),
        country: country
    }

    first_name.val(address.first_name);
    last_name.val( address.last_name);
    address_1.val( address.address_1);
    address_2.val( address.address_2);
    phone.val(     address.phone);

    $('#city').val(address.city),
    $('#state_' + address.country).val(address.state),
    $('#zip').val(address.zip);
    $('#country').val(address.country);
    
    show_states();
    update_shipping();
}

function validate_address(e) {
    if(!$('#city').val().length) {
        alert('Please enter a city');
        return false;
    }
    var country = $('#country').val();
    if(!$('#state_'+country).val().length) {
        alert('Please select a state');
        return false;
    }
    if(!$('#zip').val().length) {
        alert('Please enter a postal code');
        return false;
    }
    return true;
}

function update_shipping() {
//    var address1 = $('#address1').val();
//    var address2 = $('#address2').val();
    var country  = $('#country').val();
    var state    = $('#state_' + country).val();
    var city     = $('#city').val();
    var zip      = $('#zip').val();    

    var options = $('#shipping_options');

//    if(!address1 || !country || !state || !city || !zip) {
    if(!country || !state || !city || !zip) {
        options.text('Enter a shipping address to select shipping method');
        return;
    }

    options.html('<img src="images/spinner.gif" /> Calculating shipping options');
    update_shipping_price();

    $.ajax({
        type: 'POST',
        url: 'shipping.php',
        dataType: 'json',
        data: {
//            address1: address1,
//            address2: address2,
            city: city,
            state: state,
            zip: zip,
            country: country
        },
        success: function(data) {
            if(typeof data == 'string') {
                options.html('<span class="error">' + data + '</span>');
                return;
            }
            var html = [];
            for(var i in data) {
                html.push('<input type="radio" id="shipping_', i, '" class="shipping_option" name="shipping_option" value="', data[i].name, '" /> ', 
                          '<label for="shipping_', i, '">',
                          data[i].name, ' - <span id="shipping_', i, '_price">$', format_price(data[i].price), '</span></label><br />');
            }
            options.html(html.join(''));

            $('.shipping_option').change(update_shipping_price);
        }
    });

    options.html();
}

function update_shipping_price() {
    var checked = $('.shipping_option:checked');
    var price = '--     ';
    if(checked.length) {
        price = $('#' + checked.attr('id') + '_price').text();
    }
    $('#shipping_price').text(price);
    update_total_price();
}

function update_total_price() {
    var price = 0.0;
    $('.subprice:visible').each(function(i) {
        var text = $(this).text();
        if(text.substr(0,1) == '$') {
            var val = parseFloat(text.substr(1));
            price += val;
        }
    });
    var discount = Math.min(price, max_discount);
    $('#discount .subprice').text('- $' + format_price(discount));
    price -= discount;
    if(!price) {
        $('#cc_title').text('Free');
    }
    else {
        $('#cc_title').text('Credit Card');
    }
    $('#price').text('$' + format_price(price));
}

function show_states() {
    var country = $('#country');
    if(!country.length) {
        return;
    }
    var state = '#state_' + country.val();
    $('.state:not('+state+')').hide();
    $(state).show();
}

// Custom Ball Pages

function validate_artwork(e) {
    var cb = $('.artwork_agree:visible');
    var rtn = true;
    cb.each(function(i) {
        if(!$(this).attr('checked')) {
            var id = this.id.split('_').pop();
            if($('input[name=options[' + id + ']]').val()) {
                alert('You must agree that you have the right to print this image before uploading it');
                rtn = false;
                return false;
            }
        }
        return true;
    });
    return rtn;
}

function update_quantity(qty) {
    $('#quantity').val(qty);
    $('#quantity').change();    
}

function update_steps() {
    $('.step:visible').each(function(i) {
        var o = $(this);
        o.attr('src', '/images/numbers/glass_numbers_' + (i+1) + '.png');
        o.attr('alt', 'Step ' + (i+1));
    });
}

function update_type() {
    var print_type = $('.print:checked').val();
    switch(print_type) {
    case '1':
        $('.two_color').hide();
        $('.full_color').hide();
        $('.one_color').show();
        break;
    case '2':
        $('.one_color').hide();
        $('.full_color').hide();
        $('.two_color').show();
        break;
    case '3':
        $('.one_color').hide();
        $('.two_color').hide();
        $('.full_color').show();
        break;
    }
    update_image();
    update_steps();
}

function update_image() {
    var ball_color = $('.ball:visible select');
    $('.ball:hidden select').val(ball_color.val());
    if(ball_color.length) {
        $('#ball_image').attr('src', '/images/products/balls/' + ball_color.val() + '.jpg');
    }
}

function update_price() {
    var qty = parseInt($('#quantity').val());
    var price, new_qty, new_price;

    for(var i=0; i < pricing.length; i++) {
        if(pricing[i].min_qty > qty) {
            if(i==0) {
                // invalid quantity
                $('#quantity').val(pricing[0].min_qty);
                return update_price();
            }
            else {
                price = pricing[i-1].price * qty;
                $('#price').text(format_price(price));
                new_qty = pricing[i].min_qty;
                new_price = pricing[i].price * new_qty;
                break;
            }
        }
    }
    if(!pricing[i-1].price) {
        // invalid quantity
        $('#quantity').val(pricing[i-1].min_qty - 1);
        return update_price();
    }

    $('#price_table tr.active').removeClass('active');
    $('#price_table tr:eq('+i+')').addClass('active');

    var diff_qty = new_qty - qty;
    var diff_price = new_price - price;
    var pct_qty = Math.round((new_qty / qty - 1) * 100);
    var pct_price = Math.round((new_price / price - 1) * 100);
    if(!new_price) {
        $('#qty_hint').html('<b>Tip:</b> Looking for ' + format_number(new_qty) + ' or more? <a href="contact.php">Get a quote</a>');
    }
    else if(pct_qty < 20 || pct_price < 20) {
        $('#qty_hint').html('<b>Tip:</b> you can get ' + format_number(diff_qty) + ' more for just $' + format_price(diff_price) + '. <a href="javascript:void(0)" onclick="update_quantity(' + new_qty + ')">Do this</a>');
    }
    else {
        $('#qty_hint').text('');
    }
}

function update_pricing() {
    pricing = [];
    if(typeof original_pricing == 'function') {
        //function call
        pricing = original_pricing();
    }
    else {
        //deep copy
        for(var i=0; i<original_pricing.length; i++) {
            pricing[i] = $.extend({}, original_pricing[i]);
        }
    }

    for(var id in options) {
        var sel = $('[name=options['+id+']]:visible:checked');
        if(!sel.length) {
            sel = $('[name=options['+id+']]:visible');
        }

        sel.each(function(j) {
            var price = options[id][$(this).val()].price;
            for(var p in pricing) {
                if(pricing[p].price) {
                    pricing[p].price += price;
                }
            }
        });
    }
    update_pricing_display();
}

function update_pricing_display() {
    var table = ['<table id="price_table"><tr><th class="qty">Quantity</th><th>Price</th></tr>'];
    for(var i=0; i < pricing.length; i++) {
        table.push('<tr><td class="qty">', format_number(pricing[i].min_qty));
        if(i == pricing.length - 1) {
            table.push('+');
        }
        else if(pricing[i].min_qty != pricing[i+1].min_qty - 1) {
            table.push(' - ', format_number(pricing[i+1].min_qty - 1));
        }
        table.push('</td><td>');
        if(pricing[i].price) {
            table.push('$', format_price(pricing[i].price));
        }
        else {
            table.push('<a href="contact.php">Contact Us</a>');
        }
    }
    table.push('</table>');
    $('#price_table').replaceWith(table.join(''));

    update_price();
}

function format_price(num) {
    return format_number(num.toFixed(2));
}

function format_number(num) {
    num += '';
    x = num.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

