﻿var sessionKey = "";
var sessionUser = "";
var sessionAgency = "";
var allowsOverride = "";
var superUser = "";
var ONEDAY = (1000 * 60 * 60 * 24);
var currentErrors = new Array;
var currentMainForm = "";
var currentWorkID = "";
var currentModalForm = "";
var modalErrors = new Array;
var inTheShow = false;
var formatNumb = new NumberFormat(0);
var inRequote = false;
var inFormInit = false;
var validZips = new Array;
var cookieOptions = { expiresAt: new Date(2015, 1, 1), secure: false };
formatNumb.setCommas(true);
formatNumb.setCurrency(false);
formatNumb.setPlaces(0);

$(document).ready(function() {

    $(window).resize(function() {
        sizeAll();
    });

    $(window).trigger("resize");

    $("#login-button").click(function() {
        formLogin();
    });
    $("#register-button").click(function() {
        var aWin = window.open('');
        aWin.document.location = 'RoundhillExpress Sign Up Sheet.pdf';
    });
    $("#claim-button").click(function() {
        var aWin = window.open('');
        aWin.document.location = 'RoundhillExpress Claim Form.pdf';
    });
    $("#test-login").click(function() {
        $("#user-login").val("test@roundhillexpress.com");
        $("#pwd-login").val("password");
        formLogin();
    });
    $("#login-form :input").keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            formLogin();
            return false;
        }
        else {
            return true;
        }
    });
    $('input#pwd-login').bind('cut copy paste', function(e) {
        e.preventDefault();
    });

    $("#logout-button").click(function() {
        logout();
        location = "index.html";
    });
    $(window).unload(function() {
        if (sessionKey != '') {
            logout();
        }
    });

    sessionUser = $.cookies.get('lastUser') ? $.cookies.get('lastUser') : '';
    $("#save-user-pwd")[0].checked = $.cookies.get('lpflag') ? $.cookies.get('lpflag') : true;

    $("#user-login").val(sessionUser);
    if (sessionUser == '') {
        $("#pwd-login").val('');
    } else {
        $("#pwd-login").val(($.cookies.get('lpowd') ? $.cookies.get('lpowd') : ''));
    }

    if ($("#user-login").val() == '') {
        $("#user-login").focus();
    } else {
        $("#pwd-login").focus();
    }

    $("#send-user-pwd").click(function() { pwdRequested(); });

    if ($.browser) {
        if ($.browser.msie) {
            if ($.browser.version < "7.0") {
                //showNotificationWindow("<h2 class='msg-indent'>Time To Upgrade</h2>", "<p class='msg-indent'>You are using an unsupported browser.</p><p class='msg-indent'>For best performance, please upgrade your browser or switch to Google Chrome.</p>");
            }
        }
    }
});
function logout() {
    if (sessionKey != '') {
        if (sessionUser != 'test@roundhillexpress.com') {
            $.cookies.set('lastUser', sessionUser, cookieOptions);
        }
        var sData = '{"key":"' + sessionKey + '"}'
        accessService("CloseSession", sData,
                    function(data) {
                        var ret = new String(data.d);
                        if (ret.indexOf('Error -') == 0) {
                            showNotificationWindow("<h2 class='msg-indent'>Problem Closing Session</h2>", data.d);
                        }
                    }
                );
    }
    sessionKey = "";
    sessionUser = "";
}
function sizeAll() {
    var contentArea = $(window).height() - 98;
    var contentWidth = $(window).width();

    $("#body-wrapper").css("height", contentArea);
    $("#body-wrapper .form-wrapper").css("height", contentArea - 20);

    var frms = $("#body-wrapper .form-wrapper");
    for (i = 0; i < frms.length; i++) {
        var bpnl = $("#" + frms[i].id + " .wizard-buttons-panel");
        if (bpnl.length > 0) {
            $("#" + frms[i].id + " .content-wrapper").css("height", contentArea - 12 - bpnl[0].clientHeight);
        }
        else {
            $("#" + frms[i].id + " .content-wrapper").css("height", contentArea - 12);
        }
    }

    $("#logout-box").css("left", contentWidth - 435);
    $("#body-errors").css("left", (contentWidth / 2));

}
function accessService(funcToCall, dataToPass, successFunc) {
    $.ajax({
        type: "POST",
        url: "services/AccessService.svc/" + funcToCall,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: dataToPass,
        async: false,
        success: successFunc,
        error: errorHandler
    });
}
function accessServiceBackground(funcToCall, dataToPass, successFunc) {
    $.ajax({
        type: "POST",
        url: "services/AccessService.svc/" + funcToCall,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: dataToPass,
        async: true,
        success: successFunc,
        error: errorHandler
    });
}
function errorHandler(xhr, errorMsg, thrown) {
    showNotificationWindow("<h2 class='msg-indent'>Network Error</h2>", "<p class='msg-indent'>There was an error during the call to the network.  Error text: " + xhr.responseText + "</p>");
}
function pwdRequested() {
    var tUser = $("#user-login").val();
    if (tUser == '') {
        showNotificationWindow("<h2 class='msg-indent'>Password Request</h2>", "<p class='msg-indent'>User name (your email) needed to send password.</p>");
    } else {
        accessService("SendMePassword", '{"name":"' + tUser + '"}', function(data) {
            var msg = '';
            var ret = new String(data.d);
            if (ret.indexOf("Error -") == 0) {
                msg = "<p class='msg-indent'>Email was NOT sent.  The server responded with this message:</p><p></p><p class='msg-indent'>" + data.d + "</p>";
            } else {
                msg = "<p class='msg-indent'>Email sent to " + tUser + ".</p>";
            }
            showNotificationWindow("<h2 class='msg-indent'>Password Request</h2>", msg);
        });
    }
}

function formLogin() {

    var aPwd = '';
    sessionUser = $("#user-login").val();
    aPwd = $("#pwd-login").val();
    var sData = '{"name":"' + sessionUser + '", "password":"' + aPwd + '", "cHeight":"' + document.body.clientHeight + '", "cWidth":"' + document.body.clientWidth + '"}';
    var stTime = new Date;
    accessService("GetSessionKey", sData,
                function(data) {
                    var ret = new String(data.d);
                    if (ret.indexOf("Error -") == 0) {
                        showNotificationWindow("<h2 class='msg-indent'>Login Error</h2>", "<p class='msg-indent'>The user name and password could not be authenticated.</p><p class='msg-indent'>Please confirm user name and password are correct and try again.</p>");
                    }
                    else {
                        var enTime = new Date;
                        if (sessionUser != 'test@roundhillexpress.com') {
                            $.cookies.set('lastUser', sessionUser, cookieOptions);
                            if ($("#save-user-pwd")[0].checked) {
                                $.cookies.set('lpowd', aPwd, cookieOptions);
                                $.cookies.set('lpflag', true, cookieOptions);
                            } else {
                                $.cookies.del('lpowd');
                                $.cookies.set('lpflag', false, cookieOptions);
                            }
                        }

                        var thisSession = eval('(' + data.d + ')');
                        sessionKey = thisSession.key;
                        allowsOverride = thisSession.allowOverride;
                        sessionAgency = thisSession.agency;
                        superUser = thisSession.superUser;

                        var ds = $.base64.decode(thisSession.deskTop);
                        var dat = $.base64.decode(thisSession.currentWork);

                        var stDesk = new Date;
                        setupDesktop(ds, dat);
                        var enDesk = new Date;

                        finishWizardSetup(dat); // launch background loads for the rest of the wizard forms

                    }
                }
            );
}
function refreshWizard() {
    accessService("GetCurrentWork", '{"sessionKey":"' + sessionKey + '"}',
                function(data) {
                    var ret = new String(data.d);
                    if (ret.indexOf('Error -') == 0) {
                        showNotificationWindow("<h2 class='msg-indent'>Data Retrieval Error</h2>", "<p class='msg-indent'>There was a problem retrieving the data.  Contact support.</p>");
                    }
                    else {
                        setFormData(data.d);
                    }
                }
            );
}
function finishWizardSetup(wizdata) {
    accessServiceBackground("GetWizardItem", '{"sessionKey":"' + sessionKey + '", "aClass":"Business.Contract", "anItem":"2"}',
        function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-index'>Error</h2>", "<p>Server Reported:</p><p>" + data.d + "</p>");
            } else {
                $("#Business-Contract-Wizard .content-wrapper").append(data.d);
                initControls("#BoundQuote-form");
                setFormData(wizdata);

            }
        });
        accessServiceBackground("GetWizardItem", '{"sessionKey":"' + sessionKey + '", "aClass":"Business.Contract", "anItem":"3"}',
        function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-index'>Error</h2>", "<p>Server Reported:</p><p>" + data.d + "</p>");
            } else {
                $("#Business-Contract-Wizard .content-wrapper").append(data.d);
                initControls("#BoundQuote-PremiumValues-form");
                setFormData(wizdata);
                if (allowsOverride == 'no') {
                    $('#BoundQuote-PremiumValues-AgencyFee').attr('disabled', 'disabled');
                }
            }
        });
        accessServiceBackground("GetWizardItem", '{"sessionKey":"' + sessionKey + '", "aClass":"Business.Contract", "anItem":"4"}',
        function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-index'>Error</h2>", "<p>Server Reported:</p><p>" + data.d + "</p>");
            } else {
                $("#Business-Contract-Wizard .content-wrapper").append(data.d);
                initControls("#Payment-form");
                setFormData(wizdata);
            }
        });
        accessServiceBackground("GetWizardItem", '{"sessionKey":"' + sessionKey + '", "aClass":"Business.Contract", "anItem":"5"}',
        function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-index'>Error</h2>", "<p>Server Reported:</p><p>" + data.d + "</p>");
            } else {
                $("#Business-Contract-Wizard .content-wrapper").append(data.d);
                initControls("#Binder-form");
                setFormData(wizdata);
            }
        });
        accessServiceBackground("GetWizardItem", '{"sessionKey":"' + sessionKey + '", "aClass":"Business.Contract", "anItem":"6"}',
        function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-index'>Error</h2>", "<p>Server Reported:</p><p>" + data.d + "</p>");
            } else {
                $("#Business-Contract-Wizard .content-wrapper").append(data.d);
                initControls("#AntiArsonInfo-form");
                setFormData(wizdata);
            }
        });
        accessServiceBackground("GetWizardItem", '{"sessionKey":"' + sessionKey + '", "aClass":"Business.Contract", "anItem":"7"}',
        function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-index'>Error</h2>", "<p>Server Reported:</p><p>" + data.d + "</p>");
            } else {
                $("#Business-Contract-Wizard .content-wrapper").append(data.d);
                initControls("#Signature-form");
                setFormData(wizdata);
            }
        });
}
function setupDesktop(deskData, currentWorkData) {
    $("#main-logo").attr("src", "images/Logo-Background-Small.jpg");
    $("#main-logo").css("height", "50px");
    $("#main-logo").css("top", "3px");
    $("#main-logo").css("left", "3px");
    $("#logout-box").css("visibility", "visible");
    $("#login-text").html("Logged in as " + sessionUser + ".");
    $("#company-box").css("display", "none");
    $("#body-wrapper").css("display", "block");
    $("#body-navigator").css("display", "block");

    createAppItems(deskData, currentWorkData);
    initControls("#PreviewQuestions-form");
    resetWizardButtons();

    $("#body-errors").css("top", 140);
    $("#body-errors").css("left", $("#body-wrapper .form-wrapper")[0].offsetLeft + 600);

    if (sessionAgency.toLowerCase() == 'roundhill') {
        $("#Business-Agency-AddButton").show();
        $("#navButt1").hide();
        $("#navButt2").hide();
    } else {
        $("#Business-Agency-AddButton").hide();
        $(".secure-remove").hide();
        $("#navButt4").hide();
        $("#navButt6").hide();
        $("#navButt7").hide();

    }

    focusForm($("#" + $("#Business-Contract-Wizard .wizard-buttons-panel button")[0].id).attr("rel"));
    $('#' + $('#body-navigator button')[0].id).addClass('nav-selected');
}
function initControls(sel) {
    inFormInit = true;
    $(sel + " .currency-rules").numeric();
    $(sel + " .floating-rules").numeric();
    $(sel + " .integer-rules").numeric();
    $(sel + " .state-pick").alpha({ allcaps: true });

    $(sel + "  select").css("width", "182px");

    $(sel + ' input.currency-rules, ' + sel + ' input.floating-rules, ' + sel + " input.integer-rules").focus(function() {
        var newVal = $('#' + this.id).val();
        newVal = newVal.replace(/,/g, '');
        $('#' + this.id).val(newVal);
        $('#' + this.id).select();
    });
    $(sel + ' input.currency-rules, ' + sel + ' input.floating-rules, ' + sel + " input.integer-rules").blur(function() {
        var newVal = $('#' + this.id).val().replace(/,/g, '');
        var valInt = parseInt(newVal, 10) ? parseInt(newVal, 10) : 0;
        if (valInt == 0) {
            $('#' + this.id).val('');
        } else {
            if ($('#' + this.id).hasClass('floating-rules') || $('#' + this.id).hasClass('currency-rules')) {
                formatNumb.setNumber(valInt);
                $('#' + this.id).val(formatNumb.toFormatted());
            } else {
                $('#' + this.id).val(newVal);
            }
        }
    });
    $(sel + ' input.no-paste').bind('paste', function(e) {
        e.preventDefault();
    });

    inFormInit = false;
}
function resetWizardButtons() {
    var wizButts = $("#Business-Contract-Wizard .wizard-buttons-panel button");
    for (n = 0; n < wizButts.length; n++) {
        $("#" + wizButts[n].id).attr("disabled", "disabled");
    }
    $("#" + wizButts[0].id).removeAttr("disabled");
    $("#" + wizButts[1].id).removeAttr("disabled");
    $("#" + wizButts[wizButts.length - 1].id).removeAttr("disabled");
    $("#" + wizButts[wizButts.length - 2].id).removeAttr("disabled");
}
function buildDeskUI(list) {
    var heads = "";
    var bods = "";
    var openForms = new Array;

    var appItems = eval('(' + list + ')');
    var aLength = appItems.NewAppItems.length;
    if (aLength > 0) {
        for (i = 0; i < aLength; i++) {
            var aBody = '';
            if (appItems.NewAppItems[i].BodyData != '') {
                aBody = $.base64.decode(appItems.NewAppItems[i].BodyData);
            }
            openForms.push(
                {
                    type: 'NEW',
                    label: appItems.NewAppItems[i].Description,
                    className: appItems.NewAppItems[i].TypeName,
                    bodyData: aBody,
                    navIndex: appItems.NewAppItems[i].navIndex,
                    navItemName: appItems.NewAppItems[i].navItemName
                }
            );
        }
    }
    aLength = appItems.BrowserItems.length;
    if (aLength > 0) {
        for (i = 0; i < aLength; i++) {
            var aBody = '';
            if (appItems.BrowserItems[i].BodyData != '') {
                aBody = $.base64.decode(appItems.BrowserItems[i].BodyData);
            }
            openForms.push(
                {
                    type: 'BROWSE',
                    label: appItems.BrowserItems[i].Description,
                    className: appItems.BrowserItems[i].TypeName,
                    bodyData: aBody,
                    navIndex: appItems.BrowserItems[i].navIndex,
                    navItemName: appItems.BrowserItems[i].navItemName
                }
            );
        }
    }

    for (var x = 0; x < openForms.length; x++) {
        if (openForms[x].bodyData != '') {
            heads = heads + "<button type='button' navRef='" + openForms[x].navItemName + "' navType='" + openForms[x].type + "' id='navButt" + openForms[x].navIndex + "' browserRef='" + openForms[x].className + "'>" + openForms[x].label + "</button>";
            bods = bods + openForms[x].bodyData;
        } else {
            heads = heads + "<button type='button' navRef='" + openForms[x].navItemName + "' bodyNotLoaded='bodyNotLoaded' navType='" + openForms[x].type + "' id='navButt" + openForms[x].navIndex + "' browserRef='" + openForms[x].className + "'>" + openForms[x].label + "</button>";
        }
    }
    $("#body-navigator").empty();
    $("#body-navigator").prepend(heads);
    $("#body-wrapper").empty();
    $("#body-wrapper").prepend(bods);
}
function createAppItems(list, curdata) {
    inFormInit = true;

    buildDeskUI(list);

    $("#Business-Contract-Wizard .wizard-buttons-panel button").click(function() {
        var currentWizForm = $("#Business-Contract-Wizard .wizard-buttons-panel button.button-selected").attr('rel');

        if (this.id.indexOf("CancelButton") >= 0) {
            if (currentWizForm != "") {
                clearFormRules(currentWizForm);
                currentWizForm = "";
            }
            accessService("ClearCurrentWork", '{"sessionKey":"' + sessionKey + '"}',
                function(data) {
                    var ret = new String(data.d);
                    if (ret.indexOf('Error -') == 0) {
                        showNotificationWindow("<h2 class='msg-index'>Error</h2>", "<p>Server Reported:</p><p>" + data.d + "</p>");
                    } else {
                        setFormData(data.d);
                    }
                });

            $('#Binder-MortgageeList-GridEdit tbody').empty();
            $('#AntiArsonInfo-Owners-GridEdit tbody').empty();
            resetWizardButtons();
            $("#PreviewQuestions-button").trigger("click");
            return true;
        }
        if (this.id.indexOf("SaveButton") >= 0) {
            reQuote();
            accessService("SaveQuote", '{"sessionKey":"' + sessionKey + '"}',
                function(data) {
                    var ret = new String(data.d);
                    if (ret.indexOf('Error -') == 0) {
                        showNotificationWindow("<h2 class='msg-index'>Error</h2>", "<p>Server Reported:</p><p>" + data.d + "</p>");
                    } else {
                        setFormData(data.d);
                    }
                });

            $('#Binder-MortgageeList-GridEdit tbody').empty();
            $('#AntiArsonInfo-Owners-GridEdit tbody').empty();
            resetWizardButtons();
            //refreshBrowser('Business.SavedQuote');
            $("#PreviewQuestions-button").trigger("click");
            return true;
        }
        if (currentWizForm == "") {
            focusForm($("#" + this.id).attr("rel"));
        } else {
            var currentBNum = getButtonIndex($('#Business-Contract-Wizard .wizard-buttons-panel button'), currentWizForm.replace("-form", "-button"));
            var requestBNum = getButtonIndex($('#Business-Contract-Wizard .wizard-buttons-panel button'), this.id);

            var fValid = $("#" + currentWizForm).validate().form();
            if (fValid) {
                clearFormRules(currentWizForm);
                for (l = (currentBNum + 1); l < requestBNum; l++) {
                    if ((l < ($('#Business-Contract-Wizard .wizard-buttons-panel button').length - 2)) &&
                                (!$("#" + $('#Business-Contract-Wizard .wizard-buttons-panel button')[l].id).hasClass('not-needed'))) {

                        var xb = $('#Business-Contract-Wizard .wizard-buttons-panel button')[l].id.replace('-button', '-form');

                        focusForm(xb);

                        fValid = $("#" + xb).validate().form();
                        if (!fValid) {

                            showCurrentErrors();
                            
                            break;
                        } else {
                            clearFormRules(xb);
                        }
                    }
                }
                if (!fValid) {
                    return false;
                }
            } else {
                if (!(requestBNum < currentBNum)) {
                    showCurrentErrors();
                    return false;
                }
            }
            focusForm($("#" + this.id).attr("rel"));
        }
    });


    $("#body-navigator button").click(function() {
        $("#body-navigator button").removeClass("nav-selected");
        $("#body-wrapper div.form-wrapper").css("display", "none");

        var thisName = $(this).attr('navRef');

        if ($(this).attr('bodyNotLoaded')) {
            var thisClass = $(this).attr('browserRef');
            var sData = '{"sessionKey":"' + sessionKey + '", "name":"' + thisClass + '"}';
            if ($(this).attr('navType') == 'BROWSE') {
                accessService('GetSetLayout', sData, function(data) {
                    var ret = new String(data.d);
                    if (ret.indexOf('Error -') == 0) {
                        showNotificationWindow("<h2 class='msg-indent'></h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
                    } else {
                        $('#body-wrapper').prepend(data.d);
                    }
                });
                if ($('#' + thisName + ' table')[0].rows.length <= 1) {
                    refreshBrowser($(this).attr('browserRef'));
                }
            } else {
                accessService('GetObjectLayout', sData, function(data) {
                    var ret = new String(data.d);
                    if (ret.indexOf('Error -') == 0) {
                        showNotificationWindow("<h2 class='msg-indent'></h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
                    } else {
                        $('#body-wrapper').prepend(data.d);
                    }
                });
            }
            $(this).removeAttr('bodyNotLoaded');
            if (sessionAgency.toLowerCase() == 'roundhill') {
                $("#Business-Agency-AddButton").show();
                $("#navButt1").hide();
                $("#navButt2").hide();
            } else {
                $("#Business-Agency-AddButton").hide();
                $(".secure-remove").hide();
            }
        } else {
            if ($(this).attr('navType') == 'BROWSE') {
                if ($('#' + thisName + ' table')[0].rows.length <= 1) {
                    refreshBrowser($(this).attr('browserRef'));
                }
            }
        }

        if (thisName.indexOf("Wizard") == -1) {
            $("#body-errors").css("top", -600);
        } else {
            $("#body-errors").css("top", 140);
        }

        $("#" + thisName).css("display", "block");
        $(this).addClass("nav-selected");
        sizeAll();

    });
    inFormInit = false;
}
function focusForm(aFormName) {
    $("#Business-Contract-Wizard.form-wrapper form").addClass("editing-form-hidden");
    if (aFormName != "") {
        activateForm(aFormName);
        nextButtonCheck(aFormName.replace('-form', '-button'));
        $('#' + aFormName.replace('-form', '-button')).addClass("button-selected");
    }
}
function isValidDate(aDate) {
    var isDate = false;
    accessService('ValidateDate', '{"sessionKey":"' + sessionKey + '", "aDate":"' + aDate + '"}', function(data) {
        var ret = new String(data.d);
        if (ret.indexOf('Error -') == 0) {
            showNotificationWindow("<h2 class='msg-index'>Error</h2>", "<p>Server Reported:</p><p>" + data.d + "</p>");
        } else {
            var dataItems = eval('(' + ret + ')')
            isDate = (dataItems.values[0].value == 'true');
        }
    });
    return isDate;
}
function getButtonIndex(anArr, aName) {
    var retVal = -1;
    for (n = 0; n < anArr.length; n++) {
        if (anArr[n].id == aName) {
            retVal = n;
            break;
        }
    }
    return retVal;
}
function nextButtonCheck(buttonName) {
    if ($("#" + buttonName + " + button").hasClass('not-needed')) {
        $("#" + buttonName + " + button").attr('disabled', 'disabled');
        $("#" + $("#" + buttonName + " + button")[0].id + " + button").removeAttr("disabled");
    } else {
        $("#" + buttonName + " + button").removeAttr("disabled");
    }
}
function checkAntiArson(source) {
    if (($('#Binder-InsuredName').val().toLowerCase().indexOf(' llc') >= 0) ||
        ($('#Binder-InsuredName').val().toLowerCase().indexOf(' inc') >= 0) ||
        ($('#Binder-InsuredName').val().toLowerCase().indexOf(' corp') >= 0)) {

        //$('#AntiArsonInfo-button').removeClass('not-needed');
        $('#Binder-ApplicantLegal').val('Other (LLC, Corp)');
    }
    if (($('#Binder-ApplicantLegal').val().indexOf('Individual') >= 0) || ($('#Binder-ApplicantLegal').val().indexOf('Joint') >= 0)) {
        $('.AntiArsonInfo-Owners-Group').hide();
        if ((parseFloat($('#BoundQuote-Units').val()) < 5) && ($('#Binder-ApplicantLegal').val().indexOf('Occupied') >= 0)) {
            $('#AntiArsonInfo-button').addClass('not-needed');
        } else {
            $('#AntiArsonInfo-button').removeClass('not-needed');
        }
    } else {
        $('#AntiArsonInfo-button').removeClass('not-needed');
        $('.AntiArsonInfo-Owners-Group').show();
    }
    if (source == 'Units') {
        var aaDis = $("#AntiArsonInfo-button").attr("disabled");
        var sigDis = $("#Signature-button").attr("disabled");
        if ((!aaDis) || (!sigDis)) {
            if ($("#AntiArsonInfo-button").hasClass('not-needed')) {
                $("#AntiArsonInfo-button").attr("disabled", "disabled");
                $("#Signature-button").removeAttr("disabled");
            } else {
                $("#AntiArsonInfo-button").removeAttr("disabled");
                $("#Signature-button").attr("disabled", "disabled");
                $("#Business-Contract-CompleteButton").attr("disabled", "disabled");
            }
        }
    }
    if (source == 'ApplicantLegal') {
        if ($("#AntiArsonInfo-button").hasClass('not-needed')) {
            $("#AntiArsonInfo-button").attr("disabled", "disabled");
            $("#Signature-button").removeAttr("disabled");
        } else {
            $("#AntiArsonInfo-button").removeAttr("disabled");
            $("#Signature-button").attr("disabled", "disabled");
            $("#Business-Contract-CompleteButton").attr("disabled", "disabled");
        }
    }
}
function isValidCheckNumber() {
    return ($('#Signature-PayChoice').val() == 'Paper Check');
}
function totalInsuredValue() {
    return (totalBuildingValue() + totalContentsValue() + totalPersonalContentsValue() + totalGarageValue() + totalIncomeValue());
}
function totalFullContents() {
    return (totalContentsValue() + totalPersonalContentsValue());
}
function totalBuildingValue() {
    return (parseFloat($('#BoundQuote-BuildingValue').val().replace(/,/g, '')) ? parseFloat($('#BoundQuote-BuildingValue').val().replace(/,/g, '')) : 0);
}
function totalContentsValue() {
    return (parseFloat($('#BoundQuote-Contents').val().replace(/,/g, '')) ? parseFloat($('#BoundQuote-Contents').val().replace(/,/g, '')) : 0);
}
function totalPersonalContentsValue() {
    return (parseFloat($('#BoundQuote-PersonalContent').val().replace(/,/g, '')) ? parseFloat($('#BoundQuote-PersonalContent').val().replace(/,/g, '')) : 0);
}
function totalGarageValue() {
    return (parseFloat($('#BoundQuote-Garage').val().replace(/,/g, '')) ? parseFloat($('#BoundQuote-Garage').val().replace(/,/g, '')) : 0);
}
function totalIncomeValue() {
    return (parseFloat($('#BoundQuote-BusinessIncome').val().replace(/,/g, '')) ? parseFloat($('#BoundQuote-BusinessIncome').val().replace(/,/g, '')) : 0);
}
function totalAgreedSqFt() {
    return (parseFloat($('#BoundQuote-AgreedSqFootage').val().replace(/,/g, '')) ? parseFloat($('#BoundQuote-AgreedSqFootage').val().replace(/,/g, '')) : 0);
}
function totalSqFootage() {
    return (parseFloat($('#Binder-TotalSqFootage').val().replace(/,/g, '')) ? parseFloat($('#Binder-TotalSqFootage').val().replace(/,/g, '')) : 0);
}
function setTotalSqFootage() {
    if (totalSqFootage() == 0) {
        if (totalAgreedSqFt() > 0) {
            $('#Binder-TotalSqFootage').val(totalAgreedSqFt());
        } else {
            if (totalBuildingValue() > 0) {
                $('#Binder-TotalSqFootage').val(totalBuildingValue() / 125);
            }
        }
    }
}
function formatPhone(aValue) {
    var newVal = aValue.replace(/-/g, '').replace('(', '').replace(')', '').replace(/ /g, '');
    if (newVal.length > 0) {
        return '(' + newVal.substr(0, 3) + ') ' + newVal.substr(3, 3) + '-' + newVal.substr(6, 4);
    } else {
        return '';
    }
}
function indexOf(anArray, anItem) {
    var retVal = -1;
    for (n = 0; n < anArray.length; n++) {
        if (anArray[n] == anItem) {
            retVal = n;
            break;
        }
    }
    return retVal;
}
function parsedIndexOf(anArray, anItem) {
    var retVal = -1;
    for (n = 0; n < anArray.length; n++) {
        var ts = anArray[n].split('-');
        if (ts[0] == anItem) {
            retVal = n;
            break;
        }
    }
    return retVal;
}
function validForm(aFormName) {
    $("#" + aFormName).validate({
        submitHandler: function(form) {
        },
        showErrors: function(errorMap, errorList) {
            if (inTheShow) { return true; }
            inTheShow = true;
            if (errorList.length > 0) {
                for (i = 0; i < errorList.length; i++) {
                    var isFound = false;
                    for (e = 0; e < currentErrors.length; e++) {
                        isFound = (currentErrors[e].elid == errorList[i].element.id);
                        if (isFound) {
                            break;
                        }
                    }
                    if (!isFound) {
                        $("#" + errorList[i].element.id).attr("title", errorList[i].message);
                        $("#" + errorList[i].element.id).addClass("invalid-field");
                        currentErrors.push({ elid: errorList[i].element.id, elmsg: errorList[i].message });
                    }
                }
            }
            if (this.successList.length > 0) {
                for (i = 0; i < this.successList.length; i++) {
                    var isFound = -1;
                    for (e = 0; e < currentErrors.length; e++) {
                        if (currentErrors[e].elid == this.successList[i].id) {
                            isFound = e;
                            break;
                        }
                    }
                    if (isFound > -1) {
                        var fName = currentErrors[isFound].elid;
                        $("#" + fName).removeAttr('title');
                        $("#" + fName).removeClass('invalid-field');
                        currentErrors.splice(isFound, 1);

                        if (fName == "BoundQuote-PremiumValues-DontIncludeTria") {
                            $("#BoundQuote-PremiumValues-IncludeTria").removeAttr('title');
                            $("#BoundQuote-PremiumValues-IncludeTria").removeClass('invalid-field');
                            var tFound = -1;
                            for (t = 0; t < currentErrors.length; t++) {
                                if (currentErrors[t].elid == 'BoundQuote-PremiumValues-IncludeTria') {
                                    tFound = t;
                                    break;
                                }
                            }
                            if (tFound > -1) {
                                currentErrors.splice(tFound, 1);
                            }
                        }
                        if (fName == "BoundQuote-PremiumValues-IncludeTria") {
                            $("#BoundQuote-PremiumValues-DontIncludeTria").removeAttr('title');
                            $("#BoundQuote-PremiumValues-DontIncludeTria").removeClass('invalid-field');
                            var tFound = -1;
                            for (t = 0; t < currentErrors.length; t++) {
                                if (currentErrors[t].elid == 'BoundQuote-PremiumValues-DontIncludeTria') {
                                    tFound = t;
                                    break;
                                }
                            }
                            if (tFound > -1) {
                                currentErrors.splice(tFound, 1);
                            }

                        }
                    }
                }
            }
            if (currentErrors.length > 0) {
                $("#body-errors").css("display", "block");
            } else {
                $("#body-errors").css("display", "none");
            }
            inTheShow = false;
        }
    });
    $("#" + aFormName + " input").removeClass('invalid-field');
    $("#" + aFormName + " select").removeClass('invalid-field');
    currentMainForm = aFormName;
    setFormRules(aFormName);
}
function showCurrentErrors() {
    if (currentErrors.length > 0) {
        var eMsg = "<p>The following errors need to be corrected before moving to the next screen.</p><ul>";
        for (i = 0; i < currentErrors.length; i++) {
            eMsg = eMsg + "<li>" + currentErrors[i].elmsg + "</li>";
        }
        eMsg = eMsg + "</ul>";
        showNotificationWindow("Incomplete Form / Errors", eMsg);
    }
}
function validModalForm(aFormName) {
    $("#" + aFormName).validate({
        submitHandler: function(form) {

        },
        showErrors: function(errorMap, errorList) {
            if (inTheShow) { return true; }
            inTheShow = true;
            if (errorList.length > 0) {
                for (i = 0; i < errorList.length; i++) {
                    var isFound = false;
                    for (e = 0; e < modalErrors.length; e++) {
                        isFound = (modalErrors[e].elid == errorList[i].element.id);
                        if (isFound) {
                            break;
                        }
                    }
                    if (!isFound) {
                        $("#" + errorList[i].element.id).attr("title", errorList[i].message);
                        $("#" + errorList[i].element.id).addClass("invalid-field");
                        modalErrors.push({ elid: errorList[i].element.id, elmsg: errorList[i].message });
                    }
                }
            }

            if (this.successList.length > 0) {
                for (i = 0; i < this.successList.length; i++) {
                    var isFound = -1;
                    for (e = 0; e < modalErrors.length; e++) {
                        if (modalErrors[e].elid == this.successList[i].id) {
                            isFound = e;
                            break;
                        }
                    }
                    if (isFound > -1) {
                        $("#" + modalErrors[isFound].elid).removeAttr('title');
                        $("#" + modalErrors[isFound].elid).removeClass('invalid-field');

                        modalErrors.splice(isFound, 1);
                    }
                }
            }

            if (modalErrors.length > 0) {
                $("#modal-errors").css("display", "block");
                $("#modal-errors").css("top", "10px");
                $("#modal-errors").css("left", "600px");
            } else {
                $("#modal-errors").css("display", "none");
            }

            inTheShow = false;
        }
    });
    currentModalForm = aFormName;
    setFormRules(aFormName);
}
function clearFormRules(aFormName) {
    inFormInit = true;
    var rstr = aFormName.replace("-form", "clearrules()");
    rstr = rstr.replace(/-/g, "");
    eval(rstr + ";");
    rstr = aFormName.replace("-form", "afteraction()");
    rstr = rstr.replace(/-/, "");
    eval(rstr + ";");
    inFormInit = false;
}
function setFormRules(aFormName) {
    inFormInit = true;
    var estr = aFormName.replace("-form", "setrules()");
    estr = estr.replace(/-/g, '');
    eval(estr + ";");
    estr = aFormName.replace("-form", "beforeaction()");
    estr = estr.replace(/-/g, '');
    eval(estr + ";");
    inFormInit = false;
}
function activateForm(aFormName) {
    inFormInit = true;
    $("#" + aFormName).removeClass("editing-form-hidden");
    $("#Business-Contract-Wizard .wizard-buttons-panel button").removeClass("button-selected");
    currentErrors = new Array;
    sizeAll();
    $("#body-errors").css("display", "none");
    validForm(aFormName);
    inFormInit = false;
}
function getInputs(inputSelect) {
    var oNames = '';
    var oFields = '';
    var retVal = new Array;
    for (i = 0; i < inputSelect.length; i++) {
        if ((inputSelect[i].id != '') && (inputSelect[i].type != 'button')) {
            if (i > 0) {
                oNames = oNames + '\t';
                oFields = oFields + '\t';
            }
            oNames = oNames + inputSelect[i].id;
            var t = $('#' + inputSelect[i].id).val();
            var ot = '';

            if (inputSelect[i].type == 'select-one') {
                ot = $('#' + inputSelect[i].id + ' option:selected').attr('objID');
                if (ot) {
                }
            }

            if ((ot) && (ot != '')) {
                oFields = oFields + ot;
            } else {
                if ($('#' + inputSelect[i].id).hasClass('currency-rules') ||
                    $('#' + inputSelect[i].id).hasClass('integer-rules') ||
                    $('#' + inputSelect[i].id).hasClass('floating-rules')) {
                    t = t.replace(/,/g, '');
                    if (t == '') { t = '0'; }
                    oFields = oFields + t;
                } else {
                    oFields = oFields + t;
                }

            }
        }
    }
    retVal.push(oNames);
    retVal.push(oFields);
    return retVal;
}
function setFormData(list) {
    var dataItems = eval('(' + list + ')');
    if (dataItems.values.length > 0) {
        for (i = 0; i < dataItems.values.length; i++) {
            var thisName = dataItems.values[i].name;
            if ($('#' + thisName).hasClass('currency-rules') ||
                $('#' + thisName).hasClass('integer-rules') ||
                $('#' + thisName).hasClass('floating-rules')) {
                if (parseInt(dataItems.values[i].value, 10) == 0) {
                    $('#' + thisName).val('');
                } else {
                    if ($('#' + thisName).hasClass('currency-rules') || $('#' + thisName).hasClass('floating-rules')) {
                        formatNumb.setNumber(dataItems.values[i].value);
                        $('#' + thisName).val(formatNumb.toFormatted());
                    } else {
                        $('#' + thisName).val(dataItems.values[i].value);
                    }
                }
            } else {
                if ($('#' + thisName).hasClass('tinytable-editor')) {
                    // set grid rows
                    var bdDecode = $.base64.decode(dataItems.values[i].value);
                    setGridRows(thisName.replace("-GridEdit", ""), bdDecode);
                } else {
                    $('#' + thisName).val(dataItems.values[i].value);
                }
            }
        }
    }
    if (dataItems.id != '0') {
        currentWorkID = dataItems.id;
    }
}
function loadExternalWin(aDoc) {
    window.open(aDoc, '').focus();
}
function loadPDFWin(aDoc) {
    var aWin = window.open('');
    aWin.document.location = aDoc;
}
function loadPrintQuote() {
    accessService("GetPrintQuote", '{"sessionKey":"' + sessionKey + '"}', function(data) {
        var ret = new String(data.d);
        if (ret.indexOf('Error -') == 0) {
            showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
        } else {
            showNotificationWindow("<h2 class='msg-indent'>Print Quote</h2>", "<p class='msg-indent'>A window with an Adobe PDF file should have opened for you to print.</p><p class='msg-indent'>Press OK here when finished...</p>");
            loadPDFWin(data.d);
        }
    });
}
function showPaymentDetails() {
    var i = "<h3 class='msg-indent'>One Pay - Payment Due on Binding</h3><p class='msg-indent'>1.  100% of premium.</p><h3 class='msg-indent'>Two Pay - Payments Due on Binding and at 30 Days</h3><p class='msg-indent'>1.  Payment 1 = 30% of premium.</p><p class='msg-indent'>2.  Payment 2 (30 days after Effective Date) = 70% of premium.</p><h3 class='msg-indent'>Three Pay - Payments Due on Binding and at 60 and 120 Days</h3><p class='msg-indent'>1.  Payment 1 = 35% of premium.</p><p class='msg-indent'>2.  Payment 2 (60 days after Effective Date) = 35% of premium.</p><p class='msg-indent'>3.  Payment 3 (120 days after Effective Date) = 30% of premium.</p><br/>";
    showNotificationWindow("<h2 class='msg-indent'>Payment Plan Details</h2>", i);
}
function doBindPolicy() {
    var currentWizForm = $("#Business-Contract-Wizard .wizard-buttons-panel button.button-selected").attr('rel');
    var fValid = $("#" + currentWizForm).validate().form();
    if (fValid) {
        reQuote();
        accessService("BindPackage", '{"sessionKey":"' + sessionKey + '"}', function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
            } else {
                showNotificationWindow("<h2 class='msg-indent'>Binding Process</h2>", "<p class='msg-indent'>A window with a Binder Package (Adobe PDF) should have opened for you.</p><p class='msg-indent'>This Binder Package is also being sent your email address.</p><p class='msg-indent'>Press OK here when finished...</p>");
                loadPDFWin(data.d);
            }
        });

        $('#Binder-MortgageeList-GridEdit tbody').empty();
        $('#AntiArsonInfo-Owners-GridEdit tbody').empty();
        //refreshBrowser('Business.Contract');
        $("#Business-Contract-CancelButton").trigger("click");
    }
}
function refreshGridEdit(aClass, aGridName) {
    if (aClass) {
        var formattedName = aClass.replace('.', '-');

        var lastSelected = $('#' + aGridName + '-GridEdit tbody tr.selected').attr('row-id');

        var sData = '{"sessionKey":"' + sessionKey + '", "gridClassName":"' + aClass.replace(/-/g, '.') + '", "propertyName":"' + aGridName + '"}';

        accessService("GetGridSet", sData, function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
            } else {
                setGridRows(aGridName, data.d);
            }
        });
    }
}
function setGridRows(aGridName, rows) {
    var lastSelected = $('#' + aGridName + '-GridEdit tbody tr.selected').attr('row-id');
    $('#' + aGridName + '-GridEdit tbody').empty();
    if (rows) {
        $('#' + aGridName + '-GridEdit tbody').prepend(rows);
        if (lastSelected) {
            $('#' + aGridName + '-GridEdit tbody tr[row-id$=' + lastSelected + ']').addClass('selected');
            $('#' + aGridName + '-EditButton').removeAttr('disabled');
        } else {
            $('#' + aGridName + '-EditButton').attr('disabled', 'disabled');
        }
    }
}
function refreshDataCombos(aClass) {
    var cSet = $('select.data-driven');
    if (cSet.length > 0) {
        for (n = 0; n < cSet.length; n++) {
            var thisDBCue = $('#' + cSet[n].id).attr('dataCue');
            accessService('RefreshCombo', '{"sessionKey":"' + sessionKey + '", "className":"' + thisDBCue + '"}', function(data) {
                var ret = new String(data.d);
                if (ret.indexOf('Error -') == 0) {
                    showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
                } else {
                    $('#' + cSet[n].id).empty();
                    $('#' + cSet[n].id).prepend(data.d);
                }
            });
        }
    }
}
function refreshBrowser(aClass) {
    if (aClass) {
        var bFlags = '';
        var bName = aClass.replace(".", "-");
        if (aClass == 'Business.Contract') {
            // check for include tests flag
            if ($('#Business-Contract-IncludeTests').attr('checked')) {
                bFlags = 'WITHTESTS';
            } else {
                bFlags = 'NOTESTS';
            }
        }
        if (aClass == 'Business.SavedQuote') {
            // check for include tests flag
            if ($('#Business-SavedQuote-IncludeTests').attr('checked')) {
                bFlags = 'WITHTESTS';
            } else {
                bFlags = 'NOTESTS';
            }
        }
        // check for show softdelete d's
        if ($('#' + bName + '-IncludeRemoved').attr('checked')) {
            bFlags = bFlags + 'WITHREMOVED';
        } else {
            bFlags = bFlags + 'NOREMOVED';
        }

        var sData = '{"sessionKey":"' + sessionKey + '", "className":"' + aClass + '", "flags":"' + bFlags + '"}';
        accessService("RefreshBrowserSet", sData, function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
            } else {
                setBrowserRows(aClass, data.d);
            }
        });
    }
}
function removeBrowserItem(aClass, aBrowser) {
    var editRowID = $('#' + aBrowser + ' tbody tr.selected').attr('row-id');
    if (editRowID) {
        if (editRowID > 0) {
            var bFlags = '';
            var bName = aClass.replace(".", "-");
            if (aClass == 'Business.Contract') {
                // check for include tests flag
                if ($('#Business-Contract-IncludeTests').attr('checked')) {
                    bFlags = bFlags + 'WITHTESTS';
                } else {
                    bFlags = bFlags + 'NOTESTS';
                }
            }
            // check for show softdelete d's
            if ($('#' + bName + '-IncludeRemoved').attr('checked')) {
                bFlags = bFlags + 'WITHREMOVED';
            } else {
                bFlags = bFlags + 'NOREMOVED';
            }


            var sData = '{"sessionKey":"' + sessionKey + '", "className":"' + aClass + '", "anID":"' + editRowID + '", "flags":"' + bFlags + '"}';
            accessService("RemoveBrowserItem", sData, function(data) {
                var ret = new String(data.d);
                if (ret.indexOf('Error -') == 0) {
                    showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
                } else {
                    setBrowserRows(aClass, data.d);
                }
            });
        }
    }
}
function sendBrowserItem(aClass, aBrowser) {
    var editRowID = $('#' + aBrowser + ' tbody tr.selected').attr('row-id');
    if (editRowID) {
        if (editRowID > 0) {
            var sData = '{"sessionKey":"' + sessionKey + '", "anEmail":"' + sessionUser + '", "anID":"' + editRowID + '"}';
            accessService("SendPackageDocs", sData, function(data) {
                var ret = new String(data.d);
                if (ret.indexOf('Error -') == 0) {
                    showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
                } else {
                    //setBrowserRows(aClass, data.d);
                }
            });
        }
    }
}
function setBrowserRows(aClass, rows) {
    var lastSelected = $('#' + formattedName + '-Browser tbody tr.selected').attr('row-id');
    var formattedName = aClass.replace('.', '-');
    $('#' + formattedName + '-Browser tbody').empty();
    if (rows) {
        $('#' + formattedName + '-Browser tbody').prepend(rows);
        if (lastSelected) {
            $('#' + formattedName + '-Browser tbody tr[row-id$=' + lastSelected + ']').addClass('selected');
            if (superUser == 'yes') {
                $('#' + formattedName + '-EditButton').removeAttr('disabled');
            } else {
                $('#' + formattedName + '-EditButton').attr('disabled', 'disabled');
            }
        } else {
            $('#' + formattedName + '-EditButton').attr('disabled', 'disabled');
        }
    }
}
function restoreQuote(aClass, gridName) {
    var editRowID = $('#' + gridName + ' tbody tr.selected').attr('row-id');
    sData = '{"sessionKey":"' + sessionKey + '", "className":"' + aClass.replace(/-/g, '.') + '", "anID": "' + editRowID + '"}';
    accessService('EditSavedQuote', sData, function(data) {
        var ret = new String(data.d);
        if (ret.indexOf('Error -') == 0) {
            showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
        } else {
            $('#Binder-MortgageeList-GridEdit tbody').empty();
            $('#AntiArsonInfo-Owners-GridEdit tbody').empty();
            setFormData(data.d);
            $("#body-navigator button")[0].click();
            $("#BoundQuote-button").click();
            $("#BoundQuote-PremiumValues-button").click();
            $("#Binder-button").click();
            $("#Signature-button").click();
        }
    });
}
function showModalDialog(aClass, gridName, isNew, closeFunction) {
    // if its a savedquote, then call the restoreQuote routine
    if (aClass == 'Business.SavedQuote') {
        restoreQuote(aClass, gridName);
        return false;
    }

    var isBrowser = (gridName.indexOf('-Browser') >= 0);
    var isGrid = (gridName.indexOf('-GridEdit') >= 0);
    var pName = '';
    if (isBrowser) {
        pName = gridName.replace('-Browser', '');
    }
    if (isGrid) {
        pName = gridName.replace('-GridEdit', '');
    }

    $("#modalTitle").empty();
    $("#modalCol").empty();
    modalErrors = new Array;

    var sData = '{"sessionKey":"' + sessionKey + '", "name":"' + aClass.replace(/-/g, '.') + '"}';
    var stopError = false;
    accessService("GetObjectLayout", sData, function(data) {
        var ret = new String(data.d);
        if (ret.indexOf('Error -') == 0) {
            showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
            stopError = true;
        } else {
            $("#modalCol").prepend(data.d);
        }
    });
    if (stopError) {
        return false;
    }
    $("#modalCol").prepend("<div id='modal-errors'>Information needed. Hover over the highlighted fields.</div>");
    initControls("#modalCol");
    refreshDataCombos('test');

    var editRowID = '';
    if (isNew) { editRowID = 'NEW'; } else { editRowID = $('#' + gridName + ' tbody tr.selected').attr('row-id'); }
    if (editRowID == undefined) {return false; }
    if (isBrowser) {
        sData = '{"sessionKey":"' + sessionKey + '", "className":"' + aClass.replace(/-/g, '.') + '", "anID": "' + editRowID + '"}';
        accessService('GetBrowserItem', sData, function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
                stopError = true;
            } else {
                setFormData(data.d);
            }
        });
    } else {
        sData = '{"sessionKey":"' + sessionKey + '", "gridClassName":"' + aClass.replace(/-/g, '.') + '", "propertyName":"' + pName + '", "anIndex": "' + editRowID + '"}';
        accessService('GetGridItem', sData, function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
                stopError = true;
            } else {
                setFormData(data.d);
            }
        });
    }
    if (stopError) {
        return false;
    }

    if (sessionAgency.toLowerCase() == 'roundhill') {
        $(".MODAL-Comments-Group").show();
        $("#MODAL-DomainName").removeAttr('disabled');
        $('.MODAL-AdditionalFeesandReferences-Group').show();
    } else {
        $('.MODAL-AdditionalFeesandReferences-Group').hide();
        $(".MODAL-Comments-Group").hide();
        $("#MODAL-DomainName").attr('disabled', 'disabled');
        if (aClass == 'Business.User') {
            $("#MODAL-DomainName").val(sessionAgency);
        }
    }

    var aFormID = $('#modalCol form')[0].id;
    validModalForm(aFormID);
    $("#titleRow").css("height", "0px");

    $("#ok-butt").css("display", "inline");
    $("#can-butt").css("display", "inline");
    $("#ok-butt").removeClass("simplemodal-close");
    $("#modal-content").attr("object_id", editRowID);
    $("#modal-content").modal({ maxWidth: 960, minHeight: 100,
        onShow: function(dialog) {
            var fHeight = $("#modalCol .form-wrapper .content-wrapper form").height() + 20;
            var contentArea = $(window).height() - 117;

            if (fHeight > contentArea) {
                fHeight = contentArea;
            }
            $("#modalCol .form-wrapper .content-wrapper").css("height", fHeight); // ($(window).height() * .4));
            $(dialog.container).css('height', fHeight + 65);
            var winHeight = $(window).height();
            $(dialog.container).css('top', ((winHeight / 2) - ((fHeight + 65) / 2) - 4));

            $('#ok-butt').click(function(e) {
                e.preventDefault();
                if ($('#' + aFormID).validate().form()) {
                    var dataArr = getInputs($('#modalCol :input'));
                    if (isBrowser) {
                        sData = '{"sessionKey":"' + sessionKey + '", "className":"' + aClass.replace(/-/g, '.') + '", "anID": "' + editRowID + '", "names":' + JSON.stringify(dataArr[0]) + ', "values":' + JSON.stringify(dataArr[1]) + '}';
                        accessService('SetBrowserItem', sData, function(data) {
                            var ret = new String(data.d);
                            if (ret.indexOf('Error -') == 0) {
                                showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
                            } else {
                                refreshBrowser(aClass);
                            }
                        });
                        if ($.isFunction(closeFunction)) { closeFunction.apply(); }
                        $.modal.close();
                    } else {
                        sData = '{"sessionKey":"' + sessionKey + '", "gridClassName":"' + aClass.replace(/-/g, '.') + '", "propertyName":"' + pName + '", "anIndex": "' + editRowID + '", "names": ' + JSON.stringify(dataArr[0]) + ', "values": ' + JSON.stringify(dataArr[1]) + '}';
                        accessService('SetGridItem', sData, function(data) {
                            var ret = new String(data.d);
                            if (ret.indexOf('Error -') == 0) {
                                showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
                            } else {
                                refreshGridEdit(aClass, pName); 
                            }
                        });
                        if ($.isFunction(closeFunction)) { closeFunction.apply(); }
                        $.modal.close();
                    }
                }
            });
        }
    });
}
function removeCurrentGridRow(aClass, aGrid) {
    var delRowID = $('#' + aGrid + ' tbody tr.selected').attr('row-id');
    var pName = $('#' + aGrid).attr('rel');
    pName = aGrid.replace('-GridEdit', '');
    if (delRowID) {
        sData = '{"sessionKey":"' + sessionKey + '", "gridClassName":"' + aClass.replace(/-/g, '.') + '", "propertyName":"' + pName + '", "anIndex": "' + delRowID + '"}';
        accessService('RemoveGridItem', sData, function(data) {
            var ret = new String(data.d);
            if (ret.indexOf('Error -') == 0) {
                showNotificationWindow("<h2 class='msg-indent'>Error</h2>", "<p>Server reported:</p><p>" + data.d + "</p>");
            } else {
                refreshGridEdit(aClass, pName);
            }
        });
    }
}
function showNotificationWindow(aTitle, aMessage) {
    $("#notify-titleRow").css("height", "16px");
    $("#notify-col").empty()
    $("#notifyTitle").empty();
    $("#notifyTitle").html('<p>' + aTitle + '</p>');
    $("#notify-col").html(aMessage);
    $("#notify-ok").css("display", "inline");
    $("#notify-cancel").css("display", "none");
    $("#notify-ok").addClass("simplemodal-close");
    $("#modal-notify").modal({ maxWidth: 960, minHeight: 100, maxHeight: 650,
        onShow: function(dialog) {
        var fHeight = $("#notify-col").height() + 20;
            var contentArea = $(window).height() - 117;

            if (fHeight > contentArea) {
                fHeight = contentArea;
            }
            $("#notify-col").css("height", fHeight); // ($(window).height() * .4));
            $(dialog.container).css('height', fHeight + 120);
            var winHeight = $(window).height();
            $(dialog.container).css('top', ((winHeight / 2) - ((fHeight + 65) / 2) - 4));
        }
    });
}
function showConfirmation(aTitle, aMessage, closeFunction) {
    $("#notify-titleRow").css("height", "16px");
    $("#notify-col").empty();
    $("#notifyTitle").empty();
    $("#notifyTitle").html('<p>' + aTitle + '</p>');
    $("#notify-col").html(aMessage);
    $("#notify-ok").removeClass("simplemodal-close");
    $("#notify-ok").css("display", "inline");
    $("#notify-cancel").css("display", "inline");
    $("#modal-notify").modal({ maxWidth: 960, minHeight: 100, maxHeight: 650,
        onShow: function(dialog) {
            var fHeight = $("#notify-col").height() + 20;
            var contentArea = $(window).height() - 117;

            if (fHeight > contentArea) {
                fHeight = contentArea;
            }
            $("#notify-col").css("height", fHeight); // ($(window).height() * .4));
            $(dialog.container).css('height', fHeight + 120);
            var winHeight = $(window).height();
            $(dialog.container).css('top', ((winHeight / 2) - ((fHeight + 65) / 2) - 4));
            $('#notify-ok').click(function() {
                if ($.isFunction(closeFunction)) {
                    closeFunction.apply();
                }
                $.modal.close();
            });
        }
    });
}
