var _ceHeader = null;
var _ceConsumerExperienceImageName = null;
var _ceConsumerExperienceVariationName = null;
var _ceSecureUrl = null;
var _ceSiteId = null;
var _ceButton = null;
var _ceButton2 = null;
var _ceButton3 = null;
var _ceContent = null;
var _ceInnerContent = null;
var _ceSelectedImage = null;
var _ceFirstLoad = false;
var _ceChangingVariation = false;
var _conex;
var _changeCount = 0;
var _ceBrowser = '';
var _ceIsIE = null;
var _ceIsChrome = null;
var _ceWaitingForImageLoad = false;
var _ceImageLoadAttemptCounter = 0;
var _ceWaiterPeriodicalExecutor = null;
var _ceBackgroundImage = null;
var _ceBackgroundImages = null;
var _ceLinkImage = null;
var _ceImageIndex = 0;

function InitializeConsumerExperience(header, siteId, secureUrl, selectedImageName)
{
		_ceHeader = $(header).down('div.heading');
		_ceButton = _ceHeader.down('span').next('span');
		_ceButton2 = _ceHeader.down('span');
		_ceButton3 = _ceHeader.down('span').next('span').next('span');
		_ceContent = _ceHeader.next('div');
		_ceInnerContent = _ceContent.down('div');
		_ceSelectedImage = $('selectedImage');
		
		_ceConsumerExperienceImageName = 'wmxCEI_' + siteId;
		_ceConsumerExperienceVariationName = 'wmxCEV_' + siteId;
		
		_ceSiteId = siteId;
		_ceSecureUrl = secureUrl;

		_ceHeader.addClassName('heading_closed');
		_ceContent.addClassName('content');
		_ceInnerContent.addClassName('inner_content');
		_ceSelectedImage.innerHTML = selectedImageName;
		
		_ceButton.onclick = _ceButton_OnClick;
		_ceButton2.onclick = _ceButton_OnClick;
		_ceButton3.onclick = _ceButton_OnClick;
		
		_ceBrowser = GetBrowserString();
		_ceIsIE = IsInternetExplorer();
		_ceIsChrome = IsChrome();
		
		if(!window.XMLHttpRequest)
		{
			this.CreateIframe();
			_ceIframe = _ceContent.previous('iframe');
		}
}

function _ceButton_OnClick()
{
	if(_ceButton.className == 'form_hidden') 
	{
		ShowConsumerExperience(); 
	}
	else 
	{
		if(typeof waPost == 'function')
		{
			createEvent('Consumer Experience Closed','Consumer Experience','');
			waPost();
		}
		HideConsumerExperience(); 
	}
}



//This is the image onclick function. Everything else is called from here.
function ChangeImage(imageName, imageId, imagePath, colorCode, themeName, variationId, variationHref)
{
	if (!_ceWaitingForImageLoad)
	{
		var currentDateTime = new Date();
            
		var requestSrc = _ceSecureUrl + "ConsumerExperienceHandler.ashx?wmxCEI=true";
		requestSrc += "&SiteId=" + _ceSiteId + "&ImageId=" + imageId;
		requestSrc += "&VariationId=" + variationId;

		var secureScript = document.createElement('script');
		secureScript.type = 'text/javascript';
		secureScript.src = requestSrc + "&DT=" + currentDateTime.getTime();
		document.getElementsByTagName('head')[0].appendChild(secureScript);

		cookieValue = imageId;
		CreateCookie(_ceConsumerExperienceImageName, cookieValue, 30);

		cookieValue = variationId;
		CreateCookie(_ceConsumerExperienceVariationName, cookieValue, 30);

		_ceSelectedImage.innerHTML = imageName;

        _ceImageLoadAttemptCounter = 0;
		
		if(typeof waPost == 'function')
		{
			createEventWithDetails('Consumer Experience Image Selected','Consumer Experience','', new Array('ConsumerExperienceImageId=' + imageId));
			waPost();
		}
	}
      
	if(_ceWaiterPeriodicalExecutor)
	{
		_ceWaiterPeriodicalExecutor.stop();
	}
	  
	if (!_ceBackgroundImage && !_ceLinkImage)
	{
		_ceBackgroundImage = new Element('img', { src: imagePath });
		_ceLinkImage = new Element('img', { src: variationHref });
	}
      
	if ((_ceBackgroundImages && ($(_ceBackgroundImages).indexOf(_ceBackgroundImage.src) > -1)) || (_ceBackgroundImage.complete))
	{
		if (!_ceBackgroundImages)
		{
			_ceBackgroundImages = new Array();
		}
		
		if ($(_ceBackgroundImages).indexOf(_ceBackgroundImage.src) < 0)
		{
			_ceBackgroundImages[_ceImageIndex] = _ceBackgroundImage.src;
			_ceImageIndex++;
		}
		
		_ceBackgroundImage = null;
		_ceLinkImage = null;
		
		ChangeVariation(themeName, variationHref, variationId);

		document.body.style.backgroundImage = "url('" + imagePath + "')";
		document.getElementsByTagName("html")[0].style.backgroundColor = colorCode;
		
		_ceWaitingForImageLoad = false;
		_ceImageLoadAttemptCounter = 0;
		HideConsumerExperience();
		return false;
	}
	else
	{
		if (_ceImageLoadAttemptCounter < 100)
		{
			_ceWaitingForImageLoad = true;
			_ceImageLoadAttemptCounter++;
			_ceWaiterPeriodicalExecutor = new PeriodicalExecuter(ChangeImage.bind(this, imageName, imageId, imagePath, colorCode, themeName, variationId, variationHref), 0.5);
		}
		else
		{
			_ceWaitingForImageLoad = false;
			_ceImageLoadAttemptCounter = 0;
		}
	}
}

function ChangeVariation(themeName, newVariationHref, variationId)
{
	var currentThemeName = themeName;
	var currentVariation = $$('link[title=variation]').last();

	var changeStylesheet = false;
	if (!(currentVariation.href == newVariationHref))
	{
		changeStylesheet = true;
	}

	if (changeStylesheet)
	{
		_changeCount = _changeCount + 1;
		
		var newVariationHrefIsValid = false;
		if (newVariationHref != "")
		{
			newVariationHrefIsValid = true;
		}

		// If the new variation is valid, consumerExperience exists, and variation isn't already changing, do it.
		if (newVariationHrefIsValid && !_ceChangingVariation && !_conex)
		{
			_ceChangingVariation = true;

			var newVariationSheet = $$('link[href=' + newVariationHref + ']').first();
			
			var wasNewVariationSheetCreated = false;
			if (!newVariationSheet)
			{
				newVariationSheet = new Element('link', 
				{
					href: newVariationHref,
					type: 'text/css',
					rel: 'stylesheet',
					media: 'all',
					title: 'variation'
				});
				
				wasNewVariationSheetCreated = true;
			}

			var allVariationSheets = $$('link[title=variation]');
			var allSheets = $$('head link');
			var siteSheets = new Array();
			
			// reverse the allSheets array so that the most specific sheet is loaded first in the array
			if (allSheets.length != 0)
			{
				allSheets.reverse();
			}
			
			// check all the stylesheets to find the SiteCss sheet, and add that sheet to the siteSheets array.
			if (siteSheets)
			{
				for (var i = 0, j = allSheets.length; i < j; i++)
				{
					if (allSheets[i].href.indexOf(_ceSiteId) != -1)
					{
						siteSheets.push(allSheets[i]);
					}
				}
			}
	
			if (_ceIsIE)
			{
				if (_ceBrowser == "IE8")
				{
					ChangeIE8VariationSheets(wasNewVariationSheetCreated, newVariationSheet, allVariationSheets, siteSheets);
				}
				
				if (_ceBrowser == "IE7")
				{
					ChangeIE7VariationSheets(wasNewVariationSheetCreated, newVariationSheet, allVariationSheets, siteSheets);
				}
				
				if (_ceBrowser == "GenericIE")
				{
					ChangeGenericIEVariationSheets(wasNewVariationSheetCreated, newVariationSheet, allVariationSheets, siteSheets);
				}
			}

			if (_ceIsChrome)
			{
				ChangeChromeVariationSheets(wasNewVariationSheetCreated, newVariationSheet, allVariationSheets, siteSheets);
			}
			
			if (_ceBrowser == "GenericBrowser")
			{
				ChangeGenericBrowserVariationSheets(wasNewVariationSheetCreated, newVariationSheet, allVariationSheets, siteSheets);
			}
		}
	}
}

function ChangeGenericIEVariationSheets(wasNewVariationSheetCreated, newVariationSheet, allVariationSheets, siteSheets)
{
	if (wasNewVariationSheetCreated)
	{
		// if we have variation sheets, make sure none are disabled.
		// then insert the new variation sheet after the others.
		if (allVariationSheets.length > 0) 
		{
			newVariationSheet.disabled = false;
			allVariationSheets[ allVariationSheets.length - 1 ].insert({after: newVariationSheet});
		}
		
		// IE needs to reload siteSheets after variation changes.
		var newVariationSheets = $$('link[title=variation]');
		
		for (var index = 0, k = siteSheets.length; index < k; index++)
		{
			newVariationSheets [newVariationSheets.length - 1].insert({after: siteSheets[index]});
		}
	}
	else
	{
		if (allVariationSheets.length > 0) 
		{
			newVariationSheet.disabled = false;
			
			allVariationSheets[ allVariationSheets.length - 1 ].insert({after: newVariationSheet});
			
			var currentVariationSheets = $$('link[title=variation]');
		
			for (var index = 0, k = siteSheets.length; index < k; index++)
			{
				currentVariationSheets [currentVariationSheets.length - 1].insert({after: siteSheets[index]});
			}
		}
	}
	
	var timeout = 0.2;
	
	_conex = new PeriodicalExecuter(function() 
	{
		_conex.stop();
			
		_conex = null;
		_ceChangingVariation = 0;
	}, timeout);
}

function ChangeIE8VariationSheets(wasNewVariationSheetCreated, newVariationSheet, allVariationSheets, siteSheets)
{
	if (wasNewVariationSheetCreated)
	{
		// if we have variation sheets, make sure none are disabled.
		// then insert the new variation sheet after the others.
		if (allVariationSheets.length > 0) 
		{
			newVariationSheet.disabled = false;
			allVariationSheets[ allVariationSheets.length - 1 ].insert({after: newVariationSheet});
		}
	}
	else
	{
		
		if (allVariationSheets.length > 0) 
		{
			newVariationSheet.disabled = false;
			allVariationSheets[ allVariationSheets.length - 1 ].insert({after: newVariationSheet});
			
			var currentVariationSheets = $$('link[title=variation]');
		
			for (var index = 0, k = siteSheets.length; index < k; index++)
			{
				currentVariationSheets [currentVariationSheets.length - 1].insert({after: siteSheets[index]});
			}
		}
	}
	
	var timeout = 0.2;
	
	_conex = new PeriodicalExecuter(function() 
	{
		_conex.stop();
		_conex = null;
		_ceChangingVariation = 0;
	}, timeout);
}

function ChangeIE7VariationSheets(wasNewVariationSheetCreated, newVariationSheet, allVariationSheets, siteSheets)
{
	if (wasNewVariationSheetCreated)
	{
		// if we have variation sheets, make sure none are disabled.
		// then insert the new variation sheet after the others.
		if (allVariationSheets.length > 0) 
		{
			newVariationSheet.disabled = false;
			allVariationSheets[ allVariationSheets.length - 1 ].insert({after: newVariationSheet});
		}
		
		// IE needs to reload siteSheets after variation changes.
		var newVariationSheets = $$('link[title=variation]');
		
		for (var index = 0, k = siteSheets.length; index < k; index++)
		{
			newVariationSheets [newVariationSheets.length - 1].insert({after: siteSheets[index]});
		}
	}
	else
	{
		if (allVariationSheets.length > 0) 
		{
			newVariationSheet.disabled = false;
			// slightly changing the href solves the issue of IE7 forgetting to reload the base sheet.
			newVariationSheet.href = newVariationSheet.href + "?count=" + _changeCount;
			
			allVariationSheets[ allVariationSheets.length - 1 ].insert({after: newVariationSheet});
			
			var currentVariationSheets = $$('link[title=variation]');
		
			for (var index = 0, k = siteSheets.length; index < k; index++)
			{
				currentVariationSheets [currentVariationSheets.length - 1].insert({after: siteSheets[index]});
			}
		}
	}
	
	var timeout = 0.5;
	
	_conex = new PeriodicalExecuter(function() 
	{
		_conex.stop();
			
		_conex = null;
		_ceChangingVariation = 0;
	}, timeout);
	
	//IE7 has problems with reordering style sheets.
	if (!wasNewVariationSheetCreated)
	{
		location.reload(true);
	}
}

function ChangeChromeVariationSheets(wasNewVariationSheetCreated, newVariationSheet, allVariationSheets, siteSheets)
{
	if (wasNewVariationSheetCreated)
	{
		// if we have variation sheets, make sure none are disabled.
		// then insert the new variation sheet after the others.
		if (allVariationSheets.length > 0) 
		{
			newVariationSheet.disabled = false;
			allVariationSheets[ allVariationSheets.length - 1 ].insert({after: newVariationSheet});
		}
	}
	else
	{
		if (allVariationSheets.length > 0) 
		{
			newVariationSheet.disabled = false;
		}
	}
	
	var timeout = 0.1;
	
	_conex = new PeriodicalExecuter(function() 
	{
		// refresh for chrome, otherwise it won't load variations after all have been clicked.
		var allVariationSheets = $$('link[title=variation]');
		for (var i = 0, j = allVariationSheets.length; i < j; i++) 
		{
			if (allVariationSheets[i].href != newVariationSheet.href)
			{
				allVariationSheets[i].disabled = true;
			}
			else 
			{
				allVariationSheets[i].disabled = false;
			}
		}	
			
		_conex.stop();
		_conex = null;
		_ceChangingVariation = 0;
	}, timeout);
	
	var currentVariationSet = $$('link[title=variation]');
	for (var i = 0, j = currentVariationSet.length; i < j; i++) 
	{
		if (currentVariationSet[i].href = newVariationSheet.href)
		{
			currentVariationSet[i].disabled = false;
		}
	}

}

//this should handle Firefox and Safari.
function ChangeGenericBrowserVariationSheets(wasNewVariationSheetCreated, newVariationSheet, allVariationSheets, siteSheets)
{
	if (wasNewVariationSheetCreated)
	{
		// if we have variation sheets, make sure none are disabled.
		// then insert the new variation sheet after the others.
		if (allVariationSheets.length > 0) 
		{
			newVariationSheet.disabled = false;
			allVariationSheets[ allVariationSheets.length - 1 ].insert({after: newVariationSheet});
		}
	}
	else
	{
		if (allVariationSheets.length > 0) 
		{
			newVariationSheet.disabled = false;
			allVariationSheets[ allVariationSheets.length - 1 ].insert({after: newVariationSheet});
		}
	}
	
	var timeout = 0.2;
	
	_conex = new PeriodicalExecuter(function() 
	{
		_conex.stop();
			
		_conex = null;
		_ceChangingVariation = 0;
	}, timeout);

}

function preloadVariation(variationHref)
{
	var oImg = new Element('img', {	src: variationHref });
}

function HideConsumerExperience()
{
	_ceButton.className = 'form_hidden';
	_ceButton2.className = 'form_hidden';
	_ceButton3.className = 'form_hidden';
	
	if (_ceHeader.hasClassName('heading_open'))
	{
		_ceHeader.removeClassName('heading_open');
	}
	
	if (!_ceHeader.hasClassName('heading_closed'))
	{
		_ceHeader.addClassName('heading_closed'); 
	}
	
	_ceContent.style.display = 'none';
	if(!window.XMLHttpRequest)
	{
		this.HideIframe();
	}
}

function ShowConsumerExperience()
{
	if(!_ceFirstLoad)
	{
		if(typeof waPost == 'function')
		{
			createEvent('Consumer Experience Viewed','Consumer Experience','');
			waPost();
		}
		_ceFirstLoad = true;
	}
	_ceButton.className = 'form_visible';
	_ceButton2.className = 'form_visible';
	_ceButton3.className = 'form_visible';
	
	if (_ceHeader.hasClassName('heading_closed'))
	{
		_ceHeader.removeClassName('heading_closed');
	}
	if (!_ceHeader.hasClassName('heading_open'))
	{
		_ceHeader.addClassName('heading_open');
	}
	
	_ceContent.style.display = 'block';
	if(!window.XMLHttpRequest)
	{
		this.ShowIframe();
	}
}

function CreateCookie(name,value,days)
{
	if (days)
 	{
  		var date = new Date();
  		date.setTime(date.getTime()+(days*24*60*60*1000));
  		var expires = "; expires="+date.toGMTString();
 	}
 	else
	{
 		var expires = "";
	}

	document.cookie = name+"="+value+expires+"; path=/";
}

function ReadCookie(name)
{
	var nameEQ = name + "=";
 	var ca = document.cookie.split(';');

 	for(var i=0;i < ca.length;i++)
 	{
  		var c = ca[i];
  		while (c.charAt(0)==' ') c = c.substring(1,c.length);
  		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
 	}

 	return null;
}

function EraseCookie(name) 
{
	CreateCookie(name,"",-1);
}

function CreateIframe()
{
	var iframe = new Element('iframe', {'class': 'consumer_iframe', src: 'about:blank'});
	Element.insert(this._ceHeader, {'after': iframe});
	iframe.setStyle({display: 'none'});
}

function ShowIframe()
{
	var contentHeight = this._ceContent.getHeight();
	var contentWidth = this._ceContent.getWidth();
	var contentLeft = this._ceContent.getStyle('left');
	var contentRight = this._ceContent.getStyle('right');
	var contentTop = this._ceContent.getStyle('top');
	var contentZIndex = this._ceContent.getStyle('z-index');
	
	if(contentLeft)
	{
		this._ceIframe.setStyle({
			height: contentHeight + 'px',
			width: contentWidth + 'px',
			position: 'absolute',
			left: contentLeft,
			top: contentTop,
			zIndex: contentZIndex - 5,
			display: 'block'
		});
	}
	
	if(contentRight)
	{
		this._ceIframe.setStyle({
			height: contentHeight + 'px',
			width: contentWidth + 'px',
			position: 'absolute',
			right: contentRight,
			top: contentTop,
			zIndex: contentZIndex - 5,
			display: 'block'
		});
	}
}

function HideIframe()
{
	this._ceIframe.setStyle({display: 'none'});
}

// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
function GetInternetExplorerVersion()
{
	// Return value assumes failure.
	var rv = -1; 
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
	var ua = navigator.userAgent;
	var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
	if (re.exec(ua) != null)
	  rv = parseFloat( RegExp.$1 );
	}
	return rv;
}

function IsInternetExplorer()
{
	var isIE = false;
	var ieVersion = GetInternetExplorerVersion();
	if (ieVersion != -1)
	{
		isIE = true;
	}
	return isIE;
}

function IsChrome()
{
	var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	return isChrome;
}

function GetBrowserString()
{
	var isIE = GetInternetExplorerVersion();
	var browserString;
	
	if (isIE != -1)
	{
		//this is an IE browser
		browserString = "GenericIE";
		if (isIE == 7)
		{
			browserString = "IE7";
		}
		if (isIE == 8)
		{
			browserString = "IE8";
		}
	}
	else
	{
		browserString = "GenericBrowser";
		var isChrome = IsChrome();
		if (isChrome)
		{
			browserString = "Chrome";
		}
	}

	return browserString;
}
