var BR_OTHER = 0;
var BR_MSIE = 1;
var BR_CHROME = 2;
var BR_DISABLE = 9;

const PLAYER_JPEGSNAP     = 0;
const PLAYER_ACTIVEX      = 1;
const PLAYER_CHROMEPLUGIN = 2;
const PLAYER_JAVAAPP      = 3;
const PLAYER_WEBSOCKET    = 4;

function downloadFile(filename){
		console.log(' filename='+filename);
	window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
	window.requestFileSystem(window.PERSISTENT, 30*1024*1024, function(fs) {
		console.log(' fs.root='+fs.root);
		fs.root.getFile(filename, {create: false}, function(fileEntry) { // /test is filename
			console.log(' fs.root.getFile OK');
			//location.href = fileEntry.toURL();
			var link = document.createElement("a");
			link.download = filename;//"test";
			link.href = fileEntry.toURL();
			link.click();
		}, function() {});
	}, function() {});
}

function downloadBrowse(){
	window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
	window.requestFileSystem(window.PERSISTENT, 30*1024*1024, function(fs) {
		console.log(' fs.root='+fs.root);
		fs.root.getDirectory('/', {create: false}, function(fileEntry) { // /test is directory
			console.log(' fs.root.getFile OK');
			location.href = fileEntry.toURL();
		}, function() {});
	}, function() {});
}

function sleep(milliseconds)
{
	var start = new Date().getTime();
	for (var i = 0; i < 1e7; i++)
	{
		if ((new Date().getTime() - start) > milliseconds)
		{
			break;
		}
	}
}

function VXGMP_GetBrowser()
{
    var agt = navigator.userAgent.toLowerCase();
	//console.log(agt);
	if (parseInt(readSetupByKey("SYS_TTA_SECURITY_VERIFIED")) == 1) return BR_OTHER;

    if (agt.indexOf("msie") != -1 || agt.indexOf("trident") != -1) return BR_MSIE;
//    else return BR_DISABLE;
    
    else if (agt.indexOf("opera") != -1 || agt.indexOf("opr") != -1) return BR_OTHER; // Opera
	else if (agt.indexOf("edge") != -1 || agt.indexOf("edg/") != -1) return BR_OTHER; // Edge(old) or Edge(Chromium)
	else if (agt.indexOf("whale/") != -1) return BR_OTHER; // Whale 
    else if (agt.indexOf("chrome") != -1) {
		if (parseInt(readSetupByKey("SYS_IS_STEINSVIKSPECIFIC")) == 1) {
		   	return BR_OTHER;
		} 
		else {
		   	return BR_CHROME; // Chrome
		}
	}
    else if (agt.indexOf("safari") != -1) return BR_OTHER; // Safari
    else if (agt.indexOf("firefox") != -1) return BR_OTHER; // Firefox
    else return BR_OTHER;
    
}


function VXGMP_GetPlayer(activex, browser, valgo, detectioncam)
{
    var player;

    if (trnPlayerForceJpeg)
    {
        player = PLAYER_JPEGSNAP;
        return player;
    }

    if (activex == 1)
    {
        if (browser == BR_MSIE)
        {
            player = PLAYER_ACTIVEX;
        }
        else if (browser == BR_CHROME)
        {
            if (trnPlayerSupportWS == 1)
            {
                var chromeplugin = parseInt(getCookie('truenchromeplugin'));
                if (chromeplugin == 1)
                {
                    player = PLAYER_CHROMEPLUGIN;
                }
                else
                {
                    if (valgo == 0/*H.264*/)
                    {
                        if (detectioncam == 1 && trnDetectionCamPlayerSupportWS != 1) {
                            player = PLAYER_JPEGSNAP;
                        }
                        else {
                            player = PLAYER_WEBSOCKET;
                        }
                    }
                    else
                    {
                        player = PLAYER_JPEGSNAP;
                    }
                }
            }
            else
            {
                player = PLAYER_CHROMEPLUGIN;
            }
        }
        else
        {
            if (trnPlayerSupportWS == 1)
            {
                if (valgo == 0/*H.264*/)
                {
                    if (detectioncam == 1 && trnDetectionCamPlayerSupportWS != 1) {
                        player = PLAYER_JPEGSNAP;
                    }
                    else {
                        player = PLAYER_WEBSOCKET;
                    }
                }
                else
                {
                    player = PLAYER_JPEGSNAP;
                }
            }
            else
            {
                player = PLAYER_JPEGSNAP;
            }
        }
    }
    else
    {
		player = PLAYER_JAVAAPP;
    }

    return player;
}

function VXGMP_createPlayer(id, addr, width, height, target)
{    
    var playerId = id;
    var div = document.createElement('div');
    div.setAttribute("id", playerId);
    div.setAttribute("class", "vxgplayer");
    var runtimePlayers = document.getElementById(target);
    runtimePlayers.appendChild(div);
    var player = vxgplayer(playerId, {
            url: '',
            nmf_path: 'media_player.nmf',
            nmf_src: '/vxgplayer/pnacl/Release/media_player.nmf',
            latency: 300,
            aspect_ratio_mode: 0,
            autohide: 3,
            controls: false,
            custom_digital_zoom: true
    });
	
	if(player == undefined) {
		return;
	}

	player.ready(function(){
        console.log(' =>ready player '+playerId);
        vxgplayer(playerId).src(addr);
        vxgplayer(playerId).size(width, height);
        vxgplayer(playerId).autoreconnect(1);
        vxgplayer(playerId).play();
        console.log(' <=ready player '+playerId);
    });
}

function VXGMP_restartPlayer(playerId, addr, width, height, target)
{        
        console.log(' =>VXGMP_restartPlayer '+playerId);
        vxgplayer(playerId).src(addr);
        vxgplayer(playerId).size(width, height);
        vxgplayer(playerId).autoreconnect(1);
        vxgplayer(playerId).play();
        console.log(' <=VXGMP_restartPlayer '+playerId);

}

function VXGMP_resizePlayer(playerId, width, height)
{        
        console.log(' =>VXGMP_resizePlayer '+playerId);
        vxgplayer(playerId).size(width, height);
        console.log(' =>VXGMP_resizePlayer '+width+' '+height);
}

function VXGMP_GetsizePlayer(playerId)
{        
        var size;
        size = vxgplayer(playerId).size();
        return size;
}

function VXGMP_term(playerId)
{
    vxgplayer(playerId).dispose();
}

function VXGMP_fullscreen(playerId, val)
{
    if(val == 1){
        vxgplayer(playerId).aspectRatioMode(1);
    }
    else{
        vxgplayer(playerId).aspectRatioMode(0);
    }    
    vxgplayer(playerId).fullscreen();
}

function VXGMP_aspectRatioMode(playerId, val)
{
    if(val == 1){
        vxgplayer(playerId).aspectRatioMode(1);
    }
    else{
        vxgplayer(playerId).aspectRatioMode(0);
    }    
}

function VXGMP_GetaspectRatioMode(playerId)
{
    rc = vxgplayer(playerId).aspectRatioMode();
    if(rc == 1) return 1;
    else return 2;
}

function VXGMP_SetBuffer(playerId, val)
{
    var latency = val * 100;
    if(latency < 300) latency = 300;
    console.log("VXGMP_SetBuffer : " + latency);
    vxgplayer(playerId).latency(latency);
}

function VXGMP_RecStartPlayer(playerId)
{
    rc = vxgplayer(playerId).record_start();
}

function VXGMP_RecStopPlayer(playerId)
{
    rc = vxgplayer(playerId).record_stop();
    sleep(1000);
}

function VXGMP_RecBrowsePlayer(playerId)
{
    rc = vxgplayer(playerId).record_stop();
    sleep(1000);
    downloadBrowse();
}

function VXGMP_RecDownloadPlayer(playerId, filename)
{
    rc = vxgplayer(playerId).record_stop();
    sleep(1000);
    downloadFile(filename);
}

function VXGMP_CustomDigitalZoom(playerId, ratio, x, y)
{
    vxgplayer(playerId).setCustomDigitalZoom(ratio, x, y);
}

function VXGMP_Snapshot(playerId)
{
    rc = vxgplayer(playerId).takescreenshot();
}


////////////////////////////////////////////////////////////////////////////////////
// WebSocket
////////////////////////////////////////////////////////////////////////////////////
function VXGWSMP_createPlayer(id, addr, wsaddr, width, height, buf, target, user, pw)  {
	var playerId = id;
	var div = document.createElement('div');
	div.setAttribute("id", playerId);
	div.setAttribute("class", "vxgwsplayer");
	var runtimePlayers = document.getElementById(target);
	runtimePlayers.appendChild(div);
	var player = vxgwsplayer(playerId, {
			wsurl: wsaddr,
			rtspurl: addr,
			user: user,
			password: pw,
			//latency: 500000, //300000, // 300
            latency: (300 + (buf * 10)),
            width: width,
            height: height,
			aspect_ratio_mode: 2,
			//autohide: 3,
			controls: false,
            muted: true,
            volume: 1.0,
			//async: true,
			clipname: "dynamicTestClip",
			clipH264maxsize: 536870912, //1073741824,
			clipG711maxsize: 44640000,  //89280000,
			//autoreconnect: 1
			custom_digital_zoom: true
	}).ready(function(){
        console.log(' =>ready player '+playerId);
        vxgwsplayer(playerId).setSource();
        vxgwsplayer(playerId).play();
        console.log(' <=ready player '+playerId);
	});

    if (vxgwsplayer_last_mute == false) {
        vxgwsplayer(playerId).mute();
    }
}

function VXGWSMP_resizePlayer(playerId, width, height)
{
    console.log(' =>VXGWSMP_resizePlayer '+playerId);
    vxgwsplayer(playerId).size(width, height);
    console.log(' =>VXGWSMP_resizePlayer '+width+' '+height);
}

function VXGWSMP_GetsizePlayer(playerId)
{
    var size;
    size = vxgwsplayer(playerId).size();
    return size;
}

function VXGWSMP_term(playerId)
{
    vxgwsplayer(playerId).stop();
    vxgwsplayer(playerId).dispose();
}

function VXGWSMP_fullscreen(playerId, val)
{
    if(val == 1){
        vxgwsplayer(playerId).aspectRatioMode(1);
    }
    else{
        vxgwsplayer(playerId).aspectRatioMode(0);
    }
    vxgwsplayer(playerId).fullscreen();
}

function VXGWSMP_aspectRatioMode(playerId, val)
{
    if(val == 1){
        vxgwsplayer(playerId).aspectRatioMode(1);
    }
    else{
        vxgwsplayer(playerId).aspectRatioMode(0);
    }
}

function VXGWSMP_GetaspectRatioMode(playerId)
{
    rc = vxgwsplayer(playerId).aspectRatioMode();
    if(rc == 1) return 1;
    else return 2;
}

function VXGWSMP_SetBuffer(playerId, val)
{
    vxgwsplayer(playerId).latency(300 + (val*10)); // min: 300ms + (0 ~ 1000)ms
    vxgwsplayer(playerId).restart();
}

function VXGWSMP_RecStartPlayer(playerId, filename)
{
    vxgwsplayer(playerId).defaultClipName = filename;
    rc = vxgwsplayer(playerId).startRecord(3600 * 1000); // 3600s == 1hours
}

function VXGWSMP_RecStopPlayer(playerId)
{
    rc = vxgwsplayer(playerId).stopRecord();
}

function VXGWSMP_CustomDigitalZoom(playerId, ratio, x, y)
{
    vxgwsplayer(playerId).setCustomDigitalZoom(ratio, x, y);
}

function VXGWSMP_Snapshot(playerId)
{
    rc = vxgwsplayer(playerId).takescreenshot();
}

function VXGWSMP_RecGetStatus(playerId)
{
    return vxgwsplayer(playerId).recordStatus();
}

var vxgwsplayer_last_mute = true;
function VXGWSMP_VolumeMute(playerId)
{
    vxgwsplayer(playerId).mute(); // toggle mute
    vxgwsplayer_last_mute = vxgwsplayer(playerId).isMute();
    return vxgwsplayer_last_mute;
}

function VXGWSMP_ShowError(playerId, errstr)
{
    vxgwsplayer(playerId).showerror(errstr);
}

function VXGWSMP_HideError(playerId)
{
    vxgwsplayer(playerId).hideerror();
}

function VXGWSMP_StartBackwardAudio(playerId)
{
	vxgwsplayer(playerId).startBackwardAudio();
}

function VXGWSMP_StopBackwardAudio(playerId)
{
	vxgwsplayer(playerId).stopBackwardAudio();
}
