﻿var apiKey;     // OpenTok sample API key. Replace with your own API key.
var sessionId;  // Replace with your session ID.
var token;      // Should not be hard-coded.
var isInterestOwner = false;         // The owner of the Interest

/// MARK - Add to the page using the OpenTok server-side libraries.
var session;
var publisher;
var subscribers = {};
var globalGroup;

var debug = false;                  // ToxBox event alerting
var participants = 0;               // Number of paticipants in the call
var watchers = 0;                   // Number of users watching but not participating
var participatingIn = 0;

function signalReceivedHandler(event) {
    alert("Received a signal from connection " + event.fromConnection.connectionId);
}
//--------------------------------------
//  LINK CLICK HANDLERS
//--------------------------------------

/*
If testing the app from the desktop, be sure to check the Flash Player Global Security setting
to allow the page from communicating with SWF content loaded from the web. For more information,
see http://www.tokbox.com/opentok/build/tutorials/helloworld.html#localTest
*/


function connect() {
    session.connect(apiKey, token);
    opentokClass.updateStatusText('connecting...');
}

function disconnect() {
    session.disconnect();
    opentokClass.updateStatusText('disconnected');
    $('otok_status').set('style', 'border-left:4px solid red;padding-left:3px;');
    hide('disconnectLink');
    hide('promote_link')
    hide('publishLink');
    hide('unpublishLink');
    if ($('bio_feed'))
        $('bio_feed').removeClass('dnd');
    if ($('video_chat')) {
        $('video_chat').addClass('dnd');
        $('video_chat').empty();
    }
    ///Update status OnLine
    var openTOK_Status_ajx = new WADJAX('misc', { statusBar: false });
    openTOK_Status_ajx.send('updateLastActivity', profileInfo.viewerID, gl_label_id, '0', function (res) {
        if (res.error) return;
    });

    show('btn_joinroom');
    hide('btn_exitroom');
    if ($('btn_joinroom').hasClass('dndD')) { $('btn_exitroom').removeClass('dndD'); }
    if ($('btn_exitroom').hasClass('dndD')) { }
    else { $('btn_exitroom').addClass('dndD'); }
    if ($('loadingVideo')) 
        $('loadingVideo').addClass('dnd');

    if ($('btn_joinroom')) {

        if (!$('btn_joinroom').hasClass('lnk')) {

            $('btn_joinroom').addClass('lnk');

        }
    }
}

// Called when user wants to start publishing to the session
function startPublishing() {
    if (!publisher) {
        /* Publish my stream to the session */
        publishStream();
       
        /* Re-layout the container with the new streams */
        OT_LayoutContainer.layout();
      
        hide('streamContainer_empty');
        ///show('unpublishLink');
        hide('publishLink');

        ///Update status OnLine
        var openTOK_Status_ajx = new WADJAX('misc', { statusBar: false });
        openTOK_Status_ajx.send('updateLastActivity', profileInfo.viewerID, gl_label_id, '1', function (res) {
            if (res.error) return;
        });
        participatingIn = gl_label_id;
        /* UX metrix */
        if (mp_metrix) mpmetrics.track("Participate in video chat", { "label name": gl_label_id });
    }
}

function stopPublishing() {
    if (publisher) {
        session.unpublish(publisher);
    }
    participants--;
    publisher = null;
    
    ///Update status OnLine
    var openTOK_Status_ajx = new WADJAX('misc', { statusBar: false });
    openTOK_Status_ajx.send('updateLastActivity', profileInfo.viewerID, gl_label_id, '0', function (res) {
        if (res.error) return;
    });

    show('publishLink');
    hide('unpublishLink');
}

//--------------------------------------
//  OPENTOK EVENT HANDLERS
//--------------------------------------

function sessionConnectedHandler(event) {
  
    opentokClass.updateStatusText("connected");
    $('otok_status').addClass('dnd');
    $('otok_status').set('style', 'border-left:4px solid orange;padding-left:3px;');

    show('disconnectLink');
    show('promote_link');
    show('publishLink');
    hide('connectLink');

    subscribeToStreams(event.streams);
    session.publish();
   
    var btnexitroom = new Element('span', { 'html': 'Leave room','class':'f12 lnk video_chat' });
    btnexitroom.onclick = new Function('disconnect();');

    if ($('btn_exitroom').hasClass('dndD')) {$('btn_exitroom').removeClass('dndD');}

    //show('btn_exitroom');
    //hide('btn_joinroom');
    if ($('btn_joinroom').hasClass('dndD')) { }
    else {$('btn_joinroom').addClass('dndD'); }
    if ($('loadingVideo'))
        $('loadingVideo').addClass('dnd');

    startPublishing();
    $('video_chat').removeClass('dnd');
    return;
    
    
    globalGroup = event.groups[0];

}
function groupPropertiesUpdatedHandler(event) {
    if (event.target.groupId == globalGroup.groupId) {
        if (event.target.getGroupProperties().echoSuppression.isEnabled) {
            setEchoSuppressionButton("disable");
        } else {
            setEchoSuppressionButton("enable");
            if (publisher) {
                // Mute audio to remove risk of feedback
                publisher.publishAudio(false);
            }
        }
    }
}


function streamCreatedHandler(event) {
    if (debug) {
        alert("streamCreatedHandler");
        dumpStreams(event.streams, "");
    }

    // Subscribe to the newly created streams
    subscribeToStreams(event.streams);

    // Re-layout the container with the new streams
    OT_LayoutContainer.layout();

    opentokClass.updateStatusText("Participating");
    $('otok_status').set('style', 'border-left:4px solid green;padding-left:3px;');

    /*
    // Subscribe to the newly created streams
    for (var i = 0; i < event.streams.length; i++) {

        var conenctionID = event.streams[i].connection.connectionId;
        if (event.streams[i].connection.connectionId != event.target.connection.connectionId) {
            addStream(event.streams[i]);
            watchers--;
        } else {
            // Our publisher just started streaming
            // Update status, controls and counts
            opentokClass.updateStatusText("Participating");
            $('otok_status').set('style', 'border-left:4px solid green;padding-left:3px;');
            participants++;
            watchers--;
        }
    }
    opentokClass.updateCountDisplays();
    */
}

function streamDestroyedHandler(event) {
    // Get all destroyed streams
    for (var i = 0; i < event.streams.length; i++) {
        // For each stream get the subscriber to that stream
        var subscribers = session.getSubscribersForStream(event.streams[i]);
        for (var j = 0; j < subscribers.length; j++) {
            // Then remove each stream
            OT_LayoutContainer.removeStream(subscribers[j].id);
        }
    }

    // Re-layout the container without the removed streams
    OT_LayoutContainer.layout();

    hide("unpublishLink");
    show("publishLink");
    publisher = null;
}

function sessionDisconnectedHandler(event) {
    // This signals that the user was disconnected from the Session. Any subscribers and publishers
    // will automatically be removed. This default behaviour can be prevented using event.preventDefault()
    publisher = null;
    if (event.reason == "forceDisconnected") {
        alert("A moderator has disconnected you from the session.");
    }
    show('connectLink');
    hide('disconnectLink');
    hide('publishLink');
    hide('unpublishLink');
}

function connectionDestroyedHandler(event) {
    // This signals that connections were destroyed
    if (debug) {
        alert("connectionCreatedHandler");
        dumpConnections(event.connections, "");
    }
    //$('otok_logfile').set('html', $('otok_logfile').get('html') + '<br>CD:' + session.connection.connectionId);
    watchers -= event.connections.length;
    opentokClass.updateCountDisplays();
}

function connectionCreatedHandler(event) {
    if (debug) {
        alert("connectionDestroyedHandler");
        dumpConnections(event.connections, event.reason);
    }
    watchers += event.connections.length;
    opentokClass.updateCountDisplays();
    // This signals new connections have been created.
    //$('otok_logfile').set('html', $('otok_logfile').get('html') + '<br>CR:' + session.connection.connectionId);
}

/*
If you un-comment the call to TB.addEventListener("exception", exceptionHandler) above, OpenTok calls the
exceptionHandler() method when exception events occur. You can modify this method to further process exception events.
If you un-comment the call to TB.setLogLevel(), above, OpenTok automatically displays exception event messages.
*/
function exceptionHandler(event) {
    alert("Exception: " + event.code + "::" + event.message);
}

//--------------------------------------
//  HELPER METHODS
//--------------------------------------

function addStream(stream) {
    // Check if this is the stream that I am publishing, and if so do not publish.
    if (stream.connection.connectionId == session.connection.connectionId) {
        return;
    }
    var subscriberDiv = document.createElement('div'); // Create a div for the subscriber to replace
    var subHeight = 330;//90
    var subWidth = 330; //120
   
    subProps = { width: subWidth, height: subHeight };

    subscriberDiv.setAttribute('id', stream.streamId); // Give the replacement div the id of the stream as its id.
    document.getElementById("tvchannels").appendChild(subscriberDiv);//subscribers
    // Create a div for the force disconnect link

    if (isInterestOwner) {
        var forceDisconnect = document.createElement('div');
        forceDisconnect.style.float = "bottom";
        forceDisconnect.innerHTML = '<a href="#" onClick="javascript:forceDisconnectStream(\'' + stream.streamId + '\')">Force Disconnect</a>'
+ ' · <a href="#" onclick="javascript:forceUnpublishStream(\'' +
stream.streamId + '\')">Force Unpublish</a>'
        document.getElementById("subscribers").appendChild(forceDisconnect);
    }
    /// re-arrange cameras
    /// reArrangeScreens();
    subscribers[stream.streamId] = session.subscribe(stream, subscriberDiv.id, subProps);
}
function reArrangeScreens() {
    var i = 0;
    $$('object').each(function (element, index) {
        if (element.get('id').indexOf('publish') >= 0 || element.get('id').indexOf('subscr')>=0) {
            i++;
            //A-row
            //1
            //2
            //3
            //4

            //B-row
            //5
            //6
            //7
            //8
        }
    });
    alert(i);
    var j = 0;
    $$('object').each(function (element, index) {
        if (element.get('id').indexOf('publish') >= 0 || element.get('id').indexOf('subscr') >= 0) {
            j++;
            if (i == 3) {
                if (j >= 2) {
                    alert('A:'+j);
                    $(element.get('id')).setProperties({
                        width: '165',
                        height: '165'
                    });
                }
            }
            else if (i == 4) {
                alert('B:'+j);
                $(element.get('id')).setProperties({
                    width: '165',
                    height: '165'
                });
            }

        }
    });


}

function shrink(id) {
    var scaling = .70;
    var videoObject = document.getElementById(id);
    videoObject.height *= scaling;
    videoObject.width *= scaling;
} 

function forceDisconnectStream(streamId) {
    session.forceDisconnect(subscribers[streamId].stream.connection.connectionId);
}
function forceUnpublishStream(streamId) {
    session.forceUnpublish(subscribers[streamId].stream);
}
function show(id) {
    if ($(id))
        $(id).removeClass('dndD');
}
function hide(id) {
    if ($(id))
        $(id).addClass('dndD');
}


var opentokClass = {
    updateCountDisplays: function () {
        /* watching but not participating */
        $('otok_watchers_num').set('html', watchers);
        //$('otok_participants_num').set('html', participants); 
    },
    updateStatusText: function (etext) {
        $('otok_status').set('html', etext);
    }
}
// Generic function to dump connectionEvents to the alert box
function dumpConnections(connections, reason) {
    for (var i = 0; i < connections.length; i++) {
        alert("connectionId: " + connections[i].connectionId + " \n" +
            "reason: " + reason);
    }
}

//Layout management
function publishStream() {
    // Make up an id for our publisher
    var divId = 'opentok_publisher';

    // Pass in TRUE since this is a publisher
    OT_LayoutContainer.addStream(divId, true);

    session.publish(divId);
}
function subscribeToStreams(streams) {
    // For each stream
    try {
        for (var i = 0; i < streams.length; i++) {
            // Check if this is the stream that I am publishing, and if so do not subscribe.
            if (streams[i].connection.connectionId != session.connection.connectionId) {
                // Make a unique div id for this stream
                var divId = 'stream_' + streams[i].streamId;

                // Pass in FALSE since this is a subscriber
                OT_LayoutContainer.addStream(divId, false);

                session.subscribe(streams[i], divId);
            }
        }
    }
    catch(oterr)
    {
    
    }
}
