/**
 * Create RFQ wizard which guides the customer through
 * the process making an EZ Parts Quote
 */

// Set global ExtJS Variables
Ext.BLANK_IMAGE_URL = 'images/default/s.gif';
Ext.SSL_SECURE_URL = 'images/default/s.gif';

$(document).ready(function() {

    $('#formArmour').hide();
    

    // Setup the extjs datepickers
    for (var i = 1; i <= 5; i++) {
        var minDate = new Date().add(Date.DAY, 2);
        var dayOfWeek = minDate.format('w');

        // In case minDate falls on a disabled date
        // Add 1 day for Sunday, 2 Days for Saturday
        if (dayOfWeek === 0) {
            minDate = minDate.add(Date.DAY, 1).format('m/d/Y');
        } else if (dayOfWeek === 6) {
            minDate = minDate.add(Date.DAY, 2).format('m/d/Y');
        }

        new Ext.form.DateField({
            renderTo: 'txt_date' + i,
            id: 'partDate' + i,
            name: 'partDate' + i,
            minValue: minDate,
            disabledDays: [0, 6]
        });
    }

    // Reset the line items textboxes
    for (i = 1; i <= 5; i++) {
         $('#txt_partnum' + i).val('');
         $('#txt_quantity' + i).val('');
         $('#txt_mfg' + i).val('');
         $('#txt_desc' + i).val('');
    }


    $('#CreateRfqForm').validate({
        onsubmit: true,
        onkeyup: false,
        onfocusout: false,
        errorElement: 'span',
        errorPlacement: function(error, element) {
            error.appendTo(element.parent('td'));
        },
        invalidHandler: function(form, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                $('#input-form').show();
                $('#input-summary').hide();
            }
        },
        rules: {
            name: 'required',
            company: 'required',
            email: {
                required: true,
                email: true
            },
            phone: 'required'
        },
        messages: {
            name: 'Please enter a valid Contact Name.',
            company: 'Please enter a valid Company Name.',
            email: {
                required: 'Please enter a valid Email Address.',
                email: 'Your Email Address must be in the format:<br/>name@domain.com...'
            },
            phone: 'Please enter a valid Phone Number...'
        },
        submitHandler: function(form) {
            var valid = false;
            var empty = true;
            $('#lineItemEmpty').hide();

            // Make sure at least requested one part
            for (var i = 1; i <= 5; i++) {
                var pn = $('#txt_partnum' + i).val();

                if (pn != '') {
                    empty = false;
                    if ($('#txt_quantity' + i).val() == '') {
                        $('#lineItemValidation').show();
                        valid = false;
                        break;
                    }

                    /*** Removed target date validation
                    if (!Ext.getCmp('partDate' + i).isValid()) {
                        $('#lineItemValidation').show();
                        valid = false;
                        break;
                    }
                    ***/
                    valid = true;
                }
            }

            // Form is empty
            if (empty) {
                $('#lineItemEmpty').show();
            }

            // Form is valid
            if (valid) {
                form.submit();
            } else {
                $('#input-form').show();
                $('#input-summary').hide();
            }
        }
    });

    $('#contactPopupForm').validate({
        onsubmit: true,
        onkeyup: false,
        onfocusout: false,
        errorElement: 'em',
        rules: {
            visitorName: 'required',
            visitorEmail: {
                required: true,
                email: true
            },
            visitorComments: 'required'
        },
        messages: {
            visitorName: 'Enter your name...',
            visitorComments: 'Enter your comments...',
            visitorEmail: {
                required: 'Enter your email...',
                email: 'Invalid email format...'
            }
        }
    });

    $("#alert").overlay({
        expose: '#999'
    });


    var currentEl;


    // Setup contact us overlays
    $("a[rel]").each(function() {
        $(this).click(function() {
            $('#visitorSubject').html(this.title);
            $('#visitorSubjectValue').val(this.title);
            $('#visitorTarget').val(this.name);
            $('#visitorEmail').val('');
            $('#visitorComments').val('');
            currentEl = $(this);
        });

        $(this).overlay({
            closeOnClick: false,
            expose: {
                color: '#999',
                closeOnClick: false
            },
            onClose: function() {
                var form = $('#contactPopupForm');
                var validator = form.validate();
                validator.resetForm();
                document.getElementById('contactPopupForm').reset();
            }
        });
    });

    $('#contactPopupForm').submit(function() {
        if ($(this).valid()) {
            currentEl.overlay().close();

            $.post('contact_service.php', {
                visitorName: $("#visitorName").val(),
                visitorTarget: $('#visitorTarget').val(),
                visitorSubject: $('#visitorSubjectValue').val(),
                visitorEmail: $('#visitorEmail').val(),
                visitorComments: $('#visitorComments').val()
            }, function(data) {
                $('#sendConfirmation').html(data.msg);
                $('#alert').overlay().load();

                var status = $('#sendStatus');
                var message = $('#sendMessage');

                if (data.success) {
                    status.addClass('success').html('Message sent successfully!');
                    message.html('An AEI representative will contact you shortly.');
                } else {
                    status.addClass('failure').html('Message was not sent!');
                    //message.html(data.msg);
                }
            }, 'json');
        }

        return false;
    });
});


/**
 * Shows the summary before submitting the order
 */
function showSummary() {
    $('#frm_email').html($('#txt_email').val());
    $('#frm_company').html($('#txt_company').val());
    $('#frm_name').html($('#txt_name').val());
    $('#frm_phone').html($('#txt_phone').val());
    $('#frm_comments').html($('#txt_comments').val());

    var c1 = '#FFFFFF;';
    var c2 = '#F5F5F5;';
    var c = c1;

    var d1 = '<div style="background-color: ';
    var d2 = ' padding: 2px;"><div style="border: 1px;"><table id="rfqTable" cellpadding="3" cellspacing="0" style="width: 100%;">' +
              '<thead><tr> <th align="left" style="width: 170px;"><label>Part Number</label></th><th style="width: 120px;" align="left"><label>Mfg</label></th><th style="width: 120px;" align="left"><label>Description</label></th>' +
               '<th style="width: 60px;" align="left"><label>Condition</label></th><th style="width: 60px;" align="left"><label>Qty</label></th><th style="width: 80px;" align="left"><label>Target Date</label></th></tr></thead>';
    var d3 = '</table></div></div>';

    $('#summary').html('');
    var html = '';
    for (var i = 1; i <= 5; i++) {
        var pn = $('#txt_partnum' + i).val();
        if (pn != '') {
            var qt = $('#txt_quantity' + i).val();
            var cd = $('#txt_cond' + i).val();
            var ds = $('#txt_desc' + 1).val();
            var mf = $('#txt_mfg' + i).val();

            var dt = Ext.getCmp('partDate' + i).value;

            var h = d1 + c + d2 + '<tbody><tr><td>' + pn + '</td><td>' + mf + '</td>' +
               '<td>' + ds + '</td><td>' + cd + '</td>' +
               '<td>' + qt + '</td><td>' + dt + '</td></tr></tbody>' + d3;
           html = html + h;
        }

        if (c == c1) {
            c = c2;
        } else {
            c = c1;
        }
    }
    $('#summary').html(html);
}
