// Do not copy and paste the script to your document.
// It needs to be included as an external script!
// Please include this script in the <head> section of your (X)HTML document only!
//
// Version: 1.8.6

// --- USAGE ---
// writeFlashCode(flash_movie, fallback_image, flash_parameters);
// flash_movie      - URL to Flash Movie
// fallback_image   - URL to Fallback Image
// flash_parameters - Flash Parameters, e.g. width=775;height=600;version=6,0,65,0

// --- CUSTOMIZABLE PARAMETERS ---
var fsiPresetFlashVersion='6,0,65,0';   // Default value for required Flash version
var fsiImageFallbackLinked=true;        // Add a link to Flash Player download location to the fallback image
var fsiTextFallbackActive=true;         // Activate text fallback?
var fsiTextFallbackText='Flash Player Required.\nWould you like to download the latest version of Flash Player now?';
var fsiTextTouchDevice='Tap for mobile edition';
var flashFallbackImage='';

//
// EDITING THE LINES BELOW IS NOT RECOMMENDED
//

function flashDetector(presetFlashVersion, imageFallbackLinked, textFallbackActive, textFallbackText){

	this.flashVersion = 0;
	var flashDownload;
	var flashDownloadCab;

	var isFPMCompatible = false;

	var registeredLoadMethods = new Array();
	var monitorID = 0;

	this.init = function(){

		var scheme;
		if (window.location && window.location.protocol.indexOf('https') > -1) scheme='https://';
		else scheme='http://';
		flashDownload = scheme+'www.adobe.com/go/getflashplayer';
		flashDownloadCab = scheme+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab';
		var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
		var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
		var isOpera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1) ? true : false;

		if (isIE && isWin && !isOpera) {
			try {
				var axTester = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
				var axVersionFull = axTester.GetVariable("$version");
				if (axVersionFull){
					var regVersion = axVersionFull.match(/(\d+),\d+,\d+,\d+/);
					if (regVersion && regVersion[1]){
						this.flashVersion = parseInt(regVersion[1]);
					}
				}
			}
			catch (e){}
		}
		else {
			var napl;
			if (navigator.plugins) napl = navigator.plugins;
			else napl = false;
			if (napl && napl.length > 0 && (napl["Shockwave Flash 2.0"] || napl["Shockwave Flash"])) {
				var flashDesc = napl["Shockwave Flash" + (napl["Shockwave Flash 2.0"] ? " 2.0" : "")].description;
				this.flashVersion = parseInt(flashDesc.split(" ")[2].split(".")[0]);
			}
		}
		// Scan Win/IE Old
		if (this.flashVersion == 0 && isIE && isWin && !isOpera) {
			pushVBDetection();
		}

		// Register new onload handler
		if (window.addEventListener){
			window.addEventListener("load", function(){
				onloadHandler();
			}, false);
		}
		else if (document.attachEvent){
			window.attachEvent('onload', function(){
				onloadHandler();
			});
		}

	};

	var onloadHandler = function(){
		for (var fMethod in registeredLoadMethods){
			if (registeredLoadMethods[fMethod] && registeredLoadMethods[fMethod].method) {
				registeredLoadMethods[fMethod].method.call(this, registeredLoadMethods[fMethod].param);
			}
		}
	};

	var touchDeviceDetection = function(allowIOS, allowAndroid, allowHTC){

		var result = new Object();

		var isIOS = false;
		var isAndroid = false;
		var isHTC = false;

		if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
			isIOS = true;
			result.os = "iOS";
		}
		else if ((navigator.userAgent.indexOf('Android') != -1)){
			isAndroid = true;
			result.os = "Android";
			if (navigator.userAgent.match(/[\W]HTC_/)){
				isHTC = true;
			}
		}
		else if ((navigator.platform && navigator.vendor && navigator.platform.indexOf('armv') != -1 && navigator.vendor.indexOf('Google') != -1)){
			isAndroid = true;
			result.os = "Android";
			if (navigator.userAgent.match(/[\W]HTC_/)){
				isHTC = true;
			}
		}

		if (isIOS){
			if (allowIOS) result.pass = true;
			else result.pass = false;
		}
		else if (isAndroid){
			if (allowAndroid){
				if (isHTC && allowHTC) result.pass = true;
				else if (isHTC) result.pass = false;
				else result.pass = true;
			}
			else result.pass = false;
		}

		return result;
	};

	this.writeFlashCode = function (fsiurl, fallbackimg, parameters){

		var objcode='<object type="application/x-shockwave-flash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+flashDownloadCab;
		var emdcode='<embed type="application/x-shockwave-flash" pluginspage="'+flashDownload+'"';

		var params = new Object();
		if (parameters){
			var parameters = parameters.split(";");
			for (var c=0; c < parameters.length; c++){
				var parameter=parameters[c].split("=");
				if (parameter[1]) params[parameter[0].toLowerCase()]=parameter[1];
				else if (parameter!="") alert("Wrong parameter: " + parameter);
			}
		}

		var mobileViewer = false;
		var mobileViewerBase = null;
		var mobileViewerQuery = null;
		var fpmOS = "unknown";

		if (params["mobilesupport"] != undefined && params["mobilesupport"] == "true") {

			var iOS = true;
			var android = true;
			var htcSupport = false;
			var hasMobilePopUpSupport = true;

			if (params["mobileiossupport"] != undefined) {
				if (params["mobileiossupport"] == "true"){
					iOS = true;
				}
				else {
					iOS = false;
				}
				params["mobileiossupport"]='';
			}

			if (params["mobileandroidsupport"] != undefined) {
				if (params["mobileandroidsupport"] == "true"){
					android = true;
				}
				else {
					android = false;
				}
				params["mobileandroidsupport"]='';
			}

			if (params["mobilehtcsupport"] != undefined) {
				if (params["mobilehtcsupport"] == "true"){
					htcSupport = true;
				}
				else {
					htcSupport = false;
				}
				params["mobilehtcsupport"]='';
			}

			if (params["mobilepopupautomode"] != undefined){
				if (params["mobilepopupautomode"] == "true"){
					hasMobilePopUpSupport = true;
				}
				else {
					hasMobilePopUpSupport = false;
				}
				params["mobilepopupautomode"]='';
			}

			try {
				if (!window.opener || (window.opener && window.opener.document && window.opener.document.location == document.location)){
					hasMobilePopUpSupport = false;
				}
			}
			catch (ex){
				hasMobilePopUpSupport = false;
			}

			if (params["mobiletouchtext"] != undefined) {
				fsiTextTouchDevice = decodeURIComponent(params["mobiletouchtext"]);
			}

			var touchResult = touchDeviceDetection(iOS, android, htcSupport);
			var fpmSupport = touchResult.pass;
			fpmOS = touchResult.os;

			params["mobilesupport"]='';

			if (fpmSupport){
				if (fsiurl.match(/pages_dir=/i) || params["mobileforcepages"]){
					var uriParts = new RegExp("^(http?.+)fsi\.swf[?&]+(.+)").exec(fsiurl);
					if (uriParts && uriParts[1] && uriParts[2]){
						mobileViewerBase = uriParts[1]+"applications/pagesmobile/";
						mobileViewerQuery = "pages_DeferLinksToOpener=1&"+uriParts[2];
						mobileViewer = true;
					}
				}
			}

			if (params["mobileforcepages"]) params["mobileforcepages"]='';
		}

		var useVersion;
		if (params["version"]) {
			useVersion=decodeURI(params["version"]);
			params["version"]='';
		}
		else useVersion=presetFlashVersion;
		objcode+='#version='+useVersion+'"';

		if (!params["quality"]) {
			params["quality"]='High';
		}

		if (!params["allowscriptaccess"]) {
			params["allowscriptaccess"]='always';
		}
		if (!params["allowfullscreen"]) {
			params["allowfullscreen"]='true';
		}
		if (!params["fullscreenonselection"]) {
			params["fullscreenonselection"]='true';
		}

		var widthVal, heightVal;
		var widthRel = false;
		var heightRel = false;
		if (params["width"]) {
			code=' width="'+params["width"]+'"';
			objcode+=code;
			emdcode+=code;
			widthVal=params["width"];
			if (widthVal.match(/\d+%/)){
				widthRel = true;
			}
			params["width"]='';
		}
		if (params["height"]) {
			code=' height="'+params["height"]+'"';
			objcode+=code;
			emdcode+=code;
			heightVal=params["height"];
			if (heightVal.match(/\d+%/)){
				heightRel = true;
			}
			params["height"]='';
		}

		var majorversion = useVersion.split(",")[0];

		if (mobileViewer == false && this.flashVersion >= majorversion){
			var code;
			if (params["id"] || params["name"]) {
				objcode+=' id="'+params["id"]+'"';
				if (params["name"]) emdcode+=' name="'+params["name"]+'"';
				else emdcode+=' name="'+params["id"]+'"';
				params["id"]='';
				params["name"]='';
			}
			objcode+='>\n';

			var fsiPassThrough = searchFSIPassThrough();
			if (fsiPassThrough){
				fsiurl += fsiPassThrough;
			}

			fsiurl = xmlUnescape(fsiurl);

			params["src"]=xmlEscape(encodeURI(fsiurl));
			params["movie"]=xmlEscape(encodeURI(fsiurl));

			for (var pkey in params){
				if (params[pkey]){
					if (pkey != 'src') objcode+='<param name="'+pkey+'" value="'+decodeURI(params[pkey])+'"\/>\n';
					if (pkey != 'movie') emdcode+=' '+pkey+'="'+decodeURI(params[pkey])+'"';
				}
			}
			emdcode+='\/>';

			objcode+=emdcode+'\n';
			objcode+='<\/object>';
		}
		else if (mobileViewer == false && fallbackimg){
			objcode='<img src="'+xmlEscape(fallbackimg)+'" border=0 />';
			if (imageFallbackLinked) objcode='<a href="'+flashDownload+'" target="_blank">'+objcode+'</a>';
			objcode='<p align="center">'+objcode+'</p>';
		}
		else if (mobileViewer){
			if (hasMobilePopUpSupport){
				this.openWinInjector(true, fpmOS, mobileViewerBase, mobileViewerQuery);
			}
			else {
				var scripts = document.getElementsByTagName('script');
				var thisScriptTag = scripts[scripts.length-1];

				var newLoadFunction = function(parms){

					var scriptTag = parms[0];
					var monitorID = parms[1];
					var sizeDim = parms[2];
					var urlBase = parms[3];
					var urlQuery = parms[4];
					var os = parms[5];

					var thisScriptTag = document.getElementById('_fsiMon_'+monitorID);

					var pDim = sizeDim;
					if (sizeDim.widthRel || sizeDim.heightRel){
						var parentDim = calculateDim(thisScriptTag);
						if (sizeDim.widthRel){
							sizeDim.width = parentDim.width;
						}
						if (sizeDim.heightRel){
							sizeDim.height = parentDim.height;
						}
					}

					var fbImg = reorgFallbackImage(fallbackimg, pDim);

					objcode='<table cellpadding="0" onclick="fsiFD.openWinInjector(false, \''+os+'\',\''+xmlEscape(urlBase)+'\',\''+xmlEscape(urlQuery)+'\')" style="border:0px;border-collapse:collapse;border-spacing:0px;margin:auto;padding:0px;';
					if (params["bgcolor"]){
						objcode+='background-color:#'+params["bgcolor"]+';';
					}
					objcode+='width:'+pDim.width+'px;height:'+pDim.height+'px"><tr><td>';
					objcode+='<div style="position:relative;top:0;width:'+pDim.width+'px;height:'+pDim.height+'px;text-align:center;padding:0px;vertical-align:middle;line-height:'+pDim.height+'px">';
					objcode+='<img src="'+xmlEscape(fbImg)+'" style="position:absolute;top:0;bottom:0;left:0;right:0;margin:auto;" />';
					objcode+='<span style="top:0px;bottom:0px;min-height:10%;max-height:50px;padding:10px;vertical-align:middle;z-index:5;background-color:#dddddd;-webkit-border-radius:25px;opacity:0.75;-webkit-box-shadow:0px 2px 3px #000;color:#444444;font-size:15px;font-family:sans-serif;font-weight:bold;">';
					objcode+=fsiTextTouchDevice;
					objcode+='</span>';
					objcode+='</div>';
					objcode+='</td></tr></table>';

					thisScriptTag.innerHTML = objcode;
				};

				var sizeDim = new Object();
				sizeDim.width = widthVal;
				sizeDim.widthRel = widthRel;
				sizeDim.height = heightVal;
				sizeDim.heightRel = heightRel;

				var callerObj = new Object();
				callerObj.method = newLoadFunction;
				callerObj.param = new Array(scripts, monitorID, sizeDim, mobileViewerBase, mobileViewerQuery, fpmOS);

				thisScriptTag.parentNode.innerHTML = '<span id="_fsiMon_'+(monitorID++)+'"></span>';

				registeredLoadMethods.push(callerObj);

			}
		}

		if (!objcode){
			if (textFallbackActive && confirm(textFallbackText)) top.location=flashDownload;
		}
		else if(mobileViewer == false){
			document.write(objcode);
		}

	};

	var calculateDim = function(checkObj){
		var dim = new Object();

		while (!dim.width && checkObj){

			var eWidth = getComputedCSS(checkObj, "width");

			if (eWidth != "auto" && eWidth != ""){
				dim.width = parseInt(eWidth);

				var paddingTop = parseInt(getComputedCSS(checkObj, "padding-top"));
				var paddingBottom = parseInt(getComputedCSS(checkObj, "padding-bottom"));
				var oHeight = checkObj.offsetHeight;
				var nHeight = oHeight - paddingTop - paddingBottom;
				var c2Padding = getComputedCSS(checkObj, "paddingBottom");

				dim.height = nHeight;
			}

			if (checkObj.offsetTop){
				dim.offsetTop=checkObj.offsetTop;
			}
			if (checkObj.offsetLeft){
				dim.offsetLeft=checkObj.offsetLeft;
			}

			checkObj = checkObj.parentNode;
		}

		return dim;
	};

	var getComputedCSS = function(elem, attr){
		var p = document.defaultView.getComputedStyle(elem, null);
		if (p) return p.getPropertyValue(attr);
	};

	var reorgFallbackImage = function(fbURL, newDim){

		var newURL = fbURL;

		// Split
		var uriParts = new RegExp("^(http?.+)[?]+(.+)").exec(fbURL);
		if (uriParts && uriParts.length == 3){
			newURL = uriParts[1]+"?";
			var parameter = new Object();
			var kpRaw = uriParts[2].split(/&/g);
			for (var k in kpRaw){
				var keyPair = kpRaw[k].split(/=/);
				if (keyPair[0] == "width"){
					keyPair[1] = newDim.width;
				}
				else if (keyPair[0] == "height"){
					keyPair[1] = newDim.height;
				}
				parameter[keyPair[0]] = keyPair[1];
			}

			// rebuild
			var nQuery = new Array();
			for (var param in parameter){
				var p = param+"="+parameter[param];
				nQuery.push(p);
			}
			newURL += nQuery.join("&");
		}

		return newURL;
	};

	this.openWinInjector = function(selfInject, os, base, query){
		
		
		if (os == 'Android'){
			window.open(base+'?'+query, 'fpm');
			return;
		}
		else {

			// split query
			var queryArray = new Array();
			var qparts = query.split('&');
			for (var q = 0; q < qparts.length; q++){
				var pairRaw = qparts[q].split('=');
				if (pairRaw.length == 2){
					var pair = new Object();
					pair.key = decodeURIComponent(pairRaw[0]);
					pair.value = decodeURIComponent(pairRaw[1]);
					queryArray.push(pair);
				}
			}

			var htmlCode = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n';
			htmlCode += '<html xmlns="http://www.w3.org/1999/xhtml">\n';
			htmlCode += '<head>\n';
			htmlCode += '<base href="'+base+'">\n';
			htmlCode += '<title>FSI Pages mobile</title>\n';
			htmlCode += '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n';
			htmlCode += '<meta http-equiv="Content-Script-Type" content="text/javascript" />\n';
			htmlCode += '<meta http-equiv="Content-Style-Type" content="text/css" />\n';
			htmlCode += '<meta name="Copyright" content="NeptuneLabs 2010-2013">\n';
			htmlCode += '<meta name="description" content="FSI Pages mobile" />\n';
			htmlCode += '<meta name="application-name" content="FSI Pages mobile"/>\n';
			htmlCode += '<meta http-equiv="pragma" content="no-cache" />\n';
			htmlCode += '<meta name="robots" content="nofollow,noindex,noimageindex,nomediaindex">\n';
			htmlCode += '<link rel="icon" href="./icon.png" type="image/png" />\n';
			htmlCode += '<link rel="stylesheet" href="css/fsipagesmobile.css" type="text/css" />\n';
			htmlCode += '<script type="text/javascript" src="js/fsipagesmobile.js"></script>\n';
			htmlCode += '<script type="text/javascript">\n';
			htmlCode += 'Ext.setup({\n';
			htmlCode += "tabletStartupScreen : 'images/tablet_startup.png',\n";
			htmlCode += "phoneStartupScreen : 'images/phone_startup.png',\n";
			htmlCode += 'glossOnIcon : false,\n';
			htmlCode += 'statusBarStyle : "black",\n';
			htmlCode += 'onReady : function() {\n';
			htmlCode += 'var parameters = {\n';
			for (var i = 0; i < queryArray.length; i++){
				htmlCode += queryArray[i].key+' : "'+queryArray[i].value+'"';
				if (i+1 < queryArray.length) htmlCode += ',';
				htmlCode += '\n';
			}
			htmlCode += '};\n';
			htmlCode += 'new Ext.FSIPagesMobile({parameters:parameters});\n';
			htmlCode += '}\n';
			htmlCode += '});\n';
			htmlCode += '</script>\n';
			htmlCode += '</head>\n';
			htmlCode += '<body></body>\n';
			htmlCode += '</html>';

			if (selfInject == false){
				var windowName = "fpm";
				// v1.8.6: chrome on iOS returns undefined when opening a named window
				if (navigator.userAgent.indexOf(" CriOS") != -1) windowName = "_blank";

				var newDoc = window.open('', windowName);
				newDoc.document.open();
				newDoc.document.write(htmlCode);
				newDoc.document.close();
			}
			else {
				window.document.open();
				window.document.write(htmlCode);
				window.document.close();
			}
		}
	};

	// Run VBScript detection part in old IE
	pushVBDetection = function(){
		var doc = '<scr' + 'ipt type="text/vbscript"\>\n';
		doc += 'On Error Resume Next\n';
		doc += 'Dim i\n';
		doc += 'For i = 30 to 6 Step -1\n';
		doc += 'If Not(IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & i))) Then\n';
		doc += 'Else\n';
		doc += 'fsiFD.flashVersion = i\n';
		doc += 'Exit For\n';
		doc += 'End If\n';
		doc += 'Next\n';
		doc += '<\/scr' + 'ipt>\n';
		document.write (doc);
	};

	var searchFSIPassThrough = function(){

		var result;

		if (document.location.search){
			var query = document.location.search.match(/^\?(.+)/);
			if (query && query[1]){
				result = splitQuery(query[1]);
			}
		}
		if (!result && window.location.search){
			var query = window.location.search.match(/^\?(.+)/);
			if (query && query[1]){
				result = splitQuery(query[1]);
			}
		}
		try{
			if (!result && parent.location.search){
				var query = parent.location.search.match(/^\?(.+)/);
				if (query && query[1]){
					result = splitQuery(query[1]);
				}
			}
		}
		catch(e){} // may access denied

		return result;
	};

	var splitQuery = function(query){
		var result;
		var pairs = query.split("&");
		var plen = pairs.length;
		for (var c=0; c < plen; c++){
			var keyVal = pairs[c].split("=");
			if (keyVal && keyVal.length == 2){
				var keyVal2 = keyVal[0].toLowerCase();
				if (keyVal2 == "fsipassthrough"){
					result = decodeURIComponent(keyVal[1]);
					if (result[0] != "&"){
						result = "&" + result;
					}
				}
			}
		}
		return result;
	};

	var xmlEscape = function(val){
		val = val.replace(/</g, "&lt;");
		val = val.replace(/>/g, "&gt;");
		val = val.replace(/\"/g, "&quot;");
		val = val.replace(/\'/g, "&apos;");
		val = val.replace(/&/g, "&amp;");
		return val;
	};

	var xmlUnescape = function(val){
		val = val.replace(/&lt;/g, "<");
		val = val.replace(/&gt;/g, ">");
		val = val.replace(/&quot;/g, '"');
		val = val.replace(/&apos;/g, "'");
		val = val.replace(/&amp;/g, "&");
		return val;
	};

}

function writeFlashCode(fsiurl, fallbackimg, parameters){
	fsiFD.writeFlashCode(fsiurl, fallbackimg, parameters);
}

fsiFD = new flashDetector(fsiPresetFlashVersion, fsiImageFallbackLinked, fsiTextFallbackActive, fsiTextFallbackText);
fsiFD.init();

// Copyright 2000-2013 NeptuneLabs GmbH (http://www.neptunelabs.com)
