/*
 *
 * Copyright (c) 2009 by Vivox Inc.
 *
 * Permission to use, copy, distribute this software for any purpose is allowed
 * only in conjunction with the use of Vivox Services and in all cases must
 * include this notice.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND VIVOX DISCLAIMS
 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL VIVOX
 * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
 * SOFTWARE.
 */


/**
 * @copyright 2010 Vivox Inc. All Rights Reserved.
 * @author jason leggett
 */
 
var vvxHandle = null;
var voiceChannelAddress = "sip:confctl-4@regp.vivox.com";

//this is called from withing unity to starup the plugin and create the voice object, note not all 
//callbacks are set below just the ones we useed.
function VivoxUnityInit(){
		      var callbackFunctions = {
				  onConnected: vivoxConnected
				 ,onParticipantAdded: ParticipantAdded
				 ,onParticipantRemoved: ParticipantRemoved
				 ,onParticipantUpdated: ParticipantUpdated
				 ,onVersionCheck: VersionCheck
                };

		vvxHandle = new Vivox.API('https://www.regp.vivox.com/api2/',
				{
					callbacks	: callbackFunctions,
					autoDownload  : false,
					pluginVersion : '1.16.2',
                    channelUri : voiceChannelAddress,
                    ephemeralId : voiceChannelAddress
			    });
			    // alert("Init!");
}

//this is returned after creating the voice object so user can take appropriate action
function VersionCheck(event) {
    //// alert("VersionCheck result: " + event.StatusCode);
    switch( event.StatusCode ){
        case Vivox.OK:
            return;
        case Vivox.INSTALL_REQUIRED:
			GetUnity().SendMessage("VivoxHud", "onVersionCheck","0:You need to install the Vivox plugin to enjoy Voice chat.");
            return;
        case Vivox.UPGRADE_REQUIRED:
			GetUnity().SendMessage("VivoxHud", "onVersionCheck","0:You need to upgrade your Vivox plugin to enjoy Voice chat.");
            return;
        case Vivox.OS_NOT_SUPPORTED:
            GetUnity().SendMessage("VivoxHud", "onVersionCheck","1:Your operating system is not compatible with Vivox Voice.");
            return;
        case Vivox.BROWSER_NOT_SUPPORTED:
            GetUnity().SendMessage("VivoxHud", "onVersionCheck","1:Your browser is not yet supported by Vivox Voice.");
            return;        
    }
}	

//callback when connection to vivox is established
function vivoxConnected(Event) {
    //alert("connected");
		GetUnity().SendMessage("VivoxHud", "onVivoxConnected", "Connected to Vivox network!");
}

//called from unity and is passed in the player name. You can modify this to accept a passwor to login normally instead of anonymously
function VivoxLogin(player) {
    //alert("login " + player);
	if (vvxHandle.isLoggedIn()){
		return;
	}
	
	vvxHandle.anonymousLogin(player, vivoxCompletedLogin);
	//vvxHandle.login("username","password" vivoxCompletedLogin);
}

//function to determine correct download location of the plugin based on browser and os. This may not be used if packaging plugin //install with main install of game
function installLocation(){
	try{

	var install_location = "#";
	var win = (navigator.platform.indexOf("Win") != -1);
	var mac = (navigator.platform.indexOf("Mac") != -1);
	if ( navigator.userAgent.indexOf("MSIE")!=-1){
		install_location = vvxInstallLocationWin;
		
	} else if ( navigator.userAgent.indexOf("Firefox")!=-1){
		var ppc = (navigator.oscpu.indexOf("PPC") != -1);
		if(!ppc){
			if ( mac ){
				install_location = vvxInstallLocationMacFF;  
			} else {
				install_location = vvxInstallLocationWinFF;
			}
		} else {
					
		} 
	} else if ( navigator.userAgent.indexOf("Chrome")!=-1){
	
		install_location = vvxInstallLocationWin; 

	} else if ( navigator.userAgent.indexOf("Safari")!=-1){
	
			if ( mac ){
				install_location = vvxInstallLocationMac;
			} else {
				install_location = vvxInstallLocationWin;
			}

	} 
	
	return install_location;
	
	}catch(e){
		
	}
}

//can be called from unity to start download process. Works in firefox and ie but may be more efficent way of doing this
function VivoxInstall() {
    // alert("vivox install");
		var install_location = installLocation();
		try {
		    var installDiv = document.getElementById("VivoxInstall");
		    var installLink = document.createElement("a");
		    installLink.href = installLocation();
		    installLink.title = "Vivox Install";

		    var installText = document.createTextNode("Install Vivox");

		    installLink.appendChild(installText);
		    installDiv.appendChild(installLink);
            
				//window.top.location.replace(install_location);   
		}catch(e){
		}
}

//callback to unity for completed login
function vivoxCompletedLogin(Response) {
    //alert("completed login");
	if (Response.Success) {
		GetUnity().SendMessage("VivoxHud", "onVivoxLogin", "Logged into the Vivox network!");
	} else {

		return;
	}
}

function ParticipantAdded(event){
    //alert("participant added");
	/* A participant was added to the channel */
    var uri = event.Participant.Uri;
    var displayName = event.Participant.DisplayName;
	var session_uri = event.SessionUri;
	GetUnity().SendMessage("VivoxHud", "VivoxParticipantAdded", displayName);
	vvxHandle.unmuteChannelUserAudio(session_uri, uri);


}
function ParticipantRemoved(event){
    // alert("participant removed");
	/* A participant was added to the channel */
    var uri = event.Participant.Uri;
    var displayName = event.Participant.DisplayName;

	GetUnity().SendMessage("VivoxHud", "VivoxParticipantRemoved", displayName);

}
//a participant was updated in some way here we are only looking at the speaking indicator
function ParticipantUpdated(event) {
    //alert("participant updated");
	var uri = event.Participant.Uri;
    var displayName = event.Participant.DisplayName;
	 if (displayName == null) {
        		displayName = uri;
    		}
	var speaking = event.Participant.IsSpeaking;
	
	var combo = displayName + ":" + speaking;
	GetUnity().SendMessage("VivoxHud", "VivoxParticipantIsSpeaking", combo);
}

//can be called by unity to create a channel, note with anonymousLogin player will not have permissions to create a channel
function VivoxCreateChannel(channelName){
    // alert("create channel " + channelName);
	// RG: Added following line to pick up name of channel from Unity
	voiceChannelAddress = channelName;
	vvxHandle.createChannel({ChannelName : channelName}, vivoxChannelCreate);
}

function vivoxChannelCreate(Response) {
    if (Response.Success) {
		GetUnity().SendMessage("VivoxHud", "onVivoxChannelCreate", Response.ChannelURI);
} else {
		//with anonymousLogin player will not have permissions to create a channel so connecting to an Ephemeral channel
    GetUnity().SendMessage("VivoxHud", "onVivoxChannelCreate", voiceChannelAddress);
		//GetUnity().SendMessage("VivoxHud", "onVivoxChannelCreate", "Error:" + Response.StatusCode);
	}
}

//can be called from unity to connect to a channel using the channel uri and a fontid. 0 for fontid is no font
function VivoxJoinChannel(channelURI,fontId){
    //alert("channel join " + channelURI);
			vvxHandle.startSession(channelURI,{
			fontId: 0
		});
}

function VivoxLogout(channelURI) {
    vvxHandle.endSession(channelURI);
    vvxHandle.logout(vivoxCompletedLogout);
    vvxHandle.unsetCallbacks();
}
function vivoxCompletedLogout(Response) {
    if (Response.Success) {
        //    GetUnity().SendMessage("VivoxHud", "onVivoxLogout");
       // alert("logged out");
    }
}
