﻿function InitContact() {
    ContactHandlers();
    LoadToolTips();

    InquirySelect($('#cmbInquiryType option:selected').text());
    ProductSelect($('label[for="' + $('input[name="prodtype"]:radio:checked').attr('id') + '"]').text());
}

function ContactHandlers() {
    //Inquiry Type Selection
    $('#cmbInquiryType').change(function() {
        $('#cmbInquiryType.errorctl').removeClass('errorctl');
        InquirySelect($('#cmbInquiryType option:selected').text());
    });
    
    //Product Family Selection
    $('input[name=prodtype]:radio').change(function() {
        ProductSelect($('label[for="' + $('input[name="prodtype"]:radio:checked').attr('id') + '"]').text());
    });

    //Dependant Dropdown Handlers (Arrays initialized server-side)
    $('#cmbCarrotBrand').change(function() {
        CarrotBrandSelect($('#cmbCarrotBrand option:selected').val());
    });

    $('#cmbCarrotStyle').change(function () {
        CarrotStyleSelect($('#cmbCarrotStyle option:selected').val(), $('#cmbCarrotBrand option:selected').val());
    });

    $('#cmbBevFlavor').change(function () {
        BeverageFlavorSelect($('#cmbBevFlavor option:selected').val());
    });

    //datepicker controls jqueryui
    $('input.datepick').datepicker();
    
    //Validation handler for form submission
    $('#frmcontact').submit(function() {
        var valid = ValidateFields();
        $('#errormsg').remove();
        $('.errorctl').removeClass('errorctl');

        if (valid.frmvalidated) {
            ProcessFields(valid);
        } else {
            var errmsgs = '';
            for (var i = 0, l = valid.errormsgs.length; i < l; i++) {
                errmsgs += '<li>' + valid.errormsgs[i] + '</li>';
            }
            $(this).before('<div id="errormsg"><ol>' + errmsgs + '</ol></div>');
            for (var i = 0, l = valid.errorctls.length; i < l; i++) {
                $('#' + valid.errorctls[i]).addClass('errorctl');
            }
        }
        return false;
    });

}

function LoadToolTips() {
    $('a.tooltiphelp').each(function (i) {
        var tooltips = [{ img: 'beverage3.jpg', w: '209', h: '319', ot: '349', caption: 'Example - BV209Q708AQ6F06' },
                            { img: 'beverage2.jpg', w: '209', h: '319', ot: '349', caption: 'Example - 14:27' },
                            { img: 'beverage.jpg', w: '209', h: '319', ot: '349', caption: 'Example - 09/16/2008' },
                            { img: 'carrot3.jpg', w: '209', h: '179', ot: '209', caption: 'Example - BNF110H19R' },
                            { img: 'carrot2.jpg', w: '209', h: '179', ot: '209', caption: 'Example - 16V 1302' },
                            { img: 'carrot.jpg', w: '209', h: '179', ot: '209', caption: 'Example - 09/22/2008' },
                            { img: 'dressing2.jpg', w: '229', h: '369', ot: '399', caption: 'Example - BD107K25073801390' },
                            { img: 'dressing.jpg', w: '229', h: '369', ot: '399', caption: 'Example - 02/23/2008' },
                       ]
        var images = ['beverage3.jpg', 'beverage2.jpg', 'beverage.jpg'];
        var captions = ['Bottle Code', 'File Code', 'Best if used by'];
        $(this).click(function (event) {
            event.preventDefault();
        });

        $(this).hover(function () {
            var offset = $(this).offset();
            var width = '209px';
            //var left = 109 - (parseInt(width) / 2);
            var left = parseInt(width);
            var content = '<p><img src="images/' + tooltips[i].img + '" alt="' + tooltips[i].caption + '" /></p><div class="helpcaption">' + tooltips[i].caption + '</div>';
            $('body').append('<div id="divtooltip">' + content + '</div>');
            $('#divtooltip')
                .css({ 'left': (offset.left - parseInt(left)) + 'px',
                    'top': (offset.top - 600) + 'px',
                    'width': tooltips[i].w + 'px',
                    'height': tooltips[i].h + 'px',
                    'position': 'absolute',
                    'overflow': 'hidden',
                    'background': '#FFF',
                    'border': 'solid 1px orange',
                    '-webkit-border-radius': '8px',
                    '-moz-border-radius': '8px',
                    'border-radius': '8px',
                    '-webkit-box-shadow': 'rgba(0,0,0, 0.3) 0px 0px 8px',
                    '-moz-box-shadow': 'rgba(0,0,0, 0.3) 0px 0px 8px',
                    'box-shadow': 'rgba(0,0,0, 0.3) 0px 0px 8px',
                    'padding': '10px'
                })
                .stop()
                .animate({ 'top': (offset.top - tooltips[i].ot) + 'px' }, 500);
        }, function () {
            $(this).stop();
            $('#divtooltip').stop().remove();
        });
    });
}

function BeverageFlavorSelect(selection) {
    var abevflavorsize = $.grep(abottlesize, function (n, i) {
        return n.flavor == selection;
    });
    var sel = '<option value="0">--Please Select a Size--</option>';
    if (abevflavorsize.length > 1) {
        for (var i = 0, l = abevflavorsize.length; i < l; i++) {
            sel += '<option value="' + abevflavorsize[i].id + '">' + abevflavorsize[i].size + '</option>';
        }
    } else {
        sel = '<option value="' + abevflavorsize[0].id + '" selected="selected">' + abevflavorsize[0].size + '</option>';
    }

    $('#cmbBevSize').html(sel);
}

function CarrotBrandSelect(selection) {
    var acarrotbrandstyle = $.grep(acarrotstyle, function(n, i) {
        return n.brand == selection;
    });
    var sel = '<option value="0">--Please Select Style--</option>';
    if (acarrotbrandstyle.length > 1) {
        for (var i = 0, l = acarrotbrandstyle.length; i < l; i++) {
            sel += '<option value="' + acarrotbrandstyle[i].id + '">' + acarrotbrandstyle[i].type + '</option>';
        }
    } else {
        sel = '<option value="' + acarrotbrandstyle[0].id + '">' + acarrotbrandstyle[0].type + '</option>';
        CarrotStyleSelect(acarrotbrandstyle[0].id, selection);
    }

    $('#cmbCarrotStyle').html(sel);
}

function CarrotStyleSelect(selection, brand) {
    var acarrotstylesize = $.grep(acarrotsize, function(n, i) {
        return (n.style == selection && n.brand == brand);
    });
    var sel = '<option value="0">--Please Select Size--</option>';

    if (acarrotstylesize.length > 1) {
        for (var i = 0, l = acarrotstylesize.length; i < l; i++) {
            sel += '<option value="' + acarrotstylesize[i].id + '">' + acarrotstylesize[i].size + '</option>';
        }
    } else {
        sel = '<option value="' + acarrotstylesize[0].id + '">' + acarrotstylesize[0].size + '</option>';
    }

    $('#cmbCarrotSize').html(sel);

}

function ProductSelect(selection) {
    var duration = null;
    if (selection == 'Beverage') {
        $('#dressingfields').hide(duration);
        $('#carrotfields').hide(duration);
        $('#bevfields').show(duration);
    } else if (selection == 'Carrots') {
        $('#bevfields').hide(duration);
        $('#dressingfields').hide(duration);
        $('#carrotfields').show(duration);
    } else if (selection == 'Dressing') {
        $('#bevfields').hide(duration);
        $('#carrotfields').hide(duration);
        $('#dressingfields').show(duration);
    };
    $('#frmcontact').data('prodtype', selection);
} 

function InquirySelect(selection) {
    var prereq = '<span class="reqasterisk">*</span>';
    $('span.reqasterisk').remove();
    $('li.reqall').find('label').before(prereq);
    
    if ($('#frmcontact').data('type') === 'Media' && selection != 'Media'){
        SetForm('Normal')
    }
    if (selection == 'Complaint') {
        $('li.reqcomplaint').find('label').before(prereq);
    } else if (selection == 'Media') {
        SetForm('Media');
    }
    
    $('#frmcontact').data('type', selection);
    $('#frmcontact').data('prodtype', $('label[for="' + $('input[name="prodtype"]:radio:checked').attr('id') + '"]').text());
}

function SetForm(type) {
    var duration = null;
    if (type === 'Media') {
        $('#userfields').hide(duration);
        $('#divproduct').hide(duration);
        $('#ulnewsletter').hide(duration);
        $('#mediafields').show(duration);
        $('#divuser').removeClass('fsleft').addClass('fsleftmedia');
        $('#divinquirytype').removeClass('contact-type').addClass('contact-type-media');
    } else {
        $('#mediafields').hide(duration);
        $('#divuser').removeClass('fsleftmedia').addClass('fsleft');
        $('#divinquirytype').removeClass('contact-type-media').addClass('contact-type');
        $('#userfields').show(duration);
        $('#divproduct').show(duration);
        $('#ulnewsletter').show(duration);
    }
}

function ValidateFields() {
    try {
        var $inq = $('#cmbInquiryType option:selected');
        var fam = htmlEncode($('label[for="' + $('input[name="prodtype"]:radio:checked').attr('id') + '"]').text());
        var product = null;
        if (fam == 'Beverage') {
            product = {
                family: fam,
                brand: '1',
                type: htmlEncode($('#cmbBevFlavor option:selected').val()),
                size: htmlEncode($('#cmbBevSize option:selected').val()),
                biub: htmlEncode($('#txtBevBIUB').val()),
                fcode: htmlEncode($('#txtBevFileCode').val()),
                bcode: htmlEncode($('#txtBottleCode').val())
            }
        } else if (fam == 'Carrots') {
            product = {
                family: fam,
                brand: htmlEncode($('#cmbCarrotBrand option:selected').val()),
                type: htmlEncode($('#cmbCarrotStyle option:selected').val()),
                size: htmlEncode($('#cmbCarrotSize option:selected').val()),
                biub: htmlEncode($('#txtCarrotBIUB').val()),
                fcode: htmlEncode($('#txtCarrotFileCode').val()),
                bcode: htmlEncode($('#txtBagCode').val())
            }
        } else if (fam == 'Dressing') {
            product = {
                family: fam,
                brand: '1',
                type: htmlEncode($('#cmbDressFlavor option:selected').val()),
                size: htmlEncode($('#cmbDressSize option:selected').val()),
                biub: htmlEncode($('#txtDressBIUB').val()),
                fcode: null,
                bcode: htmlEncode($('#txtDressBottleCode').val())
            }
        
        } else {
            //Unhandled Product Family
        }
        var valid = {
            frmvalidated: true,
            errormsgs: [],
            errorctls: [],
            inquiry: ($inq.text() == 'Media') ? 'Media' : 'Consumer',
            mediaform: {
                name: htmlEncode($('#txtContactName').val()),
                company: htmlEncode($('#txtCompany').val()),
                phone: htmlEncode($('#txtContactPhone').val()),
                email: {
                    address: htmlEncode($('#txtContactEmail').val()),
                    valid: function() {
                        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                        return(emailReg.test(htmlEncode($('#txtContactEmail').val())));
                    }
                },
                comments: htmlEncode($('#txtComments').val()),
                byEmail: $('#chkemail').is(':checked'),
                byPhone: $('#chkphone').is(':checked')
            },
            contactform: {
                inquiryType: {
                    type: htmlEncode($inq.text()),
                    value: htmlEncode($inq.val()),
                    valid: function() {
                        return (($inq.val() == 0) ? false : true);
                    }
                },
                name: htmlEncode($('#txtName').val()),
                address: htmlEncode($('#txtAddress').val()),
                city: htmlEncode($('#txtCity').val()),
                state: htmlEncode($('#txtState').val()),
                zip: htmlEncode($('#txtZip').val()),
                email: {
                    address: htmlEncode($('#txtEmail').val()),
                    valid: function() {
                        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                        return(emailReg.test(htmlEncode($('#txtEmail').val())));
                    }
                },
                phone: htmlEncode($('#txtPhone').val()),
                store: {
                    banner: htmlEncode($('#cmbStore option:selected').text()),
                    id: htmlEncode($('#cmbStore option:selected').val())
                },
                comments: htmlEncode($('#txtComments').val()),
                bevNews: $('#chkbevnews').is(':checked'),
                carrotNews: $('#chkcarrotnews').is(':checked'),
                byEmail: $('#chkemail').is(':checked'),
                byPhone: $('#chkphone').is(':checked'),
                product: product
            }
        };

        if (!valid.contactform.inquiryType.valid()) {
            valid.errormsgs.push(valid.contactform.inquiryType.type);
            valid.errorctls.push('cmbInquiryType');
        }
        if (valid.inquiry == 'Consumer'){
            if (!valid.contactform.email.valid()) {
                valid.errormsgs.push(valid.contactform.email.address + ' is not a valid email format (eg. email@domain.com)');
                valid.errorctls.push('txtEmail');
            }
        } else {
            if (!valid.mediaform.email.valid()) {
                valid.errormsgs.push(valid.mediaform.email.address + ' is not a valid email format (eg. email@domain.com)');
                valid.errorctls.push('txtContactEmail');
            }
        }
        $('li.reqall input:visible').each(function() {
            if ($(this).val() == '') {
                valid.errormsgs.push('Please enter a value for ' + $('label[for="' + $(this).attr('id') + '"]').text());
                valid.errorctls.push($(this).attr('id'));
            }
        });
        $('li.reqall select:visible').each(function () {
            ctl = $('#' + $(this).attr('id') + ' option:selected');
            if (ctl.val() == 0) {
                valid.errormsgs.push(ctl.text());
                valid.errorctls.push($(this).attr('id'));
            }
        });
        if (valid.contactform.inquiryType.type == 'Complaint') {

            var ctl;
            $('li.reqcomplaint select:visible').each(function() {
                ctl = $('#' + $(this).attr('id') + ' option:selected');
                if (ctl.val() == 0) {
                    valid.errormsgs.push(ctl.text());
                    valid.errorctls.push($(this).attr('id'));
                }
            });
            $('li.reqcomplaint input:visible').each(function() {
                if ($(this).val() == '') {
                    valid.errormsgs.push('Please enter a value for ' + $('label[for="' + $(this).attr('id') + '"]').text());
                    valid.errorctls.push($(this).attr('id'));
                }
            });
            
        }

        if (valid.contactform.byPhone) {
            $('li.reqphone input:visible').each(function() {
                if ($(this).val() == '') {
                    valid.errormsgs.push('Please enter a value for ' + $('label[for="' + $(this).attr('id') + '"]').text() + ' (Required when respond by phone is selected)');
                    valid.errorctls.push($(this).attr('id'));
                }
            });
        }

        if (valid.errormsgs.length != 0) {
            valid.frmvalidated = false;
        }
    } catch (err) {
        alert('Error:' + err.Message);
        //valid.errormsgs.push(err);
        valid.frmvalidated = false;
    }
    return valid;
}

function ProcessFields(validation) {

    document.body.style.cursor = 'wait';
    var strJSON = JSON.stringify(validation)
    //console.log(strJSON);
    
    try {
        $.ajax({
            url: 'csxml/sqleverestxml.aspx',
            data: { paramxml: 'processcontact', paramform: strJSON },
            type: 'GET',
            dataType: 'xml',

            error: function() {
                $('p.hslabel').text('Sorry...');
                $('p.hsnote').text('There was a problem processing your submission');
                $('#content-contact').html('<p class="error">There was a problem processing your submission, a technician has been notified and will look into it soon.  Please try again later.</p>');
            },

            success: function(xml) {
                //alert('Form Processed!');
                if ($('result', xml).length > 0) {
                    $('result', xml).each(function(i) {
                        if ($(this).find('status').text() == 'Success') {
                            $('p.hslabel').text('Success');
                            $('p.hsnote').text('Thank you for your submission');
                            $('#content-contact').html('<p class="success">Your information or request has been sent successfully and someone will contact you soon.<br /><strong>Thank you again for surfing Bolthouse Farms<sup>®</sup> and come back soon!</strong></p>');
                        }
                    });
                }
            }
        });        

    } catch (err) {
        console.log('Error processing AJAX');
    }
    document.body.style.cursor = 'default';

}


function htmlEncode(value) {
    return $('<div/>').text(value).html();
}

function htmlDecode(value) {
    return $('<div/>').html(value).text();
}


function DonationStep(step) {
    if (step == -1) {
        $('.divsteps').hide();
        $('div.step-ineligible').show();
    } else {
        $('.step' + (step - 1).toString()).hide();
        $('.step' + step.toString()).show();
    }
}
function InitDonation() {
    $('input.datepick').datepicker();
    $('#butsubmit').click(function () {
        SubmitDonationApplication();
    });
}
function formNotify(notify) {
    if (notify.toggle === 'on') {
        document.body.style.cursor = 'wait';
        $('div.cdiv').html('<h6>' + notify.msg + '</h6').stop().css({ opacity: 0.0 }).fadeTo(notify.duration, 1.0);
    } else {
        document.body.style.cursor = 'default';
        $('div.cdiv').stop().fadeTo(notify.duration, 0.0);
    }
}

function fullyLoaded(boolLoad) {
    for (var t in boolLoad) {
        if (!boolLoad[t]) {
            return false;
        }
    }
    return true;
}

function SubmitDonationApplication() {
    var donationapplication = {company: $('#txtcompany').val(),
                               charity: $('#txtcharity').val(),
                               website: $('#txtwebsite').val(),
                               irs501c3: $('#txt501c3').val(),
                               eventname: $('#txteventname').val(),
                               eventdate: $('#dteventdate').val(),
                               eventsite: $('#txteventsite').val(),
                               eventdescription: $('#txteventdescription').val(),
                               itemuse: $('#txtitemuse').val(),
                               eventexpattendance: $('#txteventexpattendance').val(),
                               eventyears: $('#txteventyears').val(),
                               eventamount: $('#txteventamount').val(),
                               contactname: $('#txtname').val(),
                               contactphone: $('#txtphone').val(),
                               contactemail: $('#txtemail').val(),
                               contactaddress: $('#txtaddress').val(),
                               contactcity: $('#txtcity').val(),
                               contactstate: $('#txtstate').val(),
                               contactzip: $('#txtzip').val(),
                               contactsupervisor: $('#txtsupervisorname').val()
                           };

    formNotify({ toggle: 'on', msg: 'Saving Donation Application...', duration: 1000 });
    var boolLoaded = { savedonation: false };

    $.ajax({
        url: 'csjson/sqleverestjson.ashx',
        data: { paramjson: 'donationrequest', paramdonationform: JSON.stringify(donationapplication) },
        type: 'POST',
        dataType: 'json',

        error: function () {
            $('div.cdiv').html('<h6>Error Saving Donation Application</h6>');
            boolLoaded.savedonation = true;
            if (fullyLoaded(boolLoaded)) {
                formNotify({ toggle: 'off', duration: 500 });
            }
        },

        success: function (json) {
            DonationApplicationSuccess(json);
            boolLoaded.savedonation = true;
            if (fullyLoaded(boolLoaded)) {
                formNotify({ toggle: 'off', duration: 500 });
            }
        }
    });

}

function DonationApplicationSuccess(json) {
    $('.divsteps').hide();
    $('#headstripe').after('<div id="successmessage"><p>Thank you for your donation application.</p></div>');
}
