﻿/// <reference path="json2.debug.js"/>
/// <reference path="jquery-1.2.6.debug.js"/>
/// <reference path="jquery.simplemodal.debug.js"/>
/// <reference path="quote.debug.js"/>


function taf_displayMessage(successful, quote_id) {
    jQuery(".taf-progress-icon" + quote_id).hide();
    if (successful) {
        jQuery(".taf-success" + quote_id).show();
        jQuery(".taf-error" + quote_id).hide();
    }
    else {
        jQuery(".taf-error" + quote_id).show();
        jQuery(".taf-success" + quote_id).hide();
    }
}
//jQuery(document).ready(function() {
//    jQuery('.taf-form-submit a').click(function(event) {

function SendRequestAQuote(tmi, quote_id) {

    //        if (jQuery(event.target).is('.taf-form-submit' + tMI + ' a')) {

    //event.preventDefault();

    var validationResult = validateForm(quote_id);
    if (validationResult == "") {
        var tafData;
        var p = new Array();

        var radios = jQuery(".taf-form" + quote_id + " [name!=''][type=radio],.taf-form" + quote_id + " [name!=''][type=checkbox]");
        var radioNames = new Array();
        var radioRval = new Array();
        jQuery(radios).each(function() {
            var nameAlreadyExists = false;
            var cur = jQuery(this).attr("name");
            jQuery(radioNames).filter("[name=" + cur + "]").each(function() {
                nameAlreadyExists = true;
            });
            if (nameAlreadyExists == false) {
                radioNames.push(this);
            }
        });

        jQuery(radioNames).each(function() {
            var existChecked = false;
            var reqVal = new Array();
            jQuery(radios).filter("[name=" + jQuery(this).attr("name") + "]:checked")
                        .each(function() {
                reqVal.push(jQuery(this).val());
                existChecked = true;
            });

            if (!existChecked) {
                reqVal.push("");
            }

            var fieldName;
            var fieldVal;
            fieldName = jQuery(this).attr("name");
            fieldVal = reqVal.join(',');
            p.push(fieldName + ':\"' + fieldVal + '\"');
        });

        jQuery(".taf-form" + quote_id + " [name!=''][type!=radio][type!=checkbox]")
                    .each(function() {
            var fieldName;
            var fieldVal;
            fieldName = jQuery(this).attr("name");
            fieldVal = jQuery(this).val();
            p.push(fieldName + ':\"' + fieldVal + '\"');
        });

        p.push('tabModuleId:\"' + tmi.toString() + '\"');

        var tafDataToString = '{' + p.join(',') + '}';

        while (/\n/.test(tafDataToString)) {
            tafDataToString = tafDataToString.replace(/\n/, ' ');
        }

        //var tafData = JSON.parse(tafDataToString, null);
        eval('tafData = ' + tafDataToString);
        //alert(JSON.stringify(tafData));

        jQuery(".taf-progress-icon" + quote_id).show();
        jQuery.ajax({
            type: "POST",
            url: CurrentContextInfo.WebMethodUrl + webMethodName,
            data: JSON.stringify(tafData),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                taf_displayMessage(msg === '' || msg.d == '', quote_id);
                jQuery('.taf-form' + quote_id + ' [name!=""][type!=radio][type!=checkbox]')
                .each(function() {
                    jQuery(this).val("");
                });
                jQuery(".taf-form" + quote_id + " [name!=''][type=radio],.taf-form" + quote_id + " [name!=''][type=checkbox]").each(function() {
                    jQuery(this).attr("checked", false);
                });
                setTimeout('jQuery(".modalCloseImg").click();jQuery(".taf-success" + quoteId).hide()', 3000);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { jQuery(".taf-error" + quote_id).html("There was a problem sending your email. If the problem continues, please contact the site administrator."); taf_displayMessage(false, quote_id); }
        });
    } else {
        jQuery(".taf-error" + quote_id).html(validationResult);
        taf_displayMessage(false, quote_id);
    }
}
//    });
//});

function validateForm(quote_id) {
    var message = '';
    
    var radios = jQuery(".taf-form" + quote_id + " [name!=''][type=radio][validationtype='required'],.taf-form" + quote_id + " [name!=''][type=checkbox][validationtype='required']");
    var radioNames = new Array();
    var radioRval = new Array();
    jQuery(radios).each(function() {
        var nameAlreadyExists = false;
        var cur = jQuery(this).attr("name");
        jQuery(radioNames).filter("[name=" + cur + "]").each(function() {
            nameAlreadyExists = true;
        });
        if (nameAlreadyExists == false) {
            radioNames.push(this);
        }
    });

    jQuery(radioNames).each(function() {
        var existChecked = false;
        var reqVal = new Array();
        jQuery(radios).filter("[name=" + jQuery(this).attr("name") + "]:checked")
                    .each(function() {
            reqVal.push(jQuery(this).val());
            existChecked = true;
        });

        if (!existChecked) {
            message += jQuery(this).attr("relname") + ' is required. <br />';
        }
    });

    var contactInputs = jQuery(".taf-form" + quote_id + " [name!='']");
    for (var i = 0; i < contactInputs.length; i++) {
        var contactInput = contactInputs[i];
        var validetionType = contactInput.getAttribute("validationtype");
        var relName = contactInput.getAttribute("relname") == null ? contactInput.name : contactInput.getAttribute("relname");
        if (validetionType != null) {
            var req = /required/;
            if (req.test(validetionType)) {
                if (!contactInput.value) {
                    message += relName + ' is required. <br />';
                }
                else {
                    var emailVaild = /email/;
                    if (emailVaild.test(validetionType)) {
                        var email = contactInput.value;
                        if (!validateEmail(email)) {
                            message += relName + ' is invalid email. <br />';
                        }
                    }
                }
            }
            else {
                var emailVaild = /email/;
                if (emailVaild.test(validetionType)) {
                    var email = contactInput.value;
                    if (email && validateEmail(email)) {
                        message += relName + ' is invalid email. <br />';
                    }
                }
            }

        }
    }
    
    if (message.length > 0) {
        return message;
    }
    else {
        return "";
    }
}

function validateEmail(email) {
    var at = email.lastIndexOf("@");

    // Make sure the at (@) sybmol exists and  
    // it is not the first or last character
    if (at < 1 || (at + 1) === email.length)
        return false;

    // Make sure there aren't multiple periods together
    if (/(\.{2,})/.test(email))
        return false;

    // Break up the local and domain portions
    var local = email.substring(0, at);
    var domain = email.substring(at + 1);

    // Check lengths
    if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
        return false;

    // Make sure local and domain don't start with or end with a period
    if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
        return false;

    // Check for quoted-string addresses
    // Since almost anything is allowed in a quoted-string address,
    // we're just going to let them go through
    if (!/^"(.+)"$/.test(local)) {
        // It's a dot-string address...check for valid characters
        if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
            return false;
    }

    // Make sure domain contains only valid characters and at least one period
    if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
        return false;

    return true;
}