//Detected whether we're running in IE
var isIE = function(){
	return (navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") > -1);
}();

//Detect whether we have Flash support
var hasFlash = function(){
	var nRequiredVersion = 7;	
	
	if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") > -1){
		document.write('<script language="VBScript"\> \non error resume next \nhasFlash = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & ' + nRequiredVersion + '))) \n</script\> \n');
		/*	If executed, the VBScript above checks for Flash and sets the hasFlash variable. 
			If VBScript is not supported it's value will still be undefined, so we'll run it though another test
			This will make sure even Opera identified as IE will be tested */
		if(window.hasFlash != null){
			return window.hasFlash;
		};
	};
	
	if(navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"] && navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
		var flashDescription = (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description;
		return parseInt(flashDescription.charAt(flashDescription.indexOf(".") - 1)) >= nRequiredVersion;
	};
	
	return false;
}();

//Detect whether we should build using the DOM or innerHTML
var useDOM = function(){
	return ! isIE;
}();

//Wire us up to the events
if (isIE) { InstallFlashElements(); }
Event.observe(window, 'load', InstallFlashElements, false);
Event.observe(document, 'DOMContentLoaded', InstallFlashElements, false);

function InstallFlashElements()
{
	//Make sure the DOM is ready
    if (document.body == null)
    { return };
    
    //Don't run twice
	if (arguments.callee.done) return;
	
    //Record that we've been run already
    arguments.callee.done = true;
	
	//Test that we can run
	//if(window.hasFlash == false || !document.createElement || !document.getElementById)
	//{
	//	window.location.href = appRoot + '/Flash/Upgrade.fuel';
	//	return false;
	//}

	//Get all of the polaroid groups and init each one
	var polaroidGroups = document.getElementsByClassName('polaroidGroup');
	polaroidGroups.each(function(polaroidGroup){ InitPolaroidGroup(polaroidGroup); });
	
	//Get all of the text areas and init each one
	var textAreas = document.getElementsByClassName('textArea');
	textAreas.each(function(textArea){ InitTextArea(textArea); });
	
	//Hide all the downlevel elements
	addClass.apply(document.getElementsByTagName('html')[0],['uplevel']);
}

function InitPolaroidGroup(group)
{
	//Get ready to store the data we gather
	var areaWidth = group.clientWidth;
	var areaHeight = group.clientHeight;
	var flashParams = {
		polaroidHeight: '',
		polaroidWidth: '',
		images: '',
		fixedRotation: '',
		layoutEngine: 'stack'
	};
	
	//Get the descriptor off the group element
	//eg: polaroidGroup-pw72-ph90
	var descriptorAttribute = (group.getAttribute('class') != null ? group.getAttribute('class') : (group.className != null ? group.className : ''));
	var descriptor = descriptorAttribute.split(' ').find(function(className)
	{
		return (className.indexOf('polaroidGroup-') == 0);
	});
	
	//Process the descriptor
	if (descriptor) descriptor.split('-').each(function(descriptorPart)
	{
		var descriptorValue = descriptorPart.substring(2);
		switch (descriptorPart.substring(0, 2))
		{
			case 'pw':
				flashParams['polaroidWidth'] = descriptorValue;
				break;
			case 'ph':
				flashParams['polaroidHeight'] = descriptorValue;
				break;
			case 'pr':
				flashParams['fixedRotation'] = descriptorValue;
				break;
			case 'le':
				flashParams['layoutEngine'] = descriptorValue;
				break;
		}
	});
	
	//Process each child element (get relevant info then hide it)
	InstallPolaroidGroupProcessElement(group, flashParams, '');
	
	//Clean up the flash params then generate the query string
	flashParams['images'] = (flashParams['images'].length == 0 ? flashParams['images'] : flashParams['images'].substring(0, flashParams['images'].length - 2));
	var flashQueryString = $H(flashParams).toQueryString();
	var flashUrl = appRoot + '/Skins/FlashElements/PolaroidGenerator.swf?' + flashQueryString;
		
	//Generate the Flash object
	InstallFlashObject(group, flashUrl, areaWidth, areaHeight);
}

function InstallPolaroidGroupProcessElement(element, flashParams, target)
{
	//Process each child element (get relevant info then hide it)
	var childElements = element.getElementsByTagName('*');
	$A(childElements).each(function(childElement)
	{
		//Get any relevant info from it
		switch (childElement.nodeName.toLowerCase())
		{
			case 'a':
				var newTarget = (childElement.href ? childElement.href : childElement.getAttribute('href'));
				InstallPolaroidGroupProcessElement(childElement, flashParams, newTarget);
				break;
			case 'img':
				var imgSrc = (childElement.href ? childElement.href : (childElement.getAttribute('href') != null ? childElement.getAttribute('href') : childElement.getAttribute('src')));
				imgSrc = (imgSrc.indexOf('?') == -1 ? imgSrc : imgSrc.substring(0, imgSrc.indexOf('?')));
				imgSrc = imgSrc.replace('.jpg_', '.jpg');
				
				var imgTag = imgSrc;
				imgTag += '::';
				imgTag += (childElement.title ? childElement.title : childElement.getAttribute('title'));
				imgTag += '::';
				imgTag += target;
				imgTag += '::';
				
				if (flashParams['images'].indexOf(imgSrc) == -1)
					flashParams['images'] += imgTag;
				
				break;
		}
		
		//Hide the downlevel element
		addClass.apply(childElement,['downlevel']);
	});
}

function InitTextArea(textArea)
{
	//Get ready to store the data we gather
	var areaWidth = textArea.clientWidth;
	var areaHeight = textArea.clientHeight;
	var flashParams = {
		captionText: textArea.childNodes[0].childNodes[0].nodeValue,
		fontSize: 0
	};
	
	//Get the descriptor off the textArea element
	//eg: textArea-fs20
	var descriptorAttribute = (textArea.getAttribute('class') != null ? textArea.getAttribute('class') : (textArea.className != null ? textArea.className : ''));
	var descriptor = descriptorAttribute.split(' ').find(function(className)
	{
		return (className.indexOf('textArea-') == 0);
	});
	
	//Process the descriptor
	if (descriptor) descriptor.split('-').each(function(descriptorPart)
	{
		var descriptorValue = descriptorPart.substring(2);
		switch (descriptorPart.substring(0, 2))
		{
			case 'fs':
				flashParams['fontSize'] = descriptorValue;
				break;
		}
	});
	
	//Hide the downlevel element
	addClass.apply(textArea.childNodes[0],['downlevel']);
	
	//Clean up the flash params then generate the query string
	var flashQueryString = $H(flashParams).toQueryString();
	var flashUrl = appRoot + '/Skins/FlashElements/TextArea.swf?' + flashQueryString;
	
	//Generate the Flash object
	InstallFlashObject(textArea, flashUrl, areaWidth, areaHeight);
}

function InstallFlashObject(target, flashUrl, width, height)
{	
	if (! useDOM)
	{
		flashUrl += '&timestamp=' + new Date().toString();
		
		var nodeName = target.nodeName;
		var cssClass = (target.getAttribute('class') != null ? target.getAttribute('class') : (target.className != null ? target.className : ''));
		target.outerHTML = '<' + nodeName + ' class="' + cssClass + '"><embed type="application/x-shockwave-flash" src="' + flashUrl + '" quality="best" wmode="transparent" width="' + width + 'px" height="' + height + 'px"></embed></' + nodeName + '>';
		target.innerHTML += " ";
	}
	else
	{
		var flashObject = document.createElement('object');
		flashObject.setAttribute('type', 'application/x-shockwave-flash');
		flashObject.setAttribute('data', flashUrl);
		flashObject.setAttribute('width', width);
		flashObject.setAttribute('height', height);
		flashObject.style.width = width + "px";
		flashObject.style.height = height + "px";

		var flashMovieParam = document.createElement('param');
		flashMovieParam.setAttribute('name', 'movie');
		flashMovieParam.setAttribute('value', flashUrl);
		flashObject.appendChild(flashMovieParam);

		var flashWmodeParam = document.createElement('param');
		flashWmodeParam.setAttribute('name', 'wmode');
		flashWmodeParam.setAttribute('value', 'transparent');
		flashObject.appendChild(flashWmodeParam);
		
		//Make sure the Flash object remains visible
		addClass.apply(flashObject,['uplevel']);
		
		target.appendChild(flashObject);
	}
}
