﻿var NUSA_service = "https://sas.nuancehdp.com";

/**
 * Called after recording started.
 * Optionally implemented by the integrator.
 * @function
 * @public
 */
//function NUSA_onRecordingStarted() { }
/**
 * Called after recording stopped.
 * Optionally implemented by the integrator.
 * @function
 * @public
 */
//function NUSA_onRecordingStopped() { }
/**
 * Called after the processing of speech started.
 * Optionally implemented by the integrator.
 * @function
 * @public
 */
//function NUSA_onProcessingStarted() { }
/**
 * Called after the processing of speech stopped. No more results are pending.
 * Optionally implemented by the integrator.
 * @function
 * @public
 */
//function NUSA_onProcessingFinished() { }
/**
 * Called after the processing of speech started for (element)
 * Optionally implemented by the integrator.
 * @function
 * @param element
 * @public
 */
//function NUSA_onProcessingStartedForElement(element) { }
/**
 * Called after the processing of speech stopped for (element). No more results are pending for this element.
 * Optionally implemented by the integrator.
 * @function
 * @param element
 * @public
 */
//function NUSA_onProcessingFinishedForElement(element) { }
/**
 * Called if an application command was recognized.
 * Optionally implemented by the integrator.
 * @function
 * @param cmdId
 * @param spokenPhrase
 * @deprecated content
 * @param placeholderIds
 * @param placeholderValues
 * @public
 */
//function NUSA_onCommandRecognized(cmdId, spokenPhrase, content, placeholderIds, placeholderValues) { }
/**
 * Called after playback started.
 * Optionally implemented by the integrator.
 * @function
 * @public
 */
//function NUSA_onPlaybackStarted() { }
/**
 * Called after playback stopped.
 * Optionally implemented by the integrator.
 * @function
 * @public
 */
//function NUSA_onPlaybackStopped() { }

//////////////////////////////////////////////////////////////////////////
// Internal  /////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
var NUSAI_buildVersion = "5.6.4.1",
    NUSAI_sourceName = "nuance.speechanywhere",
    NUSAI_pageLoaded = false,
    NUSAI_scriptLoaded = false,
	NUSAI_minVersion = {
		Chrome: 102,
		Firefox: 102,
		Safari: "11.0.2",
		iPhone: "0",
		iPad: "0"
	},
	NUSAI_legacyAudio = false;

if (window.addEventListener) {
    window.addEventListener('load', NUSAI_onLoad, false);
}
else {
    window.attachEvent('onload', NUSAI_onLoad);
}

NUSAI_loadNUSAFiles();

/**
 *
 * @return {string}
 * @function
 */
function NUSAI_getNUSALocation() {
    var i,
        location = "",
        list = document.getElementsByTagName("script");

    if (list) {
        for (i = 0; i < list.length; ++i) {
            location = list[i].src;
            if (!location || (location.length === 0))
                continue;
            location = location.toLowerCase();
            var index = location.indexOf(NUSAI_sourceName);
            if (index >= 0) {
                location = location.substr(0, index);
                break;
            }
        }
    }
    return location + "../";
}
/**
 * Compares two version strings (eg 1.0 vs 1.0.1)
 * Note: versions like 1.1a are not supported (and not needed by now)
 * Returns 1 if version1 > version2
 * Returns -1 if version1 < version2
 * Returns 0 if version1 == version2
 * @param {string} version1
 * @param {string} version2
 * @return {number}
 * @constructor
 */
function NUSAI_compareVersions(version1, version2) {
	if (version1 === version2)
		return 0;

	var v1 = version1.split("."),
		v2 = version2.split("."),
		len = Math.max(v1.length, v2.length),
		i;

	for (i=0; i < len; ++i) {
		if (!v1[i])
			v1.push(0);
		if (!v2[i])
			v2.push(0);

		// works for integer values (no risk of comparing float to int as string)
		if (v1[i] < v2[i])
			return -1;

		if (v1[i] > v2[i])
			return 1;
	}
	return 0;
}
/**
 * Check if buttonDevice is supported
 * @return {boolean}
 * @function
 */
function NUSAI_isButtonDeviceSupported() {
	var agent = navigator.userAgent.toLowerCase();

	if (agent.indexOf("jxbrowser")>0 || !navigator.platform)
		return false;

	// currently only in Chrome/Edge and Windows (Edge is Chromium based and reports "chrome" in the userAgent)
	if (agent.indexOf("chrome")<0 || !navigator.platform)
		return false;

	return navigator.platform.match(/Win/)!=null;
}

/**
 * @param {string} browser the browser to check - "Chrome" or "Firefox" only
 * @return {string|null}
 * @function
 */
function NUSAI_getBrowserVersion(browser) {
	const index = navigator.userAgent.indexOf(browser);
	if (index<0)
		return null;

	// version is at browser/VERSION for Chrome & Firefox
	let version = navigator.userAgent.slice(index + browser.length+1);
	const firstPoint = version.indexOf(".");
	version = version.slice(0, firstPoint);
	return version;
}

/**
 * iPad and IPhone only!
 * @return {string|null}
 * @function
 */
function NUSAI_getIOSVersion() {
	var version,
		index = navigator.userAgent.indexOf("OS ");
	if (index<0)
		return null;
	version  = navigator.userAgent.substr(index + 3);
	while (version.indexOf("_") >= 0) {
		version = version.replace("_", ".");
	}
	return version;
}

/**
 *
 * @return {boolean}
 * @function
 */
function NUSAI_isHTML5Browser() {
    var version,
        index;

    version =  NUSAI_getBrowserVersion("Chrome");
    if (version)
        return Number(version) >= NUSAI_minVersion.Chrome;

	version =  NUSAI_getBrowserVersion("Firefox");
	if (version)
		return Number(version) >= NUSAI_minVersion.Firefox;

	index =navigator.userAgent.indexOf("Safari");
	if ( index >= 0) {
		// version is at Version/
		index = navigator.userAgent.indexOf("Version/");
		version  = navigator.userAgent.substr(index + 8);
		console.log("Safari - checking version: " + version);
		return NUSAI_compareVersions(version, NUSAI_minVersion.Safari)>=0;
	}
	// for both iPhone and iPad, although not supported, we assume html5 support (iosSDK hybrid)
	index =navigator.userAgent.indexOf("iPhone");
	if ( index >= 0) {
		version  = NUSAI_getIOSVersion();
		console.log("iPhone - checking version: " + version);
		return NUSAI_compareVersions(version, NUSAI_minVersion.iPhone)>=0;
	}
	index =navigator.userAgent.indexOf("iPad");
	if ( index >= 0) {
		version  = NUSAI_getIOSVersion();
		console.log("iPad - checking version: " + version);
		return NUSAI_compareVersions(version, NUSAI_minVersion.iPad)>=0;
	}

	return false;
}
function NUSAI_useAudioWorklet() {
	let version = NUSAI_getBrowserVersion("Chrome");
	if (version)
		return Number(version) >= NUSAI_minVersion.Chrome;

	version = NUSAI_getBrowserVersion("Firefox");
	if (version)
		return Number(version) >= NUSAI_minVersion.Firefox;

	// currently only Chrome/Edge and Firefox
	return false;
	/*
	//Safari defect with new webAudio
	try {
        const context = new OfflineAudioContext(1, 1, 44100);
		return Boolean(
            context.audioWorklet &&
            typeof context.audioWorklet.addModule === 'function');
    }
    catch (e) { return false; }
	*/
}
function NUSAI_addScript(file, callback) {
	const script = document.createElement("script");
	script.type = "text/javascript";
	script.src = file;
	if (script.readyState) {
		script.onreadystatechange = function () {
			//noinspection EqualityComparisonWithCoercionJS
			if (script.readyState == "loaded" ||
				script.readyState == "complete") {
				script.onreadystatechange = null;
				callback.call(this);
			}
		};
	}
	else {
		script.onload = callback;
	}

	document.getElementsByTagName("head")[0].appendChild(script);
}

function NUSAI_loadNUSAFiles() {
    var file,
        location = NUSAI_getNUSALocation() + NUSAI_buildVersion + "/",
	    forceLegacyAudio = false;

	//noinspection JSUnresolvedVariable
	if (typeof NUSA_legacyAudio !== "undefined") {
		//noinspection JSUnresolvedVariable
		forceLegacyAudio = !!NUSA_legacyAudio;
	}

    if (!forceLegacyAudio)
		forceLegacyAudio = !NUSAI_useAudioWorklet();
	NUSAI_legacyAudio = forceLegacyAudio;
    file = NUSAI_legacyAudio ? "scripts/nuance.speechanywhere.internal5.js" : "scripts/nuance.speechanywhere.internal5x.js";

    NUSAI_addScript(location + file, NUSAI_onMainScriptLoaded);

    var link = document.createElement("link");
    link.rel = "stylesheet";
    link.type = "text/css";
    file = "css/nuance.speechanywhere.internal5.css";
    link.href = location + file;
    document.getElementsByTagName("head")[0].appendChild(link);
}

function NUSAI_onScriptsLoaded() {
	if (document.readyState=="complete" || NUSAI_pageLoaded)
		NUSAI_onLoadInternal();
	else
		NUSAI_scriptLoaded = true;
}

function NUSAI_onMainScriptLoaded() {
	if (NUSAI_isButtonDeviceSupported()) {
		var location = NUSAI_getNUSALocation() + NUSAI_buildVersion + "/",
			file = "scripts/external/nuance.speechforms.micDeviceButtonHandler.js";
		NUSAI_addScript(location + file, NUSAI_onScriptsLoaded);
	}
	else
		NUSAI_onScriptsLoaded();
}

function NUSAI_onLoad() {
    if (NUSAI_scriptLoaded)
        NUSAI_onLoadInternal();
    else
        NUSAI_pageLoaded = true;
}
