<commit_before>/* globals SpinnerDialog */

/***
* 
* 
* 
*/

// current stargateVersion used by webapp to understand
//  the version to load based on cookie or localstorage
// @deprecated since 0.2.2
var stargateVersion = "2";

var is_staging = ("IS_STAGING = 1".slice(-1) === "1");


var argsToString = function() {
    var args = Array.prototype.slice.call(arguments);
    var result = '';
    for (var i=0; i<args.length; i++) {
        if (typeof (args[i]) === 'object') {
            result += " " + JSON.stringify(args[i]);
        }
        else {
            result += " " + args[i];
        }
    }
    return result;
};

// logger function
var log = console.log.bind(window.console, "[Stargate] ");
var err = console.error.bind(window.console, "[Stargate] ");
var war = console.warn.bind(window.console, "[Stargate] ");
if (!is_staging) {
    log = function(){
        console.log("[I] [Stargate] "+argsToString.apply(null, arguments));
    };
    err = function(){
        console.log("[E] [Stargate] "+argsToString.apply(null, arguments));
    };
    war = function(){
        console.log("[W] [Stargate] "+argsToString.apply(null, arguments));
    };
}


// device informations   // examples
var runningDevice = {
    available: false,    // true
    cordova: "",         // 4.1.1
    manufacturer: "",    // samsung
    model: "",           // GT-I9505
    platform: "",        // Android
    uuid: "",            // ac7245e38e3dfecb
    version: ""          // 5.0.1
};
var isRunningOnAndroid = function() {
    return runningDevice.platform == "Android";
};
var isRunningOnIos = function() {
    return runningDevice.platform == "iOS";
};
// - not used, enable if needed -
//var isRunningOnCordova = function () {
//    return (typeof window.cordova !== "undefined");
//};
var initDevice = function() {
    if (typeof window.device === 'undefined') {
        return err("Missing cordova device plugin");
    }
    for (var key in runningDevice) {
        if (window.device.hasOwnProperty(key)) {
            runningDevice[key] = window.device[key];
        }
    }
    return true;
};

function getAppIsDebug() {
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.AppIsDebug) {
        return new Promise(function(resolve,reject){
            window.cordova.plugins.AppIsDebug.get(
                function(appinfo){
                    resolve(appinfo);
                },
                function(error){
                    err("getAppIsDebug(): "+error, error);
                    reject(new Error(error));
                }
            );
        });
    }
    
    err("getAppIsDebug(): plugin not available!");
    return Promise.resolve({});
}

function getManifest() {
    
    if (window.cordova.file) {
        return stargateModules.file.readFileAsJSON(window.cordova.file.applicationDirectory + "www/manifest.json");
    }
    
    if (window.hostedwebapp) {
        return new Promise(function(resolve,reject){
            window.hostedwebapp.getManifest(
                function(manifest){
                    resolve(manifest);
                },
                function(error){
                    err(error);
                    reject(new Error(error));
                }
            );
        });
    }
    
    err("getManifest() no available reading mechanism!");
    return Promise.resolve({});
}

var launchUrl = function (url) {
    log("launchUrl: "+url);
    document.location.href = url;
};


var isStargateRunningInsideHybrid = false;
var isStargateInitialized = false;
var isStargateOpen = false;
var initializeCallback = null;

/**
 * appVersion: version number of the app
 */
var appVersion = '';
/**
 * appBuild: build identifier of the app
 */
var appBuild = '';
/**
 * appPackageName: package name of the app - the reversed domain name app identifier like com.example.myawesomeapp
 */
var appPackageName = '';

/**
 * appIsDebug {Boolean} true if app is compiled in debug mode
 */
var appIsDebug = false;

/**
 * InApp Purchase module type:
 *  1 => use cordova plugin https://github.com/j3k0/cordova-plugin-purchase
 *  2 => use cordova plugin https://github.com/AlexDisler/cordova-plugin-inapppurchase
 */
var stargateIapType = 0;

var STARGATEIAPTYPES = {
    /**
     * use cordova plugin https://github.com/j3k0/cordova-plugin-purchase
     */
    "full": 1,

    /**
     * use cordova plugin https://github.com/AlexDisler/cordova-plugin-inapppurchase
     */
    "light": 2,
    
    1: "full",
    2: "light"
};

/**
 * 
 * variables sent by server configuration
 * 
 */
var hybrid_conf = {},
    requested_modules = [],
    modules_conf = {};

/**
 * 
 * Application information set on initialize
 * 
 */
var appInformation = {
    cordova: null,
    manufacturer: null,
    model: null,
    platform: null,
    deviceId: null,
    version: null,
    packageVersion: null,
    packageName: null,
    packageBuild: null,
    stargate: null,
    stargateModules: null,
    stargateError: null 
};

/**
* Set on webapp that we are hybrid
* (this will be called only after device ready is received and 
*   we are sure to be inside cordova app)
*/
var setIsHybrid = function() {   
    
    var re = new RegExp(/(^https?:\/\/)(.*)/);
    var result = re.exec(window.location.origin);
    var cookieDomain = '';
    if(result){
        cookieDomain = result[result.length - 1]
            .split('.')
            .filter(function(el){
                return !(el === 'www' || el === 'www2');
            }).join('.');
        // set multidomain cookie
        window.Cookies.set("hybrid", "1", {"domain": cookieDomain});        
    }

    window.Cookies.set("hybrid", "1");

    if (!window.localStorage.getItem('hybrid')) {
        window.localStorage.setItem('hybrid', 1);
    }
};

/**
* Set on webapp what version we need to load
* (this will be called only after manifest is loaded on stargate)
*/
var setHybridVersion = function() {

    window.Cookies.set("stargateVersion", getStargateVersionToLoad());

    if (!window.localStorage.getItem('stargateVersion')) {
        window.localStorage.setItem('stargateVersion', getStargateVersionToLoad());
    }
};

var hideSplashAndLoaders = function() {
    
    
    if (! haveRequestedFeature("leavesplash")) {
        navigator.splashscreen.hide();
    }

    setBusy(false);
    
    if (typeof SpinnerDialog !== "undefined") {
        SpinnerDialog.hide();
    }
};

var onPluginReady = function (resolve) {
    log("onPluginReady() start");

    // FIXME: this is needed ??
    document.title = stargateConf.title;
    
    // set back cordova bridge mode to IFRAME_NAV overriding manifold settings
    if (isRunningOnIos() && (typeof window.cordova !== 'undefined') && window.cordova.require) {
        var exec = window.cordova.require('cordova/exec');
        exec.setJsToNativeBridgeMode(exec.jsToNativeModes.IFRAME_NAV);
    }
    bindConnectionEvents();
    // save stargate version to load on webapp 
    setHybridVersion();

    
    if (hasFeature("mfp") && haveRequestedFeature("mfp")) {
        var mfpModuleConf = getModuleConf("mfp");
        
        // configurations needed
        //stargateConf.motime_apikey,<commit_msg>support new cordova js<commit_after>/* globals SpinnerDialog */

/***
* 
* 
* 
*/

// current stargateVersion used by webapp to understand
//  the version to load based on cookie or localstorage
// @deprecated since 0.2.2
var stargateVersion = "2";

var is_staging = ("IS_STAGING = 1".slice(-1) === "1");


var argsToString = function() {
    var args = Array.prototype.slice.call(arguments);
    var result = '';
    for (var i=0; i<args.length; i++) {
        if (typeof (args[i]) === 'object') {
            result += " " + JSON.stringify(args[i]);
        }
        else {
            result += " " + args[i];
        }
    }
    return result;
};

// logger function
var log = console.log.bind(window.console, "[Stargate] ");
var err = console.error.bind(window.console, "[Stargate] ");
var war = console.warn.bind(window.console, "[Stargate] ");
if (!is_staging) {
    log = function(){
        console.log("[I] [Stargate] "+argsToString.apply(null, arguments));
    };
    err = function(){
        console.log("[E] [Stargate] "+argsToString.apply(null, arguments));
    };
    war = function(){
        console.log("[W] [Stargate] "+argsToString.apply(null, arguments));
    };
}


// device informations   // examples
var runningDevice = {
    available: false,    // true
    cordova: "",         // 4.1.1
    manufacturer: "",    // samsung
    model: "",           // GT-I9505
    platform: "",        // Android
    uuid: "",            // ac7245e38e3dfecb
    version: ""          // 5.0.1
};
var isRunningOnAndroid = function() {
    return runningDevice.platform == "Android";
};
var isRunningOnIos = function() {
    return runningDevice.platform == "iOS";
};
// - not used, enable if needed -
//var isRunningOnCordova = function () {
//    return (typeof window.cordova !== "undefined");
//};
var initDevice = function() {
    if (typeof window.device === 'undefined') {
        return err("Missing cordova device plugin");
    }
    for (var key in runningDevice) {
        if (window.device.hasOwnProperty(key)) {
            runningDevice[key] = window.device[key];
        }
    }
    return true;
};

function getAppIsDebug() {
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.AppIsDebug) {
        return new Promise(function(resolve,reject){
            window.cordova.plugins.AppIsDebug.get(
                function(appinfo){
                    resolve(appinfo);
                },
                function(error){
                    err("getAppIsDebug(): "+error, error);
                    reject(new Error(error));
                }
            );
        });
    }
    
    err("getAppIsDebug(): plugin not available!");
    return Promise.resolve({});
}

function getManifest() {
    
    if (window.cordova.file) {
        return stargateModules.file.readFileAsJSON(window.cordova.file.applicationDirectory + "www/manifest.json");
    }
    
    if (window.hostedwebapp) {
        return new Promise(function(resolve,reject){
            window.hostedwebapp.getManifest(
                function(manifest){
                    resolve(manifest);
                },
                function(error){
                    err(error);
                    reject(new Error(error));
                }
            );
        });
    }
    
    err("getManifest() no available reading mechanism!");
    return Promise.resolve({});
}

var launchUrl = function (url) {
    log("launchUrl: "+url);
    document.location.href = url;
};


var isStargateRunningInsideHybrid = false;
var isStargateInitialized = false;
var isStargateOpen = false;
var initializeCallback = null;

/**
 * appVersion: version number of the app
 */
var appVersion = '';
/**
 * appBuild: build identifier of the app
 */
var appBuild = '';
/**
 * appPackageName: package name of the app - the reversed domain name app identifier like com.example.myawesomeapp
 */
var appPackageName = '';

/**
 * appIsDebug {Boolean} true if app is compiled in debug mode
 */
var appIsDebug = false;

/**
 * InApp Purchase module type:
 *  1 => use cordova plugin https://github.com/j3k0/cordova-plugin-purchase
 *  2 => use cordova plugin https://github.com/AlexDisler/cordova-plugin-inapppurchase
 */
var stargateIapType = 0;

var STARGATEIAPTYPES = {
    /**
     * use cordova plugin https://github.com/j3k0/cordova-plugin-purchase
     */
    "full": 1,

    /**
     * use cordova plugin https://github.com/AlexDisler/cordova-plugin-inapppurchase
     */
    "light": 2,
    
    1: "full",
    2: "light"
};

/**
 * 
 * variables sent by server configuration
 * 
 */
var hybrid_conf = {},
    requested_modules = [],
    modules_conf = {};

/**
 * 
 * Application information set on initialize
 * 
 */
var appInformation = {
    cordova: null,
    manufacturer: null,
    model: null,
    platform: null,
    deviceId: null,
    version: null,
    packageVersion: null,
    packageName: null,
    packageBuild: null,
    stargate: null,
    stargateModules: null,
    stargateError: null 
};

/**
* Set on webapp that we are hybrid
* (this will be called only after device ready is received and 
*   we are sure to be inside cordova app)
*/
var setIsHybrid = function() {   
    
    var re = new RegExp(/(^https?:\/\/)(.*)/);
    var result = re.exec(window.location.origin);
    var cookieDomain = '';
    if(result){
        cookieDomain = result[result.length - 1]
            .split('.')
            .filter(function(el){
                return !(el === 'www' || el === 'www2');
            }).join('.');
        // set multidomain cookie
        window.Cookies.set("hybrid", "1", {"domain": cookieDomain});        
    }

    window.Cookies.set("hybrid", "1");

    if (!window.localStorage.getItem('hybrid')) {
        window.localStorage.setItem('hybrid', 1);
    }
};

/**
* Set on webapp what version we need to load
* (this will be called only after manifest is loaded on stargate)
*/
var setHybridVersion = function() {

    window.Cookies.set("stargateVersion", getStargateVersionToLoad());

    if (!window.localStorage.getItem('stargateVersion')) {
        window.localStorage.setItem('stargateVersion', getStargateVersionToLoad());
    }
};

var hideSplashAndLoaders = function() {
    
    
    if (! haveRequestedFeature("leavesplash")) {
        navigator.splashscreen.hide();
    }

    setBusy(false);
    
    if (typeof SpinnerDialog !== "undefined") {
        SpinnerDialog.hide();
    }
};

var onPluginReady = function (resolve) {
    log("onPluginReady() start");

    // FIXME: this is needed ??
    document.title = stargateConf.title;
    
    // set back cordova bridge mode to IFRAME_NAV overriding manifold settings
    if (isRunningOnIos() && (typeof window.cordova !== 'undefined') && window.cordova.require) {
        var exec = window.cordova.require('cordova/exec');
        if (exec.setJsToNativeBridgeMode && exec.jsToNativeModes && exec.jsToNativeModes.IFRAME_NAV) {
            exec.setJsToNativeBridgeMode(exec.jsToNativeModes.IFRAME_NAV);                    
        }
    }
    bindConnectionEvents();
    // save stargate version to load on webapp 
    setHybridVersion();

    
    if (hasFeature("mfp") && haveRequestedFeature("mfp")) {
        var mfpModuleConf = getModuleConf("mfp");
        
        // configurations needed
        //stargateConf.motime_apikey,
{'fraction_non_alphanumeric': 0.14157706093189965, 'fraction_numerical': 0.005652054039150814, 'mean_word_length': 2.4154896421845575, 'pattern_counts': {'":': 6, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 8, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4391283', 'n_tokens_mistral': 4444, 'n_tokens_neox': 4351, 'n_words': 1004}