/**
 * Called from Product Special to set the items display in the menu on the left
 */
function setMenuItems(items, clear) {
	var menu = getMenuElem();
	if (clear) {
		menu.innerHTML='';
	}
	var special = window.flashcontent || document.flashcontent;
	items.each(function(item) {
		var a = new Element('a', {href: '#' + item.ref, id: getItemId(item.ref)});
		a.onclick = function(ev) {
			selectLink(this);
			special.menuItemSelected(item.ref);
			return false;
		};
		a.ref = item.ref;
		a.innerHTML = item.label;
		var li = a.wrap('li');
		if (item.selected) {
			li.addClassName('selected');
		}
		menu.appendChild(li);
	});
	txt2img.insertImages();
	if (items.length === 0) {
		menu.style.visibility = 'hidden';
		menu.next().style.visibility = 'hidden';
	}
	else {
		menu.style.visibility = 'visible';
		menu.next().style.visibility = 'visible';
	}
}

/**
 * Called from setMenuItem(s) to extract menu item id
 */
function getItemId(ref) {
	return 'item-'+ ref.replace(/\//g, '');
}

/**
 * Called from Product Special to activate the given item represented by its
 * href
 */
function selectMenuItem(ref) {
	var menu = getMenuElem();
	var a = menu.down('a#' + getItemId(ref));
	if (a) {
		selectLink(a);
	}
}

/**
 * Called selectMenuItem to set selected state of give <a> Element and update
 * txt2img
 */
function selectLink(a) {
	if (a && !a.match('.selected a')) {
		var menu = getMenuElem();
		menu.select('li.selected').each(function (el) {
			el.removeClassName('selected');
			el = el.down('a');
			el.style.color = '#158fe1';
			el.txt2img.updateSelector();
			
		});
		a.up('li').addClassName('selected');
		a.style.color = '#131f43';
		a.txt2img.updateSelector();
	}
}

/**
 * This is a hook for content-related teaser to activate a given menu item
 * represented by its href
 */
function externalSelect(ref) {	
	var special = window.flashcontent || document.flashcontent;
	var menu = $('menu');
	if (menu) {
		var a = menu.down('a#' + getItemId(ref));
		if (a && special) {
			special.menuItemSelected(a.ref);
			selectLink(a);
		}
	}
}

/**
 * Returns the currently selected product, this only works on pages with tabs,
 * if your Product Special needs this id, pleas call #getProductIdForPS()
 * 
 * @REVISIT: is this function still in use, or #getProductIdForPS() only
 */
function getSelectedProduct() {
	if (window.tabs) {
		return tabs.activeTab.hash.match(/#product(\d+)/)[1];
	}
	return null;
}

/**
 * Called from Product Special to switch to a product tab, represented by 
 * product id
 */
function selectProduct(id) {
	if (window.tabs) {
		tabs.activateHref('#product' + id);
		if (changeSpecial('product' + id)) {
			SWFAddress.setValueAndProduct('product' + id);
		}
		else {
			restoreDeeplink('product' + id);
		}
	}
}

/**
 * Creates the wrapper for the menu, called by #setMenuItems()
 */
function getMenuElem() {
	var menu = $('menu');
	if (menu == null) {
		menu = new Element('ul', {id: 'menu'});
		$('menuBox').insert({after: menu});
		menu.insert({after: new Element('div', {'class': 'divider'})});
	}
	return menu;
}

/**
 * Hold the settings for all special for the different tabs
 */
var specialSettings = null;
/**
 * Hold the current active special url
 */
var currentSpecialUrl = null;
/**
 * Hook for single product pages, return their (only) product id
 */
var singleProductId = null;


/**
 * Called form Product Special, returns the currently selected product, 
 * this works on all product pages,single product pages also return their 
 * (only) prodduct id
 */
function getProductIdForPS() {
	var id = getSelectedProduct();
	if (!id) {
		id = singleProductId;
	}
	return id;
}

/**
 * Changes the current special display, if there is a different special 
 * configured for the new tab 
 */
function changeSpecial(tab) {
	var specialUrl = getSpecial(tab);
	if (specialUrl != currentSpecialUrl) {
		var menu = $('menu');
		if (menu) menu.remove();
		var s = specialSettings;
		
		if (specialUrl.endsWith('.swf')) {
			NFM.insertFlashMovie(specialUrl, 'flashcontent', s.width, s.height, 
					s.minFlashVersion, s.flashVars, s.params, {id: "flashcontent"});
		}
		else {
			$('flashcontent').replace('<div id="flashcontent" style="visibility:visible"><img src="' 
					+ specialUrl +'" width="' + specialSettings.width +'" height="' + specialSettings.height +'" alt="" /></div>');
		}
		var result = currentSpecialUrl != null;
		currentSpecialUrl = specialUrl;
		return result;
	}
	return false;
}

/**
 * Updates the Product Special; changes the special if needed, otherwise 
 * updated the current special, that an new product tab has been activated, so
 * the product special can react on this. Called from tab onClick Listener
 */
function updateSpecial(tab) {
	var restore = currentSpecialUrl != null;
	if (changeSpecial(tab)) {
		if (SWFAddress.setValueAndProduct) {
			SWFAddress.setValueAndProduct(tab);
		}
	}
	else {
		notifySpecial(tab);
		if (restore) {
			restoreDeeplink(tab);
		}
	}
}

/**
 * Restores the Product Special SWFAddress Deeplink (everything behind #product1245),
 * so if the tab is changed, the product special does not change its state 
 * (which would mean, goto start)
 */
function restoreDeeplink(tab) {
	var v = SWFAddress.getValue();
	var i = v.indexOf("/");
	if (i != -1) {
		v = v.substring(i);
		SWFAddress.setValueAndProduct(tab, v);
	}
	else {
		SWFAddress.setValueAndProduct(tab);
	}
}

/**
 * Returns the current active Product Special (Url), called from #changeSpecial()
 */
function getSpecial(tab) {
	if (specialSettings && specialSettings.specials) {
		if (tab && specialSettings.specials[tab]) {
			return specialSettings.specials[tab];
		}
		return specialSettings.specials.defaultSpecial;
	}
	return null;
}

/**
 * Notifies the current special, that the tab (current product) changed
 */
function notifySpecial(tab) {
	var special = window.flashcontent || document.flashcontent;
	if (special && special.productSelected) {
		var match = /product(\d+)/.exec(tab);
		if (match) {
			special.productSelected(match[1]);
		}
	}
}

/**
 * Updates the document title, addes the current product title
 */
function updateTitle(tab) {
	var el = $('tab-'+ tab);
	if (el) {
		el = el.down('.summary h3');
		var title;
		if (el.txt2img) {
			title = el.txt2img.text; 
		}
		else {
			title = el.innerHTML;
		}
		document.title = originalDocumentTitle + ' - ' +  title;					
	}
	else {
		document.title = originalDocumentTitle;
	}
}

function patchSWFAddress() {
	// This is a fix for Safari
    if (/webkit/.test(navigator.userAgent.toLowerCase())) {
    	location['swfaddress'] = {};
    }
	//SWFAddress.setHistory(false); // Produces error in Safari
	SWFAddress.setStrict(false); // Allow hashes that don't start with '/'
	
	// Original version
	SWFAddress.setValueInternal = SWFAddress.setValue;
	
	// Adds the currently selected product id
	SWFAddress.setValueAndProduct = function (tab, value) {
		value = value || '';
		if (!value.match(/^\/.*/)) {
			value = '/' + value;
		}
		SWFAddress.setValueInternal(tab + value);
		return value;
	}
	
	// Adds the product id and tracks a page view
	SWFAddress.setValue =  function (value) {
		var tab = tabs.activeTab.hash.substring(1);
		if (value && !value.indexOf('/') == 0) {
			// This happens in IE8 which registers a onhashchange listener
			// and calls setValue
			tab = value.substring(0, value.indexOf("/"));
			value = value.substring(value.indexOf("/"));
		}
		var saneValue = SWFAddress.setValueAndProduct(tab, value);
		var special = getSpecial()
			.replace(/http:\/\/.*?\/(.*)\/[^\/]*/, '$1') // http://ag1.nivea.com/specials/foo/bar/swf/preloader.swf -> specials/foo/bar/swf
			.replace(/(specials\/)?(.*?)(\/swf|$)/, '$2') // specials/foo/bar/swf -> foo/bar
			.replace(/\//g, ':'); // foo/bar -> foo:bar;
		Omniture.trackSubPageView('/' + special + saneValue);
	}
}
/**
 * Document observer; 
 * 1.) 	Creates tabs if need
 * 2.) 	Calls patchSWFAddress which adds/overwrites setValue() functions
 * 3.)	Adds a SWFAddress change listener, to switch the product tab (and special
 * 		if needed), if the hash changes 
 */
document.observe('dom:loaded', function() {
	if (window.Tabs) {
		originalDocumentTitle = document.title;
		patchSWFAddress();
		window.tabs = new Tabs('tabs', function(href) {
			var tab = /#(.*)$/.exec(href)[1];
			if (tab) {
				updateTitle(tab);
			}			
			updateSpecial(tab);			
		});
		SWFAddress.addEventListener(SWFAddressEvent.CHANGE, function () {
			var url = SWFAddress.getValue();
			// If the info tab for a product range is shown, track page view
			if (url.lastIndexOf('rangeInfo') > -1) {
				Omniture.setProduct();
				Omniture.trackSubPageView("");
			}
			else {
				var match = /product(\d+)/.exec(url);
				// If a product tab is shown
				if (match) {
					var id = match[1];
					if ($('tab-product'+ id)) {
						tabs.activateHref('#product' + id);
						changeSpecial('product' + id);
						updateTitle('product' + id);
						var productName = $('tab-product'+id).down('.summary object.productName').readAttribute('name');
						Omniture.setProduct(productName);
						Omniture.trackSubPageView('/product/' + productName); // TODO Use int product name instead of id
					}
				}
			}
		});
	}
	else {
		updateSpecial();
	}
});
