var _ceHeader = null;
var _ceCEIName = null;
var _ceCEVName = 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;

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');
	
	_ceCEIName = 'wmxCEI_' + siteId;
	_ceCEVName = 'wmxCEV_' + siteId;
	
	_ceSiteId = siteId;
	_ceSecureUrl = secureUrl;

	_ceContent.addClassName('content');
	_ceInnerContent.addClassName('inner_content');
	_ceSelectedImage.innerHTML = selectedImageName;
	
	_ceButton.onclick = _ceButton_OnClick;
	_ceButton2.onclick = _ceButton_OnClick;
	_ceButton3.onclick = _ceButton_OnClick;
	
	if(!window.XMLHttpRequest)
	{
		this.createIframe();
		_ceIframe = _ceContent.previous('iframe');
	}
}

function _ceButton_OnClick()
{
	if(_ceButton.className == 'form_hidden') 
	{
		showConsumerExperience(); 
	}
	else 
	{
		hideConsumerExperience(); 
	}
}

var _iWaitingForImageLoad = 0;
var _iImageLoadAttemptCounter = 0;
var _oWaiterPE = null;
var _oBgImg = null;
var _oLnkImg = null;		
var _aBgs = null;
var _iIndex = 0;

function ChangeImage(imageName, imageId, imagePath, colorCode, themeName, variationId, variationHref)
{
      if (!_iWaitingForImageLoad)
      {
            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(_ceCEIName, cookieValue, 30);
 
            cookieValue = variationId;
            createCookie(_ceCEVName, cookieValue, 30);
 
            _ceSelectedImage.innerHTML = imageName;
 
            _iImageLoadAttemptCounter = 0;
      }
      
      if(_oWaiterPE)
      {
            _oWaiterPE.stop();
      } 
      
      if (!_oBgImg && !_oLnkImg)
      {
            _oBgImg = new Element('img', { src: imagePath });
            _oLnkImg = new Element('img', { src: variationHref });
      }
      
      if ((_aBgs && ($(_aBgs).indexOf(_oBgImg.src) > -1)) || (_oBgImg.complete))
      {
            if (!_aBgs)
            {
                  _aBgs = new Array();
            }
            
            if ($(_aBgs).indexOf(_oBgImg.src) < 0)
            {
                  _aBgs[_iIndex] = _oBgImg.src;
                  _iIndex++;
            }
            
            _oBgImg = null;
            _oLnkImg = null;
            
            ChangeVariation(themeName, variationHref, variationId);
 
            document.body.style.backgroundImage = "url('" + imagePath + "')";
            document.getElementsByTagName("html")[0].style.backgroundColor = colorCode;
            
            _iWaitingForImageLoad = 0;
            _iImageLoadAttemptCounter = 0;
            hideConsumerExperience(); 
            return false;
      }
      else
      {
            if (_iImageLoadAttemptCounter < 100)
            {
                  _iWaitingForImageLoad = 1;
                  _iImageLoadAttemptCounter++;
                  _oWaiterPE = new PeriodicalExecuter(ChangeImage.bind(this, imageName, imageId, imagePath, colorCode, themeName, variationId, variationHref), 0.2);
            }
            else
            {
                  _iWaitingForImageLoad = 0;
                  _iImageLoadAttemptCounter = 0;
            }
      }

/*	if (!_iWaitingForImageLoad)
	{
		var currentDateTime = new Date();
		var oImg = new Image();
		var requestSrc = _ceSecureUrl + "ConsumerExperienceHandler.ashx?wmxCEI=true";
		requestSrc += "&SiteId=" + _ceSiteId + "&ImageId=" + imageId;
		requestSrc += "&VariationId=" + variationId;

		oImg.src = requestSrc + "&DT=" + currentDateTime.getTime();

		cookieValue = imageId;
		createCookie(_ceCEIName, cookieValue, 30);

		cookieValue = variationId;
		createCookie(_ceCEVName, cookieValue, 30);

		_ceSelectedImage.innerHTML = imageName;

		_iImageLoadAttemptCounter = 0;
	}
	
	if(_oWaiterPE)
	{
		_oWaiterPE.stop();
	} 
	
	if (!_oBgImg && !_oLnkImg)
	{
		_oBgImg = new Element('img', { src: imagePath });
		_oLnkImg = new Element('img', { src: variationHref });
	}
	
	if ((_aBgs && ($(_aBgs).indexOf(_oBgImg.src) > -1)) || (_oBgImg.complete))
	{
		if (!_aBgs)
		{
			_aBgs = new Array();
		}
		
		if ($(_aBgs).indexOf(_oBgImg.src) < 0)
		{
			_aBgs[_iIndex] = _oBgImg.src;
			_iIndex++;
		}
		
		_oBgImg = null;
		_oLnkImg = null;
		
		ChangeVariation(themeName, variationHref, variationId);

		document.body.style.backgroundImage = "url('" + imagePath + "')";
 		document.getElementsByTagName("html")[0].style.backgroundColor = colorCode;
 		
 		_iWaitingForImageLoad = 0;
 		_iImageLoadAttemptCounter = 0;
 		hideConsumerExperience(); 
		return false;
	}
	else
	{
		if (_iImageLoadAttemptCounter < 100)
		{
			_iWaitingForImageLoad = 1;
			_iImageLoadAttemptCounter++;
			_oWaiterPE = new PeriodicalExecuter(ChangeImage.bind(this, imageName, imageId, imagePath, colorCode, themeName, variationId, variationHref), 0.2);
		}
		else
		{
			_iWaitingForImageLoad = 0;
			_iImageLoadAttemptCounter = 0;
		}
	} */
}

var _bChangingVariation = 0;
var _conex;

function ChangeVariation(themeName, variationHref, variationId)
{
	var currentThemeName = themeName;

	if (variationHref != "" && !_bChangingVariation && !_conex)
	{
		_bChangingVariation = 1;

		var sheet = $$('link[href=' + variationHref + ']').first();
		var sheets = $$('link[title=variation]');

		if (!sheet) {
			sheet = new Element('link', {
				href: variationHref,
				type: 'text/css',
				rel: 'stylesheet',
				media: 'all',
				title: 'variation'
			});
			
			if (sheets.length > 0) {
				sheets[ sheets.length - 1 ].insert({after: sheet});
			}			
		}
		
		var vPath = sheet.href;
		
		_conex = new PeriodicalExecuter(function() {
			_conex.stop();
			if (vPath) {
				var sheets = $$('link[title=variation]');
				for (var i = 0, j = sheets.length; i < j; i++) {
					if (sheets[i].href != vPath) sheets[i].disabled = true;
					else sheets[i].disabled = false;
				}
			}
			_conex = null;
			_bChangingVariation = 0;
		}, 0.1);
	}
}

function preloadVariation(variationHref)
{
	var oImg = new Element('img', {	src: variationHref });
}

function hideConsumerExperience()
{
	_ceButton.className = 'form_hidden';
	_ceContent.style.display = 'none';
	if(!window.XMLHttpRequest)
	{
		this.hideIframe();
	}
}

function showConsumerExperience()
{
	_ceButton.className = 'form_visible';
	_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'});
}