/**
 * Utility for testing user's configuration
 * Usage:
 *  ConfigTest.getWindowsVersion():String
 *      returns the Windows OS name
 *  ConfigTest.checkOS():boolean
 *      returns true when getWindowsVersion() returns an accepted OS
 *  ConfigTest.getWMPVersion( useActivex:boolean, parse:boolean ):float
 *      returns the Windows Media Player version obtained through ActiveX/Plugin instantiation
 *          or 0 when instantiation not possible
 *      useActivex parameter is relevant only for IE and constrains the use of window.ActiveXObject (true if omitted)
 *      parse parameter tells whether to parse the version to a float format (11.057216 instead of 11.0.5721.5230)
 *          which is easier to compare (true if omitted)
 *  ConfigTest.checkWMPlayer():boolean
 *      returns true when getWMPVersion() returns an accepted version
 *  ConfigTest.getBandWidth( callback:Function )
 *      tests user's connection bandwidth with an image download; callback is called upon download completion
 *      callback parameter should have the signature: function cb( speed:number )
 *  ConfigTest.checkBandWidth( speed:number ):boolean
 *      returns true when speed parameter has an accepted value
 *  ConfigTest.getTZLocalOffset():number
 *      returns the timezone local offset in hours
 *  ConfigTest.getNetObjInfo( useActivex:boolean ):Object
 *      returns an object with the following fields populated with info from the DRM netobj instatiation
 *      - instantiable : boolean - true when instatiation was successful;
 *      - drmVersion : String - result of GetDRMVersion();
 *      - drmSecurityVersion : String - result of GetDRMSecurityVersion();
 *      - systemInfo : String - stripped result of GetSystemInfo();
 *      useActivex parameter is relevant only for IE and constrains the use of window.ActiveXObject (true if omitted)
 */
/**
 * Helper for instantiating plugins/activex with DOM objects
 * - useful with Firefox and IE/classid
 */
function PluginHelper(/*String*/ attName, /*String*/ attValue){
    this.id = 'glow-vmct-' + PluginHelper.prototype.idCounter++;
    this.attName = attName.toUpperCase();
    this.attValue = attValue;
    this.init(document.body);
}
PluginHelper.prototype = {
    /*STATIC*/
    htmlTYPE: '<OBJECT id="{ID}" type="{TYPE}" width="0" height="0" style="visibility:hidden;"></OBJECT>',
    htmlCLASSID: '<OBJECT id="{ID}" classid="{CLASSID}" width="0" height="0" style="visibility:hidden;"></OBJECT>',
    htmlDRM: '<OBJECT id="{ID}" classid="{DRM}" width="0" height="0" style="visibility:hidden;"><EMBED MAYSCRIPT TYPE="application/x-drm-v2" HIDDEN="true"/></OBJECT>',
    idCounter: 0,
    /*MEMBERS*/
    id: null,
    attName: null,
    attValue: null,
    objDOM: null,
    objContainer: null,
    objParent: null,
    init: function (/*DOM object*/ parent) {
        this.objParent = parent;
        this.objContainer = document.createElement('DIV');
        var html = this['html' + this.attName];
        html = html.replace(/\{ID\}/i, this.id).replace('{'+this.attName+'}', this.attValue);
        this.objContainer.innerHTML = html;
        this.objContainer.style.fontSize = '0';
        this.objContainer.style.lineHeight = '0';
        this.objContainer.style.height = '0';
        this.objParent.appendChild(this.objContainer);
        this.objDOM = document.getElementById(this.id);
    },
    getVersionInfo: function () {
        return this.objDOM.versionInfo;
    },
    GetDRMVersion: function () {
        return this.objDOM.GetDRMVersion();
    },
    GetDRMSecurityVersion: function () {
        return this.objDOM.GetDRMSecurityVersion();
    },
    GetSystemInfo: function () {
        return this.objDOM.GetSystemInfo();
    },
    release: function () {
        this.objParent.removeChild(this.objContainer);
    }
};
/**
 *  Bandwidth tester with image download
 */
function SpeedTestImg(/*Function*/ cb){
    this.callback = cb;
}
SpeedTestImg.prototype = {
    imgSrc: 'http://media.glowria.fr/test/img.jpg?t={t}',
    imgSize: 1006704,/*bytes*/
    objImg: null,
    timeStart: 0,
    result: 0,
    callback: null,
    bind: function (/*Function*/ func, /*Array*/ args) {
        var thiz = this;
        return function () {
            return func.apply(thiz, args?args:arguments);
        };
    },
    onLoad: function (/*Event*/ e) {
        var timeEnd = (new Date()).getTime();
        this.result = Math.round((this.imgSize/1024)/((timeEnd-this.timeStart)/1000))*8;
        if (this.callback)
            this.callback.call(this, this.result);
    },
    onError: function (/*Event*/ e) {
        alert('Erreur de chargement de l\'image');
    },
    start: function () {
        this.objImg = document.createElement('IMG');
        this.objImg.onload = this.bind(this.onLoad);
        this.objImg.onerror = this.bind(this.onError);
        this.objImg.onabort = this.bind(this.onError);
        this.timeStart = (new Date()).getTime();
        this.objImg.src = this.imgSrc.replace(/\{t\}/i, this.timeStart);
    }
};
/**
 * Configuration tester singleton
 */
var ConfigTest = {
    /*WINDOWS versions*/
    WINDOWS_NA: 'OS Inconnu',
    WINDOWS_95: 'Windows 95',
    WINDOWS_98: 'Windows 98',
    WINDOWS_ME: 'Windows ME',
    WINDOWS_NT: 'Windows NT',
    WINDOWS_2K: 'Windows 2000',
    WINDOWS_XP: 'Windows XP',
    WINDOWS_VA: 'Windows Vista',
    /*Find OS Windows version*/
    getWindowsVersion: function () {
        if (navigator.platform.toLowerCase().indexOf("win") == -1)
            return this.WINDOWS_NA;
        var ua = navigator.userAgent.toLowerCase();
        var m;
        if (m = /windows nt (\d+(\.\d+)*)/i.exec(ua)) {
            var v = parseFloat(m[1]);
            if (v >= 6.0)
                return this.WINDOWS_VA;
            if (v >= 5.1)
                return this.WINDOWS_XP;
            if (v >= 5.0)
                return this.WINDOWS_2K;
        }
        if (ua.indexOf("winnt")!=-1 || ua.indexOf("windows nt")!=-1)
            return this.WINDOWS_NT;
        if (ua.indexOf("win 9x 4.90")!=-1)
            return this.WINDOWS_ME;
        if (ua.indexOf("win98")!=-1 || ua.indexOf("windows 98")!=-1)
            return this.WINDOWS_98;
        if (ua.indexOf("win95")!=-1 || ua.indexOf("windows 95")!=-1)
            return this.WINDOWS_95;
        return this.WINDOWS_NA;
    },
    /*Check if plugin installed*/
    hasPlugin: function (/*String*/ mimeType) {
        return !!(navigator.mimeTypes[mimeType] && navigator.mimeTypes[mimeType].enabledPlugin);
    },
    /*Parse MediaPlayer version*/
    parseWMPVersion: function (/*String*/ version) {
        var vs = ('' + version).split('.');
        var v = vs[0] + '.';
        for (var x=1;x<vs.length;x++) {
            v += vs[x];
        }
        return parseFloat(v);
    },
    /*Get MediaPlayer version*/
    getWMPVersion: function (/*boolean*/useActiveX,/*boolean*/parse) {
        useActiveX = typeof(useActiveX) == 'undefined' ? true : useActiveX;
        parse = typeof(parse) == 'undefined' ? true : parse;
        var verWMP = 0.0;
        var objWMP;
        if (window.ActiveXObject && useActiveX) {// IE activeX - javascript
            try {
                objWMP = new ActiveXObject("MediaPlayer.MediaPlayer.1");
                verWMP = 6.4;
            } catch(ex) {}
            try {
                objWMP = new ActiveXObject("WMPlayer.OCX");
                verWMP = 7.0;
                if (objWMP.versionInfo) {
                    verWMP = objWMP.versionInfo;
                }
            } catch(ex) {}
        } else
        if (window.ActiveXObject && !useActiveX) {// IE activeX - html
            try {
                objWMP = new PluginHelper('CLASSID','CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6');
                if (objWMP.getVersionInfo()) {
                    verWMP = objWMP.getVersionInfo();
                }
            } catch(ex) {
                //alert(ex.message || ex);
            } finally {
                try {objWMP.release();} catch(e) {}
            }
        } else
        if (navigator.mimeTypes) {// FF plugin
            var playerType = '';
            if (this.hasPlugin("application/x-mplayer2")) {
                verWMP = 5.2;
                playerType = 'application/x-mplayer2';
            }
            if (this.hasPlugin("video/x-ms-wm") && this.hasPlugin("video/x-ms-wmv")) {
                //verWMP = 6.4;
                //playerType = 'application/x-ms-wm';
                // override WMP version for Firefox to avoid version 11.0 plugin installation
                verWMP = 10.0;
            }
            if (this.hasPlugin("application/x-ms-wmp")) {
                verWMP = 11.0;
                playerType = 'application/x-ms-wmp';
            }
            if (playerType) {
                try {
                    objWMP = new PluginHelper('TYPE',playerType);
                    if ( !/^(undefined|function)$/i.test( typeof( objWMP.getVersionInfo() ) ) ) {
                        verWMP = objWMP.getVersionInfo();
                    }
                } catch(ex) {
                    //alert(ex.message || ex);
                } finally {
                    try {objWMP.release();} catch(e) {}
                }
            }
        }
        return (parse && typeof(verWMP)!='number') ? this.parseWMPVersion(verWMP) : verWMP;
    },
    /*Check the download speed*/
    stripSystemInfo: function (/*String*/ sInfo) {
        return sInfo.replace(/(<(CLIENTID|MACHINECERTIFICATE|REVINFO)>.{5}).+?(.{5}<\/\2>)/gi, "$1...$3");
    },
    /*Get NetObj info*/
    getNetObjInfo: function (/*boolean*/useActiveX) {
        useActiveX = typeof(useActiveX) == 'undefined' ? true : useActiveX;
        var info = {instantiable:false, drmVersion:'', drmSecurityVersion:'', systemInfo:''};
        var netobj;
        if (window.ActiveXObject && useActiveX) {// IE activeX - javascript
            try {
                netobj = new ActiveXObject("DRM.GetLicense.1");
                if (netobj.GetDRMVersion()) {
                    info.instantiable = true;
                    info.drmVersion = netobj.GetDRMVersion();
                    info.drmSecurityVersion = netobj.GetDRMSecurityVersion();
                    info.systemInfo = this.stripSystemInfo(netobj.GetSystemInfo());
                }
            } catch(ex) {}
        } else
        if (window.ActiveXObject && !useActiveX) {// IE activeX - html
            try {
                netobj = new PluginHelper('DRM','CLSID:A9FC132B-096D-460B-B7D5-1DB0FAE0C062');
                //netobj.init(document.body);
                if (netobj.GetDRMVersion()) {
                    info.instantiable = true;
                    info.drmVersion = netobj.GetDRMVersion();
                    info.drmSecurityVersion = netobj.GetDRMSecurityVersion();
                    info.systemInfo = this.stripSystemInfo(netobj.GetSystemInfo());
                }
            } catch(ex) {
                //alert(ex.message || ex);
            } finally {
                try {netobj.release();} catch(e) {}
            }
        }/* else
        if (navigator.mimeTypes) {// FF plugin
            if (this.hasPlugin("application/x-drm-v2")) {
                try {
                    netobj = new PluginHelper('TYPE','application/x-drm-v2');
                    //netobj.init(document.body);
                    if (netobj.GetDRMVersion()) {
                        info.instantiable = true;
                        info.drmVersion = netobj.GetDRMVersion();
                        info.drmSecurityVersion = netobj.GetDRMSecurityVersion();
                        info.systemInfo = this.stripSystemInfo( netobj.GetSystemInfo() );
                    }
                } catch(ex) {
                    //alert(ex.message || ex);
                } finally {
                    try {netobj.release();} catch(e) {}
                }
            }
        }*/
        return info;
    },
    /*Get the download speed*/
    getBandWidth: function (/*Function*/ callback) {
        var tst = new SpeedTestImg(callback);
        tst.start();
    },
    /*Get the timezone local offset in hours*/
    getTZLocalOffset: function () {
        return (new Date()).getTimezoneOffset() / 60;
    },
    /*Check compatible OS*/
    checkOS: function () {
        var verOS = this.getWindowsVersion();
        return (verOS == this.WINDOWS_XP) || (verOS == this.WINDOWS_VA);
    },
    /*Check compatible Windows Media Player*/
    checkWMPlayer: function () {
        //return this.getWMPVersion() >= 10.0;
        return ( this.getWMPVersion() >= 10.0 ) || ( this.getWindowsVersion() == this.WINDOWS_VA );
    },
    /*Check the download speed*/
    checkBandWidth: function (/*Integer*/ actualBW) {
        return actualBW >= 800;
    }
};