﻿var displayElement;
var loadingHtml;
var loadingGridHTML;
var modalDisplay = "modalDisplay";
var autoCompleteUrl;

// Initializes global variables and session state.
function pageLoad() {
    displayElement = $get("modalBody");
    loadingHtml = "<image src='/i/progress_indicator.gif' alt='Loading' id='loadingGif' />";
    loadingGridHTML = "<div class='rgLoading'><div>Loading</div><br /><br /><img src='/i/loadingGrid.gif' alt='loading' /></div>";
}


// Callback function invoked on successful 
// completion of the page method.
function OnSucceeded(result, userContext, methodName) {
    if (methodName == "SessionExpired") {
        $get('modalBody').innerHTML = "<div style=\"border:solid 10px #fff;\">" + result + "</div><div class=\"clasr-h0\"></div>";
        doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
    }
    if (methodName == "getSummary") {
        $get(userContext[0]).innerHTML = result;
        $get(userContext[0]).className = "";
        //mark the row as read by removing the UnRead Class
        $('#trResultsRow' + userContext[6]).removeClass('UnRead');

    }
    if (methodName == "summaryViewCollapse" || methodName == "summaryRegisterView") {
        //mark the row as read by removing the UnRead Class
        $('#trResultsRow' + userContext[0]).removeClass('UnRead');
    }

    if (methodName == "getExportShortlistDisplay") {
        $get(userContext).innerHTML = result;
        $get(userContext).className = "";
        doSplash('ExportCandidateModalPage', 'ExportCandidateModalContainer', 'ExportCandidateModal', '350', '350', 'ExportCandidateModalPageiframe', 'ExportmodalBackground');
        hideSplash('modalPage')
    }

    if (methodName == "deleteShortListCandidate") {
        $get(userContext).innerHTML = result;
        $get(userContext).className = "";
        doSplash('ExportCandidateModalPage', 'ExportCandidateModalContainer', 'ExportCandidateModal', '350', '350', 'ExportCandidateModalPageiframe', 'ExportmodalBackground');
    }
    if (methodName == "DoExportShortlist") {
        $get(userContext).innerHTML = result;
        $get(userContext).className = "";
        doSplash('ExportCandidateModalPage', 'ExportCandidateModalContainer', 'ExportCandidateModal', '350', '350', 'ExportCandidateModalPageiframe', 'ExportmodalBackground');
    }

    if (methodName == "exportToExcelFail") {
        $get('modalDisplay').innerHTML = result;
        $get('modalDisplay').className = "";
        doSplash('ExportCandidateModalPage', 'ExportCandidateModalContainer', 'ExportCandidateModal', '350', '350', 'ExportCandidateModalPageiframe', 'ExportmodalBackground');
    }

    if (methodName == "getAgencyCommentsDisplay") {
        $get(userContext).innerHTML = result;
        $get(userContext).className = "";
        doSplash('ViewNotesModalPage', 'ViewNotesModalContainer', 'ViewNotesModal', '500', '400', 'ViewNotesModalPageiframe', 'ViewNotesModalBackground');
        hideSplash('modalPage');
    }

    if (methodName == "getAddCommentsDisplay") {
        $get(userContext).innerHTML = result;
        $get(userContext).className = "";
        doSplash('ViewNotesModalPage', 'ViewNotesModalContainer', 'ViewNotesModal', '500', '400', 'ViewNotesModalPageiframe', 'ViewNotesModalBackground');
        hideSplash('modalPage');
    }

    if (methodName == "addComment") {

        $get("divLastComment" + userContext[0]).innerHTML = result;
        scrollToCandidateOnGrid(userContext[0])
    }

    if (methodName == "getDisplayTagList") {
        $get(userContext).innerHTML = result;
        $get(userContext).className = "";
        doSplash('TagListModalPage', 'TagListModalContainer', 'TagListModal', '300', '300', 'TagListModalPageiframe', 'TagListModalBackground');
        hideSplash('modalPage');
    }

    if (methodName == "getManageTagsModal") {
        //$get(userContext).innerHTML = result;

        $('#' + userContext + '').empty().append("" + result + "");
        $get(userContext).className = "";
        doSplash('TagListModalPage', 'TagListModalContainer', 'TagListModal', '300', '600', 'TagListModalPageiframe', 'TagListModalBackground');
        hideSplash('modalPage');
        bindAddTagAutoComplete();
    }

    if (methodName == "AddTag") {
        $('#' + userContext + '').empty().append("" + result + "");
        $get(userContext).className = "";
        doSplash('TagListModalPage', 'TagListModalContainer', 'TagListModal', '300', '600', 'TagListModalPageiframe', 'TagListModalBackground');
        hideSplash('modalPage');
        bindAddTagAutoComplete();
    }

    if (methodName == "DeleteTagPopUp") {
        //$get(userContext).innerHTML = result;
        $('#' + userContext + '').empty().append("" + result + "");
        $get(userContext).className = "";
        doSplash('TagListModalPage', 'TagListModalContainer', 'TagListModal', '300', '300', 'TagListModalPageiframe', 'TagListModalBackground');
        hideSplash('modalPage');
    }

    if (methodName == "DeleteTag") {
        //$get(userContext).innerHTML = result;
        $('#' + userContext + '').empty().append("" + result + "");
        $get(userContext).className = "";
        doSplash('TagListModalPage', 'TagListModalContainer', 'TagListModal', '300', '600', 'TagListModalPageiframe', 'TagListModalBackground');
        hideSplash('modalPage');
        bindAddTagAutoComplete();
    }

    if (methodName == "LoadSummaryTags") {
        $get(userContext).innerHTML = result;
    }

    if (methodName == "DoResetPassword") {
        $get(userContext[0]).innerHTML = result;
        
    }

    if (methodName == "DoLocationSearch") {
        var aSuggestions = [];
        aSuggestions = result.split("|");

        userContext[0].autosuggest(aSuggestions, userContext[1]);
    }

//    if (methodName == "DeleteUser") {
//        var totalUsers = $get(userContext[5]);
//        var totalUsersCount = parseInt(totalUsers.innerHTML);
//        if (result) {
//            var ClassNameVar = $get(userContext[0]).className;
//            $get(userContext[0]).className = "displayNone";
//            $get(userContext[1]).className = "Success bold";
//            $get(userContext[2]).innerHTML = userContext[3] + " Deleted";
//            totalUsers.innerHTML = (totalUsersCount-1)
//            var boolValue = false;
//            
//            //if the className of the user is active set true
//            if (ClassNameVar == userContext[6]) {
//                boolValue = true;
//            }
//            if (boolValue) {
//                var activeUsers = $get(userContext[4])
//                var activeUsersCount = parseInt(activeUsers.innerHTML);
//                activeUsers.innerHTML = (activeUsersCount - 1);
//            }
//        }
//        else {
//            $get(userContext[1]).className = "Error";
//            $get(userContext[2]).className = "bold";
//            $get(userContext[2]).innerHTML = userContext[3] + " Deletetion Failed";
//        }
//    }


    //    userContext[0] = tableRow;
    //    userContext[1] = enableDisableButton;
    //    userContext[2] = ActiveImage;
    //    userContext[3] = DisableImage;
    //    userContext[4] = enabledClass;
    //    userContext[5] = disabledClass;
    //    userContext[6] = ActiveText;
    //    userContext[7] = disabledText;
    //    userContext[8] = ActiveUserlabel;
//    if (methodName == "EnableDisableUser") {
//        var activeUsers = $get(userContext[8])
//        var activeUsersCount = parseInt(activeUsers.innerHTML); 
//        //check against enabled class
//        if ($get(userContext[0]).className == userContext[4]) {
//            //we need to disabled the row
//            $get(userContext[0]).className = userContext[5]
//            $get(userContext[1]).src = userContext[3];
//            $get(userContext[1]).title = userContext[7];
//            activeUsers.innerHTML = activeUsersCount - 1
//        }
//        else {
//            //we need to enable the row
//            $get(userContext[0]).className = userContext[4]
//            $get(userContext[1]).src = userContext[2]
//            $get(userContext[1]).title = userContext[6];
//            activeUsers.innerHTML = activeUsersCount + 1
//        }
//        
//    }
    
    // userContext[0] = srcEl;
    // userContext[1] = profileId;
    // userContext[2] = hdnEl;
    if (methodName == "SetCheckValue") {
        if (userContext[0].checked) {
            $get(userContext[2]).value = '1:' + userContext[1];
        }
        else {
            $get(userContext[2]).value = '0:' + userContext[1];
        }
    }

    if (methodName == "ChangePageSize") {
        $get('RG').innerHTML = result;

    }

    if (methodName == "ChangeViewType") {
        $get('RG').innerHTML = result;

    }

    if (methodName == "SortResultsGrid") {
        $get('RG').innerHTML = result;

    }
    if (methodName == "SwitchPage") {
        $get('RG').innerHTML = result;
    }

//    if (methodName == "loadNetworkUpdates") {
//        $('.reportsExportButton').show();
//        $get(userContext[0]).innerHTML = result;
//    }

//    if (methodName == "loadCVProcessing") {
//        $('.reportsExportButton').show();
//        $get(userContext[0]).innerHTML = result;
//    }

//    if (methodName == "loadUserActivity") {
//        $('.reportsExportButton').show();
//        $get(userContext[0]).innerHTML = result;
//    }
    
//    if (methodName == "sortCVProcessing") {
//        $get(userContext[0]).innerHTML = result;
//    }

//    if (methodName == "sortUserActivity") {
//        $get(userContext[0]).innerHTML = result;
//    }

    if (methodName == "shortlistExportToExcel") {
        return result;
    }

    if (methodName == "selectDeselectPage" || methodName == "selectDeselectAll") {
        if (userContext != "")
        {
            processResultsGrid(userContext[0], userContext[1], userContext[2])
        }
    }

    //SaveSearches
    if (methodName == "LoadSaveSearchDisplay") {
        if (result == "SessionExpired") {
            //
            hideSplash('modalPage');
            PageMethods.SessionExpired(OnSucceeded, OnFailed);
        }
        else {
            $get(modalDisplay).innerHTML = result;
            $get(modalDisplay).className = "";
            doSplash('SaveSearchModalPage', 'SaveSearchModalContainer', 'SaveSearchModal', '350', '300', 'SaveSearchModalPageiframe', 'SaveSearchModalBackground');
            hideSplash('modalPage');
            //bind jquery events
            bindSavedSearchEvents();
        }
    }

    if (methodName == "SaveSearchData") {
        if (result == "SessionExpired") {
            //Displays Expired Session Modal
            hideSplash('SaveSearchModalPage');
            PageMethods.SessionExpired(OnSucceeded, OnFailed);
        }
        else if (result != "") {
            //other wise display the saved search display if the result is not blank
            hideSplash('SaveSearchModalPage');
            //Bind the splach for display
            displaySuccessModal(result, modalDisplay);    
        }
        else {
            //There was an error saving
            $('.SaveSearchContainer .button').show();
            $('.SaveSearchContainer .CancelButton').show();
            $('.SaveSearchContainer #loadingGif').remove();
            
            
            $('#SavedSearchError').empty().append("<div class=\"Error\">Save failed, please try again</div>").show();
        }
    }


}

// Callback function invoked on failure 
// of the page method.
function OnFailed(error, userContext, methodName) {
    var genericError = "<div class='GenericError'><h1>Unexpected Error</h1><div class='clear-h3'></div><p>An unexpected error has occurred. Please try again.</p><div class='clear-h10'></div><div><input value='Continue' onclick=\"hideSplash('modalPage');return false;\"  class='ContinueButton' type='submit'></div></div>";
    
    if (error !== null) {
        if (methodName == "getSummary") {
            $get(userContext[0]).innerHTML = userContext[2];
            $get(userContext[1]).value = "0";
            $get(userContext[3]).src = userContext[4];
            $get(userContext[3]).title = userContext[5];
            $get(userContext[3]).alt = userContext[5];
        }

        if (methodName == "getDisplayTagList") {
            $get('modalBody').innerHTML = genericError;
            doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
            hideSplash(userContext);
        }

        if (methodName == "getManageTagsModal") {
            $get('modalBody').innerHTML = genericError;
            doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
            hideSplash(userContext);
        }

        if (methodName == "AddTag") {
            $get('modalBody').innerHTML = genericError;
            hideSplash(userContext);
            doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
        }

        if (methodName == "DeleteTag") {
            $get('modalBody').innerHTML = genericError;
            hideSplash(userContext);
            doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
        }

        if (methodName == "DeleteTagPopUp") {
            hideSplash('modalPage');
            $get('modalBody').innerHTML = genericError;
            doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
        }

        if (methodName == "LoadSummaryTags") {
            $get(userContext).innerHTML = genericError;
        }
        
        if (methodName == "getExportShortlistDisplay") {
            $get('modalBody').innerHTML = genericError;
            hideSplash('ExportCandidateModalPage');
            doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
        }

        if (methodName == "deleteShortListCandidate") {
            $get('modalBody').innerHTML = genericError;
            hideSplash('ExportCandidateModalPage');
            doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
        }
        if (methodName == "DoExportShortlist") {
            $get('modalBody').innerHTML = genericError;
            hideSplash('ExportCandidateModalPage');
            doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
        }

        if (methodName == "getAgencyCommentsDisplay") {
            $get(userContext).innerHTML = genericError;
            doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
        }

        if (methodName == "addComment") {
            $get("divLastComment" + userContext[0]).innerHTML = "An unexpected error has occurred!";
            $("#divLastComment" + userContext[0] + "").focus();
        }
        
        if (methodName == "getLocationMatches") {
            //$get(userContext).innerHTML = result;
            $get(userContext).style.display = "none";
        }

        if (methodName == "DoResetPassword") {
            $get('modalBody').innerHTML = genericError;
            doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
            hideSplash(userContext[1]);

        }

        if (methodName == "DoLocationSearch") {
            userContext[0].textbox.value = "An unexpected error has occurred!";
            userContext[0].textbox.className = "StandardError";
        }

//        if (methodName == "DeleteUser") {
//            $get(userContext[1]).className = "Error";
//            $get(userContext[2]).Value = "User Deletetion Failed";
//        }

//        if (methodName == "loadCVProcessing") {
        //            $get(userContext[0]).innerHTML = "An unexpected error has occurred!";
//        }

//        if (methodName == "loadNetworkUpdates") {
        //            $get(userContext[0]).innerHTML = "An unexpected error has occurred!";
//        }
        
//        if (methodName == "sortCVProcessing") {
        //            $get(userContext[0]).innerHTML = "An unexpected error has occurred!";
//        }
//        if (methodName == "loadUserActivity") {
        //            $get(userContext[0]).innerHTML = "An unexpected error has occurred!";
//        }
//        if (methodName == "sortUserActivity") {
        //            $get(userContext[0]).innerHTML = "An unexpected error has occurred!";
//        }

        if (methodName == "shortlistExportToExcel") {
            return false;
        }

        //SaveSearches
        if (methodName == "LoadSaveSearchDisplay") {
            hideSplash(modalDisplay);
            $get('modalBody').innerHTML = genericError;
            doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');

        }

        if (methodName == "SaveSearchData") {
            $('.SaveSearchContainer .button').show();
            $('.SaveSearchContainer .CancelButton').show();
            $('.SaveSearchContainer #loadingGif').remove();
            $('#SavedSearchError').empty().append("<div class=\"Error\">Save failed, please try again</div>").show();
        }
    }
}

function GetSummary(candidateId, displayDiv, elExpandedCollapsed, elImage, expandedImage, expandedToolTip, 
                    collapsedImage, collapsedToolTip, row, rowClass, loadingError) {

    var hiddenValue = $('#' + elExpandedCollapsed + '').val();
    if (hiddenValue != undefined) {
        if ($get(elExpandedCollapsed).value == '0') {
            $get(displayDiv).className = "";
            $get(displayDiv).innerHTML = loadingHtml;
            $get(elImage).src = expandedImage;
            $get(elImage).title = expandedToolTip;
            $get(elImage).alt = expandedToolTip;
            $get(elExpandedCollapsed).value = '1';
            $get(row).className = rowClass;
            var userContext = new Array();
            userContext[0] = displayDiv;
            userContext[1] = elExpandedCollapsed;
            userContext[2] = loadingError;
            userContext[3] = elImage;
            userContext[4] = collapsedImage;
            userContext[5] = collapsedToolTip;
            userContext[6] = candidateId;
            PageMethods.getSummary(candidateId, OnSucceeded, OnFailed, userContext);
        } else if ($get(elExpandedCollapsed).value == '1') {
            var userContext = new Array();
            userContext[0] = candidateId;
            $get(elExpandedCollapsed).value = '2';
            $get(elImage).src = collapsedImage;
            $get(elImage).title = collapsedToolTip;
            $get(elImage).alt = collapsedToolTip;
            $get(displayDiv).className = "displayNone";
            $get(row).className = "displayNone";
            PageMethods.summaryViewCollapse(candidateId, OnSucceeded, OnFailed, userContext);
        } else if ($get(elExpandedCollapsed).value == '2') {
            var userContext = new Array();
            userContext[0] = candidateId;
            $get(elExpandedCollapsed).value = '1';
            $get(elImage).src = expandedImage;
            $get(elImage).title = expandedToolTip;
            $get(elImage).alt = expandedToolTip;
            $get(displayDiv).className = "";
            $get(row).className = rowClass;
            PageMethods.summaryRegisterView(candidateId, OnSucceeded, OnFailed, userContext);
        }
    }
    else {
        return false;
    }

}


function DisplayShortlistExport(displayDiv, resultsRepeater) {
    doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
    $get('modalBody').innerHTML = loadingHtml;
    
    //loop through the repeater and get the checkboxes 
    var TargetBaseControl = $get("ResultsGrid");

    var TargetChildControl = "hdnCandidateId";

    //get all the control of the type INPUT in the base control.
    var Inputs = TargetBaseControl.getElementsByTagName("input");
    var sbChecked = new StringBuilder();

    for (var n = 0; n < Inputs.length; ++n)
        if (Inputs[n].type == 'hidden' &&
            Inputs[n].id.indexOf(TargetChildControl, 0) >= 0) {
                if (Inputs[n].value.indexOf(':', 0) >= 0)
                    sbChecked.append(Inputs[n].value + ';');
            }
    PageMethods.getExportShortlistDisplay(sbChecked.toString(), OnSucceeded, OnFailed, displayDiv);
}


function DeleteShortListCandidate(displayDiv, candId) {
    PageMethods.deleteShortListCandidate(candId, OnSucceeded, OnFailed, displayDiv);
}

function DoExport(btnExport, displayDiv, rfvEl, jobRefEl) {
    if (jQuery.trim($get(jobRefEl).value) == '') {
        $get(rfvEl).style.display = 'block';
        return;
    } else {
        $get(rfvEl).style.display = 'none';
        btnExport.disabled = true;
        
    }
    PageMethods.DoExportShortlist($get(jobRefEl).value, OnSucceeded, OnFailed, displayDiv);
}



function updateStyleSheetSession(intStyleID) {
    PageMethods.updateStyleSheetSession(intStyleID, OnSucceeded, OnFailed);
}


function StringBuilder(value) {
    this.strings = new Array("");
    this.append(value);
}

// Appends the given value to the end of this instance.

StringBuilder.prototype.append = function(value) {
    if (value) {
        this.strings.push(value);
    }
}

// Clears the string buffer

StringBuilder.prototype.clear = function() {
    this.strings.length = 1;
}

// Converts this instance to a String.

StringBuilder.prototype.toString = function() {
    return this.strings.join("");
}



function setCheckValue(srcEl, profileId, hdnEl) {

    var userContext = new Array();
    userContext[0] = srcEl;
    userContext[1] = profileId;
    userContext[2] = hdnEl;
    isShortlistCandidate = false;
    if (srcEl.checked)
        isShortlistCandidate = true;

    PageMethods.SetCheckValue(profileId, isShortlistCandidate, OnSucceeded, OnFailed, userContext);
    
    
}

function resetPassword(displayDiv, usernameEl, parentDiv) {
    var validationResult = true;
    if (typeof(Page_ClientValidate) == 'function') {
        validationResult = Page_ClientValidate('forgottenPassword');
     }
     if (validationResult) {
         var userContext = new Array();
         userContext[0] = displayDiv;
         userContext[1] = parentDiv;
         PageMethods.DoResetPassword($get(usernameEl).value, OnSucceeded, OnFailed, userContext); 
    }
}


//function deleteUser(tableRow, divMessage, lblMessage, userId, userName, activeUserCount, TotalUserCount, enabledClass) {
//    $get(divMessage).className = "displayNone";
//    var userContext = new Array();
//    userContext[0] = tableRow;
//    userContext[1] = divMessage;
//    userContext[2] = lblMessage;
//    userContext[3] = userName;
//    userContext[4] = activeUserCount;
//    userContext[5] = TotalUserCount;
//    userContext[6] = enabledClass;
//    PageMethods.DeleteUser(userId, OnSucceeded, OnFailed, userContext);
//}

//function enableDisableUser(tableRow, userId, enableDisableButton, ActiveImage, DisableImage, enabledClass, disabledClass, activeText, disabledText, activeUsersLabel) {
//    var userContext = new Array();
//    userContext[0] = tableRow;
//    userContext[1] = enableDisableButton;
//    userContext[2] = ActiveImage;
//    userContext[3] = DisableImage;
//    userContext[4] = enabledClass;
//    userContext[5] = disabledClass;
//    userContext[6] = activeText;
//    userContext[7] = disabledText;
//    userContext[8] = activeUsersLabel;
//    PageMethods.EnableDisableUser(userId, OnSucceeded, OnFailed, userContext);
//}

function changePageSize(selPageSizeValue) {
    buildLoadingScreen();
    PageMethods.ChangePageSize(selPageSizeValue, OnSucceeded, OnFailed);
}

function changePageViewType(selViewAsValue) {
    buildLoadingScreen();
    PageMethods.ChangeViewType(selViewAsValue, OnSucceeded, OnFailed);
}

function sortResultsGrid(col) {
    buildLoadingScreen();
    PageMethods.SortResultsGrid(col, OnSucceeded, OnFailed);
}

function switchPage(pageNumber) {
    if (pageNumber > 0) {
        buildLoadingScreen();
        PageMethods.SwitchPage(pageNumber, OnSucceeded, OnFailed);
    }
}

function setSearchButtonClick() {
    PageMethods.SetSearchButtonClick(OnSucceeded, OnFailed);
}

//function loadReportData(sReportType, fromDate, toDate, txtFromDate, txtToDate, txtFromDateValue, txtToDateValue) {
//    //This must be wrapped around all the report controls
//    var reportContainerID = "ReportData";
//    $('#' + reportContainerID + '').html("<image src='/i/progress_indicator.gif' alt='Loading'/>");
//    $get(txtFromDate).value = txtFromDateValue;
//    $get(txtToDate).value = txtToDateValue;
//    var userContext = new Array();
//    userContext[0] = reportContainerID;
//    switch (sReportType) {
//        case "NetworkUpdates":
//            PageMethods.loadNetworkUpdates(fromDate, toDate, OnSucceeded, OnFailed, userContext);
//            break;
//        case "CVProcessing":
//            PageMethods.loadCVProcessing(fromDate, toDate, OnSucceeded, OnFailed, userContext);
//            break;
//        case "Users":
//            PageMethods.loadUserActivity(fromDate, toDate, OnSucceeded, OnFailed, userContext);
//            break;
//    }
//}

//function runReport(sReportType, txtFromDate, txtToDate, cbEnableDisableUsers) {

//    var reportContainerID = "ReportData";
//    $('#' + reportContainerID + '').html("<image src='/i/progress_indicator.gif' alt='Loading'/>");
//    var fromDate = $('#' + txtFromDate + '').val();
//    var toDate = $('#' + txtToDate + '').val();
//    
//    var userContext = new Array();
//    userContext[0] = reportContainerID;
//    
//    switch (sReportType) {
//        case "NetworkUpdates":
//            PageMethods.loadNetworkUpdates(fromDate, toDate, OnSucceeded, OnFailed, userContext);
//            break;
//        case "CVProcessing":
//            PageMethods.loadCVProcessing(fromDate, toDate, OnSucceeded, OnFailed, userContext);
//            break;
//        case "Users":
//            
//            enableDisableUsers = new Boolean();
//            if ($('#' + cbEnableDisableUsers + ':checked').val() != null) {
//                enableDisableUsers = true;
//            }

//            PageMethods.loadUserActivity(fromDate, toDate, enableDisableUsers, OnSucceeded, OnFailed, userContext);
//            break;
//    }
//}


//function sortReportGrid(sReportType, sSortColumn, eId) {
//    var userContext = new Array();
//    userContext[0] = eId;
//    $('#' + eId + '').html("<image src='/i/progress_indicator.gif' alt='Loading'/>");
//    switch (sReportType) {
//        case "NetworkUpdates":
//            //PageMethods.loadNetworkUpdates(fromDate, toDate, OnSucceeded, OnFailed, userContext);
//            break;
//        case "CVProcessing":
//            PageMethods.sortCVProcessing(sSortColumn, OnSucceeded, OnFailed, userContext);
//            break;
//        case "Users":
//            PageMethods.sortUserActivity(sSortColumn, OnSucceeded, OnFailed, userContext);
//            break;
//    }
//}

function hideMessageBar() {
    //$('#MBar').hide('slow');
    $('#MBar').slideUp('slow', function() {
        // Animation complete.
    });

    PageMethods.hideMessageBar(OnSucceeded, OnFailed);
}


//Comments section
function DisplayAgencyComments(displayDiv, sCandidateId) {
    doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
    $get('modalBody').innerHTML = loadingHtml;
    PageMethods.getAgencyCommentsDisplay(sCandidateId, OnSucceeded, OnFailed, displayDiv);
}

function DisplayAddComment(displayDiv, sCandidateId) {
    $get(displayDiv).className = "DisplayNone";
    doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
    $get('modalBody').innerHTML = loadingHtml;
    PageMethods.getAddCommentsDisplay(sCandidateId, OnSucceeded, OnFailed, displayDiv);
}

function AddComment(displayDiv, sCandidateId, txtComment, errorHolder, errorMessage) {
    var comment = $('#' + txtComment + '').val();
    if (comment != '' && comment != ' ') {
        hideSplash('ViewNotesModalPage');
        $get(displayDiv).className = "DisplayNone";
        $get("divLastComment" + sCandidateId).innerHTML = loadingHtml;
        var userContext = new Array();
        userContext[0] = sCandidateId;

        $get(displayDiv).className = "DisplayNone";
        PageMethods.addComment(sCandidateId, comment, OnSucceeded, OnFailed, userContext);
    }
    else {
        $get(errorHolder).innerHTML = errorMessage;
        $get(errorHolder).style.display = "block";
    }
}





function ExportToExcelFail() {
    PageMethods.exportToExcelFail(OnSucceeded, OnFailed);
}


// resultsRepeater = Results Repeater,
// selectIndicator: 1 = selecting, 0 = deselecting
// allIndicator: true = Full results set, false = Results on page
function SelectDeselectResults(resultsRepeater, selectIndicator, allIndicator) {
    //loop through the repeater and get the checkboxes
    var TargetBaseControl = $get("ResultsGrid");
    var TargetChildControl = "hdnCandidateId";
    var TargetCheckBox = "chkShortlist";
    
    //get all the control of the type INPUT in the base control.
    var Inputs = TargetBaseControl.getElementsByTagName("input");
    var sbChecked = new StringBuilder();
    var sbCheckedID = new StringBuilder();
    var sbCheckBoxes = new StringBuilder();

    for (var n = 0; n < Inputs.length; ++n) {
    
        if (Inputs[n].type == 'hidden' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0) {
            if (Inputs[n].value.indexOf(':', 0) >= 0) {
                res = Inputs[n].value.split(":");
                if (res[0] == selectIndicator) {
                    sbChecked.append(Inputs[n].value + ';');
                    sbCheckedID.append(Inputs[n].id + ';');
                }
                else {
                    sbChecked.append(selectIndicator + ':' + res[1] + ';');
                    sbCheckedID.append(Inputs[n].id + ';');
                }
            }
            else {
                sbChecked.append(selectIndicator + ':' + Inputs[n].value + ';');
                sbCheckedID.append(Inputs[n].id + ';');
            }
        }
        else if (Inputs[n].id.indexOf(TargetCheckBox, 0) >= 0) {
        if (selectIndicator == 1) {
                if (Inputs[n].checked == false) 
                    sbCheckBoxes.append(Inputs[n].id + ';');
            }
            else {
                if (Inputs[n].checked == true)
                    sbCheckBoxes.append(Inputs[n].id + ';');
            }
        }
    }
    var userContext = new Array();
    userContext[0] = sbCheckBoxes.toString();
    userContext[1] = sbCheckedID.toString();
    userContext[2] = selectIndicator;
    if (allIndicator == "true") {
        var ind;
        if (selectIndicator == 1)
            ind = "true"
        else
            ind = "false"

        PageMethods.selectDeselectAll(ind, OnSucceeded, OnFailed, userContext);
    }
    else
        PageMethods.selectDeselectPage(sbChecked.toString(), OnSucceeded, OnFailed, userContext);
}

function processResultsGrid(sbCheckBoxes, sbCheckedID, select) {
    var checkBoxes = [];
    checkBoxes = sbCheckBoxes.split(";");
    
    //tick the check boxes
    for (var n = 0; n < checkBoxes.length-1; ++n) {
        if (select == "1")
            document.getElementById(checkBoxes[n]).checked = true;
        else
            document.getElementById(checkBoxes[n]).checked = false;
    }
    
    //update the value of the hidden fields
    var checkedIDs = [];
    checkedIDs = sbCheckedID.split(";");
    for (var n = 0; n < checkedIDs.length - 1; ++n) {
        if (document.getElementById(checkedIDs[n]).value.indexOf(":", 0) >= 0) {
            res = document.getElementById(checkedIDs[n]).value.split(":");
            if (res[1] > 0)
                document.getElementById(checkedIDs[n]).value = select + ":" + res[1];
        }
        else{
            res = document.getElementById(checkedIDs[n]).value;
            document.getElementById(checkedIDs[n]).value = select + ":" + res;
        }
    }
}


function setEventArgument() {
    PageMethods.SetEventArgument(OnSucceeded, OnFailed);
}


//#####Tag Functions
//display tag list modal popup
function displayTagList(displayDiv, agencyId, recruiterId, returnControlId) {
    doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
    $get('modalBody').innerHTML = loadingHtml;
    PageMethods.getDisplayTagList(agencyId, recruiterId, returnControlId, OnSucceeded, OnFailed, displayDiv);
}
//Populate tag box
function populateTagsBox(tagList, tagControl) {
    if (tagControl != null & tagControl != undefined) {
        var text = $('#' + tagControl).val();
        if (text != '')
            text += ' ';
        $("#TagListLookup input[type=checkbox]").each(function() {
            if (this.checked) {
                var defaultValue = $("label[for*='" + this.id + "']").html();
                var count = defaultValue.split(" ");
                if (count.length > 1) {
                    text += '"' + defaultValue + '" ';
                }
                else
                    text += defaultValue + ' ';
            }
        });
    }
    hideSplash('TagListModalPage');
    $('#' + tagControl).val(text);
}
//Manage tag modal
function displayManageTagsModal(displayDiv, sCandidateId) {
    doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
    $get('modalBody').innerHTML = loadingHtml;
    PageMethods.getManageTagsModal(sCandidateId, OnSucceeded, OnFailed, displayDiv);

}
//Add tag error checking
function addTag(displayDiv, sCandidateId, txtAddTag, sTagErrorLabel, sTagError) {
    var tagErrorContainer = $('#' + sTagErrorLabel + '');
    tagErrorContainer.text('');
    var tagValue = $('#' + txtAddTag + '').val();
    if (tagValue != '') {
        addTagValue(displayDiv, sCandidateId, tagValue);
    }
    else {
        $('#' + txtAddTag + '').val("").focus();
        tagErrorContainer.text(sTagError);
    }
}
//Add tag to database call return momanage tag modal
function addTagValue(displayDiv, sCandidateId, tagValue) {
    if (tagValue != '') {
        hideSplash("TagListModalPage");
        doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
        $get('modalBody').innerHTML = loadingHtml;
        PageMethods.AddTag(sCandidateId, tagValue, OnSucceeded, OnFailed, displayDiv);
    }
}
//Delete tag
function deleteTag(displayDiv, sCandidateId, tagId) {
    hideSplash("TagListModalPage");
    doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
    $get('modalBody').innerHTML = loadingHtml;
    PageMethods.DeleteTag(tagId, sCandidateId, OnSucceeded, OnFailed, displayDiv);
}
//Delete tag confirmation moddal call
function deleteTagPopUp(displayDiv, sCandidateId, tagId) {
    hideSplash("TagListModalPage");
    doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
    $get('modalBody').innerHTML = loadingHtml;
    PageMethods.DeleteTagPopUp(tagId, sCandidateId, displayDiv, OnSucceeded, OnFailed, displayDiv);
}

//Load Summary tags on results grid
function loadSummaryTags(sCandidateId, splashToHide) {
    scrollToCandidateOnGrid(sCandidateId);
    hideSplash(splashToHide);
    var tagSummaryControl = "divSummaryTags" + sCandidateId
    if ($get(tagSummaryControl)) {
        $get(tagSummaryControl).innerHTML = loadingHtml;
        PageMethods.LoadSummaryTags(sCandidateId, OnSucceeded, OnFailed, tagSummaryControl);   
    }
}
//#####End Tag Functions


//#####SaveSearches Function


//Calls page method and injects SaveSearch Modal into the dom
function loadSaveSearchDisplay() {
    doSplash('modalPage', 'modalContainer', 'modal', '300', '350', 'modalPageiframe', 'modalBackground');
    $get('modalBody').innerHTML = loadingHtml;
    PageMethods.LoadSaveSearchDisplay(OnSucceeded, OnFailed);
}
//Get the data from the SaveSearch Modal
function saveSearchData() {
    
    var IsAlerted = $('#cbxIsAlert').attr('checked') ? true : false;
    var SearchOverrideId = $("input[name='SavedSearch']:checked").val();
    var SearchName = $('#txtSearchName').val();

    if ((SearchName != "") && (SearchOverrideId >= 0)) {
        //PageMethods.SaveSearch(OnSucceeded, OnFailed);
        $('.SaveSearchContainer .button').hide();
        $('.SaveSearchContainer .CancelButton').hide();
        $('.SaveSearchContainer .button').parent().prepend(loadingHtml)
        PageMethods.SaveSearchData(SearchOverrideId, SearchName, IsAlerted, OnSucceeded, OnFailed);
    }
    else {
        $('#SavedSearchError').empty().append("<div class=\"Error\">Please enter a valid search name</div>").show();
    }

}
//#####End Saved searches Function

function clearSearchSession()
{
    PageMethods.ClearSearchSession(OnSucceeded, OnFailed);
}
