﻿/// <reference name="MicrosoftAjax.js"/>

Sys.Application.add_init(AppInit);

function AppInit()
{
    //This will fire after page has updated
}

///////////////////////////////////////////////////////////////////////
// RateSession
//
// Determine if QuickTime is installed or not.
///////////////////////////////////////////////////////////////////////
function RateSession(session, score)  
{ 
    services.gartner.com.schemas.events.agendabuilder.v100.IAgendaBuilderJson.AddSessionRating(session, score, onRatingMethodCompleted, onRatingMethodFailed);
}  
///////////////////////////////////////////////////////////////////////
// onRatingMethodFailed
//
// Callback for RateSession failure 
///////////////////////////////////////////////////////////////////////
function onRatingMethodFailed(results)
{
}
///////////////////////////////////////////////////////////////////////
// onRatingMethodCompleted
//
// Callback for RateSession success 
///////////////////////////////////////////////////////////////////////
function onRatingMethodCompleted(results)
{ 
    var averageElement;
    var totalElement;
    var currentAverageElem;
    var currentAverageStyle;
    var average;
    var myRatingElem;
    var myRatingStyle;
    var userScore;
    var myCommentElem;
    var averageElementText;

    averageElement = getElementByPartialName('average_'+results.SessionId+'_sessionRating');
    if(averageElement)
    {
        averageElement.title = results.AverageScore + "/5";
    }

    totalElement = getElementByPartialName('total_'+results.SessionId+'_sessionRating');
    if(totalElement)
    {
        var totalVotesDisplayText;

            if (results.TotalVotes == 1)
            {
                totalVotesDisplayText  = voteSingular.toLowerCase();
            }
            else
            {
                totalVotesDisplayText = votePlural.toLowerCase();
            }
        totalElement.innerHTML  = results.TotalVotes + ' ' + totalVotesDisplayText;
    }
    
    currentAverageElem = getElementByPartialName('currentAverage_'+results.SessionId+ '_sessionRating'); 
    if(currentAverageElem)
    {
        currentAverageStyle = currentAverageElem.style;
        average = results.AverageScore * 100 /5;
        currentAverageStyle.width = average + "%";
    }
    
    myRatingElem = getElementByPartialName('myRating_'+results.SessionId+ '_sessionRating'); 
    if(myRatingElem)
    {
        myRatingStyle = myRatingElem.style;
        userScore = results.UserScore * 100 / 5;
        myRatingStyle.width = userScore + "%";
    }
    
    myCommentElem = getElementByPartialName('commentNumber_'+results.SessionId+ '_session'); 
    if(myCommentElem)
    {
        if(results.TotalComments > 0)
        {
            myCommentElem.innerHTML  = results.TotalComments;
        }
        else
        {
            myCommentElem.innerHTML  = noneMessage;
        }
    }
    
    averageElementText = getElementByPartialName('averageText_'+results.SessionId+'_sessionRating');
    if(averageElementText)
    {
        averageElementText.style.visibility = "visible";
    }
    
    averageElement = getElementByPartialName('averageScore_'+results.SessionId+'_sessionRating');
    if(averageElement)
    {
        var averageDisplayText;
        averageElement.innerHTML  = results.AverageScore;
        averageElement.style.visibility = "visible";
    }
    
}  


function AddEventSession(sessionId)
{
    services.gartner.com.schemas.events.agendabuilder.v100.IAgendaBuilderJson.AddEventSession(sessionId, onAddEventSessionMethodCompleted, onAddEventSessionMethodMethodFailed);
}

function onAddEventSessionMethodMethodFailed(results)
{

}

function onAddEventSessionMethodCompleted(results)
{
    var addRemoveElement;

    addRemoveElement = getElementByPartialName('AddRemove_'+results+'_cell');
    if(addRemoveElement)
    {
        addRemoveElement.innerHTML  = REMOVE_TITLE;
        addRemoveElement.onclick = new Function("RemoveEventSession("+results+");return false;");
    }

}

function RemoveEventSession(sessionId)
{
    services.gartner.com.schemas.events.agendabuilder.v100.IAgendaBuilderJson.RemoveEventSession(sessionId, onRemoveEventSessionMethodCompleted, onRemoveEventSessionMethodFailed);
}

function onRemoveEventSessionMethodFailed(results)
{

}

function onRemoveEventSessionMethodCompleted(results)
{
        var addRemoveElement;

    addRemoveElement = getElementByPartialName('AddRemove_'+results+'_cell');
    if(addRemoveElement)
    {
        addRemoveElement.innerHTML  = ADD_TITLE;
        addRemoveElement.onclick = new Function("AddEventSession("+results+");return false;");
         addRemoveElement = getElementByPartialName('AddRemove_'+results+'_cell');
    }
}


function ShowSpeakerPopup(speakerId, divAnchorId, xOffsetInPixels, yOffsetInPixels)
{
    var divImagePopup = document.getElementById('divImagePopup');
    if (divImagePopup)
    {
        divImagePopup.style.display = "";
    }
    ShowPopupAtOffset(divAnchorId, xOffsetInPixels, yOffsetInPixels);
	services.gartner.com.schemas.events.agendabuilder.v100.IAgendaBuilderJson.GetSpeaker(speakerId, onShowSpeakerPopupMethodCompleted, onShowSpeakerPopupMethodMethodFailed);
}

function onShowSpeakerPopupMethodMethodFailed(results)
{

}

function onShowSpeakerPopupMethodCompleted(results)
{
    var popupImage = document.getElementById('popupImage');
    if (popupImage)
    {
        popupImage.src = results.ImagePath;
    }
}


function HideSpeakerPopup()
{
     var divImagePopup = document.getElementById('divImagePopup');
    if (divImagePopup)
    {
        divImagePopup.style.display = "none";
    }
    HidePopup(); 
    DeletePopup();
    var popupImage = document.getElementById('popupImage');
    if (popupImage)
    {
        popupImage.src = '../Images/Common/loading_small.gif';
    }
    
}


function addUrlRowToTable(tableName, url, urlText)
{
  var tbl = getElementByPartialName(tableName); 
  var anchor;
  var lastRow = tbl.rows.length;
  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);
  
  // left cell
  var cellLeft = row.insertCell(0);
  var textNode = document.createTextNode(iteration);
 
  
 
 
 anchor = document.createElement("a"); 
 anchortext = document.createTextNode(urlText); 
 anchor.appendChild(anchortext);
 anchor.setAttribute('href',url);
 
  cellLeft.appendChild(anchor);
}

function GetFutureEvents(speakerId, eventCode, isOnsite)
{
    services.gartner.com.schemas.events.agendabuilder.v100.IAgendaBuilderJson.GetFutureEvents(speakerId, eventCode, isOnsite, onGetFutureEventsMethodCompleted, onGetFutureEventsMethodFailed);
}

function onGetFutureEventsMethodFailed(results) {

}

function onGetFutureEventsMethodCompleted(results) {
    futureEventsLoadingElement = getElementByPartialName('FutureEventsLoading');
    if (futureEventsLoadingElement) {
        Sys.UI.DomElement.removeCssClass(futureEventsLoadingElement, 'loadingSmall');
    }


    futureEventsLoadingElement = getElementByPartialName('FutureEvents');
    if (futureEventsLoadingElement) {
        futureEventsLoadingElement.innerHTML = results;
    }

}

function GetRecentPublications(authorId)
{
    services.gartner.com.schemas.events.agendabuilder.v100.IAgendaBuilderJson.GetRecentPublications(authorId, onGetRecentPublicationsMethodCompleted, onGetRecentPublicationsMethodFailed);
}

function onGetRecentPublicationsMethodFailed(results)
{

}

function onGetRecentPublicationsMethodCompleted(results)
{
   recentPublicationsLoadingElement = getElementByPartialName('RecentPublicationsLoading');
    if(recentPublicationsLoadingElement)
    {
        Sys.UI.DomElement.removeCssClass(recentPublicationsLoadingElement, 'loadingSmall');
    }
  
  
   recentPublicationsElement = getElementByPartialName('RecentPublications');
    if(recentPublicationsElement)
    {
        recentPublicationsElement.innerHTML = results;
    }

}

function LogPollingSubmission(questionId, responseId, writtenResponse)
{
    var responseText = "";
    var response = document.getElementById(writtenResponse);
    if(response)
    {
        responseText = response.value;
    }
    services.gartner.com.schemas.events.agendabuilder.v100.IAgendaBuilderJson.LogPollingSubmission(questionId, responseId, responseText, onLogPollingSubmissionMethodCompleted, onLogPollingSubmissionMethodFailed);
}

function onLogPollingSubmissionMethodFailed(results)
{

}

 // Globals
var animateBars = false;
var responseCount = 0;
var totalVoteCount = 0;

//Submission
var voteCount = new Object();
var ratio = new Object();
var currentBarWidth = new Object();
var finalBarWidth = new Object();
var intervalId = new Object();
var divPercent = new Object();
var divBar = new Object();
var divTotalVotes = new Object();
var divResponse = new Object();
var divButton = new Object();
var barDirection = new Object();


//Question
var lastSubissionTime = new Object();
var stepSpeed = 4;

function StartBars()
{
    animateBars = true;
    enablePollClientTimer();
}

function StopBars()
{
    animateBars = false;
    if (typeof disablePollClientTimer != 'undefined')
    {
        disablePollClientTimer();
    }
}


function onLogPollingSubmissionMethodCompleted(results)
{
    DrawBars(results);
}



function onGetPollingQuestionsByTypeAndIdMethodFailed(results)
{
   
}

function onGetPollingQuestionsByTypeAndIdMethodCompleted(results)
{
    for (var index = 0; index <= results.length-1; index++)
        {
            DrawBars(results[index])
        }
}

function DrawBars(results)
{
    if(lastSubissionTime[results.Id] == undefined || results.LastSubmissionTime > lastSubissionTime[results.Id])
    {
        divTotalVotes[results.Id] = divTotalVotes[results.Id] == null ? getElementByPartialName('totalVotes_' + results.Id) : divTotalVotes[results.Id];
        
        // List total votes.
        if(divTotalVotes[results.Id])
        {
            var voteTerm = results.SubmissionCount == 1 ? VOTE_SINGULAR.toLowerCase() : VOTE_PLURAL.toLowerCase(); ;
            divTotalVotes[results.Id].innerHTML = results.SubmissionCount.toString() + " " + voteTerm;
            lastSubissionTime[results.Id] = results.LastSubmissionTime;
            for (var index = 0; index <= results.Responses.length - 1; index++)
                {
                var id = results.Responses[index].Id;

                // Stop any current drawing.
                if (animateBars && intervalId[id] != undefined & intervalId[id] != 0)
                {
                    window.clearInterval(intervalId[id]);
                    intervalId[id] = 0;
                }
                        
                // Calculations and setup.
                ratio[id] = ratio[id] == undefined ? new Number(0.0) : ratio[id];
                if(results.SubmissionCount > 0)
                {
                    ratio[id] = results.Responses[index].SubmissionCount / results.SubmissionCount;
                }
                
                currentBarWidth[id] = currentBarWidth[id] == undefined ? 0 : currentBarWidth[id];
                finalBarWidth[id] = Math.round(ratio[id] * maxBarWidth);
                
                barDirection[id] = finalBarWidth[id] < currentBarWidth[id] ? -1 : 1;
                

                divResponse[id] = divResponse[id] == null ? getElementByPartialName('response_' + id) : divResponse[id];
                divButton[id] = divButton[id] == null ? getElementByPartialName('button_' + id): divButton[id];  
                

                if(divResponse[id] &&  divButton[id])
                {
                    if(results.Responses[index].CurrentUserSelection)
                    {
                        //divResponse.style.color = colorRed;
                        divResponse[id].className = "pollResponseQuestionSelected";
                        divButton[id].className = "pollResponseButtonSelected";
                    }
                    else{
                        //divResponse.style.color = colorGreen;
                        divResponse[id].className = "pollResponseQuestion";
                        divButton[id].className = "pollResponseButton";
                    }
                }
                divPercent[id] = divPercent[id] == null ? getElementByPartialName('percent_'+id) : divPercent[id];
                
                divBar[id] = divBar[id] == null ? getElementByPartialName('bar_' + id) : divBar[id];
                // Start drawing a bar.
                if(divBar[id] && divPercent[id])
                {
                    if (animateBars)
                    {
                        divBar[id].style.display = "";
                        divPercent[id].innerHTML = "";
                        intervalId[id] = window.setInterval("DrawBar('" + id + "')", 1);
                    }
                    else
                    {
                        divBar[id].style.width = finalBarWidth[id].toString() + "px";
                        divBar[id].style.height = maxBarHeight.toString() + "px";
                        divBar[id].style.display = finalBarWidth[id] == 0 ? "none" : "";
                        divPercent[id].innerHTML = (ratio[id] * 100.0).toFixed(1) + "%";
                    }
                }
            }
        }
    }
}
    
// Draw a piece of a result bar for a single response. Call repeatedly
// and it will stop when the bar is complete.
function DrawBar(id)
{
    var currentDivBar = divBar[id];
    var currentDivPercent = divPercent[id];

    currentBarWidth[id] += (stepSpeed * barDirection[id]);
    var startNumber;
    var endNumber;
    
    if(barDirection[id] > 0)
    {
        startNumber = currentBarWidth[id];
        endNumber = finalBarWidth[id];
    }
    else
    {
        startNumber = finalBarWidth[id];
        endNumber = currentBarWidth[id];
    }
    
    if (startNumber >= endNumber)
    {
        window.clearInterval(intervalId[id]);
        intervalId[id] = 0;
        currentDivPercent.innerHTML = (ratio[id] * 100.0).toFixed(1) + "%";
        currentDivBar.style.width = finalBarWidth[id].toString() + "px";
        if (finalBarWidth[id] == 0)
        {
            currentDivBar.style.display = "none";
        }
        barDirection[id] *= -1;
    }
    else
    {
        currentDivBar.style.width = currentBarWidth[id].toString() + "px";
    }
}
