// portal_data.js
var recordingsData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var voicemailsData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var callSummaryData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var menuData = [];
var listCollection = [];
var businessHoursData = [];
var trainerTraineeData = [];
var holidaysData = [];
var settingsData = [];
var skillsData = [];
var currentDate = moment().utc();
var utcOffset = 0;
var startDate = null;
var dateOffset = 0;
var hourOffset = 0;
var agentCount = 0;
var supervisorCount = 0;
var skillsPerAgentCount = 0;
var trainerCount = 0;
var traineeCount = 0;
var pendingCount = 0;
var acceptedCount = 0;
var failedCount = 0;
var debug = false;
var batchSize = 3000; // Number of items to retrieve per batch
var nextPosition = null; // Position marker for pagination
var outboundDialerCount = 0; // Counter for the total items retrieved

// Init portal data
function initPortalData() {
    retrieveTimeZone();
}

// Retrieve portal data
function retrievePortalData() {
    if (debug) {
        console.log("retrievePortalData()");
    }

    currentDate = moment().utc().utcOffset(utcOffset);
    startDate = moment().utc().utcOffset(utcOffset).month(currentDate.month() - 11);
    dateOffset = currentDate.format("MM");
    dateOffset = dateOffset.replace("0", "");
    dateOffset = parseInt(dateOffset);
    hourOffset = currentDate.format("HH");
    startDate = startDate.format("YYYY-MM-01");
    trainerTraineeData["Trainer"] = [];
    trainerTraineeData["Trainee"] = [];
    retrieveBusinesshours();
    retrieveHolidays();
    retrieveSettings();
    retrieveAgents();
    retrieveOutboundDialerCalls();
    var recordingsExists = $.inArray("Recordings", listCollection);
    if (recordingsExists != -1) {
        retrieveRecordings();
    }

    var voicemailsExists = $.inArray("Voicemails", listCollection);
    if (voicemailsExists != -1) {
        retrieveVoicemails();
    }

    var inboundScreenRecordingsExists = $.inArray("InboundScreenRecordings", listCollection);
    if (inboundScreenRecordingsExists != -1) {
        retrieveInboundScreenRecordings();
    }

    var outboundScreenRecordingsExists = $.inArray("OutboundScreenRecordings", listCollection);
    if (outboundScreenRecordingsExists != -1) {
        retrieveOutboundScreenRecordings();
    }

    retrieveCallSummary();
	addWebTitleToBrowserTab();
}

ExecuteOrDelayUntilScriptLoaded(retrieveSkillsPerAgentCount, "sp.js")

// TimeZone data Query
function retrieveTimeZone() {
    var clientContext = SP.ClientContext.get_current();
    this.timeZone = clientContext.get_web().get_regionalSettings().get_timeZone();

    clientContext.load(timeZone);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveTimeZoneSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveTimeZoneSucceeded(sender, args) {
    var info = timeZone.get_information();
    var tmpOffset = info.get_bias();
    var offsetDts = info.get_daylightBias();
    var today = new Date();

    if (today.dst()) {
        utcOffset = (tmpOffset + offsetDts) / 60;
    } else {
        utcOffset = tmpOffset / 60;
    }

    if (utcOffset < 0) {
        utcOffset *= -1;
    }
    else {
        utcOffset -= (utcOffset * 2);
    }

    retrieveMenu();
}

// Menu data Query
function retrieveMenu() {
    if (debug) {
        console.log("retrieveMenu()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('settingsList');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>");
    this.collListItemsMenu = oList.getItems(camlQuery);

    clientContext.load(collListItemsMenu);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveMenuSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveMenuSucceeded(sender, args) {
    var listItemEnumerator = collListItemsMenu.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemId = oListItem.get_item("ID");
        var oListItemTitle = oListItem.get_item("Title");
        var oListItemUrl = oListItem.get_item("wsp_ucc_URL");
        var oListItemHeader = oListItem.get_item("wsp_ucc_HeaderTitle");
        var oListItemSort = oListItem.get_item("wsp_ucc_sort");
        var oListItemVisible = oListItem.get_item("wsp_ucc_visible");

        var searchTitle = oListItemTitle.toLowerCase();
        searchTitle = searchTitle.replace(/\s/g, "");
        searchTitle = searchTitle.replace("/", "");
        var obj = { ID: oListItemId, Title: oListItemTitle, SearchTitle: searchTitle, URL: oListItemUrl, Header: oListItemHeader, Sort: oListItemSort, Visible: oListItemVisible };
        menuData.push(obj);
    }
    retrieveListCollection();
}

// List collection data Query
function retrieveListCollection() {
    if (debug) {
        console.log("retrieveListCollection()");
    }
    var clientContext = SP.ClientContext.get_current();
    this.oListCollection = clientContext.get_web().get_lists();

    clientContext.load(oListCollection);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveListCollectionSucceeded), Function.createDelegate(this, this.onQueryRetrieveListCollectionFailed));
}

function onQueryRetrieveListCollectionSucceeded(sender, args) {
    var listItemEnumerator = oListCollection.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemTitle = oListItem.get_title();

        listCollection.push(oListItemTitle);
    }
    retrievePortalData();
}

function onQueryRetrieveListCollectionFailed(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    console.log("Retry...");
    setTimeout(retrieveListCollection(), 1000);
}

// Agents data Query
function retrieveAgents() {
    if (debug) {
        console.log("retrieveAgents()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Agents');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>");
    this.collListItemsAgents = oList.getItems(camlQuery);

    clientContext.load(collListItemsAgents);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveAgentsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveAgentsSucceeded(sender, args) {
    agentCount = collListItemsAgents.get_count();
    $("#agentsCount").html(agentCount);
    $("#agentsCount").css("display", "block");
    retrieveSupervisors();
}

// Supervisors data Query
function retrieveSupervisors() {
    if (debug) {
        console.log("retrieveSupervisors()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Supervisors');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>");
    this.collListItemsSupervisors = oList.getItems(camlQuery);

    clientContext.load(collListItemsSupervisors);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveSupervisorsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveSupervisorsSucceeded(sender, args) {
    supervisorCount = collListItemsSupervisors.get_count();
    $("#supervisorsCount").html(supervisorCount);
    $("#supervisorsCount").css("display", "block");
	var countAllAgents = supervisorCount + agentCount;
	$("#countTotalAgents").html(countAllAgents);
	
    PrepDoughnutData1();
    retrieveSkills();
	retrieveVoicemailAgents();
}

// Voicemail agents data Query
function retrieveVoicemailAgents() {
    if (debug) {
        console.log("retrieveVoicemailAgents()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('VoicemailAgents');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>");
    this.collListItemsAgents = oList.getItems(camlQuery);

    clientContext.load(collListItemsAgents);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveVoicemailAgentsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveVoicemailAgentsSucceeded(sender, args) {
    voicemailAgentCount = collListItemsAgents.get_count();
    $("#voicemailAgentsCount").html(voicemailAgentCount);
    $("#voicemailAgentsCount").css("display", "block");

}

// Outbound Dialer Calls data Query
function retrieveOutboundDialerCalls() {
    if (debug) {
        console.log("retrieveOutboundDialerCalls()");
    }
    
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('OutboundDialerCalls');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><RowLimit>" + batchSize + "</RowLimit></View>");
    
    // If nextPosition is set, apply it to the query for pagination
    if (nextPosition != null) {
        camlQuery.set_listItemCollectionPosition(nextPosition);
    }

    this.collListItemsOutboundDialerCalls = oList.getItems(camlQuery);

    clientContext.load(collListItemsOutboundDialerCalls);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveOutboundDialerCallsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

// Outbound Dialer Calls data Query
function retrieveOutboundDialerCalls() {
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('OutboundDialerCalls');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><RowLimit>" + batchSize + "</RowLimit></View>");
    
    // If nextPosition is set, apply it to the query for pagination
    if (nextPosition != null) {
        camlQuery.set_listItemCollectionPosition(nextPosition);
    }

    this.collListItemsOutboundDialerCalls = oList.getItems(camlQuery);

    clientContext.load(collListItemsOutboundDialerCalls);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveOutboundDialerCallsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

// Callback for successful retrieval
function onQueryRetrieveOutboundDialerCallsSucceeded(sender, args) {
    var listItemEnumerator = collListItemsOutboundDialerCalls.getEnumerator();
    
    // Accumulate the total number of retrieved items
    outboundDialerCount += collListItemsOutboundDialerCalls.get_count();

    // Process items from this batch
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemProcessed = oListItem.get_item('wsp_ucc_odc_processed');
        var oListItemResult = oListItem.get_item('wsp_ucc_odc_result');
        var oListItemRetries = oListItem.get_item('wsp_ucc_odc_retries');
        
        // Accumulate counts for accepted, pending, and failed
        if (oListItemProcessed == true) {
            acceptedCount++;
        } else {
            if ((oListItemResult == null || oListItemResult == "") && oListItemRetries == 0) {
                pendingCount++;
            } else {
                failedCount++;
            }
        }
    }

    // Update the UI after each batch
    $("#countOutboundDialer").html(outboundDialerCount);  // Update total count
    $("#chart-label2-0 label").html(pendingCount); // Update pending count
    $("#chart-label2-1 label").html(acceptedCount); // Update accepted count
    $("#chart-label2-2 label").html(failedCount); // Update failed count

    // Check if more items exist and continue loading if needed
    nextPosition = collListItemsOutboundDialerCalls.get_listItemCollectionPosition();
    
    // If there are more batches to load, continue loading
    if (nextPosition != null) {
        retrieveOutboundDialerCalls(); // Recursively load the next batch
    }
}

// Recordings data Query
function retrieveRecordings() {
    if (debug) {
        console.log("retrieveRecordings()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Recordings');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><Where><Geq><FieldRef Name='Created' /><Value IncludeTimeValue='FALSE' Type='DateTime'>" + startDate + "</Value></Geq></Where><OrderBy><FieldRef Name='Created' /></OrderBy></Query></View>");
    this.collListItemsRecordings = oList.getItems(camlQuery);

    clientContext.load(collListItemsRecordings);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveRecordingsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveRecordingsSucceeded(sender, args) {
    var recordingsCount = collListItemsRecordings.get_count();
    $("figcaption#valueOfGraph1").html(recordingsCount);
    $("#recordingsCount").html(recordingsCount);
    $("#recordingsCount").css("display", "block");
    var listItemEnumerator = collListItemsRecordings.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemCreated = oListItem.get_item('Created');
        var createdFormatted = oListItemCreated.format("MM");
        if (createdFormatted != "10") {
            createdFormatted = createdFormatted.replace("0", "");
        }
        createdFormatted = parseInt(createdFormatted);

        var offset = 0;
        if (createdFormatted < dateOffset) {
            offset = dateOffset - createdFormatted;
        }
        else if (createdFormatted > dateOffset) {
            offset = 12 - (createdFormatted - dateOffset);
        }
        recordingsData[offset] = recordingsData[offset] + 1;
    }
    CreateGraph("1", recordingsData);
}

// Voicemails data Query
function retrieveVoicemails() {
    if (debug) {
        console.log("retrieveVoicemails()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Voicemails');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><Where><Geq><FieldRef Name='Created' /><Value IncludeTimeValue='FALSE' Type='DateTime'>" + startDate + "</Value></Geq></Where><OrderBy><FieldRef Name='Created' /></OrderBy></Query></View>");
    this.collListItemsVoicemails = oList.getItems(camlQuery);

    clientContext.load(collListItemsVoicemails);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveVoicemailsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveVoicemailsSucceeded(sender, args) {
    var voicemailsCount = collListItemsVoicemails.get_count();
    $("figcaption#valueOfGraph3").html(voicemailsCount);
    $("#voicemailsCount").html(voicemailsCount);
    $("#voicemailsCount").css("display", "block");

    var listItemEnumerator = collListItemsVoicemails.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemCreated = oListItem.get_item('Created');
        var createdFormatted = oListItemCreated.format("MM");
        if (createdFormatted != "10") {
            createdFormatted = createdFormatted.replace("0", "");
        }
        createdFormatted = parseInt(createdFormatted);

        var offset = 0;
        if (createdFormatted < dateOffset) {
            offset = dateOffset - createdFormatted;
        }
        else if (createdFormatted > dateOffset) {
            offset = 12 - (createdFormatted - dateOffset);
        }
        voicemailsData[offset] = voicemailsData[offset] + 1;
    }
    CreateGraph("3", voicemailsData);
}

// InboundScreenRecordings data Query
function retrieveInboundScreenRecordings() {
    if (debug) {
        console.log("retrieveInboundScreenRecordings()");
    }

    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('InboundScreenRecordings');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><Where><Geq><FieldRef Name='Created' /><Value IncludeTimeValue='FALSE' Type='DateTime'>" + startDate + "</Value></Geq></Where><OrderBy><FieldRef Name='Created' /></OrderBy></Query></View>");
    this.collListItemsInboundScreenRecordings = oList.getItems(camlQuery);

    clientContext.load(collListItemsInboundScreenRecordings);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveInboundScreenRecordingsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveInboundScreenRecordingsSucceeded(sender, args) {
    var inboundScreenRecordingsCount = collListItemsInboundScreenRecordings.get_count();
    $("#inboundScreenRecordingsCount").html(inboundScreenRecordingsCount);
    $("#inboundScreenRecordingsCount").css("display", "block");
}

// OutboundScreenRecordings data Query
function retrieveOutboundScreenRecordings() {
    if (debug) {
        console.log("retrieveOutboundScreenRecordings()");
    }

    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('OutboundScreenRecordings');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><Where><Geq><FieldRef Name='Created' /><Value IncludeTimeValue='FALSE' Type='DateTime'>" + startDate + "</Value></Geq></Where><OrderBy><FieldRef Name='Created' /></OrderBy></Query></View>");
    this.collListItemsOutboundScreenRecordings = oList.getItems(camlQuery);

    clientContext.load(collListItemsOutboundScreenRecordings);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveOutboundScreenRecordingsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveOutboundScreenRecordingsSucceeded(sender, args) {
    var outboundScreenRecordingsCount = collListItemsOutboundScreenRecordings.get_count();
    $("#outboundScreenRecordingsCount").html(outboundScreenRecordingsCount);
    $("#outboundScreenRecordingsCount").css("display", "block");
}

function addWebTitleToBrowserTab(){

    var clientContext = new SP.ClientContext.get_current();
    this.oWebsite = clientContext.get_web();
    
    var currentTitle = this.oWebsite.get_title();
	document.title = currentTitle;
}

function retrieveSkillsPerAgentCount() {
    if (debug) {
        console.log("retrieveAgents()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('SkillsPerAgent');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>");
    this.collListItemsAgents = oList.getItems(camlQuery);

    clientContext.load(collListItemsAgents);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryretrieveSkillsPerAgentCountSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryretrieveSkillsPerAgentCountSucceeded(sender, args) {
    skillsPerAgentCount = collListItemsAgents.get_count();
}

// CallSummary data Query
function retrieveCallSummary() {
    if (debug) {
        console.log("retrieveCallSummary()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('CallSummary');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><Where><And><Eq><FieldRef Name='wsp_ucc_Accepted' /><Value Type='Integer'>0</Value></Eq><Eq><FieldRef Name='wsp_ucc_StartTime' /><Value Type='DateTime'><Today /></Value></Eq></And></Where><OrderBy><FieldRef Name='wsp_ucc_StartTime' /></OrderBy></Query></View>");
    this.collListItemsCallSummary = oList.getItems(camlQuery);

    clientContext.load(collListItemsCallSummary);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveCallSummarySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveCallSummarySucceeded(sender, args) {
    var callSummaryCount = collListItemsCallSummary.get_count();
    $("figcaption#valueOfGraph2").html(callSummaryCount);
    $("#missedCallsTodayCount").html(callSummaryCount);
    $("#missedCallsTodayCount").css("display", "block");

    var listItemEnumerator = collListItemsCallSummary.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemStartTime = oListItem.get_item('wsp_ucc_StartTime');
        var startTimeFormatted = oListItemStartTime.format("HH");

        var minTime = hourOffset - 11;
        if (startTimeFormatted >= minTime) {
            callSummaryData[hourOffset - startTimeFormatted] = callSummaryData[hourOffset - startTimeFormatted] + 1;
        }
    }
    CreateGraph("2", callSummaryData);
}

// Skills data Query
function retrieveSkills() {
    if (debug) {
        console.log("retrieveSkills()");
    }
    skillsData = [];

    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Skills');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><OrderBy><FieldRef Name='Title' /></OrderBy></View>");
    this.collListItemsSkills = oList.getItems(camlQuery);
    this.collListContentTypesSkills = oList.get_contentTypes();

    clientContext.load(collListItemsSkills);
    clientContext.load(collListContentTypesSkills);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveSkillsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveSkillsSucceeded(sender, args) {
    var listItemEnumerator = collListItemsSkills.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemId = oListItem.get_item('ID');
        var oListItemCT = oListItem.get_item('ContentTypeId').toString();
        var oListItemCTName = "";
        var ct_enumerator = collListContentTypesSkills.getEnumerator();
        while (ct_enumerator.moveNext()) {
            var ct = ct_enumerator.get_current();
            if (ct.get_id().toString() == oListItemCT) {
                oListItemCTName = ct.get_name();
            }
        }
        var oListItemTitle = oListItem.get_item('Title');

        var obj = { ID: oListItemId, Skill: oListItemTitle, ContentType: oListItemCTName, AgentCount: 0 };
        skillsData.push(obj);
    }

    retrieveSkillsPerAgent();
}

// SkillsPerAgent data Query
function retrieveSkillsPerAgent() {
    if (debug) {
        console.log("retrieveSkillsPerAgent()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('SkillsPerAgent');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><OrderBy><FieldRef Name='Title' /></OrderBy></View>");
    this.collListItemsSkillsPerAgent = oList.getItems(camlQuery);

    clientContext.load(collListItemsSkillsPerAgent);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveSkillsPerAgentSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveSkillsPerAgentSucceeded(sender, args) {
    var skillsPerAgentCount = collListItemsSkillsPerAgent.get_count();
    $("#countSkillsPerAgent").html(skillsPerAgentCount); 
    $(".overview-items ul.actions li.ov-skillsperagent span").css("display", "block");

    var listItemEnumerator = collListItemsSkillsPerAgent.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemId = oListItem.get_item('ID');
        var oListItemSkill = oListItem.get_item('wsp_ucc_spa_skill').get_lookupValue()

        UpdateAgentCountInSkillsData(oListItemSkill);
    }

    skillsData.sort(function (a, b) {
        return (a.AgentCount < b.AgentCount) ? 1 : -1;
    });
    PrepDoughnutData2();
    PrepDoughnutData3();
	
}

// Business Hours data Query
function retrieveBusinesshours() {
    if (debug) {
        console.log("retrieveBusinesshours()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Businesshours');
    this.oFields = oList.get_fields();

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name='wsp_ucc_day' /></OrderBy><OrderBy><FieldRef Name='wsp_ucc_Start' /></OrderBy></Query></View>");
    this.collListItemsBusinesshours = oList.getItems(camlQuery);

    clientContext.load(collListItemsBusinesshours);
    clientContext.load(oFields);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveBusinesshoursSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveBusinesshoursSucceeded(sender, args) {
    var allDayFieldExists = false;
    var fieldItemEnumerator = oFields.getEnumerator();
    while (fieldItemEnumerator.moveNext()) {
        var oFieldItem = fieldItemEnumerator.get_current();
        var oFieldItemName = oFieldItem.get_title();
        if (oFieldItemName == "AllDay") {
            allDayFieldExists = true;
            break;
        }
    }

    var businessHoursCount = collListItemsBusinesshours.get_count();
    $(".overview-items ul.dialoguemanagement li.ov-businesshours span").html(businessHoursCount);
    $(".overview-items ul.dialoguemanagement li.ov-businesshours span").css("display", "block");

    var listItemEnumerator = collListItemsBusinesshours.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemDay = oListItem.get_item('wsp_ucc_day');
        var oListItemStart = oListItem.get_item('wsp_ucc_Start');
        var oListItemEnd = oListItem.get_item('wsp_ucc_End');
        var oListItemAllDay = false;
        if (allDayFieldExists == true) {
            oListItemAllDay = oListItem.get_item('wsp_ucc_AllDay');
        }

        var dayCode = 1;
        if (oListItemDay.toLowerCase() == "monday") {
            dayCode = 1;
        }
        else if (oListItemDay.toLowerCase() == "tuesday") {
            dayCode = 2;
        }
        else if (oListItemDay.toLowerCase() == "wednesday") {
            dayCode = 3;
        }
        else if (oListItemDay.toLowerCase() == "thursday") {
            dayCode = 4;
        }
        else if (oListItemDay.toLowerCase() == "friday") {
            dayCode = 5;
        }
        else if (oListItemDay.toLowerCase() == "saturday") {
            dayCode = 6;
        }
        else if (oListItemDay.toLowerCase() == "sunday") {
            dayCode = 7;
        }

        var obj = { Day: oListItemDay, DayCode: dayCode, Start: oListItemStart, End: oListItemEnd, AllDay: oListItemAllDay };
        businessHoursData.push(obj);
    }
    DisplayBusinessHours();
}

// Holidays data Query
function retrieveHolidays() {
    if (debug) {
        console.log("retrieveHolidays()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Holidays');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><Where><Or><Geq><FieldRef Name='wsp_ucc_holidays_startdatetime' /><Value Type='DateTime'><Today /></Value></Geq><And><Lt><FieldRef Name='wsp_ucc_holidays_startdatetime' /><Value Type='DateTime'><Today /></Value></Lt><Geq><FieldRef Name='wsp_ucc_holidays_enddatetime' /><Value Type='DateTime'><Today /></Value></Geq></And></Or></Where><OrderBy><FieldRef Name='wsp_ucc_holidays_startdatetime' /></OrderBy><OrderBy><FieldRef Name='Title' /></OrderBy></Query><RowLimit>1</RowLimit></View>");
    this.collListItemsHolidays = oList.getItems(camlQuery);

    clientContext.load(collListItemsHolidays);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveHolidaysSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveHolidaysSucceeded(sender, args) {
    var listItemEnumerator = collListItemsHolidays.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemHoliday = oListItem.get_item('Title');
        var oListItemStartDate = oListItem.get_item('wsp_ucc_holidays_startdatetime');
        var oListItemEndDate = oListItem.get_item('wsp_ucc_holidays_enddatetime');

        var tmpStartDate = moment(oListItemStartDate).utc().utcOffset(utcOffset);
        var tmpEndDate = moment(oListItemEndDate).utc().utcOffset(utcOffset);
        var obj = { Holiday: oListItemHoliday, MomentStartDate: tmpStartDate, MomentEndDate: tmpEndDate, FormattedStartDate: tmpStartDate.format("YYYYMMDDHHmm"), FormattedEndDate: tmpEndDate.format("YYYYMMDDHHmm") };
        holidaysData.push(obj);
    }
    DisplayHolidays();
}

// Settings data Query
function retrieveSettings() {
    if (debug) {
        console.log("retrieveSettings()");
    }
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Settings');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>");
    this.collListItemsSettings = oList.getItems(camlQuery);

    clientContext.load(collListItemsSettings);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveSettingsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveSettingsSucceeded(sender, args) {
    var settingsCount = collListItemsSettings.get_count();
    $(".overview-items ul.ucc li.ov-settings span").html(settingsCount);
    $(".overview-items ul.ucc li.ov-settings span").css("display", "block");

    var listItemEnumerator = collListItemsSettings.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemKey = oListItem.get_item('wsp_ucc_Key');
        var oListItemValue = oListItem.get_item('wsp_ucc_Value');

        var obj = { Key: oListItemKey, Value: oListItemValue };
        settingsData.push(obj);
    }
    DisplaySettings();
}

function onQueryFailed(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

function UpdateAgentCountInSkillsData(skill) {
    $.each(skillsData, function (key, value) {
        if (value.Skill == skill) {
            skillsData[key].AgentCount = skillsData[key].AgentCount + 1;
        }
		
    });
}

Date.prototype.stdTimezoneOffset = function () {
    var jan = new Date(this.getFullYear(), 0, 1);
    var jul = new Date(this.getFullYear(), 6, 1);
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

Date.prototype.dst = function () {
    return this.getTimezoneOffset() < this.stdTimezoneOffset();
}