(function($) {
    var spinner = {
        getSpinnerHTML: function(text) {
            var spinnerImg = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;";
            return spinnerImg + text;
        }
    };

    var infoDialogs = {
        alertDialog: function (message) {
            $("#alert-content").html(message);
            $("#dialog-alert").dialog("open");
        },
        alert: function(modalId, title, message, event) {
            var _title_ = "There was an error",
                    _message_ = "There was an error processing your last request.  If the problem persists, please contact technical support.",
                    $modal = $('#' + modalId);

            _title_ = (title == "") ? _title_ : title;
            _message_ = (message == "") ? _message_ : message;

            $('.modal-title', $modal).html(_title_);
            $('.modal-message', $modal).html(_message_);

            $('.modal-control').hide();
            $('.modal-close').show();

            if ((arguments[3]) && (typeof(arguments[3]) == "function")) {
                $('.modal-close', $modal).bind("click.optionalcallback", arguments[3]);
            }
            //$modal.jqmShow();
            if (event) {
                jqmWindowShow($modal, 0, 10, event);
            }
            else {
                jqmWindowShow($modal, 150, 10);
            }
        },
        confirm: function(event, modalId, title, message, okCallback, cancelCallback, okBtn, cancelBtn) {
            var _title_ = "There was an error",
                    _message_ = "There was an error processing your last request.  If the problem persists, please contact technical support.",
                    $modal = $('#' + modalId);

            _title_ = (title == "") ? _title_ : title;
            _message_ = (message == "") ? _message_ : message;

            $('.modal-title', $modal).html(_title_);
            $('.modal-message', $modal).html(_message_);

            $('.modal-control').hide();
            if (okBtn) {
                $(".modal-ok").children(":input").attr("value", okBtn);
            }
            if (cancelBtn) {
                $(".modal-cancel").children(":input").attr("value", cancelBtn);
            }
            $('.modal-ok, .modal-cancel').show();

            if (typeof(okCallback) == "function") {
                $('.modal-ok', $modal).bind("click.okcallback", okCallback);
            }
            if (typeof(cancelCallback) == "function") {
                $('.modal-cancel', $modal).bind("click.cancelcallback", cancelCallback);
            }
            jqmWindowShow($modal, 10, 10, event);
            //$modal.jqmShow();
        },
        popUp: function(modalId, title, text) {
            var _title_ = "There was an error",
                    _message_ = "There was an error processing your last request.  If the problem persists, please contact technical support.",
                    $modal = $('#' + modalId);

            _title_ = (title == "") ? _title_ : title;
            _message_ = (message == "") ? _message_ : message;

            $('.modal-title', $modal).html(_title_);
            $('.modal-message', $modal).html(_message_);

            $('.modal-control').hide();
            $('.modal-ok, .modal-cancel').show();

            if (typeof(okCallback) == "function") {
                $('.modal-ok', $modal).bind("click.okcallback", okCallback);
            }
            $modal.jqmShow();
        }

    };

    var jqmWindowShow = function($modal, topOffset, leftOffset, event) {
        $modal.css("top", ((window.pageYOffset || document.documentElement.scrollTop) + topOffset) + "px");
        if (event) {
            $modal.css("left", ((event.pageX ? event.pageX : event.clientX) + (leftOffset ? leftOffset : 5)) + "px");
            $modal.css("top", ((event.pageY ? event.pageY : event.clientY) + (topOffset ? topOffset : 5)) + "px");
        }
        else if (leftOffset) {
            $modal.css("left", ((window.pageXOffset || document.documentElement.scrollL) + leftOffset) + "px");
        }
        $modal.jqmShow();

    };

    var jqmWindowHide = function($modal) {
        $modal.jqmHide();

    };

    var extractObjectId = function(elementId) {
        return (elementId.split("_"))[1];
    };

    var trimAll = function(sString) {
        while (sString.substring(0, 1) == ' ') {
            sString = sString.substring(1, sString.length);
        }
        while (sString.substring(sString.length - 1, sString.length) == ' ') {
            sString = sString.substring(0, sString.length - 1);
        }
        return sString;
    };

    var escapeHTMLString = function(theString) {
        var div = document.createElement('div'),
                text = document.createTextNode(theString);
        div.appendChild(text);
        return div.innerHTML;
    };

    var windowUtils = {
        windowHeight : function () {
            var myHeight = 0;
            if (typeof( window.innerWidth ) == 'number') {
                //Non-IE
                myHeight = window.innerHeight;
            } else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
                //IE 6+ in 'standards compliant mode'
                myHeight = document.documentElement.clientHeight;
            } else if (document.body && ( document.body.clientWidth || document.body.clientHeight )) {
                //IE 4 compatible
                myHeight = document.body.clientHeight;
            }
            return myHeight;
        },

        windowWidth : function () {
            var myWidth = 0;
            if (typeof( window.innerWidth ) == 'number') {
                //Non-IE
                myWidth = window.innerWidth;
            } else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
                //IE 6+ in 'standards compliant mode'
                myWidth = document.documentElement.clientWidth;
            } else if (document.body && ( document.body.clientWidth || document.body.clientHeight )) {
                //IE 4 compatible
                myWidth = document.body.clientWidth;
            }
            return myWidth;
        }
    };

    var loadTabPanel = function(hash) {

/*
        var index = $('#survey-home-tabs').tabs("option", "selected");
        if (index == 0) {
            filterText = $("#survey-list-filter").children("option:first").text();
            changeSurveyList("0");
        }
        else if (index == 1) {
            initStudentProfilePanel();
        }
        else if (index == 2) {
            initScorecardPanel();
        }


*/
        //var theTab = ui.tab;

        if (hash == "#survey-list-tab-area") {
            filterText = $("#survey-list-filter").children("option:first").text();
            changeSurveyList("0");
        }
        else if (hash == "#wehuddle-tab-area") {
            initWehuddlePanel();
        }
        else if (hash == "#scorecards-tab-area") {
            initScorecardPanel();
        }
        else if (hash == "#respondent-profile-tab-area") {
            initStudentProfilePanel();
        }
    };

    var sendForgotEmail = function() {
        var spinner = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;Attempting to sign you in...";
        $("#login-spinner-container").html(spinner);
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_forgot_pwd;
        AJAXRequestDict['dataFields'] = {
            email : $("#forgot-email").val()
        };

        $.ajax({
            dataType: "json",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error while signing in.  Msg: " + txtStatus);
            },
            success: function(json) {
                responseDataDict = json["outputs"];
                var auth = responseDataDict["auth"];
                if (auth == "valid") {
                    window.location(docRoot + "/anchor")
                }
                else {
                    infoDialogs.alertDialog("Invalid signin information.</br></br>Please try again.");
                }
            }
        });

    };

    var attemptLogin = function(e, ui) {
        $("#login-error").hide();
        $("#login-spin").fadeIn();
        var AJAXRequestDict = {},
                responseDataDict;
        var req = $("#login-button").is(".forgot-button") ?
                  requestHandler.req_forgot_pwd :
                  requestHandler.req_login;
        AJAXRequestDict['reqType'] = req;
        AJAXRequestDict['dataFields'] = {
            email : $("#email").val(),
            pwd : $("#password").val()
        };

        $.ajax({
            dataType: "json",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error while signing in.<br/><br/>We've noticed recent problems with Mozilla Firefox on the Macintosh, and are working on rectifying this issue.<br/><br/>If this is how you're signing in, please click the link below to be redirected to a temporary login page, or try a different browser in the meantime.<br/><br/><a href='http://www.schoolperceptions.com//MyHome.php'>Alternate login page</a><br/><br/>Otherwise please contact your survey administrator");
//                infoDialogs.alertDialog("Our results analysis interface is experiencing issues.<br/><br/>We are attempting to rectify the situtation as soon as possible.<br/><br/>Please come back later to analyze results.");
//                infoDialogs.alertDialog("We are experiencing browser compatability issues with this login page.<br/><br/>Please click the link below to be redirected to a temporary login page.<br/>Your current email/password credentials will still be valid.<br/><br/><a href='http://www.schoolperceptions.com//MyHome.php'>Alternate login page</a>");
            },
            success: function(json) {
                responseDataDict = json["outputs"];
                if (responseDataDict["auth"] == "valid") {
                    if ($("#login-button").is(".forgot-button")) {
                        rebuildLogin();
                        infoDialogs.alertDialog("Your signin reminder has been sent.<br/><br/>You should receive it shortly.");
                    }
                    else {
                        if (responseDataDict["first"]) {
                            window.location = docRoot +"/anchor?f=t";
                        }
                        else {
                            window.location = docRoot +"/anchor?f=f";
                        }
                    }
                }
                else {
                    $("#login-spin").hide();
                    $("#password").attr("value", "");
                    $("#login-error").fadeIn();
                }
            }
        });

    };

    var attemptLogout = function(e, ui) {
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_logout;
        AJAXRequestDict['dataFields'] = {
            email : ""
        };

        $.ajax({
            dataType: "json",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error while signing out.  Msg: " + txtStatus);
            },
            success: function(json) {
                window.location = docRoot + "/login";
            }
        });

    };

    var initScorecardPanel = function() {
        var spinner = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;Building scorecard list...";
        $("#scorecards-container").html(spinner);
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_init_scorecard_list;
        AJAXRequestDict['dataFields'] = {instId : $("#survey-access-list").val()};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error retrieving the Scorecard content.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#scorecards-container").html(html);
            }
        });

    };

    var initWehuddlePanel = function() {
        var spinner = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;Building your weHuddle list...";
        $("#wehuddle-container").html(spinner);
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_init_wehuddle;
        AJAXRequestDict['dataFields'] = {instId : $("#survey-access-list").val()};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error retrieving the weHuddle content.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#wehuddle-container").html(html);
            }
        });

    };

    var initIndexAggEntry = function(e, ui) {
        var spinner = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;Retrieving your data...";
        //$("#index-agg-entry-content").html(spinner);
        $("#index-agg-entry-content").attr("idResp", $(this).attr("idResp"));
        $("#index-agg-entry-content").attr("idIdx", $(this).attr("idIdx"));
        $("#index-agg-entry-content").attr("idIndiv", $(this).attr("idIndiv"));

        $("#index-agg-entry-dialog").dialog("option","title",$(this).attr("dialogTitle"));
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_init_index_agg_entry;
        AJAXRequestDict['dataFields'] = {
            idIdx : $(this).attr("idIdx"),
            idResp : $(this).attr("idResp")
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error retrieving the index entry content.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#index-agg-entry-content").html(html);
                $("#index-agg-entry-dialog").dialog("open");
            }
        });

    };

    var aggEntrySave = function () {
        var spinner = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;Refreshing student profile...";
        $("#idx-detail-" + idIdx).html(spinner);
        var idIndiv = $("#index-agg-entry-content").attr("idIndiv");
        var idIdx = $("#index-agg-entry-content").attr("idIdx");

        //$("#index-agg-entry-content").html(spinner);

        var AJAXRequestDict = {},
                responseDataDict;

        var iaVals = {};
        var iaIds = {};
        var idx = 0;
        $(".rd-ia-def:checked").each(function() {
             iaVals[idx] = $(this).val();
             iaIds[idx] = $(this).attr("idIA");
            idx++;
        });

        AJAXRequestDict['reqType'] = requestHandler.req_save_index_agg_entry;
        AJAXRequestDict['dataFields'] = {
            idResp : $("#index-agg-entry-content").attr("idResp"),
            idIdx : idIdx,
            idIndiv : idIndiv,
            iaVals : iaVals,
            iaIds : iaIds
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error retrieving the index entry content.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#index-agg-entry-dialog").dialog("close");
                $("#idx-detail-" + idIdx).html(html);
            }
        });


    };

    var initStudentProfilePanel = function() {
        var spinner = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;Building student profile page...";
        $("#respondent-profile-container").html(spinner);
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_init_student_profile;
        AJAXRequestDict['dataFields'] = {instId : $("#survey-access-list").val()};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error retrieving the Student Profile content.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#respondent-profile-container").html(html);
                $("#resp-profile-search-box").focus();
            }
        });

    };

    var studProfileSearch = function(offset) {
        initStudentInfoArea();
        var spinner = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;Searching...";
        $("#resp-profile-content").html(spinner);
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_student_search;
        AJAXRequestDict['dataFields'] = {instId : $("#survey-access-list").val(),
            searchString:$("#search-string").text(),
            offset: offset};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error while searching for student profiles.  Msg: " + txtStatus);
            },
            success: function(html) {
                var $content = $(html);
                if ($(".search-result-item:not(.zero-result)", $content).length == 1 && offset == 0) {
                    retrieveStudentData(extractObjectId($(".search-result-item", $content).attr("id")));
                }
                else {
                    $("#resp-profile-content").html(html);
                }
            }
        });
    };

    var initStudentInfoArea = function() {
        $("#resp-profile-content").html("");

        $(".resp-profile-show").hide().removeClass("resp-profile-show");
        $(".resp-profile-header-item", $("#resp-profile-name")).text("");
        $(".resp-profile-header-item", $("#resp-profile-created")).text("");
    };

    var getStudentInfo = function(idIndiv) {
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_get_student_info;
        AJAXRequestDict['dataFields'] = {idIndiv: idIndiv};

        $.ajax({
            dataType: "json",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error while retrieving student information.  Msg: " + txtStatus);
            },
            success: function(json) {
                if (json['oh_Yeah']) {
                    responseDataDict = json["outputs"];
                    var name = responseDataDict["fName"] + " " + responseDataDict["lName"];
                    $(".resp-profile-header-item", $("#resp-profile-name")).text(name);
                    $("#resp-profile-name").addClass("resp-profile-show");
                    if (responseDataDict["created"]) {
                        $(".resp-profile-header-item", $("#resp-profile-created")).text(responseDataDict["created"]);
                        $("#resp-profile-created").addClass("resp-profile-show");
                    }
                    $(".resp-profile-show").show();

                }
                else {
                    alert(json['message']);
                }
            }
        });

    };

    var buildStudentProfile = function(idIndiv) {
        var spinner = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;Retrieving student information...";
        $("#resp-profile-content").html(spinner);
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_build_student_profile;
        AJAXRequestDict['dataFields'] = {idIndiv: idIndiv};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error while building the student profile.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#resp-profile-content").html(html);
            }
        });

    };

    var retrieveStudentData = function(idIndiv) {
        initStudentInfoArea();
        getStudentInfo(idIndiv);
        buildStudentProfile(idIndiv);
    };

    var toggleUserSurveyArchive = function(e, ui) {
        var AJAXRequestDict = {},
                responseDataDict,
                $item = $(this).parents(".survey-list-item");
        var idCS = extractObjectId($item.attr("id"));

        AJAXRequestDict['reqType'] = requestHandler.req_archive_toggle;
        AJAXRequestDict['dataFields'] = {idCS: idCS, status: $(this).attr("stat")};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error changing the archival status.  Msg: " + txtStatus);
            },
            success: function(html) {
                removeSurveyListItem($item);
            }
        });
    };

    var removeSurveyListItem = function ($item) {
        $item.remove();
        if ($(".survey-list-item", $("#survey-list-wrapper")).length == 0) {
            $("#sl-item-none").show();
        }
    };

    var buildInstAccess = function() {
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_build_access_list;
        AJAXRequestDict['dataFields'] = {};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error building your access list.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#survey-access-list").html(html);
                changeInst();
                if ($("#survey-access-list option").length > 1) {
                    $("#survey-access-wrapper").show();
                }
            }
        });
    };

    var changeInst = function() {
        var AJAXRequestDict = {},
                responseDataDict;
        initSurveyList();
        AJAXRequestDict['reqType'] = requestHandler.req_change_inst;
        AJAXRequestDict['dataFields'] = {instId : $("#survey-access-list").val()};

        $.ajax({
            dataType: "json",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error while changing institutions.  Msg: " + txtStatus);
            },
            success: function(json) {
                responseDataDict = json["outputs"];
                $("#survey-home-tabs").tabs("select",0);
                removeScorecardTab();
                if (responseDataDict["scorecardTab"] == 1) {
                    addScorecardTab();
                }
                if (responseDataDict["wehuddleTab"] == 1 && !doWehuddleTab) {
                    addWehuddleTab();
                }

                $("#inst-name").text($("#survey-access-list option:selected").text());
            }
        });
    };

    var changeSurveyList = function(offset) {
        var AJAXRequestDict = {},
                responseDataDict;
        initSurveyList();

        AJAXRequestDict['reqType'] = requestHandler.req_survey_list;
        AJAXRequestDict['dataFields'] = {instId : $("#survey-access-list").val(),
            filterType : $("#survey-list-filter").val(),
            offset: offset};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error re-filtering your survey list.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#survey-list-content").html(html);
            }
        });
    };


    var initSurveyList = function() {
        $("#survey-filter-name-detail").text(filterText);
        var spinner = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;Retrieving survey list...";
        $("#survey-list-content").html(spinner);
    };

    var showFunctions = function($container) {
        if ($container.is(".ui-state-hover")) {
            //$container.children(".sl-item-functions").show("fast");
            $container.children(".sl-item-functions").css("display", "block");
        }
    };

    var setupIndivResultsDialog = function(e, ui) {
        var AJAXRequestDict = {},
                responseDataDict;
        var bodyWidth = $("body").width();
        $("#dialog-indiv-results").dialog("option", "width", bodyWidth - 80);
        var modalWidth = $("#dialog-indiv-results").dialog("option", "width"),
                modalLeft = (bodyWidth - modalWidth) / 2;
        $("#dialog-indiv-results").dialog("option", "position", [modalLeft,50]);

        var spinner = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;Retrieving survey information...";
        var $trigger = $(this);
        var myTitle = $trigger.attr('title');
        $("#dialog-indiv-results").dialog("option", "title", myTitle);
        $("#ir-dialog-content").html(spinner);
        //$dialog.jqmShow();

        AJAXRequestDict['reqType'] = requestHandler.req_view_indiv_results;
        AJAXRequestDict['dataFields'] = {idResp:$trigger.attr("idResp"),idCS:$trigger.attr("idCS")};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error retrieving the student survey data.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#dialog-indiv-results").dialog("option", "height", windowUtils.windowHeight() - 100);
                $("#ir-dialog-content").html(html);
                $("#dialog-indiv-results").dialog("open");

            }
        });
    };

    var setupIndivResultsModal = function(e, ui) {
        var AJAXRequestDict = {},
                responseDataDict;
        var $modal = $("#indiv-results-modal");
        $modal.css("width", "85%");
        var modalWidth = $modal.width(),
                bodyWidth = $("body").width(),
                modalLeft = (bodyWidth - modalWidth) / 2;
        $modal.css('left', modalLeft);
        $modal.css('margin-left', "0");

        var spinner = "<img src=\"" + imageRoot + "/wait16trans.gif\"/>&nbsp;Retrieving survey information...";
        var $trigger = $(this);
        var myTitle = $trigger.attr('title');
        $('#indiv-results-modal-title-text').text(myTitle);
        $("#indiv-results-modal-content").html(spinner);
        $modal.jqmShow();

        AJAXRequestDict['reqType'] = requestHandler.req_view_indiv_results;
        AJAXRequestDict['dataFields'] = {idResp:$trigger.attr("idResp"),idCS:$trigger.attr("idCS")};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error retrieving the student survey data.  Msg: " + txtStatus);
            },
            success: function(html) {
                $modal.css('height', windowUtils.windowHeight() - 100);
                $("#indiv-results-modal-content").html(html);
                //let's use the anchor "title" attribute as modal window title
                //            $modal.fadeIn("slow");
                //                jqmWindowShow($modal,45,150);

            }
        });
    };

    var closeIndivResultsModal = function () {
        jqmWindowHide($("#indiv-results-modal"));
    };

    var setupMyAccountModal = function() {
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_my_account_setup;
        AJAXRequestDict['dataFields'] = {};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error retrieving your account information.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#ma-modal-content").html(html);
                jqmWindowShow($("#my-account-modal"), 45, 150);
            }
        });
    };

    var setupMyAccountDialog = function() {
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_my_account_setup;
        AJAXRequestDict['dataFields'] = {};

        $.ajax({
            async: true,
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error retrieving your account information.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#ma-dialog-content").html(html);
            }
        });
    };

    var saveMyAccountChanges = function() {
        var AJAXRequestDict = {},
                responseDataDict,
                posAccum = 0;


        $(".chk-pos:checked").each(function() {
            posAccum += parseInt($(this).val()); //this assumes that the value of the input field = 2^(bitPosition - 1)
        });

        AJAXRequestDict['reqType'] = requestHandler.req_my_account_save;
        AJAXRequestDict['dataFields'] = {
            name:$("#maName").val(),
            email:$("#maEmail").val(),
            pwd:$("#maPwd").val(),
            phone:$("#maPhone").val(),
            pos:posAccum
        };

        $.ajax({
            dataType: "json",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error saving your account information.  Msg: " + txtStatus);
            },
            success: function(json) {
                var emailUsed = json["emailUsed"];
                if (emailUsed) {
                    alert("this email address is already being used.  Please choose another.")
                }
                else {
                    closeMyAccountModal();
                    $("#welcome-area-name").text($("#maName").val());
                    $("#ma-modal-content").html("");
                }
            }
        });
    };

    var closeMyAccountModal = function () {
        jqmWindowHide($("#my-account-modal"));
    };


    var setupSFDialog = function(e, ui) {
        var $container = $(this);
        var xOffset = e.pageX + 10;
        var yOffset = e.pageY - $("#dialog-survey-function").dialog().outerHeight() / 2;
        $("#dialog-survey-function").dialog("option", "position", [xOffset,yOffset]);
        $("#dialog-survey-function").attr("holdIdCS", extractObjectId($container.attr("id")));
        $("#sf-dialog-content").html($container.children(".sl-item-functions").children(".sl-item-function-html").html());
/*
        $("#sf-dialog-title").html("<div style=\"font-size: 1.1em;font-weight:bold;\">" + $(".sl-item-title", $container).text() + "</div>");
*/

        $("#dialog-survey-function").dialog("option","title",$(".sl-item-title",$container).text());
        $("#dialog-survey-function").dialog("open");
    };

    var closeSFAccountModal = function () {
        jqmWindowHide($("#survey-function-modal"));
    };

    var maContainerFill = function(e, ui) {
        var AJAXRequestDict = {},
                responseDataDict;
        var $maTrigger = $(this);
        var $parent = $maTrigger.parents(".survey-list-item");
        var id = $parent.attr("id");
        AJAXRequestDict['reqType'] = requestHandler.req_survey_access_lookup;
        AJAXRequestDict['dataFields'] = {
            idCS:$("#dialog-survey-function").attr("holdIdCS")
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error retrieving survey access information.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#dialog-ma-content").html(html);
                $("#dialog-manage-access").attr("holdIdCS", $("#dialog-survey-function").attr("holdIdCS"))
                $("#dialog-survey-function").dialog("close");
                $("#dialog-manage-access").dialog("open");
            }
        });
    };

    var iaContainerFill = function(e, ui) {
        var AJAXRequestDict = {},
                responseDataDict;
        AJAXRequestDict['reqType'] = requestHandler.req_init_survey_access_invite;
        AJAXRequestDict['dataFields'] = {
            idCS:$("#dialog-survey-function").attr("holdIdCS")
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error retrieving survey invite information.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#dialog-ia-content").html(html);
                $("#dialog-invite-access").attr("holdIdCS", $("#dialog-manage-access").attr("holdIdCS"))
                $("#dialog-invite-access").dialog("open");
            }
        });
    };

    var saeContainerFill = function(e, ui) {
        var AJAXRequestDict = {},
                responseDataDict;
        var userId = $(this).attr("userId");
        var view = $(this).text() == "view";
        AJAXRequestDict['reqType'] = requestHandler.req_init_survey_sub_access;
        AJAXRequestDict['dataFields'] = {
            idCS: $("#dialog-manage-access").attr("holdIdCS"),
            userId: userId
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error retrieving survey sub-access information.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#dialog-sub-access-edit").attr("holdUserId",userId);
                $("#dialog-sae-content").html(html);
                if (view) {
                    $("#dialog-sub-access-edit").dialog("option","buttons",{
                    Close: function() {
                        $(this).dialog("close");
                    }
                    });
                }
                else {
                    $("#dialog-sub-access-edit").dialog("option","buttons",{
                    Save: saveSubAccess,
                    Cancel: function() {
                        $(this).dialog("close");
                    }
                    });
                }
                $("#dialog-sub-access-edit").dialog("open");
            }
        });
    };

    var saveSubAccess = function() {
        var AJAXRequestDict = {},
                responseDataDict;
        var $maTrigger = $(this);
        var $parent = $maTrigger.parents(".survey-list-item");
        var id = $parent.attr("id");
        var choices = {};
        var idx = 0;
        $(".chk-sub-choice:checked").each(function() {
            choices[idx++] = $(this).val();
        });
        AJAXRequestDict['reqType'] = requestHandler.req_edit_survey_sub_access;
        AJAXRequestDict['dataFields'] = {
            idCS: $("#dialog-manage-access").attr("holdIdCS"),
            userId: $("#dialog-sub-access-edit").attr("holdUserId"),
            choices: choices
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error setting survey access information.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#dialog-sub-access-edit").dialog("close");
                infoDialogs.alertDialog(html);
                $("#dialog-sae-content").html("");

            }
        });
    };


    var validateAccessInvite = function() {
        var AJAXRequestDict = {},
                responseDataDict;
        if (trimAll($("#txtName").val()) == "" ||
            trimAll($("#txtEmail").val()) == "") {
            infoDialogs.alertDialog("Please enter both a name and email address for this person.");
            return false;
        }
        if ($(".rdLvl:checked").length == 0) {
            infoDialogs.alertDialog("Please be sure to select an access level for this person.");
            return false;
        }

        var $maTrigger = $(this);
        var $parent = $maTrigger.parents(".survey-list-item");
        var id = $parent.attr("id");
        var choices = {};
        var idx = 0;
        $(".chk-sub-choice:checked").each(function() {
            choices[idx++] = $(this).val();
        });
        AJAXRequestDict['reqType'] = requestHandler.req_survey_access_invite;
        AJAXRequestDict['dataFields'] = {
            idCS: $("#dialog-manage-access").attr("holdIdCS"),
            name: $("#txtName").val(),
            email: $("#txtEmail").val(),
            level: $(".rdLvl:checked").val(),
            notify: $("#chkEmail").is(":checked"),
            choices: choices
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error setting survey access information.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#dialog-invite-access").dialog("close");
                $("#dialog-ma-content").html(html);
                infoDialogs.alertDialog($("#dialog-ma-content").children(".sub-area").children("#access-msg").html());
                $("#dialog-ia-content").html("");

            }
        });
    };

    var validateAccessChange = function() {
        var AJAXRequestDict = {},
                responseDataDict;

        var $maTrigger = $(this);
        var $parent = $maTrigger.parents(".survey-list-item");
        var id = $parent.attr("id");
        var ids = {};
        var levels = {};
        var idx = 0;
        $(".access-rd:checked").each(function() {
            ids[idx] = $(this).attr("name").substr(5);
            levels[idx] = $(this).val();
            idx++;
        });
        AJAXRequestDict['reqType'] = requestHandler.req_change_user_survey_access;
        AJAXRequestDict['dataFields'] = {
            idCS: $("#dialog-manage-access").attr("holdIdCS"),
            levels: levels,
            notify: $("#chk-email-access-change").is(":checked"),
            ids : ids
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error updating survey access information.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#dialog-ma-content").html(html);
                infoDialogs.alertDialog($("#dialog-ma-content").children(".sub-area").children("#access-msg").html());

            }
        });
    };

    var sendReminder = function() {
        var AJAXRequestDict = {},
                responseDataDict;

        var $maTrigger = $(this);
        var $parent = $maTrigger.parents(".survey-list-item");
        var id = $parent.attr("id");
        var user3Id = $maTrigger.attr("user3Id");
        AJAXRequestDict['reqType'] = requestHandler.req_send_access_reminder;
        AJAXRequestDict['dataFields'] = {
            idCS: $("#dialog-manage-access").attr("holdIdCS"),
            id : user3Id
        };

        $.ajax({
           dataType: "html",
           data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
           error: function(AJAXReqObj, txtStatus, exception) {
               infoDialogs.alertDialog("There was an error sending your email reminder.  Msg: " + txtStatus);
           },
           success: function(html) {
               $("#dialog-ma-content").html(html);
               infoDialogs.alertDialog($("#dialog-ma-content").children(".sub-area").children("#access-msg").html());

           }
        });
    };

    var validateAccessRequest = function() {
        var AJAXRequestDict = {},
                responseDataDict;
        var $raTrigger = $(this);
        var $parent = $raTrigger.parents(".survey-list-item");
        var id = $parent.attr("id");
        AJAXRequestDict['reqType'] = requestHandler.req_survey_access_request;

        AJAXRequestDict['dataFields'] = {
            idCS: $("#dialog-request-access").attr("holdIdCS"),
            comment: $("#ta-ra").val()
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                $("#dialog-request-access").dialog("close");
                infoDialogs.alertDialog("There was an error with your survey access request.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#dialog-request-access").dialog("close");
                infoDialogs.alertDialog(html);

            }
        });
    };

    var validateAccessGrant = function(e, ui) {
        var AJAXRequestDict = {},
                responseDataDict;
        if ($(".rdLvl:checked").length == 0) {
            infoDialogs.alertDialog("Please be sure to select an access level for this person.");
            return false;
        }

        var $gaTrigger = $(this);

        AJAXRequestDict['reqType'] = requestHandler.req_survey_access_grant;
        AJAXRequestDict['dataFields'] = {
            idAR: $gaTrigger.attr("idAR"),
            grantorId: $gaTrigger.attr("guid"),
            level: $(".rdLvl:checked").val()
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error processing your request.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#ar-wrapper").html(html);
            }
        });
    };

    var eipEdit = function(e, ui) {
        var $thisEip = $(this).parents(".eip");

        if (!$thisEip.hasClass("eip-edit")) {
            //var thiseip = ".eip:eq(" + i + ")";

            $thisEip.addClass("eip-edit");
            var $profileItem = $(this).parents(".profile-item");
            var saveWidth = $profileItem.width();
            //$profileItem.width("300px");

            var width = $(this).width() + 50;
            var currentText = $thisEip.children(".eip-wrap").text(),
                    eipInput;
            $thisEip.attr("saveIt",currentText);

            if ($thisEip.is(".eip-date")) {
                eipInput = '<span class="eip-wrap"><input id="prof-dob-datepicker_' + $thisEip.attr("field") + '" type="text" class="eip-text prof-dob-datepicker" value=" " style="width:150px;"/></span><span><button value="save" class="eip-btn eip-save ui-state-default">save</button>&nbsp;<button value="cancel" class="eip-btn eip-cncl ui-state-default">cancel</button></span>';
            }
            else {
                eipInput = '<span class="eip-wrap"><input type="text" class="eip-text" value=" " style="width:' + width + 'px;"/></span><span><button value="save" class="eip-btn eip-save ui-state-default">save</button>&nbsp;<button value="cancel" class="eip-btn eip-cncl ui-state-default">cancel</button></span>';
            }

            $thisEip.html(eipInput);
            $profileItem.addClass("rel-overlay");
            if($thisEip.is(".eip-date")) {
                if (currentText == "N/A"){
                    currentText = "mm/dd/yyyy";
                }
                $(".eip-text", $thisEip).attr('value', currentText);

                $(".prof-dob-datepicker").click();

            }
            else {
                $(".eip-text", $thisEip).attr('value', currentText).select();
            }
        }
    };

    var eipSave = function(e, ui) {
        e.preventDefault();
        e.stopPropagation();

        var $thisEip = $(this).parents(".eip"),
                thisEipText = $('.eip-text', $thisEip).attr('value'),
                thisProfileId =
                AJAXRequestDict = {};

        if (thisEipText == "") {
            thisEipText = "Click here to add your title";
        }
        $thisEip.text(thisEipText);
        $thisEip.wrapInner("<span class=\"eip-wrap eip-text\" title=\"Click to edit...\"></span>");
        $thisEip.removeClass("eip-edit");

        AJAXRequestDict['reqType'] = requestHandler.req_update_profile_info;
        AJAXRequestDict['dataFields'] = {
            value: thisEipText,
            field: $thisEip.attr("field"),
            idIndiv: $thisEip.parents("#profile-container").attr("idIndiv")};

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error processing your profile update.  Msg: " + txtStatus);
            },
            success: function(html) {
            }
        });
    };

    var eipClose = function(e, ui) {
        e.preventDefault();
        e.stopPropagation();

        var $thisEip = $(this).parents(".eip"),
                thisEipText = $('.eip-text', $thisEip).attr('value');

        $thisEip.text($thisEip.attr("saveIt"));
        $thisEip.wrapInner("<span class=\"eip-wrap eip-text\" title=\"Click to edit...\"></span>");
        $thisEip.removeClass("eip-edit");
    };

    var nsContainerFill = function(e, ui) {
        var xOffset = e.pageX + 10;
        var yOffset = e.pageY - 200;
        $("#dialog-unf-ns").dialog("option", "position", [xOffset,yOffset]);
        var AJAXRequestDict = {},
                responseDataDict;

        AJAXRequestDict['reqType'] = requestHandler.req_unf_ns;
        AJAXRequestDict['dataFields'] = {
            idCS:$("#dialog-survey-function").attr("holdIdCS")
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                infoDialogs.alertDialog("There was an error retrieving your unfinished/not started data.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#dialog-un-content").html(html);
                $("#dialog-unf-ns").attr("holdIdCS", $("#dialog-survey-function").attr("holdIdCS"))
                $("#dialog-survey-function").dialog("close");
                $("#dialog-unf-ns").dialog("open");
            }
        });
    };

    var rebuildLogin = function() {
        $("#pwd-label").show();
        $("#password").show();
        $("#forgot-link").show();
        $("#login-button").removeClass("forgot-button");
        $("#login-button").attr("value","Sign in");
        $("#login-spin").text("Please wait while we validate your credentials...");
        $("#login-spin").hide();
        $("#login-error").hide();
        $("#forgot-desc").hide();
        $("#forgot-cancel").hide();
    };


    var addWehuddleTab = function() {
        $("#survey-home-tabs").tabs("add",
                                    "#wehuddle-tab-area",
                                    "wehuddle");

         doWehuddleTab = true;
        wehuddleTabIndex = $("#survey-home-tabs").tabs("length") - 1;
    };

    var addScorecardTab = function() {
        //$("#survey-home-tabs").tabs("add","#scorecards-tab-area","Score Cards",2);
        $("#survey-home-tabs").tabs("add","#scorecards-tab-area","Score Cards",2);
        doScoreCardTab = true;
        scoreCardTabIndex = 2;
    };

    var removeScorecardTab = function() {
        if (doScoreCardTab) {
            $("#survey-home-tabs").tabs("remove",scoreCardTabIndex);
        }
        doScoreCardTab = false;
    };

    var getScorecardTabInit = function() {
        return "<div id=\"scorecards-container\"></div>";
    };

    var getWehuddleTabInit = function() {
        return "<div id=\"wehuddle-container\"></div>";
    };

    var weQuestions = function(e, ui) {
        var AJAXRequestDict = {},
                responseDataDict;
        $("#dialog-we-q-content").html(spinner.getSpinnerHTML("Please wait while we gather the questions..."));
        AJAXRequestDict['reqType'] = requestHandler.req_wehuddle_template_questions;
        AJAXRequestDict['dataFields'] = {
            templateId : $(this).attr("templateId")
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error while retrieving the wehuddle questions.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#dialog-we-q-content").html(html);
                $("#dialog-we-q").dialog("open");
            }
        });
    };

    var weSelect = function(e, ui) {
        var AJAXRequestDict = {},
                responseDataDict;
        $("#we-detail").html("");
        $("#we-title").html(spinner.getSpinnerHTML("Please wait while we scrape together the details..."));
        initSurveyList();
        AJAXRequestDict['reqType'] = requestHandler.req_select_wehuddle;
        AJAXRequestDict['dataFields'] = {
            templateId : $(this).attr("templateId")
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error while retrieving the wehuddle info.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#we-content-area").html(html);
            }
        });
    };

    var weLaunchInit = function(e, ui) {
        var AJAXRequestDict = {},
                responseDataDict;
        initSurveyList();
        AJAXRequestDict['reqType'] = requestHandler.req_wehuddle_launch_init;
        AJAXRequestDict['dataFields'] = {
            instId : $("#survey-access-list").val(),
            templateId : $(this).attr("templateId")
        };

        $.ajax({
            dataType: "html",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error while initializing your wehuddle launch.  Msg: " + txtStatus);
            },
            success: function(html) {
                $("#dialog-wr-content").html(html);
                $("#dialog-wehuddle-reg").attr("attempt",$("#wehuddle-wrapper").attr("attempt"));
                $("#dialog-wehuddle-reg").attr("templateId",$("#wehuddle-wrapper").attr("templateId"));
                $("#dialog-wehuddle-reg").dialog("open");
            }
        });
    };

    var weRegister = function(e,ui) {
        var AJAXRequestDict = {},
                responseDataDict;
        //initSurveyList();
        AJAXRequestDict['reqType'] = requestHandler.req_launch_wehuddle;
        AJAXRequestDict['dataFields'] = {
            instId : $("#survey-access-list").val(),
            templateId : $("#wehuddle-launch-wrapper").attr("templateId"),
            attempt : $("#wehuddle-launch-wrapper").attr("attempt")
        };

        $.ajax({
            dataType: "json",
            data: {ajaxRequest: JSON.stringify(AJAXRequestDict)},
            error: function(AJAXReqObj, txtStatus, exception) {
                alert("There was an error while changing institutions.  Msg: " + txtStatus);
            },
            success: function(json) {
                responseDataDict = json["outputs"];
                var newIdCS = responseDataDict["newIdCS"];
                if (newIdCS == 0) {
                    alert("All available trials were used up while your were thinking about trying.");
                }
                else {
                    $("#dialog-wehuddle-reg").dialog("close");
                    window.open(docRoot + "/genPDF?docType=101&idCS=" + newIdCS,"_blank");
                }
            }
        });
    };

    var $mainTabs;
    var doScoreCardTab = false;
    var doWehuddleTab = false;
    var scoreCardTabIndex = 0;
    var wehuddleTabIndex = 0;

    // |*|*|*|*|*|*|*|*|*|*|*|*|*|*|*|*|*|  R E A D Y   S T A T E   C O D E  |*|*|*|*|*|*|*|*|*|*|*|*|*|*|*|*|*|


    $(document).ready(function() {
        $("body").hide();
        $.ajaxSetup({
            url: AJAX_URL,
            async: false,
            type: 'POST',
            dataType: 'html',
            //contentType: 'json',
                        contentType: 'application/x-www-form-urlencoded',
            timeout: 10000
        });

        var smartupdaterHtml = "<div id='smartupdater-div' class='ui-helper-hidden data'></div>";
        $("body").prepend(smartupdaterHtml);

        $("#smartupdater-div").smartupdater({
            url: docRoot + "/howdy",
            minTimeout: 1000*60*10  //(millis per sec) * (secs per min) * (# min)
                               },
                               function(data) {
                                   //do nothing
                               }
        );

        if ($("#login-form").length > 0) {
            $("#email").focus();
        }
        else if($("#ar-container").length > 0) {

        }
        else {
            //initialize the institution access list
            buildInstAccess();
        }

        $("button.ui-state-default").livequery(function() {
            $(this).hover(
                    function() {
                        $(this).addClass("ui-state-hover")
                    },
                    function() {
                        $(this).removeClass("ui-state-hover")
                    }
                    )
        });

        $(".j-button").livequery(function() {
            $(this).addClass("ui-state-default");
            $(this).hover(
                    function() {
                        $(this).addClass("ui-state-hover")
                    },
                    function() {
                        $(this).removeClass("ui-state-hover")
                    }
                    )
        });

        $(".stripe-me").livequery(function () {
            $(this).children(".stripeable:even").addClass("alt");
        });

        $("#login-button").livequery(function() {
            $(this).bind("click",function(e,ui) {
                attemptLogin(e,ui);
            });
        });

        $("#forgot-pwd").livequery(function () {
            $(this).bind("click",function(e,ui) {
                e.preventDefault();
                e.stopPropagation();
                $("#pwd-label").hide();
                $("#password").hide();
                $("#forgot-link").hide();
                $("#login-button").addClass("forgot-button");
                $("#login-button").attr("value","Send reminder");
                $("#login-spin").hide();
                $("#login-error").hide();
                $("#forgot-desc").show();
                $("#forgot-cancel").show();
            });
        });

        $("#forgot-cancel").livequery(function () {
            $(this).bind("click",function(e,ui) {
                rebuildLogin();
            });
        });

        $(".sl-item-vr").livequery(function() {
            $(this).bind("click", function() {
                //var func = $(this).attr("func-click"); // get onclick
                $("#dialog-survey-function").dialog("close");
                //eval(func); //execute the onclick function for this item
                $("#frm-inst-id").val($(this).attr("instId"));
                $("#frm-idCS").val($(this).attr("idCS"));
                var chkItem = $(this).attr("instId") + ";" + $(this).attr("idCS") + ";";
                $("#frm-chk-item").val(chkItem);
                $("#results-form").submit();
            });
        });

        $(".scorecard-trigger").livequery(function() {
            $(this).bind("click", function() {
                $("#frm-inst-id").val($("#survey-access-list").val());
                $("#frm-scorecard").val($(this).attr("idSC"));
                $("#results-form").submit();
                $("#frm-scorecard").val("");
            });
        });

        $(".sl-item-pv").livequery(function() {
            $(this).bind("click", function() {
                var func = $(this).attr("func-click"); // get onclick
                $("#dialog-survey-function").dialog("close");
                eval(func); //execute the onclick function for this item
            });
        });


        $(".sl-item-kk").livequery(function() {
            $(this).bind("click", function() {
                var func = $(this).attr("func-click"); // get onclick
                $("#dialog-survey-function").dialog("close");
                eval(func); //execute the onclick function for this item
            });
        });

        $(".sl-item-upd-so1").livequery(function() {
            $(this).bind("click", function() {
                var func = $(this).attr("func-click"); // get onclick
                $("#dialog-survey-function").dialog("close");
                eval(func); //execute the onclick function for this item
            });
        });

        $(".sl-item-ma").livequery(function() {
            $(this).bind("click", maContainerFill);
        });

        $(".survey-access-invite-go").livequery(function() {
            $(this).bind("click", iaContainerFill);
        });

        $(".sub-access-edit-go").livequery(function() {
            $(this).bind("click", saeContainerFill);
        });

        $(".sl-item-ns").livequery(function() {
            $(this).bind("click", nsContainerFill);
        });

        $("#access-invite-button").livequery(function() {
            $(this).bind("click", iaContainerFill);
        });

        /*
         $(".access-results").livequery(function() {
         $(this).bind("click",function() {
         var func = $(".sl-item-vr",$(this)).attr("func-click"); // get onclick
         eval(func); //execute the onclick function for this item
         });
         });
         */

        //$(".access-admin,.access-results,.access-none").livequery(function() {
        $(".access-admin,.access-results").livequery(function() {
            $(this).bind("click", setupSFDialog);
        });


        $(".access-none").livequery(function() {
            $(this).bind("click", function() {
                $("#dialog-request-access").attr("holdIdCS", extractObjectId($(this).attr("id")));
                $("#dialog-request-access").dialog("open");
            });
        });


        /*
         $(".survey-list-item").livequery(function() {


         $(this).bind("mouseenter",function() {
         $(".sl-item-functions").hide();
         $(this).css("height","26px");
         $(this).addClass("ui-state-hover").addClass("ui-widget-content").addClass("ui-corner-all");
         $(this).children(".sl-item-functions").css("display","block");
         });

         $(this).bind("mouseleave",function() {
         $(".sl-item-functions").hide();
         $(this).removeClass("ui-state-hover").removeClass("ui-widget-content").removeClass("ui-corner-all");
         $(this).css("height","28px");
         });
         });
         */

        $(".sl-item-ar").livequery(function() {
            $(this).bind("click", toggleUserSurveyArchive);
        });

        $("#chk-all").livequery(function() {
            $(this).bind("click",function() {
                var $chkAll = $(this);
                $(".access-request-id").each(function() {
                    $(this).attr("checked",$chkAll.attr("checked"));
                });
            });
        });

        $("#survey-list-filter").livequery(function() {
            $(this).bind("change", function() {
                filterText = $(this).children("option:selected").text();
                changeSurveyList("0");
            });
        });

        $("#survey-access-list").livequery(function() {
            $(this).bind("change", function() {
                changeInst();
                //$("#survey-home-tabs").tabs("select", 0);
                loadTabPanel("#survey-list-tab-area");
            });
        });

        /*
         $("#my-account-trigger").livequery(function() {
         $(this).bind("click",setupMyAccountModal);
         })
         */

        $(".reminder-btn").livequery(function() {
            $(this).bind("click",sendReminder);
        });

        $("#my-account-trigger").livequery(function() {
            $(this).bind("click", function() {
                $("#dialog-my-account").dialog("open");
            });
        });

        $(".index-agg-entry-trigger").livequery(function() {
            $(this).bind("click", initIndexAggEntry);
        });

        $("#logout-trigger").livequery(function() {
            $(this).bind("click", attemptLogout);
        });

        $("#we-q-trigger").livequery(function () {
            $(this).bind("click",weQuestions);
        });

        $(".we-launch-trigger").livequery(function () {
            $(this).bind("click",weLaunchInit);
        });

        $(".we-select-trigger").livequery(function () {
            $(this).bind("click",weSelect);
        });

        /*
         $(".indiv-results-modal-trigger").livequery(function() {
         $(this).bind("click",setupIndivResultsModal);
         })
         */

        $("#ar-button").livequery(function() {
            $(this).bind("click", validateAccessGrant);
        });

        $(".indiv-results-modal-trigger").livequery(function() {
            $(this).bind("click", setupIndivResultsDialog);
        });

        $("#maSave").livequery(function() {
            $(this).bind("click", saveMyAccountChanges);
        });

        $("#maPwd").livequery(function() {
            $(this).bind("focus", function () {
                $(this).get(0).select();
            });
        });

        $("#maCnf").livequery(function() {
            $(this).bind("focus", function () {
                $(this).get(0).select();
            });
        });

        $("#resp-profile-search-go").livequery(function() {
            $(this).bind("click", function() {
                $("#search-string").text($("#resp-profile-search-box").val());
                studProfileSearch("0");
            });
        });

        $(".re-search-student").livequery(function() {
            $(this).bind("click", function() {
                studProfileSearch($(this).attr("offset"));
            });
        });

        $(".re-search-survey").livequery(function() {
            $(this).bind("click", function() {
                changeSurveyList($(this).attr("offset"));
            });
        });

        $("#resp-profile-search-box").livequery(function() {
            $(this).bind("focus", function () {
                $(this).select();
            });
            $(this).bind("keypress", function(e) {
                if (e.which == 13) {
                    e.stopPropagation();
                    e.preventDefault();
                    $("#resp-profile-search-go").click();
                }
            });
        });

        $(".search-result-item:not(.zero-result)").livequery(function() {
            $(this).hover(
                    function() {
                        $(this).addClass("ui-state-hover").css("padding", "3px 3px");
                    },
                    function() {
                        $(this).removeClass("ui-state-hover").css("padding", "4px 4px");
                    }
                    );
        });

        $(".student-list-item").livequery(function() {
            $(this).bind("click", function() {
                var idIndiv = extractObjectId($(this).attr("id"));
                retrieveStudentData(idIndiv);
            });
        });

        /*
         $(".ajax-modal-trigger").livequery(function () {
         $(this).bind("click",function() {
         $("#ajax-modal").jqmShow($(this));
         });
         });
         */

        $(".hoverable").livequery(function() {
            $(this).hover(
                    function() {
                        $(this).addClass("ui-state-hover");
                    },
                    function() {
                        $(this).removeClass("ui-state-hover");
                    }
                    );
        });

        $(".rdLvlChg").livequery(function() {
            $(this).bind("click", function() {
                currLvl = $(this).val();
            });
        });

        $("#dialog-we-q-content").livequery(function() {
            $(this).bind("mousedown", function(e) {
                e.stopPropagation();
                e.preventDefault();
            });
            $(this).bind("contextmenu", function(e) {
                e.stopPropagation();
                e.preventDefault();
            });
            $(this).bind("select", function() {
                e.stopPropagation();
                e.preventDefault();
            });
        });

        //************************* D A T E P I C K E R   A R E A *****************************

        $(".prof-dob-datepicker").live("click",function() {
            $(this).datepicker({
                changeMonth: true,
                changeYear: true,
                showOn: "focus"
            }).focus();
        });

        //************************* D I A L O G   A R E A *************************************

        $("#dialog-we-q").dialog({
            autoOpen: false,
            width: 650,
            height: 370,
            modal: true,
            buttons: {
                Close: function () {
                    $(this).dialog("close");
                }
            },
            close: function() {
                $("#dialog-we-q-content").html("");
            }
        });

        $("#dialog-wehuddle-reg").dialog({
            autoOpen: false,
            width: 700,
            height: 550,
            modal: true,
            buttons: {
                Launch: weRegister,
                Cancel: function () {
                    $(this).dialog("close");
                }
            },
            close: function() {
                $("#dialog-wr-content").html("");
            }
        });

        $("#index-agg-entry-dialog").dialog({
            autoOpen: false,
            width: 800,
            height: 600,
            modal: true,
            buttons: {
                Save: aggEntrySave,
                Cancel: function () {
                    $(this).dialog("close");
                }
            },
            close: function() {
                $("#index-agg-entry-content").html("");
            }
        });

        $("#dialog-forgot").dialog({
            autoOpen: false,
            height: 100,
            width: 350,
            modal: true,
            buttons: {
                'Send me the email': sendForgotEmail
            },
            close: function() {
            }
        });
        
        $("#dialog-unf-ns").dialog({
            bgiframe: true,
            autoOpen: false,
            modal: true,
            width: 400,
            position: ["center","center"],
            buttons: {
                'print list...': function() {
                    $("#printable-un-content").html($(this).children("#dialog-un-content").html());
                    $("#printable-unf-ns").print();
                },
                'print cards...': function() {
                    window.open(docRoot + "/unfCards.pdf?m=unfResp10Up&idCS=" + $(this).attr("holdIdCS"),"_blank");
                }
            },
            close: function() {
            }
        });

        $("#dialog-my-account").dialog({
            bgiframe: true,
            autoOpen: false,
            width: "650",
            modal: true,
            position: ["center",200],
            buttons: {
                'Save Changes': function() {
                    saveMyAccountChanges();
                    $(this).dialog("close");
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            },
            open: setupMyAccountDialog,
            close: function() {
                $("#ma-dialog-content").html("");
            }
        });

        $("#dialog-survey-function").dialog({
            bgiframe: true,
            autoOpen: false,
            title: "Survey Access Options",
            //            width: "auto",
            width: "500",
            modal: true,
            position: ["center","center"],
            close: function() {
            }
        });

        $("#dialog-manage-access").dialog({
            bgiframe: true,
            autoOpen: false,
            title: "Manage Survey Access",
            width: "700px",
            minWidth: "700px",
            modal: true,
            position: ["center","center"],
            buttons: {
                Save: validateAccessChange,
                Close: function() {
                    $(this).dialog("close");
                }
            },
            close: function() {
            }
        });

        $("#dialog-invite-access").dialog({
            bgiframe: true,
            autoOpen: false,
            title: "Invite New User",
            width: "350",
            minWidth: "350px",
            modal: true,
            position: ["center","center"],
            buttons: {
                Invite: validateAccessInvite,
                Cancel: function() {
                    $(this).dialog("close");
                }
            },
            close: function() {
                $("#dialog-ia-content").html("");
            }
        });

        $("#dialog-sub-access-edit").dialog({
            bgiframe: true,
            autoOpen: false,
            title: "Assign subset access",
            width: "350px",
            minWidth: "350px",
            modal: true,
            position: ["center","center"],
            close: function() {
                $("#dialog-sae-content").html("");
            }
        });

        $(".change-access-level-trigger").livequery(function() {
            $(this).bind("click", function(e, ui) {
                if ($(this).attr("so1") == "true") {
                    $("#al-switch-2").hide();
                    $("#al-switch-1").hide();
                }
                else {
                    $("#al-switch-2").show();
                    $("#al-switch-1").show();
                }
                var xOffset = e.pageX - $("#dialog-change-access").dialog("option", "width") - 10;
                var yOffset = e.pageY - $("#dialog-change-access").dialog("option", "height") / 2;
                holdLvl = $(this).attr("currLvl");
                currLvl = holdLvl;
                $("#dialog-change-access").dialog("option", "position", [xOffset,yOffset]);
                $("#dialog-change-access").dialog("option", "title", "Change survey access for: " + $(this).attr("userName"));
                $("#dialog-change-access").attr("userId", $(this).attr("userId"));
                $("#dialog-change-access").children("fieldset").children(".rdLvlChg").each(function () {
                    if ($(this).val() == holdLvl) {
                        $(this).click();
                    }
                });
                $("#dialog-change-access").dialog("open");
            });
        });

        $("#dialog-change-access").dialog({
            bgiframe: true,
            autoOpen: false,
            title: "Change Access for: ",
            height: 210,
            width: 375,
            minWidth: 375,
            modal: true,
            position: ["center","center"],
            buttons: {
                Save: function() {
                    saving = true;
                    $(this).dialog("close");
                    if (lvlChanged(currLvl)) {
                        validateAccessChange();
                    }
                    else
                    {
                        infoDialogs.alertDialog("No change was made to the current access Level");
                    }
                }
            },
            beforeclose: function() {
                return saving || !lvlChanged(currLvl) || confirm("Changes have not been saved.\nTo continue closing without saving click 'OK'.\nOtherwise click cancel.");
            },
            close: function() {

            }
        });

        $("#dialog-request-access").dialog({
            bgiframe: true,
            autoOpen: false,
            title: "Request Survey Access",
            width: "500px",
            minWidth: "500px",
            modal: true,
            position: ["center","center"],
            buttons: {
                Send: function() {
                    validateAccessRequest();
                    $(this).dialog("close");
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            },
            close: function() {
            }
        });


        $("#dialog-indiv-results").dialog({
            bgiframe: true,
            autoOpen: false,
            title: "Individual Survey Results",
            modal: true,
            close: function() {
            }
        });

        $("#dialog-alert").dialog({
            bgiframe: true,
            autoOpen: false,
            title: "Notice",
            modal: true,
            buttons: {
                OK : function() {
                    $(this).dialog("close");
                }
            },
            close: function() {
            }
        });

        $("#dialog-confirm").dialog({
            bgiframe: true,
            autoOpen: false,
            title: "Confirmation needed",
            modal: true,
            buttons: {
                OK : function() {
                    $(this).dialog("close");
                },
                Cancel : function() {
                    $(this).dialog("close");
                }
            },
            close: function() {
            }
        });


        var loadInIframeModal = function(hash) {
            hash.w.css("width", "85%");
            var modalWidth = hash.w.width(),
                    bodyWidth = $("body").width(),
                    modalLeft = (bodyWidth - modalWidth) / 2;

            hash.w.css('height', windowUtils.windowHeight() - 100);
            hash.w.css('left', modalLeft);
            hash.w.css('margin-left', "0");
            var $trigger = $(hash.t);
            var $modal = $(hash.w);
            var myUrl = $trigger.attr('ajaxUrl');
            var myTitle = $trigger.attr('title');
            var $modalContent = $("iframe", $modal);
            $modalContent.html('').attr('src', myUrl);
            //let's use the anchor "title" attribute as modal window title
            $('#ajax-modal-title-text').text(myTitle);
            //            $modal.fadeIn("slow");
            $modal.show();
        };

        // initialize ajax-modal
        /*
         var $ajaxModal = $('#ajax-modal').jqm({
         modal: true,
         target: '#ajax-modal-content',
         closeClass: "ajax-modal-close",
         onShow:  loadInIframeModal
         });
         */

        // initialize indiv-results-modal
        /*
         var $indivRModal = $('#indiv-results-modal').jqm({
         modal: false,
         closeClass: "indiv-results-modal-close"
         });
         */


        //************************* E I P   A R E A *****************************************************

        $('.eip-cncl').livequery('click', eipClose);
        $('.eip-save').livequery('click', eipSave);

        $('span.eip-wrap').livequery('click', eipEdit);



        $(".eip").livequery(function () {
            var spanTitle = "Click to edit..."
            $(this).wrapInner("<span class=\"eip-wrap eip-text\" title=\"" + spanTitle + "\"></span>");
        });


        //************************* V A L I D A T I O N   A R E A ***************************************

        $("#my-account-form").livequery(function() {
            $(this).validateCommon({
                rules:{
                    maName: { required: true},
                    maEmail: {
                        required: true,
                        email: true
                    },
                    maCnf: {equalTo:"#maPwd"}
                },
                messages: {
                    maName: "Name is a required field.",
                    maEmail: {
                        required: "Email is a required field.",
                        email: "Please enter a valid email adress."
                    },
                    maCnf: {
                        equalTo: "Password fields must match."
                    }
                },
                submitHandler: function (form) {
                    return false;
                }
            });
        });

        //************************* T O O L T I P   A R E A ***************************************

        $(".help-icon").livequery(function() {
            $(this).tooltip({
                delay: 400,
                track: true,
                showURL: false,
                fade: 100,
                bodyHandler: function() {
                    return $(this).attr("tip-text");
                }
            });
        });

        $(".has-helpful-info").livequery(function() {
            $(this).tooltip({
                delay: 400,
                track: true,
                showURL: false,
                fade: 100,
                bodyHandler: function() {
                    return $(this).attr("helpful-text");
                }
            });
        });
        //************************* T A B S   A R E A ***************************************

        $mainTabs = $('#survey-home-tabs').tabs({
            selected: 0,
            spinner: "Retrieving data...",
            show: function (e, ui) {
                var theTab = ui.tab;
                loadTabPanel(theTab.hash);
            },
            select: function (e, ui) {
                var theTab = ui.tab;
                loadTabPanel(theTab.hash);
            },
            add: function (e, ui) {
                var content = "Not able to process request!";
                var theTab = ui.tab;
                if (theTab.hash == "#wehuddle-tab-area") {
                    content = getWehuddleTabInit();
                }
                else if (theTab.hash == "#scorecards-tab-area") {
                    content = getScorecardTabInit();
                }
                $(ui.panel).append(content);
            }
        });

        //************************  T A B L E   S O R T E R S ************************************
        $("#tbl-indexes").livequery(function() {
            $(this).tablesorter({
                sortList : [
                    [1,1],
                    [0,0]
                ]
            });
        });

        $("#tbl-surveys").livequery(function() {
            $(this).tablesorter({
                sortList : [
                    [1,1],
                    [0,0]
                ]
            });
        });

        $("#tbl-unf-ns-data").livequery(function() {
            $(this).tablesorter({
                sortList : [
                    [0,0],
                    [1,0]
                ]
            });
        });

        if (doScoreCardTab) {
            addScorecardTab();
        }

        if (doWehuddleTab) {
            addWehuddleTab();
        }

        $("body").show();

        if (typeof(ft) != "undefined" && ft) {
            ft = !ft;
            $("#dialog-my-account").dialog("open");
        }

    });

})(jQuery);


// Create a jquery plugin that prints the given element.
jQuery.fn.print = function() {
    // NOTE: We are trimming the jQuery collection down to the
    // first element in the collection.
    if (this.size() > 1) {
        this.eq(0).print();
        return;
    } else if (!this.size()) {
        return;
    }

    // ASSERT: At this point, we know that the current jQuery
    // collection (as defined by THIS), contains only one
    // printable element.

    // Create a random name for the print frame.
    var strFrameName = ("printer-" + (new Date()).getTime());

    // Create an iFrame with the new name.
    var jFrame = $("<iframe name='" + strFrameName + "'>");

    // Hide the frame (sort of) and attach to the body.
    jFrame
            .css("width", "1px")
            .css("height", "1px")
            .css("position", "absolute")
            .css("left", "-9999px")
            .appendTo($("body:first"))
            ;

    // Get a FRAMES reference to the new frame.
    var objFrame = window.frames[ strFrameName ];

    // Get a reference to the DOM in the new frame.
    var objDoc = objFrame.document;

    // Grab all the style tags and copy to the new
    // document so that we capture look and feel of
    // the current document.

    // Create a temp document DIV to hold the style tags.
    // This is the only way I could find to get the style
    // tags into IE.
    var jStyleDiv = $("<div>").append(
            $("style").clone()
            );

    // Write the HTML for the document. In this, we will
    // write out the HTML of the current element.
    objDoc.open();
    objDoc.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
    objDoc.write("<html>");
    objDoc.write("<body>");
    objDoc.write("<head>");
    objDoc.write("<title>");
    objDoc.write(document.title);
    objDoc.write("</title>");
    objDoc.write("<style>@media print{.printable-no {display: none;}}</style>");
    objDoc.write(jStyleDiv.html());
    objDoc.write("</head>");
    objDoc.write(this.html());
    objDoc.write("</body>");
    objDoc.write("</html>");
    objDoc.close();

    // Print the document.
    objFrame.focus();
    objFrame.print();

    // Have the frame remove itself in about a minute so that
    // we don't build up too many of these frames.
    setTimeout(
            function() {
                jFrame.remove();
            },
            (60 * 1000)
            );
};


