
var colourChangerHitBoxModuleName = 'BackgroundChanger';
var colourChangerLastChosen = '';

// NOTE: The first theme here (themeRed) will always be chosen as the default if no cookie is found. Do not change the first value
// unless you want the default theme to no longer be themeRed - in which case you should update the <noscript> tag in showbiz.gsp.
var siteThemes = {
	SHOWBIZ: ['themeRed', 'themePurple', 'themeBlue', 'themeGreen', 'themeGrey']
};

// FIXME:
// Right now, this will only work for Showbiz. If we need to add it to more sites, we need a reliable way of
// getting the site. The SITE var in constants.js is always 'SHOWBIZ' as it's served from a CDN. This needs fixing
// so it is always dynamic, and always accurate. Perhaps moving it from the CDN would be appropriate?
//if (SITE) var entSiteName = SITE;
var entSiteName = 'SHOWBIZ';
var themeArray = siteThemes[entSiteName];

function setSiteBackground(eventData) {

    var theSwatch = Event.element(eventData);
	Event.stop(eventData);
	var swatchClassName = theSwatch.className;
	var selectedSwatchClass = '';
	$w(swatchClassName).each(function(theClass){
		if (theClass.indexOf('theme') == 0) {
			selectedSwatchClass = theClass;
			return;
		}
	});
	if (selectedSwatchClass != '') {
		setSiteBackgroundDetails(selectedSwatchClass);
        colourChangerLastChosen = selectedSwatchClass;
    }
}

function setSiteBackgroundDetails(selectedSwatchClass) {
	var documentBody = $$('body')[0];
	for (var loop=0, max=themeArray.length; loop<max; loop++) {
		Element.removeClassName(documentBody, themeArray[loop]);
	}
	Element.addClassName(documentBody, selectedSwatchClass);
	setCookie(entSiteName + 'PageBackground', selectedSwatchClass, 365);
}

function showSiteSwatches(eventData) {
	var theSwatches = $$('#topNavigationRight .themeSwitcher');
	if (theSwatches.length) Element.show(theSwatches[0]);
	if (eventData) Event.stop(eventData);
}

function hideSiteSwatches(eventData) {
	var theSwatches = $$('#topNavigationRight .themeSwitcher');
	if (theSwatches.length) Element.hide(theSwatches[0]);
	if (eventData) Event.stop(eventData);

    // Send through last colour chosen to hitbox
    if(typeof(_hbLink) != 'undefined' && colourChangerLastChosen != '') _hbLink(colourChangerHitBoxModuleName, colourChangerLastChosen);
}

function initSiteBackground() {
	var chooseColourText = 'Change Background';
    var colourChangerOpenerHitBoxAttribute = ' name="&lid=' + colourChangerHitBoxModuleName + '&lpos=' + colourChangerHitBoxModuleName + '_openChanger"';

	var topNavRight = $('topNavigationRight');
	if (topNavRight) {
		var themeSwitcherHTML = '<li class="navSeperator">|</li><li id="topNavColourChangerLink" class="styleSwitch"><a href="#" class="noBorder chooseColourLink"' + colourChangerOpenerHitBoxAttribute + '>' +
                                '<span>' + chooseColourText + '</span></a><span class="themeSwitcher" style="display: none;">';
		themeSwitcherHTML += '<a href="#" class="closeButton"></a>';
		themeSwitcherHTML += '<span class="swatchWrapper">';
		for (var loop=0, max=themeArray.length; loop<max; loop++) {
			themeSwitcherHTML += '<a href="#" class="' + themeArray[loop] + (loop == max - 1 ? ' lastItem' : '') + '"></a>';
		}
		themeSwitcherHTML += '</span>';
		themeSwitcherHTML += '</span></li>';
        var positionToInsert = $('topNavNewsletterLink');
        Element.insert(positionToInsert, {after: themeSwitcherHTML});
	}
	var chooseColourLink = $$('#topNavigationRight .chooseColourLink');
	if (chooseColourLink.length) Event.observe(chooseColourLink[0], 'click', showSiteSwatches);

	var closeSwatchLink = $$('#topNavigationRight .closeButton');
	if (closeSwatchLink.length) Event.observe(closeSwatchLink[0], 'click', hideSiteSwatches);

	var themeSwatches = $$('#topNavigationRight .swatchWrapper a');
	for (var loop=0, max=themeSwatches.length; loop<max; loop++) {
		Event.observe(themeSwatches[loop], 'click', setSiteBackground);
	}

	// We no longer need to set this client-side as we do it server-side to avoid flicker when changing from default red to user-selected theme
	// setSiteBackgroundDetails(getSiteBackground(entSiteName + 'PageBackground'));
}

function setCookie(cookieName, cookieValue, expireDays) {
	var expireDays = expireDays || 365;
	var today = new Date();
	var expires_date = new Date( today.getTime() + (expireDays * 1000 * 60 * 60 * 24));
	document.cookie = cookieName + "=" + escape(cookieValue) + ";path=/;expires=" + expires_date.toGMTString();
}

function getSiteBackground(check_name) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	for ( i = 0; i < a_all_cookies.length; i++ ) {
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		if ( cookie_name == check_name ) {
			b_cookie_found = true;
			if ( a_temp_cookie.length > 1 ) {
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if (!b_cookie_found) {
		return themeArray[0];
	}
}

moduleManager.registerModuleLoad(initSiteBackground);
