﻿
// The page feedback display element.
var displayResult;

// The page feedback display element.
//var sessionListDiv;

// The page number of active chats element.
var activeChatsNumDiv;
var totalActiveChats = 0;

// Constants - correspond to enum values
var SessionType_Text = 1;
var SessionType_Video = 2;
var SessionType_Audio = 3;
var SessionStatus_IncomingAwaitingConfirmation = 0;
var SessionStatus_OutgoingAwaitingConfirmation = 1;
var SessionStatus_ActiveNotOpened = 2;
var SessionStatus_ActiveAlreadyOpen = 3;

/* This variable stores the most recent list of sessions from the server.
 * It's used to check whether a session object which returned from a new call
 * is fresh, and sound is played.
 */
var lastSessionList = null;
var isFirstCallToGetSessions = true;
 

/* This function intializes the global variables and
 * assigns default values to the generated proxy.
 */
function pageLoad() 
{
    // Get page feedback display element.
    displayResult = document.getElementById("ResultId");
        
        
    // get page number of active chats element.
    activeChatsNumDiv = document.getElementById("ActiveChatsNum");
        
 }
 
 function startCheckingForSessions()
 {
    // Call GetCurrentSessions every few seconds
    setInterval("CallGetCurrentSessions()", 5000);
    
    //load the session window
    sessionWindow.init();
 }
 
 // Get a generic List.
 function CallGetCurrentSessions() 
 {	   
    GirlsTeachGuys.Website.Services.UserSessionsService.GetCurrentSessions(
    GetCurrentSessionsCompleted_Success, GetCurrentSessionsCompleted_Error); 
 } 
 
 function CallConfirmSession(sessionID) 
 {	   
    
    GirlsTeachGuys.Website.Services.UserSessionsService.ConfirmSession(sessionID);
 }
 
 function CallTextConfirmSession(sessionID) 
 {	   
    
    GirlsTeachGuys.Website.Services.UserSessionsService.ConfirmSession(sessionID);
 }
 
 function CallDeclineSession(sessionID) 
 {	   
    
    GirlsTeachGuys.Website.Services.UserSessionsService.DeclineSession(sessionID);
 }
 
 
 
 function OpenVideoChat(sessionExternalKey)
 {
    var videoChatWindow = window.open("/Chat/VideoChat.aspx?ExternalSessionKey=" + sessionExternalKey + "&audioOnly=false" ,"VideoChat","status=1,width=800,height=600"); 
 }
 
 function OpenAudioChat(sessionExternalKey)
 {
    var videoChatWindow = window.open("/Chat/VideoChat.aspx?ExternalSessionKey=" + sessionExternalKey + "&audioOnly=true" ,"VideoChat","status=1,width=650,height=500"); 
 }
 
 function OpenTextualChat(sessionExternalKey)
 {
    var videoChatWindow = window.open("/Chat/VideoChat.aspx?ExternalSessionKey=" + sessionExternalKey + "&textualOnly=true" ,"VideoChat","status=1,width=650,height=500"); 
 }
 

 // This is the failed callback function.
function GetCurrentSessionsCompleted_Error(error)
{

}

/* Callback function invoked when the call to 
 * the Web service methods succeeds. 
 */
function GetCurrentSessionsCompleted_Success(result, userContext, methodName)
{ 
    
    if(result == null)
    {
        sessionWindow.deleteAll();    // if we dont have any result we will delete the window and all the sessions        
    }
    else
    {
        // load the sessions result the session window UI
        sessionWindow.loadSessions(result);
        
        //Upadte the active panding chats in the toolbox
        activeChatsNumDiv.innerHTML = "(" + result.length + ")";

        // On the first call to this method
        if (isFirstCallToGetSessions)
        {
            // Indicate that future calls are no longer the first one
            isFirstCallToGetSessions = false;
        }
            // If this is not the first call to GetSessions
        else
        {
            // Check and beep on new awaiting sessions as necessary
            CheckForNewSessionsAwaitingConfirmation(result);
        }
    
        lastSessionList = result;
    }
}

/* Iterates the new list of sessions returned from the server.
 * If any new session (session whose ID did not appear in the previous)
 * is discovered, a beep sound is played
 */
function CheckForNewSessionsAwaitingConfirmation(newList)
{
    var discoveredNewWaitingSession = false;
    
    // Iterate all new sessions
    for (var newItem in newList)
    {
        var newSession = newList[newItem];
        
        // If the status is awaiting confirmation
        if (newSession.Status == SessionStatus_IncomingAwaitingConfirmation)
        {
            var found = false;
        
            for (var previousItem in lastSessionList)
            {
                var sessionInPreviousList = lastSessionList[previousItem];
                
                if (sessionInPreviousList.Status == SessionStatus_IncomingAwaitingConfirmation &&
                    newSession.ID == sessionInPreviousList.ID)
                {
                    found = true;
                    break;
                }
            }

            // If session hasn't been found in previous list
            if (!found)
            {
                discoveredNewWaitingSession = true;
                break;
            }
        }
    }
    
    // Check if any new session was discovered
    if (discoveredNewWaitingSession)
    {   
        sessionWindow.playBeepSound();
        sessionWindow.show();     
    }
}

    
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();



//session window UI
var sessionWindow = {
    
    init:function()
    {
       sessionWindow.ID = 'sessionWindow';
       sessionWindow.Name= "New Chats";
       
       //add session div to the body
       jQuery("body").append('<div id="'+sessionWindow.ID+'"><p>'+sessionWindow.Name+'</p><ul></ul></div><div id="'+sessionWindow.ID+'_beepSound"></div>');
       
       //bind on click event 
       jQuery('#'+sessionWindow.ID+' p').click(
			function() { jQuery(this).siblings('ul').slideToggle() }
		);
		
		soundPlayer.init({container:sessionWindow.ID+'_beepSound',filepath:'/sounds/bloop.mp3',hidden:true});
    },
      
    //add new session to the window
    addNewSession:function(session)
    {
         acceptLink = "";
         declineLink = "";
         sessionInfo ="";
         
        if (session.Status == SessionStatus_IncomingAwaitingConfirmation)
            {
                switch(session.Type)
                {
                    case 1:
                        sessionInfo = "Text Chat";
                        break;
                    case 2:
                        sessionInfo = "Webcam Chat";
                        break;
                    case 3:
                        sessionInfo = "Voice Chat";
                        break;
                }
              
                if(session.Type == SessionType_Text)
                {
                    callFunctions = "CallTextConfirmSession(" + session.ID +");sessionWindow.addConnectingMsg("+ session.ID +");"
                }
                else
                {
                    callFunctions = "CallConfirmSession(" + session.ID + ");sessionWindow.addConnectingMsg("+ session.ID +");"
                }

                acceptLink = "<a href=\"javascript:" + callFunctions +"\"><img src='/images/accept.png' alt='accept'> Accept</a>";
                declineLink = "<a href=\"javascript:CallDeclineSession(" + session.ID + ");sessionWindow.deleteSession("+ session.ID +");\"><img src='/images/delete.png' alt='Decline'> Decline</a>";
            }
            else if (session.Status == SessionStatus_OutgoingAwaitingConfirmation)
            {
                //do not display waiting meessge if we in text chat mode
                // OLD CHAT MODE
                //if(session.Type == SessionType_Text)
                //{
                //    return;
                //}
                
                sessionInfo = "<img src='images/ajaxLoadingSmall.gif'> Waiting confirmation";
                declineLink = "<a href=\"javascript:CallDeclineSession(" + session.ID + ");sessionWindow.deleteSession("+ session.ID +");\"><img src='/images/delete.png' alt='Decline'> Cancel</a>";
            }
            else if(session.Status == SessionStatus_ActiveAlreadyOpen)
            {
                return;
            }
        
            output = "<div >"+
                "<div style=\"float:left;\">"+
                    "<img border=\"0\" width=\"50\" height=\"50\" src=\"" + session.OtherUserThumbnailURL + "\">"+
                "</div>"+
                "<div style=\"text-align:left;padding-left:6px;float:left\">"+
                    "<div><a href=\"ProfilePage.aspx?userID="+ session.OtherUserID +"\">"+session.OtherUserName + "</a></div>"+
                    "<div class='ChatInfo' id='sessionInfo'>" + sessionInfo + "</div>"+
                    "<div  class=\"ButtomLinks\">" +
                       acceptLink + " " + declineLink;
                    "</div>"+
                 "</div>"+
                "</div>";
            
            //Prepend session to the window and add slide effect
            jQuery('#'+sessionWindow.ID)
				.show().children('ul').prepend('<li id="li_'+ session.ID + '">' + output + '</li>')	
				.children('li:first').slideDown(200);
				
	        // check if we need to add open now link
	        if(session.Status == SessionStatus_ActiveNotOpened)
            {
                sessionWindow.changeToActiveNotOpened(session);
            }
            
            setTimeout("sessionWindow.show()",500);			
    },
    
    //change session info and add the open now link for video and voice chat
    changeToActiveNotOpened:function(session)
    {
        // if we are here we have only a video chat or a voice chat
        if (session.Type == SessionType_Text)
        {
            funcName = "OpenTextualChat('" + session.ExternalKey + "');";
        }
        else if (session.Type == SessionType_Video)
        {
            funcName = "OpenVideoChat('" + session.ExternalKey + "');";
        }
        else
        {
            funcName = "OpenAudioChat('" + session.ExternalKey + "');";
        }
        
        acceptLink = "<a id='accept_"+ session.ID+"' href=\"javascript:" + funcName + " sessionWindow.deleteSession("+ session.ID +");\"><img src='/images/accept.png' alt='accept'> Start Chat</a>";
    
        sessionInfo = "Connected";
      
        jQuery('#'+sessionWindow.ID).find('#li_'+ session.ID + ' .ChatInfo').html(sessionInfo);
        jQuery('#'+sessionWindow.ID).find('#li_'+ session.ID + ' .ButtomLinks').html(acceptLink); 
    },
    
    //if the session exists check if we need to add the open chat window
    handleeExistingSession:function(session)
    { 
        //check if we are alredy have open now link if not we will added it
        if(session.Status == SessionStatus_ActiveNotOpened && jQuery('#'+sessionWindow.ID +' div').find('#accept_'+ session.ID).length == 0)
        {
            sessionWindow.changeToActiveNotOpened(session);    
        }
        else if(session.Status == SessionStatus_ActiveAlreadyOpen)
        {
            sessionWindow.deleteSession(session.ID);         
        }
        // OLD CHAT METHOD
        //else if(session.Status == SessionStatus_OutgoingAwaitingConfirmation && session.Type == SessionType_Text)
        //{
        //    sessionWindow.deleteSession(session.ID); 
        //}
    },
    
    //change the info message to connecting after session confirmation 
    addConnectingMsg: function(sessionID)
    { 
       sessionInfo = "<img src='images/ajaxLoadingSmall.gif'> Connecting...";
       jQuery('#'+sessionWindow.ID).find('#li_'+ sessionID + ' .ChatInfo').html(sessionInfo);
       jQuery('#'+sessionWindow.ID).find('#li_'+ sessionID + ' .ButtomLinks').html(''); 
    },
    
    //find inActive sessions and delete them
    deleteOldSessions:function(result)
    {
        jQuery('#'+sessionWindow.ID +' li').each(function(){
            
            tempId = this.id.substring(3);
            
            flagArr = jQuery.grep(result, function (tmpSession) { 
                return tmpSession.ID == tempId; 
            })
            
            //elemnt is not in the list delete it;
            if(flagArr.length == 0)
            {
                sessionWindow.deleteSession(tempId);
            }
        });
    },
    
    //delete session from the window by id
    deleteSession:function(sessionID)
    {
         jQuery('#'+sessionWindow.ID).find('#li_'+ sessionID ).slideUp("slow",function(){
           
             jQuery(this).remove();
   
            //hide the panel if the are no sessions
            if(jQuery('#'+ sessionWindow.ID +' li').size()==0){
                sessionWindow.hide();
            }
        });  
    },
    
    //hides the session window
    hide:function()
    {
        jQuery('#'+sessionWindow.ID).slideUp("slow");
    },
    
    //show session window
    show:function()
    {
        jQuery('#'+sessionWindow.ID+' p').siblings('ul').slideDown("slow");  
    },
    
    toggle:function()
    {
        jQuery('#'+sessionWindow.ID+' p').siblings('ul').slideToggle("slow");  
    },
    
    //load new session to the session window 
    loadSessions:function(results)
    {
        // delete old sessions from the window
        sessionWindow.deleteOldSessions(results);
       
        bounceFlag = ""; 
      
        //close the window if we do not have a sessions in the result;
        if(results.length > 0 )
        {  
            jQuery.each(results, function() {
                
                //check if our session exists in the session window
                if (jQuery('#'+sessionWindow.ID).find('#li_'+ this.ID).length == 0)
                {
                    sessionWindow.addNewSession(this); 
		        }
		        else
		        {
		            // check if we need to bounce the window
                    if(this.Status != SessionStatus_OutgoingAwaitingConfirmation )
                    {
                        bounceFlag = 1;
                    }
		            
		            sessionWindow.handleeExistingSession(this)
		        }	
            });
            
            //bounce baby bounce
            if(bounceFlag == 1 )
            {
               sessionWindow.bounce();  
            }
        }
    },
    
    //bounce the session window if it collpased and we have a padding session    
    bounce:function()
    {
        //animte the session title if it collpased
		if ( jQuery('#'+sessionWindow.ID+' ul').is(':hidden')) {
			
			jQuery('#'+sessionWindow.ID+' p').fadeIn(100).animate({top:"-=20px"},100).animate({top:"+=20px"},100).animate({top:"-=20px"},100).animate({top:"+=20px"},100).animate({top:"-=20px"},100).animate({top:"+=20px"},100);
		}
    },
    playBeepSound:function()
    {
       soundPlayer.play();
    },
    
    //deletes all sessions from the window
    deleteAll:function()
    {
        jQuery('#'+sessionWindow.ID +' li').each(function(){
            sessionWindow.deleteSession( this.id.substring(3));
        });   
    }
}


