var openingPreview;
var selectedCategoryClassName;
var previouslySelectedCategory;
var themePreviewDisplay = null;
var selectedThemeRequiresPurchase ;

function cleanupSWF() {
    themePreviewDisplay.cleanup();
}

var themePreview = function() {
	var previewCallback = function(o) {
		streamName = o.responseXML.getElementsByTagName('url')[0].firstChild.data;
		actuallyShowPreview();
	}

	function macFFHack() {
		if (!browser.isMac) {
			return;
		}
		// this code is here to undo a "fix" for Mac FF in the YUI library which actually causes more harm -
		// prior to hiding the panel it runs the below code which modifies the "overflow" property;
		// unfortunately this causes the SWF to refresh in FF (and re-ping the preview URL).
		// should be safe since we don't need to worry about scrolling in this popup.
		var el = YAHOO.util.Dom.get(panel.id).parentNode;
		YAHOO.util.Dom.removeClass(el, 'show-scrollbars');
		YAHOO.util.Dom.addClass(el, 'hide-scrollbars');
	}

	function actuallyShowPreview() {
		macFFHack();

		var flashVars = '&autoPlay=true&streamName=' + (contextPath ? contextPath + streamName : streamName);
        themePreviewDisplay = FlashEmbed.playThemePreview('themePreviewDisplay', flashVars);
		openingPreview = false;
	}

	function activatePreview() {
		if (streamName) {
			actuallyShowPreview();
		} else {			
			var url = "project_get_preview_url?work_id=" + workIdentifier + "&template_id=" + themeIdentifier;
			OTMConnection.connect('GET', url, previewCallback, genericError, null, null);
		}
	}

	function deactivatePreview() {
		cleanupSWF();
		YAHOO.util.Dom.get('themePreviewDisplay').innerHTML = '';
	}

	var panel;
	function init() {
		panel = new YAHOO.widget.Panel("theme_preview", {
			fixedcenter: true,
			draggable: false,
			visible: false,
			close: true,
			modal: true,
			underlay: "none",
			zIndex: 101
		});

		// sets up listener to hide the panel if ESC is pressed
		var kl = new YAHOO.util.KeyListener(document, { keys:27 }, { fn:panel.hide, scope:panel, correctScope:true });
		panel.cfg.queueProperty("keylisteners", kl);

		YAHOO.util.Dom.setStyle(['theme_preview'], 'display', 'block');

		panel.render();

		var onPreviewHide = function() {
			deactivatePreview();
		}

		panel.beforeHideEvent.subscribe(onPreviewHide, panel);

		var onPreviewShow = function() {
			activatePreview();
		}

		panel.showEvent.subscribe(onPreviewShow, panel);
	}

	YAHOO.util.Event.onDOMReady(init);

	var streamName;
	var themeIdentifier;
	var workIdentifier;
	var contextPath;

	return {
		setTitle : function(title) {
			YAHOO.util.Dom.get('popupTitle').innerHTML = title;			
		},
		showPreviewStatic : function(url, context) {
			streamName = url;
			contextPath = context;
			panel.show();
		},
		showPreviewDynamic : function(workId, themeId) {
			streamName = null;

			workIdentifier = workId;
			themeIdentifier = themeId;

			panel.show();
		},
		hidePreview : function() {
			panel.hide();
		}
	}
}();

var selectedTheme;
var themeHolders = new Object();

function drawThemeThumb(theme, handleEvents, includeName) {
	var el = '<div class="styleThumb" style="background-image: url(images/themes/thumb_' + theme.assetName + '.jpg)"';
	if (handleEvents) {
		el += ' onMouseOver="swapThis(this,\'styleThumb over\')" onMouseOut="swapThis(this,\'styleThumb\')" onclick="return onThemeClicked(' + theme.id + ')"';
	}
	el += '>';
	if (includeName) {
		el += '<div>' + theme.name + '</div>';
	}
	el += '<img src="images/void.gif" width="124" height="108" /></div>';

	return el;
}

function appendThemeThumbnail(container, theme) {
	container = (container && container.tagName) ? container : document.getElementById(container);
	container.innerHTML += drawThemeThumb(theme, true, true);		
}

function redrawStyles(themeHolder) {
	var freeThemes = themeHolder.freeThemes;
	var premiumThemes = themeHolder.premiumThemes;

	document.getElementById('freeStylesThumbs').innerHTML = '';
	document.getElementById('premiumStylesThumbs').innerHTML = '';

	var theme;
	var freeDiv = YAHOO.util.Dom.get('freeStylesThumbs');
	for (var i = 0; i < freeThemes.length; i++) {
		theme = freeThemes[i];
		appendThemeThumbnail(freeDiv, theme);
	}
	var premiumDiv = YAHOO.util.Dom.get('premiumStylesThumbs');
	for (i = 0; i < premiumThemes.length; i++) {
		theme = premiumThemes[i];
		appendThemeThumbnail(premiumDiv, theme);
	}

	var showElements = [];
	if (freeThemes.length > 0) {
		showElements.push('freeStyles');
	}
	if (premiumThemes.length > 0) {
		showElements.push('premiumStyles');
	}

	YAHOO.util.Dom.setStyle(showElements, 'display', 'block');
}

function themeFromElement(el) {
	return {
		id: el.getAttribute('id'),
		name: el.getAttribute('name'),
		premium: el.getAttribute('premium'),
		assetName: el.getAttribute('asset_name'),
		requiresPurchase: el.getAttribute('requires_purchase'),
		numSlots: el.getAttribute('num_slots'),
		duration: el.getAttribute('duration'),
		workPassString: el.getAttribute('work_pass_string')
	}
}

function genericError() {
	alert('Error retrieving style data. If this persists, please contact Customer Service.');
	openingPreview = false;
}

var loadingTimeoutId;

function categoryCallback(o) {
	var freeThemes = new Array();
	var premiumThemes = new Array();
	var themes = o.responseXML.getElementsByTagName('theme');
	for (var i = 0; i < themes.length; i++) {
		var themeElement = themes[i];
		var theme = themeFromElement(themeElement);
		if (theme.premium == 'true') {
			premiumThemes.push(theme);
		} else {
			freeThemes.push(theme);
		}
	}
	var themeHolder = {freeThemes: freeThemes, premiumThemes: premiumThemes};
	themeHolders[o.argument[0]] = themeHolder;
	redrawStyles(themeHolder);

//	clearTimeout(loadingTimeoutId);
	YAHOO.util.Dom.setStyle('loading', 'display', 'none');	
}

function onCategoryChange(themeGroupId) {
	previouslySelectedCategory = themeGroupId;

	var selectedName = selectedCategoryClassName ? selectedCategoryClassName : 'cgCategoryActive';
	var deselectedName = selectedCategoryClassName ? '' : 'cgCategoryOff';

	YAHOO.util.Dom.getElementsByClassName(selectedName, '*', 'categoryContainer', function(o) {
		o.className = deselectedName;
	});

	var categoryElement = YAHOO.util.Dom.get('category_' + themeGroupId);
	
	categoryElement.className = selectedName;

	YAHOO.util.Dom.setStyle(['freeStyles', 'premiumStyles'], 'display', 'none');
	
	var themeHolder = themeHolders[themeGroupId];
	if (themeHolder) {
		redrawStyles(themeHolder);
	} else {		
		YAHOO.util.Dom.setStyle('loading', 'display', 'block');
//		loadingTimeoutId = setTimeout(function() {
//		}, 100);
		OTMConnection.connect('GET', 'get_themes_for_theme_group?theme_group_id=' + themeGroupId,
				categoryCallback, genericError, [themeGroupId], null);
	}

	// workaround for FF redraw bug - prevents style thumbnail section of page from overrunning bottom border
	if (YAHOO.env.ua.gecko) {	
		var el = YAHOO.util.Dom.get('cgStyleBox');
		setTimeout(function() {
			el.setAttribute('height', '99%');
			setTimeout(function() {
				el.setAttribute('height', '100%');
			}, 0);
		}, 0);
	}

	return false;
}

function metadataCallback(o) {
	var themeElement = o.responseXML.getElementsByTagName('theme')[0];
	var theme = themeFromElement(themeElement);

	var themeGroups = o.responseXML.getElementsByTagName('theme_group');

	var arg = o.argument;
	var currentThemeIdentifier = arg.currentThemeIdentifier;
	var workIdentifier = arg.workIdentifier;

	drawThemeInfo(theme, currentThemeIdentifier, themeGroups, workIdentifier);

	if (workIdentifier) {
		themePreview.showPreviewDynamic(workIdentifier, theme.id);
	} else {
		themePreview.showPreviewStatic('/themes/' + theme.assetName + 'Preview', '/assets');
	}
}

function drawThemeInfo(theme, currentThemeIdentifier, themeGroups, workIdentifier) {
	if (theme.requiresPurchase == 'true') {
		selectedThemeRequiresPurchase = true;
	} else {
		selectedThemeRequiresPurchase = false;
		if (workIdentifier) {	// otherwise use constant "Buy To Use" class
			var className;
			if (theme.id == currentThemeIdentifier) {
				className = 'reapplystyle';
			} else {
				className = 'applystyle';
			}
			YAHOO.util.Dom.get('confirmButton').className = className;
		}
	}

	themePreview.setTitle('Preview "' + theme.name + '"');
	YAHOO.util.Dom.get('popupThemeName').innerHTML = theme.name;

	YAHOO.util.Dom.setStyle('innerMetadata', 'display', 'block');
	var imageContainer = YAHOO.util.Dom.get('popupThemeThumb');
	imageContainer.innerHTML = drawThemeThumb(theme);

	var blurbContainer = YAHOO.util.Dom.get('popupThemeCategoryList');
	blurbContainer.innerHTML = '';

	if (themeGroups && themeGroups.length > 0) {
		YAHOO.util.Dom.setStyle('popupThemeCategoryContainer', 'visibility', 'inherit');
		for (i = 0; i < themeGroups.length; i++) {
			var themeGroupEl = themeGroups[i];
			blurbContainer.innerHTML += themeGroupEl.getAttribute('name');
			if (i != themeGroups.length - 1) {
				blurbContainer.innerHTML += ', ';
			}
		}
	} else {
		YAHOO.util.Dom.setStyle('popupThemeCategoryContainer', 'visibility', 'hidden');
	}	
}

function showPreview(id, workIdentifier, currentThemeIdentifier) {
	if (openingPreview) {
		return;
	}

	openingPreview = true;

	if (id == '0') {
		var theme = { name: 'No Style', assetName: 'NoTheme' }
		drawThemeInfo(theme);
		themePreview.showPreviewDynamic(workIdentifier, '0');
	} else {
		var arg = new Object();
		arg.workIdentifier = workIdentifier;
		arg.currentThemeIdentifier = currentThemeIdentifier;

		OTMConnection.connect('GET', 'get_theme_metadata?theme_id=' + id,
				metadataCallback, genericError, arg, null);
	}
}

function applyTheme(id, workIdentifier, url) {
	var postApplyUrl = url ? url : 'auth_preview';
	postApplyUrl += postApplyUrl.indexOf('?') > 0 ? '&' : '?';
	cleanupSWF();
	if (workIdentifier) {
		OTMConnection.connect('POST', 'project_apply_theme?work_id=' + workIdentifier,
				function() {
					MM_goToURL('parent', postApplyUrl + 'work_id=' + workIdentifier);
				}, genericError, null, 'theme_id=' + id);
	} else {
		MM_goToURL('parent', postApplyUrl + 'theme_id=' + id);
	}
	return false;
}
