/*global window, theform, submitBtnID, alert, document, iframesrc, menu_id, editorIframe, FullJDialogWidth */
function errorItem(elemID) {
    var parType;
    parType = $(elemID).parent().parent();
    if (parType.get(0).tagName === "TD") {
        parType = $(elemID).parent().parent().parent();
    }
    //alert (parType.get(0).tagName);
    parType.addClass("error");
    $(elemID).focus(function () {
        $(this).parent().parent().removeClass("error");
        $("#submitErrors").remove();
    });
}
(function ($) {
    $.fn.lsvalidate = function (options) {
        //append error style to head
        var lsvalStyles, image1, emailReg, dateReg, usPhoneReg, isNumericReg, usZipReg, isDateReg, theFormID, newAlert;
        image1 = $('<img />').attr('src', '/assets/images/busy.gif');
        lsvalStyles = '<style type="text/css">';
        lsvalStyles += 'tr.error td { border-style: solid none solid none; border-width: 1px; border-color: #6E1422!important; background-color: #FEC7AF!important; border-collapse: separate!important; }';
        lsvalStyles += '';
        lsvalStyles += '</style>';
        $('head').append(lsvalStyles);
        //Define regular expressions for various input types
        emailReg = /^([a-zA-Z0-9_.\-.'.+])+@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        dateReg = /^\d{2}(\/)\d{2}\1\d{4}$/;
        //usPhoneReg = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
		usPhoneReg = /^(?:\([2-9]\d{2}\)\ ?|(?:[2-9]\d{2}\-))[2-9]\d{2}\-\d{4}$/;
        isNumericReg = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
        usZipReg = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
        isDateReg = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
        //Get the form ID
        theFormID = "#" + this.get()[0].id;
        //Start the Check on submition
        $(theFormID).submit(function (event) {
            var checkboxError, formIDInputs, firstAlert, finalAlert, elemTitle, elemID, elemVal, multiEmailAlert, ne, somethingchecked, divOffset, processingDialog;
            $("#submitErrors").remove();
            $("#processingDialog").remove();
            checkboxError = "";
            $("#submitErrors").remove();
            formIDInputs = $(theFormID + " :input");
            firstAlert = "";
            finalAlert = "";
            $.each(formIDInputs, function (i, n) {
                elemTitle = this.title;
                elemID = '#' + this.id;
                elemVal = $(elemID).val();
                //Validate that it has a value (required if title is present)
                if (elemTitle !== '') {
                    if (!elemVal) {
                        if (!firstAlert) {
                            firstAlert = elemID;
                        }
                        finalAlert = finalAlert + "<li>" + elemTitle + "</li>";
                        errorItem(elemID);
                    }
                }
                //Validate Email format
                if (($(this).hasClass("validemail") || $(this).hasClass("valid_email")) && !emailReg.test(elemVal) && elemVal) {
                    if (!firstAlert) {
                        firstAlert = elemID;
                    }
                    finalAlert = finalAlert + "<li>Valid Email (example joe@site.com)</li>";
                    errorItem(elemID);
                }
                //Validate Multiple Emails
                if (($(this).hasClass("validmultipleemail") || $(this).hasClass("valid_multiple_email")) && elemVal) {
                    var subemails = elemVal.split(",");
                    multiEmailAlert = "";
                    $.each(subemails, function (ii, ee) {
                        ne = $.trim(ee);
                        if (!emailReg.test(ne)) {
                            if (!firstAlert) {
                                firstAlert = elemID;
                            }
                            multiEmailAlert += " " + ne + ",";
                        }
                    });
                    if (multiEmailAlert !== "") {
                        finalAlert = finalAlert + "<li>Invalid Email in a comma seperated email list (" + multiEmailAlert + ")</li>";
                        errorItem(elemID);
                    }
                }
                //Validate Date format
                if (($(this).hasClass("validdate") || $(this).hasClass("valid_date")) && !isDateReg.test(elemVal) && elemVal) {
                    if (!firstAlert) {
                        firstAlert = elemID;
                    }
                    finalAlert = finalAlert + "<li>Valid Date (example: 07/01/2009)</li>";
                    errorItem(elemID);
                }
                //Validate Zip Code
                if (($(this).hasClass("validezip") || $(this).hasClass("valid_zip")) && !usZipReg.test(elemVal) && elemVal) {
                    if (!firstAlert) {
                        firstAlert = elemID;
                    }
                    finalAlert = finalAlert + "<li>Valid Zip Code Format</li>";
                    errorItem(elemID);
                }
                //Validate US Phone format
                if (($(this).hasClass("validphone") || $(this).hasClass("valid_phone")) && !usPhoneReg.test(elemVal) && elemVal) {
                    if (!firstAlert) {
                        firstAlert = elemID;
                    }
                    finalAlert = finalAlert + "<li>Valid Phone (example 800-555-5555)</li>";
                    errorItem(elemID);
                }
                //Validate Is Number
                if ($(this).hasClass("validenum") || $(this).hasClass("valid_num")) {
                    $(elemID).val(elemVal.replace(/,/g, "").replace(/\$/g, ""));
                    elemVal = $(elemID).val();
                }
                if (($(this).hasClass("validenum") || $(this).hasClass("valid_num")) && !isNumericReg.test(elemVal) && elemVal) {
                    if (!firstAlert) {
                        firstAlert = elemID;
                    }
                    finalAlert = finalAlert + "<li>Must be a number</li>";
                    errorItem(elemID);
                }
                //Validate group of checkbox
                if ($(this).parent().hasClass("checkone") || $(this).parent().parent().hasClass("checkone")) {
                    somethingchecked = 0;
                    $(this).parent().children().each(function () {
                        if ($(this).attr('checked')) {
                            somethingchecked = 1;
                        }
                    });
                    if (somethingchecked === 0) {
                        if (!firstAlert) {
                            firstAlert = elemID;
                        }
                        if (!checkboxError) {
                            checkboxError = "<li>Missing Required Check Boxes<br/>(Check at least one per area)</li>";
                            finalAlert = finalAlert + checkboxError;
                        }
                        errorItem(elemID);
                    }
                }
            });
            if (finalAlert) {
                //stop the Submit
                $("#submitErrors").remove();
                newAlert = "";
                event.preventDefault();
                divOffset = $(firstAlert).offset().top - 20;
                newAlert = '<div id="submitErrors" style="dispaly:none;text-align:left;" title="Submission Errors" >';
                newAlert += "The following highlighed areas require at least one selection or valid value:<ul style='margin-left:30px;'>" + finalAlert + "</ul>";
                newAlert += "<p style='color:red;'>Remember to <strong>RE-SUBMIT</strong> your form after you have made the highlighted corrections.</p>";
                newAlert += '</div>' + "\n";
                $("body").prepend(newAlert);
                $('html,body').animate({
                    scrollTop: divOffset
                }, 700, function () {
                    $("#submitErrors").dialog({
                        resizable: false
                    });
                });
                checkboxError = "";
            } else {
                processingDialog = "<div id='processingDialog' title='Processing your form...'><p style='text-align:left;font-size:14px;font-height:1.1em;'><img src='/include/jquery/images/busy.gif' style='margin-bottom:30px;margin-right:10px;' align='left' /> Please do not click the back button or reload this page...</p></div>";
                $("body").append(processingDialog);
                $("#processingDialog").dialog({
                    resizable: false,
                    modal: true,
                    closeOnEscape: false,
                    draggable: false,
                    height: 120
                });
                $('.ui-dialog-titlebar-close').css({
                    'visibility': 'hidden'
                });
            }
            return true;
        });

    };
})(jQuery);

var keyup_count = 0;

function begin_auto_complete(the_data, parent_id) {
    $(parent_id + " .qas_address").autocomplete({
        source: the_data,
        select: function () { /* alert($(this).val()); */ }
    });
}

function start_atuo_complete(nozip, noautocomplete, parent_id) {
    var the_data = [];
    var the_zip = encodeURI($(parent_id + " .qas_zip").val());
    if (!isNaN(the_zip.replace("-",""))) {
        var the_city = encodeURI($(parent_id + " .qas_city").val());
        var the_state = encodeURI($(parent_id + " .qas_state").val());
        var the_address = encodeURI($(parent_id + " .qas_address").val());
        var the_address2 = encodeURI($(parent_id + " .qas_address2").val());
        var request_url = "/Controls/qas_proxy.aspx?action=search&country=USA&searchstring=" + the_address + "|" + the_address2 + "|" + the_city + "|" + the_state + "|";
        if (!nozip) { request_url += the_zip; }
        request_url = request_url.replace("undefined", "");
        $.ajax({
            url: request_url,
            dataType: "xml",
            success: function (xmlResponse) {
                var verifylevel = $(xmlResponse).find("verifylevel").text().toLowerCase();
                var the_zip_found, the_city_found, the_state_found, the_address_found, format_address, last_city_state, cs_constant = 1;
                if (verifylevel != "none" && verifylevel != "streetpartial") {
                    $(parent_id + " .num_missing").remove();
                    $(xmlResponse).find("picklistitem").each(function () {
                        the_zip_found = $(this).find("zip").text();
                        the_city_found = $(this).find("city").text();
                        the_state_found = $(this).find("state").text();
                        the_address_found = $(this).find("addresstext").text();
                        if (last_city_state != the_city_found + the_state_found && last_city_state) {
                            cs_constant = 0;
                        }
                        last_city_state = the_city_found + the_state_found;
                        the_data.push(the_address_found);
                    });
                    if (!noautocomplete) { begin_auto_complete(the_data, parent_id); }
                    if (verifylevel != "streetpartial") {
                        if (cs_constant) {
                            $(parent_id + " .qas_city").val(the_city_found);
                            $(parent_id + " .qas_state").val(the_state_found);
                        } else {
                            $(parent_id + " .qas_city").val("");
                            $(parent_id + " .qas_state").val("");
                        }
                        if (verifylevel = "verified") {
                            $(parent_id + " .qas_zip").val(the_zip_found);
                        } else {
                            $(".qas_zip").val("");
                        }
                    }
                } else if (!nozip && the_city_found && the_state_found && !noautocomplete) {
                    start_atuo_complete(1)
                }

                if (verifylevel === "streetpartial") {
                    $(parent_id + " .num_missing").remove();
                    $(parent_id + " .qas_address").after("<div class='num_missing' style='color:red;font-size:.8em;clear:both;'>You are missing a address number.</div>");
                } else {
                    $(parent_id + " .num_missing").remove();
                }

            }

        });
    }
}

$(document).ready(function () {
    $(".qas_zip, .qas_ciy, .qas_state").bind("change focusout", function (e) {
        var parent_id = "#" + $(".qas_zip, .qas_ciy, .qas_state").parent().closest('[id]').attr("id");
        start_atuo_complete(0, 0, parent_id);
    });
    $(".qas_address").bind('change keyup focusout', function (e) {
        var parent_id = "#" + $(".qas_address").parent().closest('[id]').attr("id");
        keyup_count++;
        if (keyup_count >= 5 && e.keyCode != 32 || e.type == "focusout") {
            start_atuo_complete(0, 0, parent_id);
            keyup_count = 0
        }
        if (e.keyCode == 46 || e.keyCode == 8) {
            var cZip = $(".qas_zip").val().split("-");
            $(".qas_zip").val(cZip[0]);
        }
    });
});

