// FIXME back-button and product-container: only nice on FF3
// FIXME safari -> disabled: safari-Bugs: back-button
// FIXME safari -> disabled: opera-Bugs: hash-update???

// Working FF3, FF4, Chrome, IE6, IE7, IE8, IE9

(function(topWin) {
	// create topWin.ehHashUrls{} only in top-window
	var ua = {};
	try {
		if (topWin.location.href !== topWin.top.location.href) { return; }
		ua = (function() {
			var rwebkit = /(webkit)[ \/]([\w.]+)/,
				ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
				rmsie = /(msie) ([\w.]+)/,
				rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
				ua = navigator.userAgent.toLowerCase();

			var match = rwebkit.exec(ua) ||
				ropera.exec(ua) ||
				rmsie.exec(ua) ||
				(ua.indexOf("compatible") < 0 && rmozilla.exec(ua)) ||
				[];

			var result = { browser: match[1] || "", version: match[2] || "0" };
			if (result.browser === "webkit") {
				if (/\bchrome\b/.test(ua)) {
					result.browser = "chrome";
				} else if (/safari/.test(ua)) {
					result.browser = "safari";
				}
			}
			return result;
		}());
	} catch (e) {
		return;
	}
	if (topWin.ehHashUrls) { return; }
	var fixedLocationSearch = function(location) {
		// needed for IE6
		if (location && location.href) {
			var m = location.href.match(/[^#\?]*(\?[^#]*)?(#.*)?/);
			var search = m[1] || '';
			return search;
		}
		return '';
	}
	var fixedLocationHash = function(location) {
		// needed for IE6
		if (location && location.href) {
			var m = location.href.match(/[^#\?]*(\?[^#]*)?(#.*)?/);
			var hash = m[2] || '';
			hash = hash.replace('%23', '#'); // needed for safari
			return hash;
		}
		return '';
	}
	// check for browser compatibility
	var updateHashes = (ua.browser === 'msie' || ua.browser === 'mozilla' || ua.browser === 'chrome');
	var emptyHashIsWorking = (ua.browser !== 'msie');
	if (fixedLocationSearch(topWin.location) && !fixedLocationSearch(topWin.location).match(/&EHhashUrls=force(&|$)/i)) {updateHashes =  false; } // don't update hashes if there are query-params
	// FIXME function recommendWin()
	
	// create topWin.ehHashUrls{}
	var lastHash = '';
		
	var hashchange = function() {
		var hash = fixedLocationHash(topWin.location);

		if (hash !== false && hash !== lastHash) {
			lastHash = hash;
			var match = hash.match(/^#([^?]+)\/([^?\/]+)(\?[^#]*)?(\#.*)?$/);
			var url = '';
			if (match && (match[1] === 'page/id' || match[1] === 'page')) {
				if (topWin.contentpath) { url = topWin.contentpath + match[2] + decodeSearch(match[3] || '') + decodeHash(match[4] || ''); }
			}
			if (match && (match[1] === 'products/id' || match[1] === 'products' || match[1] === 'product/id' || match[1] === 'product')) {
				if (topWin.SCproductpath) { url = topWin.SCproductpath + "contentview/" + match[2] + decodeSearch(match[3] || '') + decodeHash(match[4] || ''); }
			}
			if (url && topWin.frames && topWin.frames.fContent) {
				topWin.frames.fContent.location.replace(url);
			}
		}
	};

	// register hashchange as event
	if (topWin.attachEvent) {
		topWin.attachEvent("onhashchange", hashchange);
	} else if (topWin.addEventListener) {
		topWin.addEventListener("hashchange", hashchange, false);
	}
	if (topWin.addEventListener) {
		topWin.addEventListener("popstate", hashchange, false);
	}
	window.setInterval(hashchange, 200);
	
	var encodeSearch = function(txt) {
		txt = txt.replace(/&EHhashUrls=force(&|$)/i, '$1');
		txt = txt.replace(/^\?Open&/, '?');
		return txt;
	};
	var decodeSearch = function(txt) {
		if (!txt.match(/^\?open/i)) { txt = txt.replace(/^\?/, '?Open&'); }
		//txt = txt.replace(/^\?open/i, '?Open').replace(/&&+/, '&');
		return txt;
	};
	var encodeHash = function(txt) {
		return txt;
	};
	var decodeHash = function(txt) {
		return txt;
	};
	topWin.ehHashUrls = {
		computeHash: function(w, prefix) {
			var homeUNID;
			try { 
				homeUNID = topWin.menu[0][0][3];
				// DACH
				if (homeUNID == "parent.startinit(1);" && topWin.homepage && topWin.homepage.length) {
					homeUNID = topWin.homepage[0][2];
				}
			} catch (e) {}
			if (topWin.activeEntry === -1 && homeUNID === w.docUNID) {
				// empty hash for homepage (topWin.activeEntry === -1 is not enough as it's true for singlepages also)
				// but only if we didn't have a hash before
				return (fixedLocationHash(topWin.location) && !emptyHashIsWorking? "#": "");
			}
			var pageName = '', i;
			var links = w.document && w.document.getElementsByTagName && w.document.getElementsByTagName('link');
			if (links && links.length) {
				for(i = 0; i < links.length; ++i) {
					var link = links.item(i);
					if (link && link.getAttribute && link.getAttribute('rel') === 'canonical') {
						var match = (link.getAttribute('href') || '').match(/\/contentview\/([^?]+)/i);
						if (match) { pageName = match[1]; }
						if (w.docUNID === pageName) { pageName = ''; }
						break;
					}
				}
			}
			if (pageName && w.docUNID) {
				if (!topWin.navAlias) { topWin.navAlias = {}; }
				topWin.navAlias[pageName] = w.docUNID;
			}
			if (/\/contentview\//i.test(w.location.pathname) && (pageName || w.docUNID)) {
				// FIXME testing not content-view - no UPDATE
				return '#' + (prefix || 'page') + '/' + (pageName? pageName: 'id/' + w.docUNID) + encodeSearch(fixedLocationSearch(w.location) || '') + encodeHash(fixedLocationHash(w.location) || '');
			}
			else {
				return false;
			}
		},
		getInitialContent: function(w) {
			var match = (fixedLocationHash(w.location) || '').match(/^#([^?]+)\/([^?\/]+)(\?[^#]*)?(\#.*)?$/);
			if (match && (match[1] === 'page/id' || match[1] === 'page')) {
				return topWin.contentpath + match[2] + decodeSearch(match[3] || '') + decodeHash(match[4] || '');
			}
		},
		addExternalStructure: function(w, path) {
			// callback for direct jump to external structure
			var match = (fixedLocationHash(w.location) || '').match(/^#([^?]+)\/([^?\/]+)(\?[^#]*)?(\#.*)?$/);
			if (match && (match[1] === 'products/id' || match[1] === 'products' || match[1] === 'product/id' || match[1] === 'product')) {
				addExternalStructure(path, '', match[2] + decodeSearch(match[3] || '') + decodeHash(match[4] || ''));
				return true;
			}
		},
		loadFrameset: function(w, prefix, docPath) {
			if (updateHashes) {
				// callback for loading frameset with current page as initial page
				var hash = this.computeHash(w, prefix);
				if (hash !== false) {
					topWin.location.replace((docPath || w.docPath).replace(/\.nsf$/, '.nsf/') + hash);
					return true;
				}
			}
		},
		updateFrameset: function(w, prefix) {
			var hash = this.computeHash(w, prefix);

			topWin.lastProductContainerURL = '';
			topWin.lastProductContainerDocId = '';
			
			if (updateHashes) {
				// callback for updating the hash for the frameset
				if (hash !== false) {
					lastHash = hash;
					var url = topWin.location.href.replace(/#.*$/, '') + hash;
					if (topWin.location.href !== url) {
						if (topWin.history && topWin.history.replaceState) {
							topWin.history.replaceState(null, null, url);
						} 
						else  {
							// FIXME reload on home
							topWin.location.replace(url);
						}
					}
					// make sure lastHash is encoded the way ths browser does it
					lastHash = fixedLocationHash(topWin.location);
				}
			}
		},
		rewriteProductContainerURL: function(url, w) {
			var fontsize = 11;
			url = url.replace(/[&\?]fontsize=[^&]*/i, '');
			try {
				topWin.lastProductContainerURL = url;
				topWin.lastProductContainerDocId = w && w.doc_id;
			} catch (e) {}
			try {
				fontsize += Number(topWin.frames['fTopnav'].fontSize || 0);
			} catch (e) {}
			if (url.indexOf('?') < 0) {
				url += "?";
			} else {
				url += "&";
			}
			url += "fontsize=" + fontsize
			if (w && w.location && fixedLocationSearch(w.location)) {
				var params = fixedLocationSearch(w.location);
				if (params.match(/^\?open/i)) {
					url += params.replace(/^\?open[^&]*/i, '');
				}
			}
			return url;
		}
	};	
}(window));
