var msSltLinkRewriter = function() {
	this.handle = window.location.pathname;
	this.sltLinks = new Array();
	this.domReady = false;
	this.currentSltHandle = "";
	this.currentTargetHandle = "";
	
	this.addSltLink = function(slt, target) {
		var index = this.sltLinks.length;
		this.sltLinks[index] = new Object();
		this.sltLinks[index].slt = slt;
		this.sltLinks[index].target = target;
	};
	
	this.getRelativeURL = function(from, target, linkToFile) {
		var index = 0;
		for (var i = 0; i < target.length; i++) {
			if (i >= from.length) break;
			if (from.charAt(i) != target.charAt(i)) break;
			if (from.charAt(i) == '/') index = i;
		}
		
		// Return target if there are no equals parts
		if (index == 0) return target;
		
		// Build directory change
		var prefixFrom = from.substring(index + 1);
		var prefixTarget = target.substring(index + 1);
		var relPath = "";
		for (var i = 0; i < prefixFrom.length; i++) {
			if (prefixFrom.charAt(i) == '/') {
				relPath += "../";
			}
		}
		
		// Check to append target prefix path
		if (linkToFile) {
			relPath += prefixTarget;
		} else if (prefixTarget.lastIndexOf('/') != -1) {
			relPath += prefixTarget.substring(0, prefixTarget.lastIndexOf('/'));
		}
		
		// Return relative path
		return relPath;
	};
	
	this.replaceSltLinks = function() {
		// Retrieve links from page and rewrite the url
		var aTags = document.getElementsByTagName("a");
		for (i = 0; i < aTags.length; i++) {
			var href = aTags[i].getAttribute("href");
			if (!href) continue;
			
			// Remove hostname from href
			var host = aTags[i].hostname;
			if (href.indexOf(host) != -1) {
				var pos = href.indexOf(host) + host.length;
				href = href.substring(pos);
			}
			
			for (j = 0; j < this.sltLinks.length; j++) {
				var slt = this.sltLinks[j].slt; 
				var target = this.sltLinks[j].target;
				if (href.length >= target.length) {
					// Check if the path matches (starts with target)
					if (href.substring(0, target.length) != target) continue;
					
					// Get relative paths and append it on the slt link
					var relPathToSlt = this.getRelativeURL(this.handle, slt, false);
					var relPathToTarget = this.getRelativeURL(target, href, true);					
					var newPath = ((relPathToSlt != "") ? relPathToSlt + "/" : "") + relPathToTarget;
					newPath = newPath.replace(/\/\//, "/");
					
					// Replace the href attribute
					aTags[i].setAttribute("href", newPath);
					break;
				}
			}
		}
	};
	
	this.getSltTargetUrl = function(url) {
		var relPathToSlt = this.getRelativeURL(this.handle, this.currentSltHandle, false);
		var relPathToTarget = this.getRelativeURL(this.currentTargetHandle, url, true);					
		var newPath = ((relPathToSlt != "") ? relPathToSlt + "/" : "") + relPathToTarget;
		newPath = newPath.replace(/\/\//, "/");
		return newPath;
	};
	
};