// dyyno_core.js                                                            Copyright (c) 2007-2009, Dyyno, Inc.
//
// This code is provided to you pursuant to the terms and conditions set forth in  the  evaluation  license  (or
// subsequent license agreement) between your organization and Dyyno, Inc.
//
// The code is partially based on "JavaScript Browser Sniffer" by Eric Krok, Andy King, Michel Plungjan
//                                see http://www.webreference.com/ for more information
//
// Author(s): Pierpaolo Baccichet (pier@dyyno.com)
//            Thomas Jansen (thomas@dyyno.com)
//
//                                                         $Date: 2009-03-04 14:52:47 -0800 (Wed, 04 Mar 2009) $


// ---[ DETECT THE NECESSARY BROWSERS ]--------------------------------------------------------------------------

// static global variables
var gl_is_browser_supported = false;
var gl_is_browser_supported_err_msg = "";
var gl_is_ads_supported = true;
var gl_is_ie = false;
var gl_is_mac = false;
var gl_reenter_cnt = 0;

// session global variables
var gl_host;
var gl_cport;
var gl_sid;
var gl_adzone = "dyynoads_nozone";
var gl_adparam1 = "dyynoads_noparam1";
var gl_adparam2 = "dyynoads_noparam2";
var gl_verbose = "";
var gl_secretkey = "";
var gl_verbose_flash = "0";
var gl_streamer = "dyynostreamer.swf";
var gl_volume = "";

var gl_secret_key;

var gl_used_player;
var gl_used_version;

var gl_is_vlc_receiver = false;
var gl_is_flash_receiver = false;

var gl_playerwidth  = 0;
var gl_playerheight = 0;

var gl_plaugin_div = 'dyynoplagindiv';
var gl_player_div_id = 'dyynoplayerdiv';
var player_div_id = gl_player_div_id;
var gl_error_div_id = 'errordiv';
var gl_console_div_id = 'consolediv';
var gl_status_div_id = 'statusdiv';

var gl_dyyno_launchresult;
var gl_dyyno_args;

var gl_qt_file_found = false;
var gl_updatePlayer = 0;
    
function check_browser()
{
    gl_is_browser_supported = false;
    gl_is_browser_supported_err_msg = "We're sorry, at the moment we don't support your browser"; // just a template

    // convert all characters to lowercase to simplify testing
    var agt = navigator.userAgent.toLowerCase();
    var appVer = navigator.appVersion.toLowerCase();

    // *** BROWSER VERSION ***
    var is_minor = parseFloat(appVer);
    var is_major = parseInt(is_minor);

    var is_opera = (agt.indexOf("opera") != -1);
    var is_maxthon = (agt.indexOf("maxthon") != -1);

    // Note: On IE, start of appVersion return 3 or 4
    // which supposedly is the version of Netscape it is compatible with.
    // So we look for the real version further on in the string
    // And on Mac IE5+, we look for is_minor in the ua; since
    // it appears to be more accurate than appVersion - 06/17/2004

    var is_mac = (agt.indexOf("mac") != -1);
    var iePos = appVer.indexOf('msie');
    if (iePos != -1)
    {
        if (is_mac)
        {
            var iePos = agt.indexOf('msie');
            is_minor = parseFloat(agt.substring(iePos + 5, agt.indexOf(';', iePos)));
        }
        else
            is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)));
        is_major = parseInt(is_minor);
    }

    // ditto Konqueror
    var is_konq = false;
    var kqPos = agt.indexOf('konqueror');
    if (kqPos != -1)
    {
        is_konq  = true;
        is_minor = parseFloat(agt.substring(kqPos+10,agt.indexOf(';',kqPos)));
        is_major = parseInt(is_minor);
    }

    var is_safari = ((agt.indexOf('safari') != -1) && (agt.indexOf('mac') != -1));
    var is_khtml  = (is_safari || is_konq);

    var is_gecko = ((!is_khtml) && (navigator.product) && (navigator.product.toLowerCase() == "gecko"));
    var is_gver  = 0;
    if (is_gecko)
        is_gver=navigator.productSub;

    var is_fb = ((agt.indexOf('mozilla/5')!=-1) && (agt.indexOf('spoofer')==-1) &&
               (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1)  &&
               (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)     &&
               (is_gecko) && (navigator.vendor=="Firebird"));
    var is_fx = ((agt.indexOf('mozilla/5')!=-1) && (agt.indexOf('spoofer')==-1) &&
               (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1)  &&
               (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)     &&
               (is_gecko) && ((navigator.vendor=="Firefox")||(agt.indexOf('firefox')!=-1)));
    var is_moz   = ((agt.indexOf('mozilla/5')!=-1) && (agt.indexOf('spoofer')==-1) &&
                  (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1)  &&
                  (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)     &&
                  (is_gecko) && (!is_fb) && (!is_fx) &&
                  ((navigator.vendor=="")||(navigator.vendor=="Mozilla")||(navigator.vendor=="Debian")));
    var is_ie   = ((iePos!=-1) && (!is_opera) && (!is_khtml));
    
    //if (is_mac && !is_fx)
    //    gl_is_browser_supported_err_msg = "We're sorry, at the moment we only support Firefox on Mac OS X. Stay tuned, however, we will have full Mac support in the near future!";
    //else 
    if (agt.indexOf('win') == -1 && !is_mac) // Linux or similar
        gl_is_browser_supported_err_msg = "We're sorry, at the moment you can only watch Dyyno video on Windows or MacOSX.";
    //else if (agt.indexOf('win64') != -1 || agt.indexOf('x64') != -1) //64bit browser
    //    gl_is_browser_supported_err_msg = "We're sorry, at the moment you can only watch Dyyno video in 32bit browser.";
    //else if (!is_moz && !is_fx && !is_ie) // unsupported browser family
    //    gl_is_browser_supported_err_msg = "We're sorry, at the moment you can only watch Dyyno video in Internet Explorer or Firefox.";
    else // OK
    {
        gl_is_browser_supported = true;
        gl_is_browser_supported_err_msg = "";
    }
    
    gl_is_mac = is_mac;
    gl_is_ie = is_ie;
    gl_is_ads_supported = !is_maxthon; // we have a problem to show ads in Maxthon, should be fixed soon

    return;
}

// specifics of the server and plugin version
function isVista()
{
    return (navigator.userAgent.indexOf("Windows NT 6.0") > -1);
}

function detectNPPlugin(searchPlugin, desired_version)
{
    if (!navigator.plugins || navigator.plugins.length == 0)
        return false;
        
    // consider pluginFound to be false until proven true
    var pluginFound = false;
    // if plugins array is there and not fake
    if (navigator.plugins && navigator.plugins.length > 0)
    {
        var pluginsArrayLength = navigator.plugins.length;
        // loop through all desired names and check each against the current plugin name
        var numFound = 0;
        for(pluginsArrayCounter = 0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++)
        {
            // if desired plugin name is found in either plugin name or description
            if ( (navigator.plugins[pluginsArrayCounter].name.indexOf(searchPlugin) >= 0) ||
                (navigator.plugins[pluginsArrayCounter].description.indexOf(searchPlugin) >= 0) )
            {
                
                if (typeof desired_version == 'undefined' || desired_version == null || desired_version == "") //is version check needed
                    return true;
                    
                var verAt = navigator.plugins[pluginsArrayCounter].description.indexOf("ver:");
                var verString;
                if (verAt >= 0)
                    verString = navigator.plugins[pluginsArrayCounter].description.substr(verAt + 4);
                else
                    verString = "0.0.0.0";

                pluginFound = checkVersion(verString, desired_version);
                if (pluginFound)
                    break;
            }
        }
    }
    return pluginFound;
} // detectNPPlugin

function init_session_global_vars()
{
    gl_host = null;
    gl_cport = null;
    gl_sid = null;
    gl_adzone = "dyynoads_nozone";
    gl_adparam1 = "dyynoads_noparam1";
    gl_adparam2 = "dyynoads_noparam2";
    gl_verbose = "";
    gl_secretkey = "";

    gl_used_player = null;
    gl_used_version = null;

    gl_is_vlc_receiver = false;
    gl_is_flash_receiver = false;

    gl_playerwidth  = 0;
    gl_playerheight = 0;

    gl_player_div_id = 'dyynoplayerdiv';
    var player_div_id = gl_player_div_id;
    gl_error_div_id = 'errordiv';
    gl_console_div_id = 'consolediv';
    gl_status_div_id = 'statusdiv';

    gl_dyyno_launchresult = null;
    gl_dyyno_args = null;

    oldDyynoKilled = 0;
    gl_qt_file_found = false;
    
    gl_updatePlayer = 0;
    
    gl_streamer = "dyynostreamer.swf";
}

function div_append(div_id, newhtml)
{
    var the_div = document.getElementById(div_id);
    var the_div_innerHTML = the_div.innerHTML;
    the_div_innerHTML = the_div_innerHTML + newhtml;
    the_div.innerHTML = the_div_innerHTML;
}

function div_replace(div_id, newhtml, hide)
{
    var the_div = document.getElementById(div_id);
    if (hide)
    {
        the_div.style.height     = 0;
        the_div.style.fontSize   = 0;
        the_div.style.lineHeight = 0;
    }
    if (the_div)
        the_div.innerHTML = newhtml;
}

function isdefined(variable)
{
    return !(typeof(window[variable]) == "undefined");
}

function dyynoLoadingCallback(active, percent_done) 
{
    var width = 550; 
    var height = 400;
    if (gl_playerwidth > 0)
        width = gl_playerwidth;
    if (gl_playerheight > 0)
        height = gl_playerheight;

//    if (active)
//        div_replace(gl_status_div_id, 'Buffering... <br> <object width='+width+' height='+height+'><param name="movie" value="somefilename.swf"><param name="wmode" value="transparent"><embed src="'+dyynourl_tng+'/logo3.swf" width='+width+' height='+height+' wmode="transparent"></embed></object></center>');
//    else 
    var progress_div = document.getElementById("dyyno_progress_div");
    if (active)
    {
        if (progress_div == null)
            div_replace(gl_status_div_id, '<center><div id="dyyno_progress_div">Loading content ('+percent_done+'% done)...</div><br/> <object width='+width+' height='+height+'><param name="movie" value="somefilename.swf"><param name="wmode" value="transparent"><embed src="'+dyynourl_tng+'/logo3.swf" width='+width+' height='+height+' wmode="transparent"></embed></object></center>');
        else
            div_replace("dyyno_progress_div", 'Loading content ('+percent_done+'% done)...');
    }
    else
    {
        if (progress_div == null)
            div_replace(gl_status_div_id, '<center><div id="dyyno_progress_div">Waiting for video...</div><br/> <object width='+width+' height='+height+'><param name="movie" value="somefilename.swf"><param name="wmode" value="transparent"><embed src="'+dyynourl_tng+'/logo3.swf" width='+width+' height='+height+' wmode="transparent"></embed></object></center>');
        else
            div_replace("dyyno_progress_div", 'Waiting for video...');
    }
} 

function addEvent(obj, type, fn)
{
    if (obj.attachEvent)
        obj.attachEvent('on' + type, fn);
    else
        obj.addEventListener(type, fn, false);
}

// Should only be called by the flash player when it is ready to resize.
function changePlayerDivSizeAndColor(newwidth, newheight, newcolor) 
{
    var the_div = document.getElementById(gl_player_div_id);
    the_div.style.width =  "" + newwidth + "px";
    the_div.style.height = "" + newheight + "px";
    the_div.style.bgcolor = "" + newcolor;
}

function destroy_flashembed()
{
    //TODO Send message and destroy Flash player here
}

function dyynoSetPlayerSizeCallback(event_desc, size)
{
}


/*!
    \brief Open the Dyyno player. RC3.0 version.
*/

function open_dyyno_player(thehost, thedport, thecport, thesid, thewidth, theheight, theadzone, theadparam1, theadparam2, thewidth, theheight, thesecretkey, thedebug, theplayer)
{
    launch_dyyno_player(thehost, thecport, thesid, theadzone, theadparam1, theadparam2, thewidth, theheight, thesecretkey, thedebug, theplayer);
}

/*!
    \brief Launch the Dyyno player. RC3.1 version.
*/
function launch_dyyno_player(thehost, thecport, thesid, theadzone, theadparam1, theadparam2, thewidth, theheight, thesecretkey, thedebug, theplayer, thebroadcaster)
{
    if (!gl_is_browser_supported)
    {
        div_replace(gl_player_div_id, gl_is_browser_supported_err_msg);
        alert(gl_is_browser_supported_err_msg);
        return;
    }
    
    if (gl_reenter_cnt > 0)
        destroy_flashembed();
    ++gl_reenter_cnt;    
    
    init_session_global_vars();
    
    gl_host  = thehost;
    gl_cport = thecport;
    gl_sid   = thesid.substr(0,16);

    // ---

    var info = tracker_to_info[gl_host];

    if (info           == null) { info           = new Object(); }
    if (info.version   == null) { info.version   = 'default';    }
    if (info.receiver  == null) { info.receiver  = 'flash';      }

    if (theplayer == null)
        gl_used_player = info.receiver;
    else
        gl_used_player = theplayer;

    gl_used_version = info.version;

    gl_is_vlc_receiver   = (gl_used_player == 'vlc');
    gl_is_flash_receiver = (gl_used_player == 'flash');

    // ---

    while(gl_sid.length < 16)
        gl_sid += "0";

    if (typeof thedebug != "undefined" && thedebug != null)
        gl_verbose   = thedebug;
    else
        gl_verbose   = 0;

    if (typeof theadzone != "undefined" && theadzone != null)
    {
        gl_adzone = theadzone;
    }

    if (typeof theadparam1 != "undefined" && theadparam1 != null)
        gl_adparam1 = theadparam1;

    if (typeof theadparam2 != "undefined" &&  theadparam2 != null)
        gl_adparam2 = theadparam2;

    if (typeof thewidth != "undefined" && thewidth != null)
        gl_playerwidth = thewidth;

    if (typeof theheight != "undefined" && theheight != null)
        gl_playerheight = theheight;

    if (typeof thesecretkey != "undefined" && thesecretkey != null)
        gl_secretkey = thesecretkey;
    if (typeof thebroadcaster != "undefined" && thebroadcaster != null && thebroadcaster == "1")
        gl_volume = "0";
        
    addEvent(window, 'unload', destroy_flashembed);
    addEvent(window, 'beforeunload', destroy_flashembed);

    launchDyynoClient();
}

function launchDyynoClient()
{
    var cmdLine = "";

    if (gl_is_vlc_receiver)
        cmdLine = '-p ' + gl_host + ' -c ' + gl_cport + ' -S ' + gl_sid + ' -I v';
    else if (gl_is_flash_receiver)
        cmdLine = '-p ' + gl_host + ' -c ' + gl_cport + ' -S ' + gl_sid;

    if (gl_verbose != "")
        cmdLine = cmdLine + ' -D ' + gl_verbose;

    if (gl_secretkey != "")
        cmdLine = cmdLine + ' -P ' + gl_secretkey;

    if (gl_host == "")
        cmdLine = "";
        
    launchDyyno(cmdLine);
}

/*!
    \brief Launch the Dyyno client
*/
function launchDyyno(args)
{
    var launchResult = 0;

    gl_dyyno_args = args; //+ ' -C 0';
    
    var platform = '';
    if (gl_is_mac)
        platform = 'MacOSX/';

    var v_compare_url = dyynourl_tng + '/tracker-versions/' + platform + gl_used_player + '/' + gl_used_version;
    
    // Embed flash object
    var finalplayersize = {width: 640, height: 480};
    if (gl_playerwidth > 0)
        finalplayersize.width = gl_playerwidth;
    if (gl_playerheight > 0)
        finalplayersize.height = gl_playerheight;
     
    if (typeof customSetPalyerSizeCallback == "function")
        customSetPlayerSizeCallback("ads", finalplayersize);
    else
        dyynoSetPlayerSizeCallback("ads", finalplayersize);
        
    changePlayerDivSizeAndColor(finalplayersize.width, finalplayersize.height, "#000000");
    var the_div = document.getElementById(gl_player_div_id);
    if (gl_verbose != "")
        gl_verbose_flash = "" + gl_verbose;                    
    if (false == flashembed(the_div,
               dyynourl_tng+"/dyyno-client/" + gl_streamer,
               { sessionID : gl_sid,
                 sessionServer: "backend-rc31.dyyno.com",
                 adZone: gl_adzone,
                 adParam1: gl_adparam1,
                 adParam2: gl_adparam2,
                 //divWidth: "" + finalplayersize.width,
                 //divHeight: "" + finalplayersize.height,
        	 tracker_ip: gl_host,
		 tracker_port: gl_cport,
		 secret_key: gl_secret_key,
		 compare_url: v_compare_url,
                 debugPlayer: gl_verbose_flash  ,
                 volume: gl_volume
               })
        )
    {
        // Flash Player not started
        alert('Flash Player not started');
    }
}

function screenSize()
{
	return new Array(screen.height, screen.width);
}

function exitOnError(error_desc)
{
    setTimeout('terminateDyyno("' + error_desc +'")', 2000);
}

function launcherMessageFromFlash()
{
    alert('launcherMessageFromFlash');
}

function terminateDyyno(error_desc)
{
    var errorHTML = '<p class="error">' + error_desc + '</p>';
    div_replace(gl_player_div_id, errorHTML);
}

function no_launcher_running()
{
    var install_name = "dyyno_launcher.msi";

    if (gl_is_mac)
        install_name = "MacOSX/DyynoViewer.dmg";

    div_replace("statusdiv", "To view this broadcast, please download the Dyyno Viewer.<form action=\"" + dyynourl_tng + "/dyyno-client/" + install_name + "?param="+Math.floor(Math.random()*10000)+"\" method=get><input type=submit value=\"Download Dyyno Viewer\"></form><span style=\"color:red\">If you have an old version, you will need to download and install again. The latest version lets you watch on any browser!</span><br/>&nbsp;");
}

function connected_to_launcher()
{
     div_replace("statusdiv", "");
}

//static code
check_browser();
