﻿// #### Start Up code ####


$(function() {
    setupFeedback();
    setupExpandingSections();

    // All popup message div should have a close element.  Clicking on this runs CloseMessage fn
    $("div.popupMessage .close").click(function() { closeMessage(this) });
    //Setup ViewTutorial divs
    $("#ViewTutorial").click(function() {
        $("#TutorialSection").slideToggle("slow", function() {
            var txt = $("#ViewTutorial").html()
            if (txt == "hide tutorial") { $("#ViewTutorial").html("view tutorial"); }
            else { $("#ViewTutorial").html("hide tutorial"); }
        });
    });
});

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

//Selects list of Users On GroupUsers control 
function SelectedUserIDs() {

    var target = "input[id$='cbUserSelected']";
    if (arguments.length == 0) { target += ":checked "; }
    var ids = new Array();
    $(target).each(
                   function() { ids.push($(this).parent().find("input:hidden[id$='hdSelUserID']").val()); }
         );

    return ids;
}

function MGSSummaryUserIDs() {
    var ids = new Array();
    $("tr.candidateRow").each(function() {
        var E = $(this).find("a.MGSSum");
        if (E != undefined && E.length > 0) {
            ids.push($(this).find("td p input:hidden[id$='hdSelUserID']").val())
        } 
    });
    return ids;
}

function ToggleCheckBoxesState(Source, ID) {

    $("input[id$='" + ID + "']").each(function() {
        $(this).attr('checked', $(Source).attr('checked'));

        if ($(Source).attr('checked')) {
            $(this).parent().parent().parent().addClass("selected")
        }
        else {
            $(this).parent().parent().parent().removeClass("selected")
        }        
    }
   );
}

//Class for constructing data ready for JSON post. Use Function $.toJSON to convert
function PostData() {
    var a = arguments;
    var d = {};
    d.command = a[0];
    for (i = 1; i < a.length; i += 2) {
        d[a[i]] = a[i + 1];
    }
    this.JSON = d;
    this.addValue = addValue;
}
//Function for PostData class
function addValue(name, value) {
    this.JSON[name] = value;
}
// Class for creating an array of checkbox selections
function cbArray(K, Container, cbGroup) {
    this.key = K;
    var A = new Array();
    $("#" + Container + " :input:checked[id^=" + cbGroup + "]").each(function() {
        var o = {}; o.key = $(this).attr("id"); o.value = $(this).val();
        A.push(o);
    });
    this.value = A;
}

//MCQ Exam class
function Exam() {
    var a = arguments;
    this.key = a[0].key + a[0].value;
    var attr = new Array();
    for (i = 1; i < a.length; i += 1) {
        if (a[i] != undefined) { attr.push(a[i]) };
    }
    this.attributes = attr;
}

//MCQ Exam Attribute class
function xA(O, K, L) {
    var E = {};
    var V = $(O).find("#" + K).val();
    V = ((V == 'on') ? 'checked' : V);
    if (V != undefined && V != '') {
        E.key = L;
        E.value = V;
    } else { E = undefined; }
    return E;
}

function NextAspectPage(e, Obj, TargetSection, Cmd) {
    e.preventDefault();

    var scores = new Array;
    var complete = true;

    var sectionName = $(Obj).attr("href");
    var hasErrors = true;

    // are we clicking the restart questionnaire button?
    if (sectionName == "restart") {
        // ensure that the alert isn't displayed
        hasErrors = false;
    } else {
        // need to remove all of the URL string that IE6/7 adds to the href tag
        var snipFrom = sectionName.lastIndexOf("/");
        var snip = sectionName.substring(snipFrom + 1);

        // find our section using the snipped href tag
        var section = $("#" + snip);

        // cycle through all question rows
        $(section).find("#QuestionList #QRow").each(function() {
            // get hidden ID
            // TODO: find a way to pass as parameter, enforces unnecessary rigidity on the HTML. Named class/id selectors would work better.
            var ID = $(this).find("input:hidden").val();

            // get checked radio button answer
            var ans = $(this).find("input:radio:checked").val();

            // determine whether the page has errors
            // TODO: remove from this section and add to page in way of required field validation
            complete = (complete == true && ans != undefined) ? true : false;

            var S = {}; S.key = ID; S.value = ans;
            scores.push(S);
            if (ans == undefined) {
                $(this).addClass("highlight");
                hasErrors = true;
            } else {
                $(this).removeClass("highlight");
                hasErrors = false;
            }

        });
    }

    if (hasErrors) {
        alert("Please ensure that all questions have been answered before progressing");
    } else {
        var readonly = $("#hdAdviserView").val();

        // submit to DB if complete - don't submit if adviser/readonly
        if ((complete.toString().toLowerCase() == 'true') && (readonly.toString().toLowerCase() == 'false')) {
            // TODO: really needs looking at, enforces unnecessary rigidity on the HTML
            var Pg = $.trim($(Obj).parent().find("span").text());
            N = new PostData(Pg, "target", TargetSection, "qtype", Cmd);
            N.addValue("ans", scores);
            N.addValue("userid", $("#hdUserID").val());
            N.addValue("readonly", readonly);
            AJAXpost("CandidateFunctions.asmx/SaveAspects", N, CheckAspectsComplete(Pg, TargetSection));
        }
    }
}

function CheckAspectsComplete(Page, TargetSection) {
    if (Page == 99) {
        var SectId = $('#' + TargetSection).find(' #sectionIdx').val();
        var nextSect = 4; SectId == 3 ? nextSect = 4 : nextSect = 1;
        SwitchMCQTab($(".sectionNav .tab")[nextSect]);
        ShowStatus(SectId, 2, true);
    }
}

function SwitchMCQTab(C) {
    if (C != undefined) {
        $("#navigation_tier2 .sectionNav .tab a").removeClass("current");
        $("div.mcqpanes .paneTab").hide();
        var pane = $(C).find("a").addClass("current").attr("href");
        pane = pane.slice(pane.indexOf("#"), pane.lastIndexOf("#"));
        $(pane + "Section").show();
        return false;
    }
}

//Function to post data to AdviserFunctions web service
function AJAXpost(fn, dObj, callback, ShowM) {
    $.ajax({
        type: "POST",
        url: "/Pages/Services/" + fn,
        data: $.toJSON(dObj),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            if (msg.d != '' && msg.d != "ERROR" && msg.d != undefined) {
                if (msg.d.TransferURL != undefined && msg.d.TransferURL != '') {
                    window.location = msg.d.TransferURL;
                } else {
                    if (msg.d.TargetContainer != "") {
                        $("#" + msg.d.TargetContainer).html(msg.d.NewHTML);
                        if (msg.d.Success) { try { callback(msg.d); } catch (err) { } }
                    } else {
                        if (typeof (ShowM) == "undefined") { ShowM = 'True'; }
                        if (ShowM == 'True' || ShowM == true) { showMessage(msg.d.Message, msg.d.MessageIdx); }
                        if (msg.d.Success) { try { callback(msg.d); } catch (err) { } }
                    }
                }
            } else {
                showMessage(msg.d);
            }
        },
        error: function(xhr, msg, e) {
            showMessage(msg.d);
        }
    });
}

//Function to display MGS Candidate summary on Candidates page
function getCandidateModal(CandID, ReportP) {
    if (CandID > 0) {
        //Show Summary Report
        $("#CurrentSummaryUserID").val(CandID);
        $("#CandSummaryFrame").attr("src", "http://" + ReportP + "pages/summary.aspx?CID=" + CandID + "&RPT=2&SID=1&ADV=False&RT=true");
    } else {
        //Show Report Gen options

    }

    //Set height of contentBox
    var cH = $(window).height();
    $('#SummaryModal').css({ 'height': cH - 80 });
    $('#SummaryContent').css({ 'height': cH - 160 });
    $('#SummaryContent iframe').css({ 'height': cH - 190 });

    //transition effect
    dimTheLights();
    $("#SummaryModal").pause(1000).show(0);
}
function dimTheLights() {
    //Set height and width of mask
    var mH = $(document).height();
    var mW = $(window).width();
    $('#mask').css({ 'width': mW, 'height': mH });

    $('#mask').fadeTo(0, 0.7).fadeIn(1000);
}

function turnOnTheLights() {
    $('#mask').hide();
}

//Function to display a message - either showing a hidden element or via an alert
function showMessage(P, i) {
    //Set height and width of mask

    // close any existing messages
    closeMessage("div.popupMessage .close");
    if ($(P).attr("id") == undefined) {
        if (P != '') { alert(P); }
    } else {
        var div = $(P).find("div.popupMessage div").get(i);
        $(div).css("display", "block");
        $(P).find("div.popupMessage").slideDown(1000, 'easeOutElastic');
    }
}
// Function to Close parent of close element
function closeMessage(obj) {
    $(obj).parent().slideUp(250, 'easeInOutQuad', function() {
        $(this).find("div").css("display", "none");
    });
}



//Functions for User Summary

var _reportPath = "www.morrisby.com/tmoreports/"

function HideMCtrl() { $("#PrevRec, #NextRec, #CandSummaryFrame, #ReportGenOptions, #MoveCopyOptions").hide(); }
function FormatLongUserNames() {
    $(".UserLogin").each(
            function() {
                var login = $.trim($(this).text()).split("/");
                login[0] = $.trim(login[0]);
                if (login[0].length > 45) { $(this).text($(this).text().replace(login[0], "Long Username")); } else { $(this).parent().text($(this).text()) }
            }
        )
}

function SetupPrefinioPopups() {
    $(".PSumPop").parent().hover(
                        function() { $(this).find(".PSumPop").show() },
                        function() { $(this).find(".PSumPop").hide() }
            );
}

function EmailCand(email) {
    if (email.length > 0) {
        window.location = 'mailto:' + email;
    }
}

//Turn Summary on/off based on Role
function SetupSummaryLink() {
    if ($("#IsSuperAdviser").val() == 'True') {
        $(".MGSSum ").show()
        $(".MGSSum ").click(function(e) { $("#PrevRec, #NextRec, #CandSummaryFrame").show(); getCandidateModal($(this).parent().parent().parent().find("td").find("input:hidden[id$='hdUserID']").val(), _reportPath); })
    }
}

function ConnectModalBtns() {
    //Connect 'close modal' button
    $("#CloseModal").click(function(e) { e.preventDefault(); $("#SummaryModal, #mask").hide(); HideMCtrl(); $("body").attr("style", "overflow: scroll"); })
    //Connect Prev/Next summary controls
    $("#PrevRec,#NextRec").click(function(e) {
        e.preventDefault();
        inc = ($(this).attr("id") == 'NextRec') ? 1 : -1;
        var cID = $("#CurrentSummaryUserID").val();
        var IDs = MGSSummaryUserIDs(); //SelectedUserIDs(false);
        var i = 0; var k = 0;
        for (j in IDs) { if (IDs[j] == cID) { k = i; } i++; }
        n = ((k + inc) == IDs.length) ? 0 : k + inc;
        n = (n < 0) ? IDs.length - 1 : n;
        getCandidateModal(IDs[n], _reportPath);
    })

    //Move/Copy options
    $("#LBMOVE, #LBCOPY").click(function(e) {
        e.preventDefault();
        var fn = $(this).attr("name");
        var N = new PostData($(this).attr("name"), "userids", SelectedUserIDs());

        N.addValue("currentgroupid", $("#CurrentGroupID").val());
        N.addValue("newgroupid", $("[id*='GroupsDDL']").val());
        AJAXpost("AdviserFunctions.asmx/CopyMoveUsers", N, function(e) {
            if (fn == "MOVE") {
                N = new PostData("REFRESH", "target", "UserSummaryOuter");
                N.addValue("currentgroupid", $("#CurrentGroupID").val());
                AJAXpost("AdviserFunctions.asmx/RefreshUserList", N);
            }
        });
    });

    //Report generation Options
    $("#ReportGenOptions li").click(function(e) {
        e.preventDefault();
        var N = new PostData($(this).attr("id"), "userids", SelectedUserIDs());
        N.addValue("currentgroupid", $("#CurrentGroupID").val());
        AJAXpost("AdviserFunctions.asmx/BatchOrdered", N);
    });
}

function ConnectGroupOpBtns() {
    //Move/Copy btns
    $(".groupOperations li a").filter("[id='MOVECOPY']").click(function(e) {
        e.preventDefault();
        $("#MoveCopyOptions").show();
        getCandidateModal(0);
    });
    //report generation btns
    $(".groupOperations li a").filter("[id='GETREPORTS']").click(function(e) {
        e.preventDefault();
        $("#ReportGenOptions").show();
        getCandidateModal(0);
    });
    //MCQ Release
    $(".groupOperations li a").filter("[id='lbMCQRelease']").click(function(e) {
        e.preventDefault();
        var N = new PostData($(this).attr("name"), "userids", SelectedUserIDs());
        AJAXpost("AdviserFunctions.asmx/MCQRelease", N, function() {
            N = new PostData("REFRESH", "target", "UserSummaryOuter");
            N.addValue("currentgroupid", $("#CurrentGroupID").val());
            AJAXpost("AdviserFunctions.asmx/RefreshUserList", N);
        });
    });
    //CSV Download
    $(".groupOperations li a").filter("[id='lbDownloadCSV']").click(function(e) {
        e.preventDefault();
        var N = new PostData($(this).attr("name"), "userids", SelectedUserIDs());
        N.addValue("currentgroupid", $("#CurrentGroupID").val());
        N.addValue("msgdiv", "#UserSummary");
        N.addValue("erridx", 0);
        AJAXpost("AdviserFunctions.asmx/DownLoadUsers", N, function(e) {
            window.open(e.NewWindowURL, "Download");
        });
    });


    //Setup Batch emails
    $(".groupOperations li a").filter("[id='lbSendBatchEmail']").click(function(e) {
        e.preventDefault();
        var emails = new Array();
        $(".candidateRow input[id$='cbUserSelected']:checked ").each(
                    function() { var e = $(this).parent().find("input:hidden[id$='hdEmail']").val(); if (e != '' && e !== undefined) { emails.push(e); } }
                 );
        if (emails.length > 0) {
            window.location = 'mailto:training@morrisby.com?bcc=' + emails.join(";");
        } else {
            alert("Please select at least one candidate with an e-mail address.");
        }
    });

}





function UserSummaryStartUp() {
    HideMCtrl();
    ConnectModalBtns();
    ConnectGroupOpBtns();
}

/* JS for expandable sections in groups/candidates etc*/

function setupExpandingSections() {
    $(".expandSectionLink").click(function() {

        var id = $(this).attr("id");

        $(".expandSection").each(function(e) {
            var sID = $(this).attr("id");
            if (sID != id + "Form" && $(this).css("display") == "block") { $(this).hide(250); SetExpandLink(sID.substr(0, sID.length - 4)); }
        });

        $("#" + id + "Form").slideToggle(250, "easeInOutQuad", SetExpandLink(id));
    });

    $(".grouplink div.linkinner").click(function(event) {
        if ($(event.target).is('div, p')) { $(this).find("input[id$='lbUserCount']").click(); }
    })



    function SetExpandLink(LinkID) {
        var txt = $("#" + LinkID).html();
        if (txt == "hide") { $("#" + LinkID).html(ExpandSectionLinks[LinkID]); }
        else { StoreExpandLink(LinkID, txt); $("#" + LinkID).html("hide"); };
    }

    var ExpandSectionLinks = new Array();
    function StoreExpandLink(LinkID, txt) {
        var LT = ExpandSectionLinks[LinkID];
        if (LT == undefined) { ExpandSectionLinks[LinkID] = txt; }
    }
}