/*******************************************************
* initLauncher
*
* NOTE: Has dependency on vars set on the page - have to
*       because we need those var values from Normandy.
*
******************************************************/
function initLauncher() {
    var lp = launchParams;

    // set target player from url
    if (lp.player != '' && (lp.player == 'std' || lp.player == 'hq'))
        lp.def = lp.player;

    // set default player cookie
    if (!lp.def || lp.def == null || (lp.def != 'hq' && lp.def != 'std'))
        createCookie(lp.defCookieName,lp.defaultStream,365);
    
    if (lp.kswitch == 'on') {
        lp.def = 'std';
        launchParams.queryObj.ks = 1;
    }
    
    if (lp.e) { // handle errors
        document.getElementById('pageCnt').style.display = 'block';
        errorHandler(lp.e);
    }
    else if (lp.def == 'hq') { // default is hq
        //createCookie(lp.defCookieName,'hq',365);
        getBandwidth('hq',bandwidthCheck);
    }
    else if (lp.def == 'std') { // default is std
        createCookie(lp.defCookieName,'std',365);
        getBandwidth('std',bandwidthCheck);
    }
}

/*******************************************************
* xmlHTTPObject - HTTP object factory
******************************************************/
var xmlHTTPObject = function() {
    try { return new XMLHttpRequest(); } catch(ex) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (ex) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (ex) {}
    return false;
}

/*******************************************************
* getBandwidth
*
* PARAMETERS:
*   quality:   HQ|STD
*   callback:  the name of the callback function to pass
*              the data object to
*
* DATA OBJECT:
*   bandwidth: boolean -> is bandwidth available
*   wait_time: seconds to wait before trying again
*              if no bandwidth is available
******************************************************/
var getBandwidth = function(quality,callback) {
    quality = quality || 0;

    var readystatechange = function() {
        if (http.readyState == 4 && http.status == 200) {
            var data = http.responseText;
            data = data.replace(/\<\!--.*?--\>/gi, ''); // need this to kill normandy comment
            data = eval('('+data+')');
            callback(data,quality);
        }
    }

    launchParams.host = launchParams.host || 'mmod.ncaa.com';
    var http = new xmlHTTPObject();
    var url = encodeURI('http://'+launchParams.host+'/mmod/bandwidth.json?r='+Math.floor(Math.random()*new Date().getTime()));
    http.open("GET",url,true);
    http.onreadystatechange = readystatechange;
    http.send(null);


}

function errorHandler(e) {
    switch(e) {
        case 1: // Wait Message
            getError('1');
            break;
        case 2: // STD at capacity
            getError('2');
            break;
        case 3: // HQ at capacity
            getError('3');
            break;
        case 4: // Capacity reached
            getError('4');
            break;
        case 5: // Error
            getError('5');
            break;
        case 6: // Inactivity check.
            getError('6');
            break;
        default:
    }
}


function bandwidthWait(time,quality,callback){
    var timerId = null;
    clearTimeout(timerId);
    var errorLink = '';
    if (launchParams.player == 'std') {
        launchParams.queryObj.player = 'hq';
        errorLink = '<p><b><a href="/video' + packQuery(launchParams.queryObj) + '">Click here</a> to try the HQ player.</b></p>';
        launchParams.queryObj.player = 'std';
    }
    else if (launchParams.player == 'hq') {
        launchParams.queryObj.player = 'std';
        errorLink = '<p><b><a href="/video' + packQuery(launchParams.queryObj) + '">Click here</a> to try the standard player.</b></p>';
        launchParams.queryObj.player = 'hq';
    }
    if (time > 0) {
        var pl = (time == 1) ? '' : 's';
        writeError('<h1>Player at capacity, please stand by.<br/>Trying again in ' + (time) + ' second' + pl + '.</h1>' + launchParams.errorMsg + errorLink);
        timerId = setTimeout("bandwidthWait("+(time-1)+",'"+quality+"',"+callback+")",1000);
    }
    else {
        writeError('Trying again...');
        launchParams.waitIt++;
        setTimeout("getBandwidth('"+quality+"',"+callback+")",500);
    }
}


function bandwidthCheck(data,quality) {
    var rnd = parseInt(Math.floor(Math.random() * 100)+1);
    if (data.HQ == 100 && data.STD == 100) {
        window.location.href = 'http://'+launchParams.host+'/video/4'+packQuery(launchParams.queryObj);
    }
    else if (data.HQ == 100 && quality == 'hq' && data.STD != 100) {
        window.location.href = 'http://'+launchParams.host+'/video/3'+packQuery(launchParams.queryObj);
    }
    else if (data.HQ != 100 && data.STD == 100 && quality == 'std') {
        window.location.href = 'http://'+launchParams.host+'/video/2'+packQuery(launchParams.queryObj);
    }
    else if (rnd > data.HQ && quality == 'hq') {
        launchParams.queryObj.ts = launchParams.ts;
        launchParams.queryObj.t = launchParams.token;
        launchParams.queryObj.i = launchParams.waitIt;
        launchParams.queryObj.w = launchParams.waitTime;
        delete launchParams.queryObj.player;
        window.location.href = 'http://'+launchParams.host+'/video/hq/player'+packQuery(launchParams.queryObj);

        writeError('Loading...');
    }
    else if (rnd > data.STD && quality == 'std') {
        launchParams.queryObj.ts = launchParams.ts;
        launchParams.queryObj.t = launchParams.token;
        launchParams.queryObj.i = launchParams.waitIt;
        launchParams.queryObj.w = launchParams.waitTime;
        delete launchParams.queryObj.player;
        window.location.href = 'http://'+launchParams.host+'/video/std'+packQuery(launchParams.queryObj);

        writeError('Loading...');
    }
    else {
        var time = data.WAIT;
        launchParams.waitTime = time;
        document.getElementById('pageCnt').style.display = 'block';
        bandwidthWait(time,quality,bandwidthCheck);
    }
}




/*******************************************************
* getError
*
* PARAMETERS:
*   error_code: The error code data to retrieve
*
* DATA OBJECT:
*   content:    Error content
******************************************************/
function getError(error_code, action) {

    var readystatechange = function() {
        if (http.readyState == 4 && http.status == 200) {
            var data = http.responseText;
            data = data.replace(/\<\!--.*?--\>/gi, ''); // need this to kill normandy comment
            launchParams.queryObj.player = '';
            data = data.replace(/\|\|\|QUERY\|\|\|/gi, packQuery(launchParams.queryObj)); // carry the query string
            if (action == 'read') launchParams.errorMsg = data;
            else writeError(data);
        }
    }

    launchParams.host = launchParams.host || 'mmod.ncaa.com';
    var http = new xmlHTTPObject();
    var url = encodeURI('http://'+launchParams.host+'/video/error-handler/'+error_code+'?r='+Math.floor(Math.random()*new Date().getTime()));
    http.open("GET",url,true);
    http.onreadystatechange = readystatechange;
    http.send(null);
}

function writeError(m) {
    if (document.getElementById('errorDiv')) {
        document.getElementById('errorDiv').innerHTML = m;
        return true;
    }
}


function createCookie(name,value,days) {
	try {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }
    catch (ex) {
        return false;
    }
    return true;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	try {
        createCookie(name,"",-1);
    }
    catch (ex) {
        return false;
    }
    return true;
}

function unpackQuery(queryString) {
    var pairs = (queryString.substring(1)).split("&");
    var queryObj = {};
    for (p in pairs) {
        var thisPair = pairs[p].split("=");
        if (thisPair.length == 2 && thisPair[0] != '' && thisPair[1] != '') {
            queryObj[thisPair[0].toLowerCase()] = thisPair[1].toLowerCase();
        }
    }
    return queryObj;
}

function packQuery(queryObj) {
    var pairs = [];
    for (o in queryObj) {
        if (o != '' && queryObj[o] != '')
        pairs.push(o + '=' + queryObj[o]);
    }
    return '?' + pairs.join("&");
}