/**
 * Common JavaScript functions for
 *
 * CPLIB - CorePublish
 */

// variable declarations
var cp2_loaded = false;
var cp2_keywordlayer;
var x;
var y;


/* ========================= Common functions ============================== */

/**
 * 	Function to init
 */
function cp2_init() {
	// Mouse position capture
	ns4 = document.layers?true:false;
	ns5 = (document.getElementById && !document.all)?true:false;
	ie5 = document.all?true:false;
	ie4 = (!document.getElementById && document.all)?true:false;

	if(ns4) {
        document.captureEvents(Event.MOUSEMOVE);
    }

	document.onmousemove=catchXY;

	// Tell that document is loaded.
	cp2_loaded = true;
}

// Calling the init function.
window.onload = cp2_init;
document.onclick = cp2_keywords_hide;

var cpNavigatorUserAgent = navigator.userAgent.toLowerCase() ;
var cpNavigatorUserAgentInfo = {
    isIE     : (cpNavigatorUserAgent.indexOf('msie')>-1),
    isIE7    : (cpNavigatorUserAgent.indexOf('msie 7')>-1),
    isGecko  : (cpNavigatorUserAgent.indexOf('gecko/')>-1),
    isSafari : (cpNavigatorUserAgent.indexOf('safari')>-1),
    isOpera  : (cpNavigatorUserAgent.indexOf('opera')>-1),
    isMac    : (cpNavigatorUserAgent.indexOf('macintosh')>-1)
};

/**
 *  Function that reads a cookies value. Returns null if the requested cookie is not found
 */
function cpReadCookie(cookieName){
    cookieName += '=';
    var cookies = document.cookie.split(';');
    for (var i=0; i<cookies.length; i++){
        var cookie = cookies[i];
        while (cookie.charAt(0)==' ') cookie = cookie.substr(1);
        if (cookie.indexOf(cookieName) == 0) return cookie.substr(cookieName.length);
    }
    return null;
}

/**
 *	This is a function to catch the x and y coordinates of the mouse
 */
function catchXY(e) {
   // capture click coordinates
   x=(ns4 || ns5)?e.pageX:event.x+document.body.scrollLeft;
   y=(ns4 || ns5)?e.pageY:event.y+document.body.scrollTop;
}


/**
 *  Function to easy open an window
 */
function ct_win(win_url,height,width, props) {
	win_name = "ct_win";
    if (props &&  props.length > 1 ) {
        win_props = props ;
    } else {
        win_props ="height="+height+",width="+width+",screenX=400,screenY=100";
    }

	// TODO: added return from corepublish.js to window.open, check that this does not break anything
	return window.open(win_url,win_name,win_props);
}


/**
 *  Function that returns the position for the given element.
 */
function getAbsoluteElementPosition(el){
    var origEl = el;
    for(var lx=0,ly=0;el!=null;
        lx+=el.offsetLeft-((el.offsetParent && el.offsetParent.offsetParent)?el.offsetParent.scrollLeft:0),
        ly+=el.offsetTop-((el.offsetParent && el.offsetParent.offsetParent)?el.offsetParent.scrollTop:0),
        el=el.offsetParent); // end: for
    el = origEl;
    if(el && !document.all) {
        do {
            if(el.parentNode && !(el.parentNode.tagName && el.parentNode.tagName.toUpperCase()=='BODY')) {
                if (el.parentNode.scrollTop) {
                    ly -= el.parentNode.scrollTop;
                }
                if (el.parentNode.scrollLeft) {
                    lx -= el.parentNode.scrollLeft;
                }
            }
        } while (el = el.parentNode);
    }
    return {x:lx,y:ly}
}

/**
 * Scroll container to display the element.
 */
function scrollToElement(container, element) {
    container = getElement(container);
    element = findSubElement(container, element);
    
    // If element is null the provided element is not a child of the
    // scrollElement. Since we cannot scroll to a noexisting element we simply
    // return
    if(element == null) {
        return;
    }
    
    var offsetTop = 0;
    el = element;
    do {
        offsetTop += el.offsetTop;
        el = el.offsetParent;
    } while(el && findSubElement(el, container) == null);
    
    container.scrollTop = offsetTop - container.offsetTop;
}

/**
 * Find a spesific element below a containing parent. Both elements can be
 * either a full element object or a element id. The function returns false
 * if the element is not found as an ancestor to the container.
 */
function findSubElement(container, element) {
    container = getElement(container);
    element = getElement(element);
    
    var children = container.childNodes;
    for(var i=0; i<children.length; i++) {
        if(children[i] == element) {
            return element;
        } else {
            var foundElement = findSubElement(children[i], element);
            if(foundElement != null) {
                return foundElement;
            }
        }
    }
    
    return null;
}

/**
 * Get an element by element id. The function argument can be both a element
 * object or an element id. In both cases the element object is returned.
 */ 
function getElement(element) {
    if(typeof element == 'object') {
        return element;
    } else {
        var newElement = document.getElementById(element);
        if(typeof newElement == 'object') {
            return newElement;
        } else {
            return null;
        }
    }
}

/* ===================== Event handling functions ========================== */

function CpAddEvent(elm, evType, fn, useCapture) {
    if(elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    }
    else if(elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    }
    else {
        elm['on' + evType] = fn;
    }
}

function CpRemoveEvent(elm, evType, fn, useCapture) {
    if(elm.removeEventListener) {
        elm.removeEventListener(evType, fn, useCapture);
        return true;
    }
    else if(elm.detachEvent) {
        var r = elm.detachEvent('on' + evType, fn);
        return r;
    }
    else {
        elm['on' + evType] = null;
    }
}

/* ==================== Image and preload functions ======================== */

function ct_image(img) {
    if(!cp2_loaded) {
        return false;
    }

    a=new Image();
    a.src=img;
    return a;
}

function ct_swap(docname,swapimage) {
	if(!cp2_loaded) {
		return;
    }
	document[docname].src = swapimage.src ;
}

/* ================= Functions used by article elements ==================== */

/**
 *  Function used to print flash and movies inline
 *  Done this way to avoid the EOLAS patent
 */
function cpWriteActiveX(activeXstring){
    document.write(activeXstring);
}

/**
 *  Function used to print flash and movies inline
 *
 *  *) These settings might not work in all browser plugins
 *
 *  @src         string The full URL to the video
 *  @sessionName string The session name where users sessionid is stored (used for IE)
 *  @width       int The width
 *  @height      int The height
 *  @mimetype    string The files mimetype
 *  @loop        boolean Whether or not to loop the video *
 *  @autoplay    boolean Whether or not to start the video when it's loaded *
 *  @controller  boolean Whether or not to include plugin controllers *
 */
function cpWriteMediaObject(src, sessionName, width, height, mimeType, loop, autoplay, controller, objId, flashVars, skipIEWindowOnLoad) {
    var objectSettings = '';
    
    if(typeof skipIEWindowOnLoad == 'undefied' && skipIEWindowOnLoad != true) {
        skipIEWindowOnLoad = false;
    }
    
    // Detect protocol for codebase
    var codebaseProtocol = (src.substr(0,5)=='https'?'https':'http');

    // Check if this is a flash movie
    var isFlashMovie = new Object();
    isFlashMovie['video/x-flv'] = true;
    isFlashMovie['application/x-flash-video'] = true;
    isFlashMovie['video/flv'] = true;
    if (isFlashMovie[mimeType] != null){
        var displayheight = null;
        // set to same as height for floating controls
        if(typeof flashVars != 'undefined' && typeof flashVars['floatingcontrols'] != 'undefined' && flashVars['floatingcontrols'] == 'true') {
	        var displayheight = height;
        }
        
	    var flashVars = new Object();
	    flashVars["file"] = encodeURIComponent(src);
	    flashVars["width"] = width;
	    flashVars["height"] = height;
	    
	    if(displayheight != null) {
	        flashVars['displayheight'] = height;
	    }
	    
	    flashVars["overstrech"] = 'true';
	    flashVars["frontcolor"] = '0xFFFFFF';
	    flashVars["backcolor"] = '0x000000';
	    flashVars["lightcolor"] = '0xFFFFFF';
	    flashVars["autostart"] = autoplay?'true':'false';
	    flashVars["repeat"] = loop?'true':'false';
        flashVars["usefullscreen"] = 'true';

        // Add flash movie parameters
        objectSettings += '<param name="allowscriptaccess" value="always" />';
        objectSettings += '<param name="allowfullscreen" value="true" />';
        objectSettings += '<param name="flashvars" value="' + getQueryParamsFromObject(flashVars) + '" />';

        mimeType = 'application/x-shockwave-flash';
        src = CPLIBHTMLROOT +'/mediaplayer.swf';
    }

    // Handling IE specialties
    var rewriteMimeType = new Object();
    if (cpNavigatorUserAgentInfo.isIE){
        rewriteMimeType['audio/mpeg'] = 'application/x-mplayer2';
        rewriteMimeType['video/mpeg'] = 'application/x-mplayer2';
        rewriteMimeType['video/x-msvideo'] = 'video/x-ms-wmv';
    }
    // In some cases we must change the mimetype for IE :/
    if (rewriteMimeType[mimeType] != null){
        mimeType = rewriteMimeType[mimeType];
    }

    // Add object parameters
    if (mimeType != 'application/x-shockwave-flash') {
        objectSettings += '<param name="loop" value="' +(loop?'true':'false') +'" />';
        objectSettings += '<param name="autostart" value="' +(autoplay?'true':'false') +'" />';
        objectSettings += '<param name="controller" value="' +(controller?'true':'false') +'" />';
    } else {
        objectSettings += '<param name="wmode" value="opaque" />';
        if(typeof flashVars != "undefined") {
            objectSettings += '<param name="flashVars" value="' + getQueryParamsFromObject(flashVars) + '" />';
        }
    }

    // IE: We need to add sessionid to the URL in order for the video plugin to use the same session
    //     as IE. If sessionid is not sent, the video plugin will try to load the URL without a valid
    //     session causing the session to be destoyed.
    //     -----------------------------
    //     NOTE from Kurt: The session id broke together with the new JW FLV player. I first tried removing
    //     this alltogether, and it seem to work, event with user protected files. I can't get it
    //     to break whatever I do. To be sure not to reintroduce old bugs, I move this session stuff
    //     down here. This way it will be added for the non JW FLV players.
    if (cpNavigatorUserAgentInfo.isIE){
        var sep = (src.indexOf('?') > -1?'&':'?');
        var sessionID = cpReadCookie(sessionName);
        if (sessionID != null && sessionID.length > 0){
            var src = src +sep +sessionName +'=' +sessionID;
        }
    }

	// Build object tag and content
    var objectString = '';
    var objectStringStart = '<object type="' +mimeType +'" data="' +src +'" width="' +width +'" height="' +height +'">';
    var objectStringName = '<param name="movie" value="' +src +'" />';
    var objectStringFallback = '<p>(No plugin detected for your OS/browser)</p>';
    var objectStringEnd = '</object>';
    switch (mimeType) {
        case 'application/x-shockwave-flash':
            if (cpNavigatorUserAgentInfo.isIE){
                var objectStringStart = '<object codebase="'+codebaseProtocol+'://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' +width +'" height="' +height +'">';
            }
            break;
        case 'application/x-mplayer2':
        case 'video/x-ms-wmv':
        case 'video/x-msvideo':
    		// WMV, MPEG
            objectStringName = '<param name="src" value="' +src +'" />';
    		break;

    	case 'video/quicktime':
    	    // Quicktime in IE
    	    if (cpNavigatorUserAgentInfo.isIE){
    	        objectStringStart = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="'+codebaseProtocol+'://www.apple.com/qtactivex/qtplugin.cab" width="' +width +'" height="' +height +'">';
                objectStringName  = '<param name="src" value="' +src +'" />';
                break;
    	    }
    	    break;

    	case 'video/x-ms-asf':
    	    // ASF in IE
    	    if (cpNavigatorUserAgentInfo.isIE){
                objectStringName = '<param name="FileName" value="' +src +'" />';
                break;
    	    }
    	    break;

    	default:
    		break;
    }

    objectString += objectStringStart;
    objectString += objectStringName;
    objectString += objectSettings;
    objectString += objectStringFallback;
    objectString += objectStringEnd;
    
    // If no objId is provided, the object is written directly to the document
    // at the current rendering position
    if(objId == null || objId == false) {
        document.write(objectString);
    } else {
        try {
        	// When altering the DOM while the DOM is still loading, Internet
        	// Explorer will sometimes trigger the DOM Ready event to early. This
        	// can cause the infamous Operation Aborted error. We prevent this by
        	// delaying the innerHTML assigning until the DOM is fully loaded.
        	if(cpNavigatorUserAgentInfo.isIE && !skipIEWindowOnLoad) {
    	    	CpAddEvent(window, 'load', function() {
    	    		document.getElementById(objId).innerHTML = objectString;
    	    	});
        	} else {
        		document.getElementById(objId).innerHTML = objectString;
        	}
        } catch(e){
    		document.write(objectString);
        }
    }
}

/**
 *  Whenever possible use prototype.js Object.toQueryString(object) instead.
 *  This function is used in cpWriteMediaObject to ensure backward compatibility
 *  with old sites that do not use prototype.js
 *
 *  Returns a query string (useful as flashvars) from a object and its
 *  attributes.
 *
 *  Example:
 *
 *  obj = new Object();
 *  obj["file"] = "testfile";
 *  obj["showControls"] = "true";
 *
 *  getQueryParamsFromObjectAttributes(obj) ==>
 *  file=testfile&showControls=true
 *
 *  @deprecated Use prototype.js Object.toQueryString(object) instead
 */
function getQueryParamsFromObject(object) {
    var query = "";
    for(var attr in object) {
        if(query.length > 0) {
            query += "&";
        }
        query += attr +"=" + encodeURIComponent(object[attr]);
    }
    return query;
}

/**
 *  Slideshow function, used to navigate back and forward in a slideshow element.
 */
function slideshow(thearray, imgname, pos, what, theform){
	if(!cp2_loaded) {
		return;
    }

	i=eval("slidepos"+pos);
	count=eval("count"+pos);

	// Show next picture
	if(what=="next" && thearray[i+1]) {
		// Load image before we display it, then swap
		temp = ct_image(thearray[i+1]);
		document[imgname].src = temp.src;
		eval("slidepos"+pos+"++"); // increase counter
		theform.slidetext.value = (i+2)+ " av "+ count; // Set status text
    }

	// Show previous picture
	if(what=="previous" && i>0 && thearray[i-1]) {
		temp = ct_image(thearray[i-1]);
		document[imgname].src = temp.src;
		eval("slidepos"+pos+"--");
		theform.slidetext.value = (i)+ " av "+ count;
    }
}

/**
 *  Function to display keywords in a litle popup box.
 */
function cp2_keywords(keyword_id) {
	cp2_keywordlayer.moveTo(x,y);
	cp2_keywordlayer.setSource("keywords_popup.php?id="+keyword_id,160,160);
	cp2_keywordlayer.show();
}

function cp2_keywords_hide() {
	if(!cp2_loaded) {
	   return;
    }

	try {
		if(typeof cp2_keywordlayer != "undefined" && cp2_keywordlayer.isVisible()) {
			cp2_keywordlayer.hide();
		}
	} catch (e) {
		// no-op
	}
}


/* ======================== Tile system function =========================== */

var cplibTileLoaderXMLHttpObjectArray = new Object();

if(typeof htmlroot != "undefined") {
    var cplibXmlHttpUrl = htmlroot + "xmlhttprequest.php";
} else {
    // htmlroot not available, assuming root
    var cplibXmlHttpUrl = "/xmlhttprequest.php";
}

function cplibRenderAjaxTile(categoryTemplateId, categorytemplateTileId, placeholdername, categoryId, articleId,  callbackFunction) {

    cplibTileLoaderXMLHttpObjectArray[categorytemplateTileId] = new CtXMLHttpRequest();
    var xmlHttp = cplibTileLoaderXMLHttpObjectArray[categorytemplateTileId];

    // create the xmlhttprequest object

    xmlHttp.SetOnreadystatechange(
        function () {
            if (xmlHttp.getReadyState() == 4) {
	            try {
	                document.getElementById("cplibajaxtilecontainer-" + categorytemplateTileId + "-loading").style.display ="none";
	                document.getElementById("cplibajaxtilecontainer-" + categorytemplateTileId).style.display ="block";
	                document.getElementById("cplibajaxtilecontainer-" + categorytemplateTileId).innerHTML = xmlHttp.getResponseText();

	                // call the callback function
	                if (typeof callbackFunction != "undefined" && callbackFunction != null) {
	                   callbackFunction.call(categorytemplateTileId, placeholdername);
	                }

	            } catch (e) {
	                // alert("noe gikk galt:" + e);

	            }
            }

         });

    var parameters = new Object();
    parameters['categorytemplatetileID']    = categorytemplateTileId;
    parameters['categorytemplateID']        = categoryTemplateId;
    parameters['categoryID']                = categoryId;
    parameters['articleID']                 = articleId;
    parameters['placeholdername']           = placeholdername;

    // Add all existing get parameters so that tiles expecting get parameters are still working
    // get all url parameters into a key=>value array
    if (location.search.length > 0) {
	    var tmp = location.search.substring(1).split("&");
	    for (var key=0; key < tmp.length; key++) { // var key in tmp) {
	        var split = tmp[key].split("=");
	        parameters[split[0]] = split[1];
	    }
     }

    xmlHttp.openCorePublishService(cplibXmlHttpUrl ,'categorytemplate.renderajaxtile' , 'html', parameters );
}


/* ======================== Statistics function =========================== */
function cpRegisterStatistics(){ 
	
	now = new Date();
	
	if(typeof window.cpstatDomain == "undefined") {
		window.cpstatDomain = "/";
	}
	
	// get page specific data which is printed on the page 
	var info = eval(window.cpstatInfo);
	
	/* 
 	- s => screen.width+"x"+screen.height;
    - c => color depth
    - r => render time in ms
    - f => flash version 
    - e => referer
    - a => current url
    - t => document title
	*/
	
	// append other information we can find through javascript
	info['s'] 	= +screen.width+"x"+screen.height;
	info['c'] 	= +screen.colorDepth;
	info['r'] 	= now.getMilliseconds() - CPLIBSTARTTIME.getMilliseconds();
	info['f']= AFPGetSwfVer();
	info['e'] 	= escape(cpStatisticsGetReferer());
	info['a'] 	= escape(document.location.href);
	info['t'] 	= escape(document.title);
	
	// find or create tracking cookie and the trackingID 
	info['w']		= cpStatisticsGetTrackingId();
	
	str = "";
	for (var k in info) { 
		str += k + ":" + info[k] + "\n";
	}
	
	// start to generate url 
	url = window.cpstatDomain + "/regstat.php?reg=1";
	for (var key in info) { 
		url += "&"+key +"="+info[key];
	}

	// alert(url);
	
	img =  new Image(1,1);
	img.src = url;

	// info['useragent'] = +screen.width+"x"+screen.height;

}

function cpRegisterStatisticsArrayToUrl(arr, name){
	
}


function cpStatisticsGetReferer() { 
	try{
		if (top.document.referrer){
			return top.document.referrer;
		} else{
			return document.referrer;
		}		
	}
	catch(e){
		return document.referrer;
	}
}

function cpStatisticsGetTrackingId() {
	id = cpGetCookieVal("__ctsid");
	
	if (id == null || id.length < 1) { 
		
		
		// generate new tracking id.
		id = cpgenTrackingId();
		//console.log("no id found, generating new:" + id);
		cpSetCookieVal("__ctsid", id, 365*5);
	}
	
	//console.log("found tracking id is" + id);
	
	return id; 
	
	// value =cpGetCookieVal("CorePublishSession_sitebase_arve_x2_intra_coretrek_com");
	// alert(value);
	
}

function cpGetCookieVal(cookiename) { 
	var entries = document.cookie.split(";");
	cookies = new Object();
	for (i=0; i< entries.length; i++) { 
		cookieInfo = entries[i].split("=");
		cName =  cookieInfo[0].replace(" ", "");
		//console.log("fetching cookie [" + cookieInfo[0] + "] having value ["+ cookieInfo[1] +"]");
		if (cName == cookiename) {
			//console.log("found matching cookie " + cookiename);
			return cookieInfo[1];
		}
	}
	 
	// console.log("did not find any cookie");
	return null; 
}
	
function cpSetCookieVal(name,value,days) {
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	var domain  = "; domain=" + cpstatDomain;

	document.cookie = name+"="+value+expires+domain+"; path=/";
}

function cpgenTrackingId() {
	var id = new Date().getTime().toString() + ".";
	for (x=0; x< 3;x++) { 
		id += Math.floor(Math.random()*100+1);
	}
	return id; 

}

// FLASH version detection

var AFPisIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var AFPisWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var AFPisOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function AFPControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	if (version != -1) {
	    version = version.substr(4);
	    version = version.replace(",",".").replace(",",".").replace(",",".").replace(",",".");
	}

	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function AFPGetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( AFPisIE && AFPisWin && !AFPisOpera ) {
		flashVer = AFPControlVersion();
	}	
	return flashVer;
}

