var np = {};

np.data = {

    // price band data must be objects in an array to maintain order in Chrome
    "plates": [
        { "id": "10", "val": "2.50" },
        { "id": "6", "val": "3.00" },
        { "id": "3", "val": "3.50" },
        { "id": "0", "val": "4.00" }
    ],
    "products": {
        "npc-001": "3.00",
        "4mm-ngg16": "4.00",
        "7mm-ngg16": "6.00"
    },
    "extras": {
        "paint": "2.00"
    }

}

np.forms = function() {

    var pub = {
    
        init: function() {
        
            $.root = $(document);
            
            pub.setupAddFormRow();
            pub.setupNotesField();
            pub.setupFormCalculator();
            pub.setupExternalLinks();
            
            pub.reprice();
        
        },
        
        setupAddFormRow: function() {

            // create DOM template for form rows        
            var rowTemplate = $.root.find('table tbody tr:first').clone();
            
            // insert 'add' button and click behaviour on links in table
            $.root.find('table').after('<div class="buttons"><button id="new">Add another</button></div>').bind("click",function(e) {
            
                var target = $(e.target);
            
                if (target.is('a')) {
                
                    target.closest('tr').remove();
                    pub.reprice();
                
                    return false;
                
                }
                
            });

            // form row insert behaviour
            $.root.find('#new').bind('click',function() {
            
                var tableObj = $.root.find('table tbody'),
                    nextRow = rowTemplate.clone(),
                    nextRowId = tableObj.find('tr').length + 1;
                    
                nextRow.find(':input').each(function() {
                
                    this.id = this.id.split('_')[0] + '_' + nextRowId;
                    this.value = '';
                    
                });
            
                nextRow.find('td.remove').html('<a href="#" title="remove">X</a>');
            
                tableObj.append(nextRow);
                
                return false;
            
            });

        },
        
        setupNotesField: function() {
        
            $.root.find('a.showNotes').click(function() {
                
                $(this).closest('div').hide().parent().find('textarea').show();
            
                return false;
            
            });
        
        },
        
        setupFormCalculator: function() {

            // insert estimated cost display            
            $.root.find('button.submit').after('<span class="estimate">Estimated cost <strong>£0.00</strong></span>');
            
            // estimate calculator when plate details are added
            $.root.find('form table').change(function(e) {
            
                var target = $(e.target),
                    row = target.closest('tr');
                    
                // return immediately if there is no value as the row will be incomplete
                // skip optional colour value
                if (e.target.name != 'colour[]' && target.val() == '') {
                
                    // if this is clearing data from a completed row then reprice the estimate
                    if (row.hasClass('complete')) {
                    
                        row.removeClass('complete').addClass('incomplete');
                        pub.reprice();
                        
                    }
                    
                    return false;
                    
                // reprice on change of colour option    
                } else if (e.target.name == 'colour[]') {
                
                    pub.reprice();
                
                }


                // skip optional colour value
                var restOfRow = row.find(':input').not(target).not('[name=colour[]]');
                
                if (restOfRow.filter('[value!=""]').length == restOfRow.length) {
                
                    row.removeClass('incomplete').addClass('complete');
                    pub.reprice();
                
                } 
            
            });
            
            // estimate calculator when additional products are added
            $.root.find('fieldset.additional select').change(function() {
                
                pub.reprice();
            
            });        
        
        },
        
        setupExternalLinks: function() {
        
            $.root.find('a[rel=external]').attr({
                'target':'blank',
                'title' :'Link opens in a new window'
            });
        
        },
        
        reprice: function() {
        
            var price = 0;
        
            // determine how many rows of plate details have been completed and price accordingly
            var plateRows = $.root.find('form table tr.complete'),
                band = np.data.plates[0];
            
            $.each(np.data.plates,function(i,n) {
            
                if (plateRows.length >= n.id) {

                    band = n.val;
                    
                    return false;
                }                    
            
            });            

            price += plateRows.length * band;
        
            // check for 'painted' option - any number of painted plates adds the same option cost
            if ($.root.find('select[name=colour[]]').filter('[value!=""]').length > 0) {
            
                price += parseInt(np.data.extras['paint']);
            
            }
            
            // find and total any "additional" fixed cost items
            $.root.find('fieldset.additional select').each(function() {
            
                var val = $(this).val();
                
                if (val != '') {
                
                    price += val * np.data.products[this.id];
                
                }
            });
            
            // update the estimate on the page
            $.root.find('span.estimate strong').html('&pound;'+price.toFixed(2));
            
            // update hidden value field
            $.root.find('#estimate').val(price.toFixed(2));
        
        }
    
    }
    
    return pub;

}();

$(function() {

    np.forms.init();

});
