﻿    // global variables
    var isError = 0;
    var isMessageSentToVidyoApplet = 0;
    var isPopupShown = 0;
    var isVidyoClientReady = 0; 
    var delayTimeForResend = 500;
    var messageForVidyoClient = "";
    var refreshElement = "";
    var applet = "";
    var enablePopupAutoHide = 0;
    var isPopupAutoHideEnabled = 0;
    var isVidyoAlreadyInstalled = 0;
    var allowAutoFullPostback = 1;
    var signInCommand = "";
    
    // global variables for vidyo client install logging
    var vidyoSessionId= 0;
    var webPortalId = 0;
    var currentUrl = "";
    var userAgent = "";
    var isVidyoInstallLogDone = 0;
    
	// show jquery popup (also accept the element to refresh when hiding popup)
    function ShowPopup(elementToRefreshWhenHidePopup, blockUIwidthPercent, blockUIleftPercent)
    {
        ConsoleLog("ShowPopup('" + elementToRefreshWhenHidePopup + "') called");
        
        refreshElement = elementToRefreshWhenHidePopup;
        
        $.blockUI({ 
                    message: '<div id="viyoPopupContent" style="background-color:White; padding-top:10px; padding-bottom:5px; z-index: 200010;">' +
                             '<h1><img src="/v3/images/progress-indicator.gif" /><br />' +
                             '<div id="vidyoPopupMessage" style="padding-top:5px;">Just a moment...</div></h1>' +
                             '<div id="divClosePopup" style="text-align: right; padding-right: 5px; ">' +
                             '<a id="closePopup" style="color: black; font-family: Arial,Helvetica,sans-serif; cursor: pointer;">Close</a></div></div>' ,
                    css: { 
                            border: 'none', 
                            padding: '10px', 
                            backgroundColor: '#3AA8CD', 
                            color: '#fff',
                            width : blockUIwidthPercent + '%',
                            left : blockUIleftPercent + '%'
                        }
                  });  
                  
        // close popup on close popup link click event
        $("#closePopup").live("click", function(){
                            HideVidyoPopup();
                        });
                  
        // hide the div for close popup button
        $("#divClosePopup").hide();
        
        EnableAutoHide();
        
        isPopupShown = 1; 
    }
    
    function EnableAutoHide()
    {
        // enable popup auto hide mechanism if allowed to auto hide and already not enabled yet
        if (enablePopupAutoHide == 1 && isPopupAutoHideEnabled == 0)
        {
            // show close link on popup after 40 seconds
            setTimeout('ShowClosePopupLink()', 40000);
            
            // hide popup in 2 mins
            setTimeout('HideVidyoPopup()', 120000);
            
            isPopupAutoHideEnabled = 1;
        }
    }
    
    function ShowVidyoPopup(elementToRefreshWhenHidePopup, blockUIwidthPercent, blockUIleftPercent, isAutoFullPostbackAllowed)
    {
        // load popup once page is loaded
        $(document).ready(function() {
        
            ConsoleLog("ShowVidyoPopup('" + elementToRefreshWhenHidePopup + "', " + blockUIwidthPercent + ", " + blockUIleftPercent + ", " + isAutoFullPostbackAllowed + ") called and isPopupShown is " + isPopupShown);
            
            allowAutoFullPostback = isAutoFullPostbackAllowed;
            
            if(isPopupShown == 0)
            {
                ShowPopup(elementToRefreshWhenHidePopup, blockUIwidthPercent, blockUIleftPercent);
            }
        });
    }
    
    function HideVidyoPopup()
    {
        if(isPopupShown == 1)
        {
            $.unblockUI();
            isPopupShown = 0;
            
            resetGlobalVariables()
            
            // refresh updatepanel
            RefreshVideoCallStatus();
        }
    }
    
    function resetGlobalVariables()
    {
        ConsoleLog('Reseting Vidyo helper Global Variables');
        isError = 0;
        isMessageSentToVidyoApplet = 0;
        isPopupShown = 0;
        isVidyoClientReady = 0; 
        delayTimeForResend = 500;
        messageForVidyoClient = "";
        refreshElement = "";
        applet = "";
        enablePopupAutoHide = 0;
        isPopupAutoHideEnabled = 0;
        isVidyoAlreadyInstalled = 0;
        signInCommand = "";
        
        vidyoSessionId = 0;
        webPortalId = 0;
        currentUrl = "";
        userAgent = "";
        isVidyoInstallLogDone = 0;
    }
    
    function SetSignInCommand(value)
    {
        signInCommand = value;
    }
    
    function RequestVideoCallStatus(elementToRefresh, interval)
    {
        refreshElement = elementToRefresh;    
        
        // Process manual refresh request only if popup is not shown
        if(isPopupShown == 0)
        {
            ConsoleLog("manual request to refresh { " + refreshElement + " } ");
           
            setTimeout('RefreshVideoCallStatus();', interval);
        }
    }
    
    // do partial postback
    function RefreshVideoCallStatus()
    {
        ConsoleLog("going to refresh '" + refreshElement + "' and allowAutoFullPostback = " + allowAutoFullPostback);

        // simulate button click programatically
        var button = null;
        
        if(refreshElement.length > 0)
        {
            button = document.getElementById(refreshElement);
        }
        
        if(button != null)
        {
            // do partial postback
            button.click();
        }
        else
        {
            if(allowAutoFullPostback == 1)
            {
                // do full postback by reloading current page
                window.location = window.location.href;
            }
        }
    }
    
    // show link to close popup
    function ShowClosePopupLink()
    {
        if(isPopupShown == 1)
        {
            $("#divClosePopup").show();
        }
    }
    
    function SendMessageToVidyoApplet(message)
    {
        $(document).ready(function()
        {
            // set global var
            messageForVidyoClient = message;
            
            ConsoleLog("SendMessageToVidyoApplet( "+ message + ") called and isVidyoClientReady = " + isVidyoClientReady);
            
            applet = document.getElementById('vidyoApplet');
            if(applet) 
            {
                // send command to vidyo client if vidyo client is ready to accept message
                if(isVidyoClientReady == 1)
                {
                    // send the message to client in half second
                    setTimeout(function()
                        {
                            applet.sendMsg(messageForVidyoClient);
                            
                            isMessageSentToVidyoApplet = 1;

                        }, delayTimeForResend);
                }
            }
            else
            {
                ShowVidyoErrorMessage('There was an error trying to load a java component. Please go to the <a href="/setupvideo">Set Up / Test Video</a> page to verify your computers configuration.')
            }
        });
    }
    
    function ShowVidyoPopupMessage(message)
    {
        if(isError == 0)
        {  
            $("#vidyoPopupMessage").html("").html(message);
        }
                    
        EnableAutoHide();
    }
    
    function ShowVidyoErrorMessage(message)
    {
        ShowVidyoPopupMessage(message);
        
        // show error message in Firebug console as well
        ConsoleLog("ShowVidyoErrorMessage( "+ message + ") called");
        
        isError = 1;
        
        // show link to close popup
        ShowClosePopupLink();
    }
    
    function onAppletLoad()
    {
        enablePopupAutoHide = 1;
        
        ShowVidyoPopupMessage('Starting your vidyo desktop client');
    }

    function setSuccessStatus()
    { 
        isVidyoClientReady = 1;
 
        ConsoleLog('setSuccessStatus() called and isError = '+ isError + ' and isMessageSentToVidyoApplet = ' + isMessageSentToVidyoApplet + ' and isVidyoClientReady = ' + isVidyoClientReady);
        
        // hide popup if 
        //    it is not in error state (and ignore first setSuccessStatus() call because it arise from sign in command)
        if(isError == 0)
        {   
            ConsoleLog("going to call HideVidyoPopup() in 5 second");
            
            // hide popup in 5 seconds to make sure that vidyo call db records are updated
            var delayPeriod = 5000 + delayTimeForResend;
            setTimeout('HideVidyoPopup()', delayPeriod);
            
            // if message not sent to vidyo client ( in case, vidyo client just installed) then send message again
            if(isMessageSentToVidyoApplet == 0)
            {
                ConsoleLog("send message again to vidyo client" + messageForVidyoClient);
               
                // send message again to vidyo client
                SendMessageToVidyoApplet(messageForVidyoClient);
            }
        }
    }
    
    function TryManualVidyoCall()
    {
        ConsoleLog("going to manually login and the call");

        // if message not sent to vidyo client ( in case, vidyo client just installed) then send message again
        if(isMessageSentToVidyoApplet == 0)
        {
            applet = document.getElementById('vidyoApplet');
            if(applet) 
            {
                // send the signin command to vidyo client
                if(signInCommand.length > 0)
                {
                    isMessageSentToVidyoApplet = 1;
                                   
                    applet.sendMsg(signInCommand);
                    
                    if(messageForVidyoClient.length > 0)
                    {
                        // send the join conference command in 5 seconds                
                        setTimeout(function()
                            {
                                applet.sendMsg(messageForVidyoClient);
                                
                            }, 500);
                    }
                    // hide the popup in next 5 seconds
                    setTimeout('HideVidyoPopup()', 5000);
                }
                else
                {
                    ConsoleLog('signin attribute not found in Applet');
                }
            }
            else
            {
                ShowVidyoErrorMessage('There was an error trying to load a java component. Please go to the <a href="/setupvideo">Set Up / Test Video</a> page to verify your computers configuration.')
            }
        }

    }

    function installDownload()
    { 
        enablePopupAutoHide = 1;

        ShowVidyoPopupMessage('Downloading the vidyo desktop client');
        isMessageSentToVidyoApplet = 0;
    }

    function installDownloaded()
    { 
        enablePopupAutoHide = 1;
        
        ConsoleLog('installDownload() called');
        
        ShowVidyoPopupMessage('Vidyo desktop client download complete');
        isMessageSentToVidyoApplet = 0;
    }
    
    function installed()
    {
        enablePopupAutoHide = 1;
        
        ShowVidyoPopupMessage('Vidyo desktop client installation complete');
        isMessageSentToVidyoApplet = 0;
    }        
    
    function setFailedStatus() 
    { 
        enablePopupAutoHide = 1;
        
        if(isVidyoAlreadyInstalled == 0)
        {
            ShowVidyoErrorMessage('The vidyo desktop client could not be started. Please restart your browser and try again.');
        }
        else
        {
            ShowVidyoErrorMessage("The vidyo desktop client could not be upgraded.<br/> Attempting to proceed with the currently installed version.<br/>For the latest software please restart your browser as the administrator and retry. "); 
            
            TryManualVidyoCall();
        }
    }
    
    function runAsAdmin()
    {
        enablePopupAutoHide = 1;
        
        if(isVidyoAlreadyInstalled == 0)
        {
            ShowVidyoErrorMessage('The vidyo desktop client could not be installed. Please restart your browser as the administrator and try again.');
        }
        else
        {
            ShowVidyoErrorMessage("The vidyo desktop client could not be upgraded.<br/> Attempting to proceed with the currently installed version.<br/>For the latest software please restart your browser as the administrator and retry. "); 
            
            TryManualVidyoCall();
        }
    }

    function notinstalled() 
    {
        // Callback when VidyoDesktop.exe was not successfully installed
        enablePopupAutoHide = 1;
        
        if(isVidyoAlreadyInstalled == 0)
        {
            ShowVidyoErrorMessage("The vidyo desktop client could not be installed. Please go to the <a href='/setupvideo'>Set Up / Test Video</a> page to verify your computers configuration."); 
        }
        else
        {
            ShowVidyoErrorMessage("The vidyo desktop client could not be upgraded. Please go to the <a href='/setupvideo'>Set Up / Test Video</a> page to verify your computers configuration. <br/> Attempting to proceed with the currently installed version..."); 
            
            TryManualVidyoCall();
        }
    }
    
    
    function showChangingPortal(elementToRefreshWhenHidePopup, blockUIwidthPercent, blockUIleftPercent, isAutoFullPostbackAllowed)
    {
        ConsoleLog("showChangingPortal() called");

        ShowVidyoPopup(elementToRefreshWhenHidePopup, blockUIwidthPercent, blockUIleftPercent, isAutoFullPostbackAllowed);
        ShowVidyoPopupMessage('Changing your vidyo server. <br/> This may take up to a minute.');
    }
    
    function hideEnvPopupAndShowChangingPortal(elementToHide, elementToRefreshWhenHidePopup, blockUIwidthPercent, blockUIleftPercent, isAutoFullPostbackAllowed)
    {
        // hide the element and background
        $("#" + elementToHide + ",.modalBackground").hide();
        
        showChangingPortal(elementToRefreshWhenHidePopup, blockUIwidthPercent, blockUIleftPercent, isAutoFullPostbackAllowed);
    }
    
    function downloadedForSilentInstall()
    {
        enablePopupAutoHide = 1;

        ShowVidyoPopupMessage('Upgrading the vidyo desktop client');
        isMessageSentToVidyoApplet = 0;
        isVidyoAlreadyInstalled = 1;
    }
    
    function reinstalled()
    {
        enablePopupAutoHide = 1;

        ShowVidyoPopupMessage('Reinstalling the vidyo desktop client');
        isMessageSentToVidyoApplet = 0;
        isVidyoAlreadyInstalled = 1;
    }
    
    // function to set values for vidyo client install logging
    function SetVidyoInstallLogVars(vsid, wpid, url, agent)
    {
        vidyoSessionId = vsid;
        webPortalId = wpid;
        currentUrl = url;
        userAgent = agent;
        
        isVidyoInstallLogDone = 0;
    }
    
    function logNewInstall(clientInfo)
    {
        logNewInstall(clientInfo, null, null);
    }
        
    function logNewInstall(macAddress, ipAddress, hostName)
    {
        ConsoleLog('logNewInstall called with macAddress=' + macAddress + ' ; ipAddress=' + ipAddress + ' ; hostName=' + hostName);
        
        if(isVidyoInstallLogDone == 0)
        {
            // check if there is parameter mismatch issue of vidyo client 1.4
            if(macAddress != null && ipAddress == null && hostName == null)
            {   
                var clientInfo= new String(macAddress);
                var clientInfos = clientInfo.split('&'); // split on &            
                
                macAddress= clientInfos[0].replace( /macAddress=/,'');
                ipAddress= clientInfos[1].replace( /ipAddress=/,'');
                hostName= clientInfos[2].replace( /hostName=/,'');
            }
        
            AttendAnywhere.VidyoClientInstallLog.LogVidyoInstall(macAddress, ipAddress, hostName, vidyoSessionId, webPortalId, currentUrl, userAgent, OnLogVidyoInstallComplete);
            
            ConsoleLog('AttendAnywhere.VidyoClientInstallLog.LogVidyoInstall called');
        }
    }
    
    function OnLogVidyoInstallComplete(result)
    {
        ConsoleLog('OnLogVidyoInstallComplete called');
        isVidyoInstallLogDone = 1;
    }
