﻿/*           Form Validator - Missing information Div with fillable form for .net mvc 3.0           */
/*                                      Author: Clay Crosland                                       */
/*                                      Created: 6/1/2011                                           */
/*                                  Dependencies:   jquery 1.4.4                                    */
/*                                                  jquery-ui (for date fields)                     */
/*                                                  jq UI css (for date fields)                     */

$(document).ready(function () {

    // preload the close over image...cwc
    imOb = new Array();
    strImages = "/images/close-over.jpg";
    imageArr = strImages.split(",");
    for (i = 0; i < imageArr.length; i++) {
        imOb[i] = new Image;
        imOb[i].src = imageArr[i];
    }
});

var reqInputArr = new Array();
rName = [];
function initializeInputs() {
    reqInputArr = new Array();
    // create elements in an array...cwc
    var allInputs = $('input[data-var]').add('select[data-var]').add('textarea[data-var]');
    // loop over my array..cwc
    // set rName array for radio button lists

    allInputs.each(function () {
        // determine if it's a radio button list and if so continue past the first one...cwc
        if (this.type == "radio") {
            if ($.inArray(this.name, rName) >= 0) {
                return true;
            }
            else {
                rName.push(this.name);
            }
        }
        // find out if they're text fields to validate type...cwc
        if ($(this).is('[data-type]')) {
            // add blur event handlers for type...cwc
            $(this).blur(function () {
                checkValidField(this, $(this).data('type'));
            });
        }
        // now add all elements to the array for checking if they're there...cwc
        reqInputArr.push($(this).data('fieldtype') + "||" + this.name + "||" + $(this).data('var') + ($(this).is('[data-type]') ? "||" + $(this).data('type') : ""));
    });
}

function checkValidField(obj, type) {

    if (type == "n" || obj.value == "")
        return true;
    //alert(type);
    fromPop = false;
    if (obj.id.indexOf("new") > -1) {
        var parentErr = obj.id.replace("_new", "");
        $("#" + parentErr + "_newErr").remove();
        fromPop = true;
    }
    $("#" + obj.id + "_newErr").remove();
    //var pattern;
    var errorText = "";
    switch (type) {
        case "e":
            pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            errorText = "Invalid Email Address.";
            break;
        case "p":
            pattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
            errorText = "Invalid Phone Number. <br />Use: (888) 888-8888 format";
            break;
        case "u":
            pattern = /^(\d)+$/;
            errorText = "You May Only Enter Numbers";
            break;
        case "d":
            pattern = /^(\d){1,2}\/(\d){1,2}\/(\d){4}$/;
            errorText = "Invalid Date. <br /> Use: mm/dd/yyyy";
            break;
    }

    if (!pattern.test(obj.value)) {
        // check to see if this is checkkng parent from missing info div, if so just return false if pattern fails
        if (arguments[2]) {
            return false;
        }
        _errMsgElement = document.createElement("span");
        _errMsgElement.id = obj.id + "_newErr";
        _errMsgElement.innerHTML = "<br />" + errorText;
        $(_errMsgElement).attr("style", "color:red");
        $(obj).after(_errMsgElement);
    }
    return true;
}

function checkFile(obj, where) {
    //alert(obj.id);
    if (obj.value != '') {
        var errMsg = "";
        var valArr = obj.value.split('.');
        var fileExt = valArr.pop();
        var fileext = fileExt.toLowerCase();
        if (fileext != "doc" && fileext != "docx" && fileext != "txt" && fileext != "xls" && fileext != "xlsx" && fileext != "pdf" && fileext != "zip" && fileext != "jpg" && fileext != "jpeg" && fileext != "gif" && fileext != "png")
            errMsg = "Invalid File Type, Only Document Types Allowed";
        try {
            var oas = new ActiveXObject("Scripting.FileSystemObject");
            var d = obj.value;
            var e = oas.getFile(d);
            var f = e.size;
            if (f > 4194304) {
                if (errMsg.length > 0)
                    errMsg += " And ";
                errMsg += "File Size Too Big, Limit 4MB Per File";
            }
        }
        catch (e) {
        }
        //check if this is on missing info div...cwc
        if (where == "div") {
            if (errMsg.length > 0)
                return errMsg;
            else
                return "ok";
        }
        else {
            if (errMsg.length > 0) {
                if ($.browser.msie && $.browser.version > 8)
                    alert(errMsg);
                var _errMsgElement = document.createElement("span");
                _errMsgElement.id = obj.id + "_newErr";
                _errMsgElement.innerHTML = errMsg;
                $(_errMsgElement).attr("style", "color:red");
                $(obj).after(_errMsgElement);
            }
        }
    }
    return true;
}


FileInputs = new Array();
var dateField = null;
function __doSubmit() {
    // grab all of the form fields on the page..cwc
    initializeInputs();
    // hide the veil...cwc
    $("#__veil").hide();
    try {
        count = 0;
        //check if the array is populated, if so loop over it and check field values...cwc
        if (reqInputArr.length > 0) {
            for (i = 0; i < reqInputArr.length; i++) {
                __inputType = reqInputArr[i].split("||")[0];
                switch (__inputType) {
                    case "A":
                        __fieldName = reqInputArr[i].split("||")[1];
                        __promptText = reqInputArr[i].split("||")[2];
                        __field = document.getElementById(__fieldName);
                        if (!__field)
                            continue;

                        if (__field.value == "") {
                            count++;
                            _mrow = document.getElementById("_tblmissinginfo").insertRow(document.getElementById("_tblmissinginfo").rows.length);
                            _mcell0 = _mrow.insertCell(0);
                            _mcell0.style.width = "50%";
                            _mcell0.style.verticalAlign = "top";
                            _mcell0.innerHTML = __promptText;
                            _mcell0.style.textAlign = "left";

                            _minput = document.createElement("textarea");
                            _minput.style.width = __field.style.width;
                            _minput.style.height = __field.style.height;
                            _minput.name = __fieldName + "_new";

                            $(_minput).data('parent', $(__field).attr("id"));
                            $(_minput).keyup(function () {
                                __updateParent($(this).val(), $(this).data('parent'));
                            });
                            _mcell1 = _mrow.insertCell(1);
                            _mcell1.style.width = "50%";
                            _mcell1.style.verticalAlign = "top";
                            _mcell1.appendChild(_minput);
                            _mcell1.style.textAlign = "right";
                        }
                        break;
                    case "T":
                        dateField = null;
                        __fieldName = reqInputArr[i].split("||")[1];
                        __promptText = reqInputArr[i].split("||")[2];
                        __validType = reqInputArr[i].split("||")[3];
                        __field = document.getElementById(__fieldName);
                        if (!__field)
                            continue;

                        // set boolean value for checking field type
                        var isValidType = checkValidField(__field, __validType, 'p');

                        if ((__field.value == "" && (__field.offsetWidth > 0 || __field.offsetHeight > 0)) || !isValidType) {
                            count++;
                            _mrow = document.getElementById("_tblmissinginfo").insertRow(document.getElementById("_tblmissinginfo").rows.length);
                            _mcell0 = _mrow.insertCell(0);
                            _mcell0.style.width = "50%";
                            _mcell0.style.verticalAlign = "top";
                            _mcell0.innerHTML = __promptText;
                            _mcell0.style.textAlign = "left";

                            _minput = document.createElement("input");
                            _minput.name = __fieldName + "_new";
                            _minput.id = __fieldName + "_new";
                            _minput.type = "text";
                            _minput.style.width = __field.offsetWidth + "px";
                            if (!isValidType) {
                                _minput.value = __field.value;
                            }

                            //get parent object before the date check since the update type will (change vs keyup) will differ 
                            $(_minput).data('parent', $(__field).attr("id"));
                            if (__validType != "n") {
                                $(_minput).data("vtype", __validType);
                                $(_minput).blur(function () {
                                    checkValidField($(this).get(0), $(this).data('vtype'));
                                });
                                if (__validType == "d") {
                                    $(_minput).datepicker();
                                    dateField = _minput;
                                    $(_minput).change(function () {
                                        __updateParent($(this).val(), $(this).data('parent'));
                                    });
                                }
                            }

                            $(_minput).keyup(function () {
                                __updateParent($(this).val(), $(this).data('parent'));
                            });

                            _mcell1 = _mrow.insertCell(1);
                            _mcell1.style.width = "50%";
                            _mcell1.style.verticalAlign = "top";
                            _mcell1.appendChild(_minput);
                            _mcell1.style.textAlign = "right";
                            if (!isValidType)
                                checkValidField(_minput, __validType);
                        }
                        break;
                    case "D":
                        __fieldName = reqInputArr[i].split("||")[1];
                        __promptText = reqInputArr[i].split("||")[2];
                        __field = document.getElementById(__fieldName);
                        if (!__field)
                            continue;
                        if (__field.value == "") {
                            count++;
                            _mrow = document.getElementById("_tblmissinginfo").insertRow(document.getElementById("_tblmissinginfo").rows.length);
                            _mcell0 = _mrow.insertCell(0);
                            _mcell0.style.width = "50%";
                            _mcell0.style.verticalAlign = "top";
                            _mcell0.innerHTML = __promptText;
                            _mcell0.style.textAlign = "left";

                            _mselect = document.createElement("select");
                            _mselect.name = __fieldName + "_new";

                            $(_mselect).data('parent', $(__field).attr("id"));
                            $(_mselect).change(function () {
                                __updateParent($(this).val(), $(this).data('parent'));
                            });

                            for (k = 0; k < __field.options.length; k++) {
                                var __optn = document.createElement("option");
                                __optn.text = __field.options[k].text;
                                __optn.value = __field.options[k].value;
                                _mselect.options.add(__optn);
                            }
                            _mcell1 = _mrow.insertCell(1);
                            _mcell1.style.width = "50%";
                            _mcell1.style.verticalAlign = "top";
                            _mcell1.appendChild(_mselect);
                            _mcell1.style.textAlign = "right";
                        }
                        break;
                    }
                
            }
        }
        if (count > 0) {
            _mrow = document.getElementById("_tblmissinginfo").insertRow(document.getElementById("_tblmissinginfo").rows.length);
            _mcell0 = _mrow.insertCell(0);
            _mcell0.colSpan = "2";
            _mcell0.style.verticalAlign = "top";
            _mcell0.style.textAlign = "left";

            _submitButton = document.createElement("input");
            _submitButton.type = "button";
            _submitButton.value = "Try Submitting Your Information Again";

            $(_submitButton).click(function () {
                __closeMissing();
                __doSubmit();
            });

            _mcell0.appendChild(_submitButton);

            $("#__veil").css({ opacity: 0.7 });
            $("#__veil").css({ bottom: "0px" });
            $("#__veil").show();
            $("#_missinginfodiv").css({ top: "20px" }); 
            $("#_missinginfodiv").show('fast');
                     
            
            

            if (dateField != null) {
                dateField.focus();
                dateField.blur();
            }
            return;
        }
        submitAllInfo();
    }
    catch (e) {
        submitAllInfo();
    }
}

function __updateFile(obj, parent) {
    parent.append(obj);
}

function __updateParent(val, where) {
    //alert("value: " + val + " fieldname: " + where);
    if (arguments[2]) {
        if (arguments[2] == "r") {
            _rbl = document.getElementsByName(where);
            for (i = 0; i < _rbl.length; i++) {
                if (_rbl[i].value == val) {
                    _rbl[i].checked = true;
                    return;
                }
            }
        }
        else {
            if (val.checked)
                document.getElementById(where).checked = true;
            else
                document.getElementById(where).checked = false;
        }
    }
    else {
        try {
            //$(where).val(val);
            document.getElementById(where).value = val;
        }
        catch (e) {
            alert("Your Browser Does Not Support This Feature.  You Must Complete The Form On The Main Form");
            __closeMissing();
        }
    }
}

function __closeMissing() {
    $("#__veil").hide();
    $("#_missinginfodiv").hide('fast');


    mt = document.getElementById("_tblmissinginfo");
    for (j = 0; j < FileInputs.length; j++) {
        $(FileInputs[j]).data('parent').append($(FileInputs[j]));
        //reset change event hander....cwc
        $(FileInputs[j]).unbind('change');
        $(FileInputs[j]).bind('change', function () {
            checkFile(this, 'parent');
        });

    }
    FileInputs = new Array()
    for (i = mt.rows.length - 1; i > -1; i--) {
        mt.deleteRow(i);
    }
}
