$(function(){
    checkboxes = $('.checkbox_remove');
    allChecked = false;

    $.preloadImages('layout/green_check.gif', 'layout/dash.gif', 'layout/plus.gif', 'layout/x.gif'); //function defined in main.js

    $('form').attr('action', '/shop/update_cart'); //make sure this is the default action on this page

    $('.personalize_link').click(function(){
        var rows = $('tr.personalization[@parent='+$(this).attr('parent')+']');
        rows.toggle();
    });

    $('tr.personalization .field input').blur(function(){
        checkPersonalization(this);
    });
    $('tr.personalization .field input').keyup(function(){
        checkPersonalization(this);
    });
    checkPersonalization();

    function checkPersonalization(element)
    {
        if (typeof element != 'undefined') { elements = $(element); }
        else { elements = $('tr.personalization .field input'); }

        elements.each(function(){
            var image = $(this).siblings('img');
            if( $(this).val() == '') {
                image.attr('src', '/img/layout/dash.gif');
            }
            else if( /^[ a-zA-Z]{0,12}$/.test( $(this).val() )){
                image.attr('src', '/img/layout/green_check.gif');
            }
            else{
                image.attr('src', '/img/layout/x.gif');
            }
        });
    }

  //Delete Checkbox toggle for cart
    allChecked = false;
    $('#checkAll').click(function() {
        $('table#Cart :checkbox').attr('checked', (allChecked) ? false : true );
        allChecked = (allChecked) ? false : true;
    });

  //Auto-select "children" personalized rows when user clicks on the "parent" delete checkbox
    $('.checkbox_remove').click(function(){
        var relatedCheckboxes = $('tr.personalization[@parent='+$(this).attr('parent')+'] :checkbox');
        if ($(this).attr('checked')) {
            relatedCheckboxes.attr('checked', true);
        }
        else {
            relatedCheckboxes.attr('checked', false);
        }
    });


  //Logical events for personalization delete checkboxes
    $('tr.personalization :checkbox').click(function(){
      //if all personalization checkboxes are checked, auto-check the parent's checkbox
        var allSubChecked = 0;
        var parentAttr = $(this).parents('tr').attr('parent');

        $.each( $('tr.personalization[@parent=' + parentAttr + '] :checkbox'), function(i,n){
            allSubChecked += ($(n).attr('checked')) ? 0 : 1;
        });
        if (allSubChecked == 0) {
            $('tr.productRow :checkbox[@parent=' + parentAttr + ']').attr('checked', true);
        }
        else {
            $('tr.productRow :checkbox[@parent=' + parentAttr + ']').attr('checked', false);
        }
    });

});