/**
    @namespace bbc used as global namespace to hold emp_fmtj Class and related methods
*/
if(typeof bbc === "undefined") window.bbc = {};

bbc.emp_fmtj = function(o){
	// ADD THIS TO ALIGNMENT
	this._propertiesObj=new bbc.emp_fmtj_properties();
    this.domId = null;
    this._self = this;
    this._attachedToOnLoadStack = false;
    this._empPlayersArray = new Array();
    this._expressInstallUrl = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
    this._targetFlashVersion = o.version || this._propertiesObj.flashPlayerRequired;
    this._flashVersion = newsi.getFlashVersion();
    this._isSupportedVersion = this._checkFlashVersion();
}
bbc.emp_fmtj.doubleClick = false;
bbc.emp_fmtj.prototype.setEmpGlobalVariables = function(){
    this._params = {};
    this._variables = {};
    this._attributes = {};
    this.setParam("swf", this._propertiesObj.swf);
    this.setParam("id", this._propertiesObj.id);
    this.setParam("wmode", this._propertiesObj.wmode);
    this.setParam("allowFullScreen", this._propertiesObj.allowFullScreen);
    this.setVariable("config", this._propertiesObj.configURL);
    this.setVariable("companionSize", this._propertiesObj.companionSize);
    this.setVariable("companionType", this._propertiesObj.companionType);
	// set skin colour - not set via CPS
	// ADD THIS TO ALIGNMENT
	if (this._propertiesObj.skin){
		this.setVariable("config_settings_skin", this._propertiesObj.skin);
	}
	if (this._propertiesObj.showShareButton){
		this.setVariable("config_settings_showShareButton", this._propertiesObj.showShareButton);
	}
    for (player in this._empPlayersArray) {
        this.setLocalVarsAndWriteEmpObj({
            obj: this._empPlayersArray[player]
        });
    }
}
bbc.emp_fmtj.prototype.setLocalVarsAndWriteEmpObj = function(o){
    this.setVariable("preroll", "");
    if (!bbc.emp_fmtj.doubleClick && (typeof BBC === "object" && typeof BBC.adverts.empCompanion === 'function')) {
        this.setVariable("preroll", BBC.adverts.empCompanion());
        this.setVariable("companionSize", this._propertiesObj.companionSize);
        this.setVariable("companionType", this._propertiesObj.companionType);
    };
    if (!o.obj["height"] && !o.obj["width"]) {
        this.setAttribute("height", this._propertiesObj.audioHeight);
        switch (o.obj["size"]) {
            case "Small":
                this.setAttribute("width", this._propertiesObj.audioWidthSmall);
                break;
            case "Full":
                this.setAttribute("width", this._propertiesObj.audioWidthLarge);
                break;
        }
    }
    else {
        this.setAttribute("width", o.obj["width"]);
        o.obj["height"] = this._padHeightForToolbar(o.obj["height"]);
        this.setAttribute("height", o.obj["height"]);
    }
    if (o.obj["caption"]) {
        this.setAttribute("caption", o.obj["caption"])
    }
    if (o.obj["id"]) {
        this.setAttribute("name", o.obj["id"])
    };
    if (o.obj["companionId"]) {
        this.setVariable("companionId", o.obj["companionId"])
    };
    if (o.obj["config_settings_suppressItemKind"]) {
        this.setVariable("config_settings_suppressItemKind", o.obj["config_settings_suppressItemKind"])
    };
    if (o.obj["autoPlay"]) {
        this.setVariable("config_settings_autoPlay", o.obj["autoPlay"])
    };    
    if (o.obj["config_settings_autoPlay"]) {
        this.setVariable("config_settings_autoPlay", o.obj["config_settings_autoPlay"])
    };
    if (o.obj["config_settings_showPopoutButton"]) {
        this.setVariable("config_settings_showPopoutButton", o.obj["config_settings_showPopoutButton"])
    };
    if (o.obj["playlist"]) {
        this.setVariable("playlist", this._URLEncode(o.obj["playlist"]))
    };
    if (o.obj["config_plugin_fmtjLiveStats_pageType"]) {
        this.setVariable("config_plugin_fmtjLiveStats_pageType", o.obj["config_plugin_fmtjLiveStats_pageType"])
    };
    this.setVariable("embedReferer", document.referrer);
    if (o.obj["config_plugin_fmtjLiveStats_edition"]) {
        this.setVariable("config_plugin_fmtjLiveStats_edition", o.obj["config_plugin_fmtjLiveStats_edition"])
    };
    if (o.obj["fmtjDocURI"]) {
        this.setVariable("embedPageUrl", o.obj["fmtjDocURI"])
    };
    var domId = this.domId;
    var flashVars = this._hashToQueryUrl(this._variables);
    var flashArgs = this._mergeHashes(this._params, this._attributes);
    flashArgs['flashvars'] = flashVars;
    var flashEmpObject = newsi.html.flash.getObjEmbString(flashArgs);
    document.getElementById(o.obj["domId"]).innerHTML = flashEmpObject;
}
bbc.emp_fmtj.prototype.setDomId = function(value){
    this.domId = value;
}
bbc.emp_fmtj.prototype.setAttribute = function(key, value){
    this._addAttribute(key, value);
}
bbc.emp_fmtj.prototype.setParam = function(key, value){
    this._addParam(key, value);
}
bbc.emp_fmtj.prototype.setVariable = function(key, value){
    this._addVariable(key, value);
}
bbc.emp_fmtj.prototype.getEmpEmbeddedParams = function(id){
    if (this._attachedToOnLoadStack == false) {
        this._attachToOnLoadStack();
        this._attachedToOnLoadStack = true;
    }
    var parentId = document.getElementById(id);
    var objectTags = parentId.getElementsByTagName('param');
    var empParamsObj = {};
    empParamsObj["domId"] = id
    for (j = 0; j < objectTags.length; j++) {
        switch (objectTags[j].nodeType) {
            case 1:
                empParamsObj[objectTags[j].name] = objectTags[j].value;
        }
    }
    if (this._isSupportedVersion == false) {
        this._renderNoFlashContent(empParamsObj);
        return false;
    }
    else {
        this._empPlayersArray.push(empParamsObj)
    }
}
bbc.emp_fmtj.prototype._checkFlashVersion = function(){
    if (this._flashVersion < this._targetFlashVersion) {
        return false;
    }
    else {
        return true;
    }
}
bbc.emp_fmtj.prototype._renderNoFlashContent = function(paramObj){
	var warningHTML = this._propertiesObj.warningHTML;
    if (!paramObj.holding) {
        var parentTag = document.getElementById(paramObj.domId);
		parentTag.innerHTML = '<div class="audioImage"></div>' + warningHTML;    }
    else {
        var holdingImageSrc = paramObj.holding;
        var holdingImageTag = document.createElement("img");
        holdingImageTag.setAttribute("src", holdingImageSrc);
        holdingImageTag.setAttribute("width", paramObj.width);
        holdingImageTag.setAttribute("height", paramObj.height);
        holdingImageTag.setAttribute("class", "holding");
        var parentTag = document.getElementById(paramObj.domId);
		parentTag.innerHTML = warningHTML;
		parentTag.firstChild.parentNode.insertBefore(holdingImageTag, parentTag.firstChild)
    }
}
bbc.emp_fmtj.prototype._addParam = function(key, value){
    this._params[key] = value;
}
bbc.emp_fmtj.prototype._addVariable = function(key, value){
    this._variables[key] = value;
}
bbc.emp_fmtj.prototype._getVariable = function(key){
    return this._variables[key];
}
bbc.emp_fmtj.prototype._addAttribute = function(key, value){
    this._attributes[key] = value;
}
bbc.emp_fmtj.prototype._hashToQueryUrl = function(hash){
    var query = "";
    var last = hash.length;
    var current = 1;
    for (var key in hash) {
        query += key + "=" + hash[key];
        if (current != last) {
            query += "&";
        }
        current++;
    }
    return query;
}
bbc.emp_fmtj.prototype._mergeHashes = function(hash, otherHash){
    for (var key in otherHash) {
        hash[key] = otherHash[key];
    }
    return hash;
}
bbc.emp_fmtj.prototype._URLEncode = function(clearString){
    var output = '';
    var x = 0;
    clearString = clearString.toString();
    var regex = /(^[a-zA-Z0-9_.]*)/;
    while (x < clearString.length) {
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != '') {
            output += match[1];
            x += match[1].length;
        }
        else {
            if (clearString[x] == ' ') {
                output += '+';
            }
            else {
                var charCode = clearString.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
            }
            x++;
        }
    }
    return output;
}
bbc.emp_fmtj.prototype._padHeightForToolbar = function(oldHeight){
    var newHeight = parseInt(oldHeight);
    newHeight = newHeight + 35;
    return newHeight;
}
bbc.emp_fmtj.prototype._attachToOnLoadStack = function(){
    if (window.attachEvent) {
        window.attachEvent("onload", function(e){
            emp_load.setEmpGlobalVariables();
        });
    }
    else 
        if (window.addEventListener) {
            window.addEventListener("load", function(e){
                emp_load.setEmpGlobalVariables();
            }, false);
        }
}

/**
 * Creates the callout methods needed for the emp when it goes into detach mode
 * @param {Object} theParams - name value pairs of the configsettings that need to be 
 * reused by the popout player
 * @param {Object} theHeight
 * @param {Object} theWidth
 */
var embeddedMedia = { console: function(){
	var that = this;
	var thatParams;
	that.notifyParent=null;
	that.theLssrc=null;
	that.popoutVideo = function( theParams, theHeight, theWidth, theMode ){
			thatParams=theParams;
			var popVidHeight=323;
			var popVidWidth=512;
			if(that.theLssrc==null){
				var hasLs = document.getElementById("livestats");
				if(hasLs != undefined){
					that.theLssrc=hasLs.getAttribute('src');
				}
			}
			if (!that.notifyParent) {
				that.notifyParent = function(theWin){
					theWin.updatePlayer(thatParams, popVidWidth, popVidHeight, theMode, that.theLssrc);
				}
			}
			var obj = {name: "emppop", url: "http://news.bbc.co.uk/player/emp/pop.stm", height: Number(popVidHeight) + 77 + 4, width:Number(popVidWidth), scrollbars:"no", resizable:"no", toolbar:"no" };
			var newWin = newsi.window.popup(obj);
			if (window.focus) {
					newWin.focus()
			}
		}
		return that;
    }()
};






