/*******************************************************************************************
 * flashReplace
 * Written by Craig Francis
 * If the browser can support Flash, replace the Flash alternative with the Flash object.
 *
 * This script uses a Flash detection object to double check that the Flash plug-in is
 * working (not installed, but disabled)... in this rare case, a reload of the page will
 * not attempt to load the Flash file (info from a cookie).
 *
 * Example without configuration changes:
 *
 *    if (document.getElementById && flashReplace) {
 *        flashReplace.addFlashObject('myDivA', 'myFile.swf', 200, 300, '#FFF');
 *        flashReplace.addFlashObject('myDivB', 'myFile.swf', 200, 300, 'transparent');
 *    }
 *
 * Example with configuration changes:
 *
 *    if (document.getElementById && flashReplace) {
 *
 *        flashReplace.requireVersion = 6;
 *
 *        flashReplace.textBeforeLink = 'Would you like to turn the Flash ';
 *        flashReplace.textEnableLink = 'on';
 *        flashReplace.textBetweenLink = ' or ';
 *        flashReplace.textDisableLink = 'off';
 *        flashReplace.textAfterLink = '.';
 *
 *        flashReplace.addFlashObject('myDiv', 'myFile.swf', 200, 300, '#FFF');
 *
 *    }
 *
 * This source code is released under the BSD licence, see the end of this script
 * for the full details. It was originally created by Craig Francis in 2005.
 *
 * http://www.craigfrancis.co.uk/features/code/jsFlashReplace/
 *
 *******************************************************************************************/

	var flashReplace = new function () {

		//--------------------------------------------------
		// Do not allow older browsers to run this script

			if (!document.getElementById || !document.getElementsByTagName) {
				return;
			}

		//--------------------------------------------------
		// Create local variable which is easier to use
		// than the more generic 'this'

			var flashReplace = this;

		//--------------------------------------------------
		// Config variables - can be overridden

			flashReplace.versionAvailable = 0;

			flashReplace.objects = new Array();
			flashReplace.useXmlMethods = (document.contentType && document.contentType.indexOf('xml') > -1);
			flashReplace.requireVersion = 6;
			flashReplace.detectObjectUrl = '/a/swf/flashDetect.swf'; // Fails on Flash 10
			flashReplace.detectObjectUrl = '';
			flashReplace.reloadGifs = false;

			flashReplace.textBeforeLink = 'Flash [ ';
			flashReplace.textEnableLink = 'On';
			flashReplace.textBetweenLink = ' / ';
			flashReplace.textDisableLink = 'Off';
			flashReplace.textAfterLink = ' ]';

		//--------------------------------------------------
		// Simple function to set the flashAvailable
		// variable in a cookie and store in a variable
		// for this script

			flashReplace.setFlashVersionAvailable = function (version) {
				flashReplace.versionAvailable = version;
				document.cookie = 'flashAvailable=' + escape(version) + '; path=/';
			}

		//--------------------------------------------------
		// Initial value of the version available

			//--------------------------------------------------
			// See if there is a cookie set which can tell
			// us which version of flash the user has (from
			// previous page loads)

				flashReplace.versionAvailable = 0; // RUN TEST
				var cookieString = document.cookie;

				if (cookieString && cookieString.match(/^.*flashAvailable=([\-0-9]+).*$/i)) {
					flashReplace.versionAvailable = parseInt(cookieString.replace(/^.*flashAvailable=([\-0-9]+).*$/i, '$1'), 10);
				}

			//--------------------------------------------------
			// See if we are being told what to-do

				var locationString = window.location.search;

				if (locationString.match(/(\?|&)flashReplace=false/i)) {

					flashReplace.setFlashVersionAvailable(-1); // SOFT DISABLE

				} else if (locationString.match(/(\?|&)flashReplace=true/i)) {

					if (flashReplace.versionAvailable < 1) {
						flashReplace.setFlashVersionAvailable(0); // RUN TEST
					}

				}

			//--------------------------------------------------
			// If we have to check if flash exists (0), then
			// do a quick sanity check to see if the plug-in
			// exists (if it doesn't, we should disable flash
			// now... to save on processing). This section of
			// code was originally written by Christopher
			// Sheldon from http://www.microagesolutions.com

				var pluginVersion = -1;

				if (flashReplace.versionAvailable == 0) {
					if (navigator.plugins && navigator.plugins.length) {
						for (var i = (navigator.plugins.length - 1); i >= 0 && pluginVersion == -1; i--) {
							if (navigator.plugins[i].name.indexOf('Shockwave Flash') != -1) {
								pluginVersion = parseInt(navigator.plugins[i].description.split('Shockwave Flash ')[1], 10);
							}
						}
					} else if (window.ActiveXObject) {
						for (var i = (flashReplace.requireVersion + 10); i >= flashReplace.requireVersion; i--) {
							try {
								oFlash = eval('new ActiveXObject("ShockwaveFlash.ShockwaveFlash.' + i + '");');
								if (oFlash) {
									pluginVersion = i;
								}
							} catch(e) {
							}
						}
					}
					if (pluginVersion < flashReplace.requireVersion) {
						flashReplace.setFlashVersionAvailable(-2); // HARD DISABLE
					}
				}

				flashReplace.pluginVersion = pluginVersion;

		//--------------------------------------------------
		// Function called to setup / add a flash object

			flashReplace.addFlashObject = function (divId, flashUrl, flashWidth, flashHeight, flashBgColour, flashVars) {

				//--------------------------------------------------
				// If this is a SOFT DISABLE, we will give up soon,
				// but first, add the flash disable links.
				// NOTE: this might be called multiple times.

					if (flashReplace.versionAvailable == -1) {
						addLoadEvent (flashReplace.addDisableLinks);
					}

				//--------------------------------------------------
				// If version of flash is not good enough, give up

					if (flashReplace.versionAvailable < 0 || (flashReplace.versionAvailable > 0 && flashReplace.versionAvailable < flashReplace.requireVersion)) {
						return;
					}

				//--------------------------------------------------
				// If we can bypass the object detection

					if (flashReplace.versionAvailable == 0 && flashReplace.detectObjectUrl == '') {
						flashReplace.setFlashVersionAvailable(flashReplace.pluginVersion);
					}

				//--------------------------------------------------
				// Temporarily hide the flash object

					var cssRule = ' #' + divId + ' {';
					cssRule += '  visibility: hidden; ';
					cssRule += '  width: ' + flashWidth + 'px;';
					cssRule += '  height: ' + flashHeight + 'px;';
					cssRule += '}';

					addCssRule(cssRule);

				//--------------------------------------------------
				// Store the details in an array

					flashReplace.objects[flashReplace.objects.length] = {
						divId: divId,
						flashUrl: flashUrl,
						flashWidth: flashWidth,
						flashHeight: flashHeight,
						flashBgColour: flashBgColour,
						flashVars: flashVars
					}

				//--------------------------------------------------
				// If this is the first flash object, then ONLOAD
				// either create the flash detect object or bypass
				// straight into 'replaceObjects' (if we already
				// know which version of flash the user has)

					if (flashReplace.objects.length == 1) {
						if (flashReplace.versionAvailable == 0) {
							addLoadEvent (flashReplace.addDetectObject);
						} else {
							addLoadEvent (flashReplace.replaceObjects);
						}
					}

			}

		//--------------------------------------------------
		// Add the flash detection object to the page... this
		// object will call-back if everything is OK.

			flashReplace.addDetectObject = function () {

				//--------------------------------------------------
				// Until we get a response from the flash object,
				// it should be taken that the browser does not
				// support flash (for next page load)

					flashReplace.setFlashVersionAvailable(-1); // SOFT DISABLE

				//--------------------------------------------------
				// Ensure we have a path

					if (flashReplace.detectObjectUrl == '') {
						flashReplace.setFlashVersionAvailable(-2); // HARD DISABLE
					}

				//--------------------------------------------------
				// Get a reference to the body

					var bodyRef = document.getElementsByTagName('body');
					if (bodyRef[0]) {
						bodyRef = bodyRef[0];
					} else {
						flashReplace.restoreAlternative();
						return;
					}

				//--------------------------------------------------
				// Create a div which will act as an anchor for
				// a small flash detect object

					flashReplace.detectObjectDiv = createElement('div');
					flashReplace.detectObjectDiv.style.position = 'absolute';
					flashReplace.detectObjectDiv.style.top = '0';
					flashReplace.detectObjectDiv.style.left = '0';

				//--------------------------------------------------
				// Create the flash object, if the proper XML method
				// does not work (IE), then do it the old-school way

					if (flashReplace.useXmlMethods) {

						var objTag = createElement('object');
						var objMovieParam = createElement('param');

						objTag.setAttribute('type','application/x-shockwave-flash');
						objTag.setAttribute('width',  '1');
						objTag.setAttribute('height', '1');
						objTag.setAttribute('data', flashReplace.detectObjectUrl);

						objMovieParam.setAttribute('name','movie');
						objMovieParam.setAttribute('value', flashReplace.detectObjectUrl);

						objTag.appendChild(objMovieParam);
						flashReplace.detectObjectDiv.appendChild(objTag);

					} else {

						var flashHTML = '<object type="application/x-shockwave-flash" data="' + flashReplace.detectObjectUrl + '" width="1" height="1">';
						flashHTML += '	<param name="movie" value="' + flashReplace.detectObjectUrl + '" />';
						flashHTML += '</object>';

						flashReplace.detectObjectDiv.innerHTML = flashHTML;

					}

				//--------------------------------------------------
				// Add out flashDetect script to the body

					bodyRef.appendChild(flashReplace.detectObjectDiv);

			}

		//--------------------------------------------------
		// Function called from the flash detection object.

			flashReplace.detectionResult = function (version) {

				//--------------------------------------------------
				// Remove the flash detection object... it is
				// no longer required. But you cant actually
				// remove it, because IE5 MAC crashes when you
				// try to refresh the page, and you cant do
				// a "display: none" as NS 6.2 crashes on refresh

					if (flashReplace.detectObjectDiv) {
						flashReplace.detectObjectDiv.style.left = '-10px';
					}

				//--------------------------------------------------
				// If this version of flash is good enough,
				// then store the value and continue to process
				// it, otherwise restore the alternative.

					version = parseInt(version, 10);

					if (version >= flashReplace.requireVersion) {
						flashReplace.setFlashVersionAvailable(version);
						flashReplace.replaceObjects();
					} else {
						flashReplace.setFlashVersionAvailable(-2); // HARD DISABLE
						flashReplace.restoreAlternative();
					}

			}

		//--------------------------------------------------
		// When the Flash detection has been successful,
		// then replace the objects

			flashReplace.replaceObjects = function () {

				//--------------------------------------------------
				// Go though each of the objects and try to
				// replace them (if they exist yet).

					for (var k=(flashReplace.objects.length - 1); k >= 0; k--) {
						var flashObject = flashReplace.objects[k];
						var objHolder = document.getElementById(flashObject.divId);
						if (objHolder) {

							//--------------------------------------------------
							// Add the flashHolder class to the main div
							// so that it can be targeted by CSS

								cssjs('add', objHolder, 'flashHolder');

							//--------------------------------------------------
							// Create the flash object. If this fails the
							// user has a bad browser (IE) and has to be
							// told how to-do things incorrectly

								if (flashReplace.useXmlMethods) {

									//--------------------------------------------------
									// Remove all the child nodes by sending them
									// off the screen, but add a class to them, so
									// we can bring them back (if necessary).

										var ch = objHolder.childNodes;
										var chLen = ch.length;

										for (i=(chLen-1); i>= 0; i--) {
											if (ch[i].style) {

				 								cssjs('add', ch[i], 'flashAlternative');

				 								ch[i].style.position = 'absolute';
				 								ch[i].style.left = '-10000px';

				 							} else {
				 								objHolder.removeChild(ch[i]);
				 							}
										}

									//--------------------------------------------------
									// Create nodes

										var objTag = createElement('object');
										var objMovieParam = createElement('param');
										var objBgcolorParam = createElement('param');
										var objFlashVarsParam = createElement('param');

									//--------------------------------------------------
									// Setup

										objTag.setAttribute('type','application/x-shockwave-flash');
										objTag.setAttribute('width', flashObject.flashWidth);
										objTag.setAttribute('height', flashObject.flashHeight);
										objTag.setAttribute('data', flashObject.flashUrl);
										objTag.setAttribute('class', 'flashObject');

										objMovieParam.setAttribute('name','movie');
										objMovieParam.setAttribute('value', flashObject.flashUrl);

										if (flashObject.flashBgColour == 'transparent') {
											objBgcolorParam.setAttribute('name','wmode');
											objBgcolorParam.setAttribute('value', 'transparent');
										} else {
											objBgcolorParam.setAttribute('name','bgcolor');
											objBgcolorParam.setAttribute('value', flashObject.flashBgColour);
										}

										objFlashVarsParam.setAttribute('name', 'FlashVars');
										objFlashVarsParam.setAttribute('value', (flashObject.flashVars ? flashObject.flashVars : ''));

									//--------------------------------------------------
									// Combine

										objTag.appendChild(objMovieParam);
										objTag.appendChild(objBgcolorParam);
										objTag.appendChild(objFlashVarsParam);
										objHolder.appendChild(objTag);

								} else {

									//--------------------------------------------------
									// Build the html

										var flashHTML = '<object type="application/x-shockwave-flash" data="' + flashObject.flashUrl + '" width="' + flashObject.flashWidth + '" height="' + flashObject.flashHeight + '" class="flashObject">';
										flashHTML += '<param name="movie" value="' + flashObject.flashUrl + '" />';

										if (flashObject.flashBgColour == 'transparent') {
											flashHTML += '<param name="wmode" value="transparent" />';
										} else {
											flashHTML += '<param name="bgcolor" value="' + flashObject.flashBgColour + '" />';
										}

										flashHTML += '<param name="FlashVars" value="' + (flashObject.flashVars ? flashObject.flashVars : '') + '" />';
										flashHTML += '</object>';

									//--------------------------------------------------
									// Add it to the holder

										objHolder.innerHTML = flashHTML; // Must replace all child nodes, as IE7+8 tries to continue loading those resources (and never finishes).

								}

							//--------------------------------------------------
							// Restore visibility to this holder

								objHolder.style.visibility = 'visible';

						}
					}

				//--------------------------------------------------
				// Fix IE5+6 WIN where it will stops animated gifs

					if (flashReplace.reloadGifs) {
						var images = document.getElementsByTagName('img');
						for (var i=images.length; i--;){
							if (images[i].src.match(/\.gif/i)) {
								images[i].src = images[i].src;
							}
						}
					}

				//--------------------------------------------------
				// Add the flash enable and disable links

					flashReplace.addDisableLinks();

			}

		//--------------------------------------------------
		// Add links to enable or disable flash

			flashReplace.addDisableLinks = function () {
				var flashDisableLinks = document.getElementById('flashDisableLinks');
				if (flashDisableLinks) {

					//--------------------------------------------------
					// Give up if the links already exist

						var linkE = document.getElementById('flashEnableLink');
						var linkD = document.getElementById('flashDisableLink');
						if (linkE || linkD) {
							return;
						}

					//--------------------------------------------------
					// Set the enable/disable link urls, while removing
					// any reference to the "flashReplace" variable

						var cleanQuery = window.location.search;
						cleanQuery = cleanQuery.replace(/^\?/, '');
						cleanQuery = cleanQuery.replace(/flashReplace=[^&]*&?/gi, '');
						cleanQuery = cleanQuery.replace(/&$/, '');

						if (cleanQuery != '') {
							cleanQuery = '&' + cleanQuery;
						}

						var enableUrl = './?flashReplace=true' + cleanQuery;
						var disableUrl = './?flashReplace=false' + cleanQuery;

					//--------------------------------------------------
					// Create the link elements and nodes

						var enableLink = createElement('a');
						var disableLink = createElement('a');

						var beforeContent = document.createTextNode(flashReplace.textBeforeLink);
						var enableContent = document.createTextNode(flashReplace.textEnableLink);
						var betweenContent = document.createTextNode(flashReplace.textBetweenLink);
						var disableContent = document.createTextNode(flashReplace.textDisableLink);
						var afterContent = document.createTextNode(flashReplace.textAfterLink);

					//--------------------------------------------------
					// Setup the links

						enableLink.setAttribute('href', enableUrl);
						enableLink.setAttribute('id', 'flashEnableLink');
						disableLink.setAttribute('href', disableUrl);
						disableLink.setAttribute('id', 'flashDisableLink');

					//--------------------------------------------------
					// Set one as current - setAttribute() does not
					// work with the class on IE5+6 WIN and IE5 MAC

						if (flashReplace.versionAvailable > 0) {
							cssjs('add', enableLink, 'current');
						} else {
							cssjs('add', disableLink, 'current');
						}

					//--------------------------------------------------
					// Add to the flashDisableLinks holder

						enableLink.appendChild(enableContent);
						disableLink.appendChild(disableContent);

						flashDisableLinks.appendChild(beforeContent);
						flashDisableLinks.appendChild(enableLink);
						flashDisableLinks.appendChild(betweenContent);
						flashDisableLinks.appendChild(disableLink);
						flashDisableLinks.appendChild(afterContent);

				}
			}

		//--------------------------------------------------
		// If the browser cannot support Flash, then
		// we need to restore the alternatives.

			flashReplace.restoreAlternative = function () {

				for (var k=(flashReplace.objects.length - 1); k >= 0; k--) {
					var objHolder = document.getElementById(flashReplace.objects[k].divId);
					if (objHolder) {

						objHolder.style.visibility = 'visible';
		 				objHolder.style.width = 'auto';
		 				objHolder.style.height = 'auto';

					}
				}

			}

	}

	function flashDetectionResult (version) {
		flashReplace.detectionResult(version);
	}

/************************************************************
 * Copyright (c) 2005, Craig Francis All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms,
 * with or without modification, are permitted provided
 * that the following conditions are met:
 *
 *  - Redistributions of source code must retain the
 *    above copyright notice, this list of
 *    conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce
 *    the above copyright notice, this list of
 *    conditions and the following disclaimer in the
 *    documentation and/or other materials provided
 *    with the distribution.
 *  - Neither the name of the author nor the names
 *    of its contributors may be used to endorse or
 *    promote products derived from this software
 *    without specific prior written permission.
 *
 * This software is provided by the copyright holders
 * and contributors "as is" and any express or implied
 * warranties, including, but not limited to, the
 * implied warranties of merchantability and fitness
 * for a particular purpose are disclaimed. In no event
 * shall the copyright owner or contributors be liable
 * for any direct, indirect, incidental, special,
 * exemplary, or consequential damages (including, but
 * not limited to, procurement of substitute goods or
 * services; loss of use, data, or profits; or business
 * interruption) however caused and on any theory of
 * liability, whether in contract, strict liability, or
 * tort (including negligence or otherwise) arising in
 * any way out of the use of this software, even if
 * advised of the possibility of such damage.
 ************************************************************/
