﻿// #### Start Up code ####


$(function() {
// 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(e) {
            e.preventDefault();
            var T =  $(".tutorialBox > div") ;
            ($(T).css("height") == '0px') ?  $(T).animate({'height':'400px'}) : $(T).animate({'height':'0px'});            
        });
})
        
        
        
             
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().parent().find("td input:hidden[id$='hdUserID']").val() );}            
         );
                
         return ids;
} 

function ToggleCheckBoxesState(Source,ID) {
    $("input[id$='" +ID+"']").each(
        function() { $(this).attr('checked',$(Source).attr('checked')); }        
   );
}

//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 + ' #sectionIdx').val();
        var nextSect = 4; SectId == 3 ? nextSect = 4 : nextSect = 1; 
        SwitchMCQTab($(".sectionNav .tab")[nextSect]);
        ShowStatus(SectId,2,true);
    }
}

//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(); } catch(err) {}}
                                    } else {
                                        if (typeof(ShowM)=="undefined" ) {ShowM = 'True';}
                                        if (ShowM == 'True') {showMessage(msg.d.Message, msg.d.MessageIdx);}
                                        if (msg.d.Success) {try  {callback(); } 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 and width of mask
        var mH = $(document).height();
        var mW = $(window).width();
        $('#mask').css({ 'width': mW, 'height': mH });

        //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

        $('#mask').fadeTo(500, 0.5).fadeIn(500, function() {
            $("#SummaryModal").fadeIn(250);
            $("body").attr("style", "overflow: hidden");
        });

       
    }


//Function to display a message - either showing a hidden element or via an alert
 function showMessage(P, i){
        if ($(P).attr("id") == undefined) {
            alert(P);
        } else {
        var div = $(P).find("div.popupMessage div").get(i);
        $(div).css("display","block");
        $(P).find("div.popupMessage").slideDown("slow"); 

        }
 }
 // Function to Close parent of close element
 function closeMessage(obj) {
     $(obj).parent().slideUp("slow", function() { $(this).find("div").css("display", "none"); });              
 }