/**
 * @fileoverview tdc object
 */

/**
 * tdc object
 * @class This is the main tdc namespace class
 * @constructor
 */
var tdc = function() {
	return {
		/**
		 * Creates a popup
		 * @param {String} aFile URL to popup
		 * @param {Number} aWidth Width of the popup window
		 * @param {Number} aHeight Height of the popup window
		 * @author Henrik Gemal
		 * @extends tdc
		 */
		popup : function(aURL, aWidth, aHeight, aWindowname) {
			var windowname = aWindowname ? aWindowname : '';
			window.open(aURL, windowname, "width=" + aWidth + ", height=" + aHeight + ", left=150, top=100, resizable=1, scrollbars=1");
		},

		/**
		 * Gets the URL for the i (image and css) server
		 * @param {Boolean} aForceSecure Forces the URL to be the secure one
		 * @returns The URL for the i server fx http://i.c.dk or https://i.tdconline.dk
		 * @type String
		 * @author Henrik Gemal
		 */
		getI : function(aForceSecure) {
			var pro = (location.protocol == "file:" ? "http:" : location.protocol);
			if (pro == "https:" || aForceSecure) {
				return pro + "//i.tdconline.dk";
			} else {
				return pro + "//i.c.dk";
			}
		},

		/**
		 * Redirect function
		 * @param {String} aUrl URL to redirect to
		 * @param {String} aCsref csref to attach on url 
		 * @author kimblim
		 */
		redir : function(aUrl, aCsref) {
			if (typeof(aCsref) != 'undefined' && aCsref != '' && aUrl.indexOf('csref') == -1) {
				delimiter = (aUrl.indexOf("?") > -1) ? "&" : "?";
				aUrl += delimiter + "csref=" + aCsref;
			}	
			top.location.href = aUrl;
		},
		
		/**
		 * toggle display state
		 * @param {Object} aEl which element to show/hide - refer by id
		 * @author kimblim
		 */
		toggleDisplay : function(aEl){
			var currentStyle = tdc.element.getId(aEl).style.display;
			if(currentStyle == "" || currentStyle == "none"){
				tdc.element.getId(aEl).style.display = "block";
			} else {
				tdc.element.getId(aEl).style.display = "none";
			}
		},

		/**
		 * Gets the correct THQ value
		 * @returns The THQ value or false. See <a href="http://wiki.opasia.dk/index.php/THQ">http://wiki.opasia.dk/index.php/THQ</a> for more information
		 * @requires tdc.cookie
		 * @author Henrik Gemal
		 */
		getTHQ : function() {
			var thq = false;
			// try to get the value from the browser object. It should have been set by the http://tdc.dk/js/thq.js.php script
			if (typeof(tdc.browser.thq) != "undefined") {
				// try to get the value from the browser object. It should have been set by the http://tdc.dk/js/thq.js.php script
				var thqor = tdc.cookie.get("thq_override");
				if (thqor) {
					thq = thqor;
				} else {
					thq = tdc.browser.thq;
				}
			} else {
				thq = tdc.cookie.data.get("thq");
			}
			return thq;
		},

		/**
		 * Adds a function to be executed when the document has loaded (on the onload event)
		 * @param {Function} aFunc Function to be executed
		 * @author Henrik Gemal
		 */
		addeventload : function(aFunc) {
			var oldonload = window.onload;
			if (typeof(window.onload) != "function" && typeof(aFunc) == "function") {
				window.onload = aFunc;
			} else {
				window.onload = function() {
					if (oldonload) {
						oldonload();
					}
					if (typeof(aFunc) == "function") {
						aFunc();
					}
				}
			}
		},
		
		/**
		 * Checks to see if the string is a keyword
		 * @param {String} aStr String to check
		 * @returns Is the string a keyword or not
		 * @type Boolean
		 * @author Henrik Gemal
		 */
		isKeyword : function(aStr) {
			if (aStr.search("^[1-9][0-9]{3,3}$") != -1) {
				return true;
			} else {
				return false;
			}
		},

		/**
		 * Include external JavaScript. Be aware that due to the time it takes for the browser to parse the script, the objects, variables, etc in the script may not be accessable right away
		 * @param {String} aFile URL of JavaScript to be loaded
		 * @param {String} aCharset Character set for the JavaScript. Default is ISO-8859-1
		 * @author Henrik Gemal
		 */
		include : function(aFile, aCharset) {
			var charset = aCharset ? aCharset : "ISO-8859-1";
			if (tdc.browser.onmac || tdc.browser.isie || tdc.browser.iswebkit) {
				document.write('<script type="text/javascript" charset="' + charset + '" src="'+ aFile +'"></script>\n');
			} else if (document.createElement && document.getElementsByTagName) {
				var head = document.getElementsByTagName('head')[0];
				var script = document.createElement('script');
				script.setAttribute("type", "text/javascript");
				script.setAttribute("src", aFile);
				script.setAttribute("charset", charset);
				head.appendChild(script);
			}
		},
		
		/**
		 * Include external Stylesheet. 
		 * @param {String} aFile URL of Stylesheet to be loaded
		 * @param {String} aMedia Mediatype of stylesheet (print,screen, etc)
		 * @param {String} aId Id of stylesheet (optional)
		 * @author kimblim
		 */
		addStylesheet : function(aFile,aMedia,aId) {
			var stylesheet = document.createElement('link');
			stylesheet.rel = "stylesheet";
			stylesheet.media = aMedia ? aMedia : "screen";
			stylesheet.href = aFile;
			stylesheet.id = aId ? aId : "";
			document.getElementsByTagName("head")[0].appendChild(stylesheet);
		},

		/**
		 * Checks an object for a type
		 * @param {String} aObj Object to check
		 * @param {String} aType Type to check for. Default is no type and just not undefined
		 * @returns Returns true if object if of the specific type
		 * @type Boolean
		 * @author Henrik Gemal
		 */
		checkObj : function(aObj, aType) {
			var ret = false;
			try {
				if (aType) {
					if (typeof(aObj) == aType) {
						ret = true;
					}
				} else {
					if (typeof(aObj) != "undefined") {
						ret = true;
					}
				}
			} catch(ex) {
			}
			return ret;
		}

	};
}();

/**
 * tdc.cookie object
 * @constructor
 */
tdc.cookie = function() {
	return {

		/**
		 * Return domain part of a URI
		 * @param {String} aUrl URI to search
		 * @returns A string with the domain name
		 * @type String
		 * @author Henrik Schack
		 */
		getDomain : function(aUrl) {
			return aUrl.match(/^(https?:\/\/)?([^\/]+)/i)[2].match(/[^\.\/]+(\.[^\.\/]+)?$/i)[0];
		},

		/**
		 * Gets the value of a cookie
		 * @param {String} aName Name of the cookie
		 * @returns A string with the value of the cookie
		 * @author Henrik Gemal
		 */
		get : function(aName){
			var dc = document.cookie;
			if (!dc) {
				return false;
			}
			var prefix = aName + "=";
			var begin = dc.indexOf("; " + prefix);
			if (begin == -1) {
				begin = dc.indexOf(prefix);
				if (begin != 0) {
					return null;
				}
			} else {
				begin += 2;
			}
			var end = document.cookie.indexOf(";", begin)
			if (end == -1) {
				end=dc.length;
			}
			return unescape(dc.substring(begin + prefix.length,end));
		},

		/**
		 * Sets a cookie
		 * @param {String} aName Name of the cookie to be set
		 * @param {String} aValue Value of the cookie to be set
		 * @param {String} aExpires When the cookie should expire. Default is end of session
		 * @param {String} aPath Pathname for the cookie. Default is nothing
		 * @param {String} aDomain Domain for the cookie. Default is nothing
		 * @param {Boolean} aSecure Is the cookie secure of not. Default is no
		 * @author Henrik Gemal
		 */
		set : function(aName, aValue, aExpires, aPath, aDomain, aSecure) {
			document.cookie = escape(aName) + "=" + escape(aValue) + (aExpires ? "; EXPIRES=" + aExpires.toGMTString() : "") + (aPath ? "; PATH=" + aPath : "") + (aDomain ? "; DOMAIN=" + aDomain : "") + (aSecure ? "; SECURE" : "")
		},

		/**
		 * Deletes a cookie
		 * @param {String} aName Name of the cookie to be deleted
		 * @param {String} aPath Pathname for the cookie. Default is nothing
		 * @param {String} aDomain Domain for the cookie. Default is nothing
		 * @param {Boolean} aSecure Is the cookie secure of not. Default is no
		 * @author Henrik Gemal
		 */
		remove : function(aName, aPath, aDomain, aSecure) {
			document.cookie = escape(aName) + "=null; EXPIRES=" + new Date(0).toGMTString() + (aPath ? "; PATH=" + aPath : "") + (aDomain ? "; DOMAIN=" + aDomain : "") + (aSecure ? "; SECURE" : "")
		}
	};
}();

/**
 * tdc.browser object
 * @constructor
 */
tdc.browser = function() {
	var ua = navigator.userAgent.toLowerCase();
	var uav = navigator.appVersion;
	var cookies;
	var flash;

	return {
		
		/**
		 * Is the browser a Webkit
		 * $type Boolean
		 */
		iswebkit : (ua.indexOf("webkit") != -1),	
		/**
		 * Is the browser a Firefox
		 * @type Boolean
		 */
		isfirefox : (ua.indexOf("firebird") != -1 || ua.indexOf("firefox") != -1 || ua.indexOf("minefield") != -1),
		/**
		 * Is the browser a Internet Explorer
		 * @type Boolean
		 */
		isie : (navigator.appName == "Microsoft Internet Explorer") ? 1 : 0,
		/**
		 * Is the browser a Opera
		 * @type Boolean
		 */
		isopera : (ua.indexOf("opera") != -1),
		/**
		 * Is the browser a Netscape
		 * @type Boolean
		 */
		isnetscape : (navigator.appName == "Netscape") ? 1 : 0,

		/**
		 * Is the browser running on Mac
		 * @type Boolean
		 */
		onmac : (ua.indexOf("mac") != -1),
		/**
		 * Is the browser running on Windows
		 * @type Boolean
		 */
		onwin : (ua.indexOf("windows") != -1),

		/**
		 * Status for the IP Man system. Please see http://wiki.opasia.dk/index.php/THQ for documentation
		 */
		thq : false,

		/**
		 * Get the browser version number. Version 6.7 returns 6
		 * @param {Boolean} aFullversion Get the full version number of just major
		 * @returns A string with the version number
		 * @type String
		 * @author Henrik Gemal
		 */
		getVersion : function(aFullversion) {
			var ver = false;
			if (this.isie) {
				ver = parseFloat(uav.substr(uav.indexOf("MSIE") + 5, 4));
			}
			if (!ver) {
				ver = parseFloat(uav);
			}
			return (aFullversion ? ver : parseInt(ver));
		},

		/**
		 * Get the browser sub version number. Version 6.7 returns 7
		 * @returns A string with the sub version number
		 * @type String
		 * @author Henrik Gemal
		 */
		getVersionSub : function() {
			// convert the number to a string to do string operations
			ver = "" + this.getVersion(1);
			if (ver.indexOf(".") != -1) {
				ver = ver.substring(ver.indexOf(".") + 1);
			} else {
				ver = 0;
			}
			if (!ver) {
				ver = 0;
			}
			return ver;
		},

		/**
		 * Does the browser support Flash
		 * @returns A boolean indicating if the browser supports Flash
		 * @type Boolean
		 * @author Henrik Gemal
		 */
		hasFlash : function() {
			// is the information already available?
			if (typeof(flash) == "undefined") {
				flash = false;
				if (navigator.plugins && typeof(navigator.plugins["Shockwave Flash"]) == "object") {
					flash = parseFloat(navigator.plugins["Shockwave Flash"].description.substring(navigator.plugins["Shockwave Flash"].description.toLowerCase().lastIndexOf("flash ") + 6, navigator.plugins["Shockwave Flash"].description.length))
				} else if (this.isie) {
					document.writeln('<scr' + 'ipt type="text/vbscript">');
					document.writeln('on error resume next');
					document.writeln('set f = CreateObject("ShockwaveFlash.ShockwaveFlash")');
					document.writeln('if IsObject(f) then');
					document.writeln('flashie = parseFloat(hex(f.FlashVersion())/10000)');
					document.writeln('end if');
					document.writeln('</scr' + 'ipt>');
					if (typeof(flashie) != "undefined") {
						flash = flashie;
					}
				}
			}
			return flash;
		},

		/**
		 * Does the browser support cookies
		 * @returns A boolean indicating if the browser supports cookies
		 * @type Boolean
		 * @author Henrik Gemal
		 */
		hasCookies : function() {
			// is the information already available?
			if (typeof(cookies) == "undefined") {
				if (!document.cookie) {
					tdc.cookie.set("cookietest", 1)
					cookies = document.cookie ? true : false;
					tdc.cookie.remove("cookietest");
				} else {
					cookies = true;
				}
			}
			return cookies;
		}
	}

}();



/**
 * tdc.element object
 * @constructor
 */
tdc.element = function() {
	if (document.getElementById) {
		return {
			/**
			 * Get a element
			 * @param {String} aId ID of the element to get
			 * @returns A element with the specified ID
			 * @extends tdc.element
			 * @author Henrik Gemal
			 */
			getId : function(aId) {
				return document.getElementById(aId);
			}
		}
	} else if (document.all) {
		return {
			/**
			 * @ignore
			 */
			getId : function(aId) {
				return document.all[aId];
			}
		}
	} else if (document.layers) {
		return {
			/**
			 * @ignore
			 */
			getId : function(aId) {
				return document.layers[aId];
			}
		}
	} else {
		return {
			/**
			 * @ignore
			 */
			getId : function() {
				return false;
			}
		}
	}

}();

/**
 * tdc.partner object
 * @constructor
 */
tdc.partner = function() {

	var printSnippet = false;

	/**
	 * Converts a ID to a directory name
	 * @param {String} aId ID to convert to a directory name
	 * @returns A string with the directory name
	 * @type String
	 * @author Anders Hal
	 */
	function dirlist(aId, aCount) {
		var idString = '' + aId;
		var dir = '';

		if (aId < 10) {
			if (aCount > 2) {
				dir = '00' + aId;
			} else {
				dir = '0' + aId;
			}
		} else if (aCount > 2 && aId < 100) {
			dir = dir = '0' + aId;
		} else {
			dir = idString.substr(idString.length-aCount);
		}

		var dirlist = '';
		for (var i = (aCount-1); i >= 0; i--) {
			dirlist += '/' + dir.substr(i, 1);
		}

		return dirlist;
	}

	return {

		/**
		 * Holds a array of all loaded snippets
		 * @type Array
		 */
		snippet_arr : new Array(),

		/**
		 * Prints a publish
		 * @param {String} aId ID of the publish to load
		 * @author Anders Hal
		 */
		publish : function(aId) {
			document.write('<script type="text/javascript" src="' + tdc.getI() + '/cms/publish' + dirlist(aId,2) + '/' + aId + '.js"></script>');
		},

		/**
		 * Prints a element
		 * @param {String} aId ID of the element to load
		 * @author Anders Hal
		 */
		element : function(aId) {
			document.write('<script type="text/javascript" src="' + tdc.getI() + '/cms/element' + dirlist(aId,2) + '/' + aId + '.js"></script>');
		},

		/**
		 * Loads a snippet
		 * @param {String} aId ID of the snippet to load
		 * @author Anders Hal
		 */
		loadSnippet : function(aId) {
			document.write('<script type="text/javascript" src="' + tdc.getI() + '/cms/snippet' + dirlist(aId,2) + '/' + aId + '.js"></script>');
		},

		/**
		 * Prints a snippet
		 * @param {String} aId ID of the snippet to load
		 * @author Anders Hal
		 */
		snippet : function(aId) {
			this.printSnippet = true;
			this.loadSnippet(aId);
		},

		/**
		 * Return uri to image
		 * @param {String} aId ID of the image
		 * @param {String} aSize Image size
		 * @returns A string with the directory name or "unknown"
		 * @type String
		 * @author Anders Hal
		 */
		image : function(aId, aSize) {
			var path = tdc.getI() + '/pics' + dirlist(aId,3);
			switch(aSize) {
				case 'miniteaser':
					return path + '/68x51.jpg';
					break;
				case 'maxteaser':
					return path + '/100x75.jpg';
					break;
				case 'teaser':
					return path + '/120x90.jpg';
					break;
				case 'microstandard':
					return path + '/140x105.jpg';
					break;
				case 'smallstandard':
					return path + '/180x135.jpg';
					break;
				case 'ministandard':
					return path + '/192x144.jpg';
					break;
				case 'standard':
					return path + '/220x165.jpg';
					break;
				case 'bigstandard':
					return path + '/292x219.jpg';
					break;
				case 'bigwide':
					return path + '/450x338.jpg';
					break;
				case 'smallwide':
					return path + '/192x72.jpg';
					break;
				case 'org':
					return path + '/org.jpg';
					break;
			}
			return 'unknown';
		}
	}

}();

/**
 * tdc.stats object
 * @constructor
 */
tdc.stats = function() {

	return {

		/**
		 * Add CSREF to href
		 * @param {Object} aObj document.location object
		 * @param {String} aCSRef CSREF
		 * @returns Returns true 
		 * @type Boolean
		 * @author Henrik Schack
		 */
		setref : function(aObj, aCSRef) {
			if (typeof(aCSRef) != 'undefined' && aCSRef != '' && aObj.href.indexOf('csref=') == -1) {
				if (aObj.href.indexOf("?") == -1) {
					aObj.href = aObj.href + "?csref=" + aCSRef;
				} else {
					aObj.href = aObj.href + "&csref=" + aCSRef;
				}
			}	
			return true;
		}
	}

}();

/**
 * tdc.dynmenu object
 * @constructor
 */
tdc.dynmenu = function() {

	return {
		/**
		 * Returns a link created from a dynmenu object
		 * @param {Object} aObj A dynmenu object
		 * @returns A DOM element
		 * @author Henrik Gemal
		 */
		createLink : function(aObj) {
			var ele;
			if (typeof(aObj[1]) != "undefined" && aObj[1] != "") {
				ele = document.createElement("a");
				ele.setAttribute("href", aObj[1]);
				if (typeof(aObj[2]) != "undefined" && aObj[2] != "") {
					ele.setAttribute("title", aObj[2]);
				}
				if (typeof(aObj[3]) != "undefined") {
					if (aObj[3] != "") {
						ele.setAttribute("target", aObj[3]);
					}
				} else {
					ele.setAttribute("target", "_top");
				}
				ele.appendChild(document.createTextNode(aObj[0]));
			} else {
				ele = document.createTextNode(aObj[0]);
			}
			return ele;
		}
	}

}();

/**
 * tdc.cookie.data object
 * @requires tdc.cookie
 * @constructor
 */
tdc.cookie.data = function() {

	/**
	 * Name of the cookie to store the items in
	 */
	var cname = "tdc_data_cookie";

	/**
	 * Path for the cookie
	 */
	var path = "/";

	/**
	 * Get the right cookie domain
	 */
	var domain = tdc.cookie.getDomain(document.location.href);

	/**
	 * Expire time for the cookie
	 */
	var expiretime = (60 * 60 * 24 * 30 * 12);

	/**
	 * Array of the items
	 */
	var jar = new Array();

	/**
	 * Have we loaded the jar yet
	 */
	var inited = false;

	/**
	 * Load all items from the cookie
	 * @returns Returns false if the cookie didn't contain any items, otherwise true
	 * @type Boolean
	 * @author Henrik Gemal
	 */
	function load() {
		var data = tdc.cookie.get(cname);
		if (data) {
			var singlenames = data.split(";;");
			for (var i = 0; i < singlenames.length; i++) {
				var valueline = singlenames[i];
				if (valueline == "") {
					continue;
				}
				var singlevalues = valueline.split("||");
				jar[i] = new Array();
				jar[i][0] = singlevalues[0];
				jar[i][1] = singlevalues[1];
				jar[i][2] = singlevalues[2];
			}
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Save all items into one cookie
	 * @author Henrik Gemal
	 */
	function save() {
		// if we haven't loaded the jar yet do it. this can happen if the user sets a cookie before gettin one
		if (!inited) {
			load();
			inited = true;
		}
		var cookiestring = "";
		if (jar.length > 0) {
			for (var i = 0; i < jar.length; i++) {
				var singlevalue = jar[i];
				if (timestamp() > singlevalue[2]) {
					continue;
				}
				cookiestring += singlevalue[0] + "||" + singlevalue[1] + "||" + singlevalue[2] + ";;";
			}
		}
		// set the cookie if there's anything there, otherwise get rid of it
		if (cookiestring) {
			tdc.cookie.set(cname, cookiestring, new Date((timestamp() + expiretime) * 1000), path, domain);
		} else {
			tdc.cookie.remove(cname, path, domain);
		}
	}

	/**
	 * Get the current timestamp
	 * @returns Returns current timestamp
	 * @type Number
	 * @author Henrik Gemal
	 */
	function timestamp() {
		var myDate = new Date();
		var timestamp = (myDate.getTime()/1000.0);
		return Math.round(timestamp);
	}

	return {

		/**
		 * Set a item in the cookie
		 * @param {String} aName Name of the item
		 * @param {String} aValue Value of the item
		 * @param {String} aExpire Expiration date for the item
		 * @author Henrik Gemal
		 */
		set : function(aName, aValue, aExpire) {
			var nextelement = (jar.length > 0) ? jar.length : 0;
			for (var i = 0; i < jar.length; i++) {
				if (jar[i][0] == aName) {
					nextelement = i;
				}
			}
			jar[nextelement] = new Array();
			jar[nextelement][0] = aName;
			jar[nextelement][1] = aValue;
			jar[nextelement][2] = aExpire; // Hack: aExpire can be type Undefined meaning the item will never be removed
			save();
		},

		/**
		 * Get a item from the cookie
		 * @param {String} aName Name of the item
		 * @returns Returns the value for the item or false
		 * @type String|Boolean
		 * @author Henrik Gemal
		 */
		get : function(aName) {
			load();
			if (jar.length > 0) {
				for (var i = 0; i < jar.length; i++) {
					if (jar[i][0] == aName) {
						if (jar[i][2] > timestamp()) {
							return jar[i][1];
						} else {
							jar.splice(i, 1);
							save();
							load();
						}					
					}
				}
			}
			return false;
		},

		/**
		 * Deletes a item from the cookie
		 * @param {String} aName Name of the item
		 * @returns Returns true
		 * @type Boolean
		 * @author Henrik Gemal
		 */
		remove : function(aName) {
			if (this.get(aName)) {
				for (var i = 0; i < jar.length; i++) {
					if (jar[i][0] == aName) {
						jar.splice(i, 1);
						save();
					}
				}
			}
			return true;
		},

		/**
		 * Get the current timestamp. It just calls the private timestamp function
		 * @returns Returns current timestamp
		 * @type Number
		 * @author Henrik Gemal
		 */
		getTimestamp : function() {
			return timestamp();
		}

	}

}();



/**
 * tdc ajax object
 * @constructor
 * @author kimblim
 */
tdc.ajax = function(){
	
	return {
	
		init : function(){
			var xmlhttp = false;
			/*@cc_on @*/
			/*@if (@_jscript_version >= 5)
			// JScript gives us Conditional compilation, we can cope with old IE versions and security blocked creation of the objects.
			try {
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e) {
				try	{
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(e) {
					xmlhttp = false;
				}
			}
			@end @*/
			if (!xmlhttp && typeof(XMLHttpRequest) != "undefined"){
				try {
					xmlhttp = new XMLHttpRequest();
				}
				catch(e) {
					xmlhttp = false;
				}
			}
			if (!xmlhttp && window.createRequest) {
				try {
					xmlhttp = window.createRequest();
				}
				catch(e) {
					xmlhttp = false;
				}
			}
			return xmlhttp;
		}
	}
}();


/**
 * tdc login object
 * @author Ulrik Hindø
 */
(function() {

	/*
	 * private variables
	 */
	
	var _configuration = {
		'newUserUrl'                       : "https://fastnetselvbetjening.tdconline.dk/Krump/public/onlinereg/showCustomerInformations.do?site=online",
		'forgotPasswordUrl'                : 'http://tdconline.dk/login/glemt/',
		'linkTarget'                       : "top",
		'optionsUrl'                       : 'https://selvbetjening.tdconline.dk/eservice/ditLogin.do',
		'aboutTdcLoginUrl'                 : 'http://tdc.dk/login/',
		'loginTarget'                      : document.location.href,
		'logoutTarget'                     : (location.protocol == "https:" ? "https://" : "http://") + document.location.hostname + '/',
		'extraLoggedOutLinks'              : [],
		'extraLoggedInLinks'			   : [],
		'loggedInInfo'                     : '',
		'loggedOutInfo'                     : '',
		'forceLoggedOut'                   : false
	};
	
	var _linkRedrawCallbacks = [];
	
	var _loginSiteName = 'loginsite';
	if ((new RegExp(';pet')).test(tdc.cookie.get('CoreIdTest'))) {
		_loginSiteName = 'loginsitepet.pp';
	} else if ((new RegExp(';test')).test(tdc.cookie.get('CoreIdTest'))) {
		_loginSiteName = 'loginsitetest';
	} else if ((new RegExp(';udv')).test(tdc.cookie.get('CoreIdTest'))) {
		_loginSiteName = 'loginsiteudv';
	}

	if (document.location.search) (function(){
		var re = new RegExp("[?&]ssologintarget=([^&]+)");
		var value = re.exec(document.location.search);
		if (value && value[1]) {
			_configuration.loginTarget = decodeURI(value[1]);
		}
	})();

	
	tdc.login = function() {
		/*
		 * private methods
		 */
		var _writeHiddenSsoImages = function(returnHtml){
			if (typeof(returnHtml) != 'boolean') {
				returnHtml = false;
			}
			function otherDomains()	{
				var currentDomain = _secondLevelAndTopLevelDomain(document.location.hostname);
				return jQuery.grep(_getSupportedDomains(), function(n){return n != currentDomain;});
			}
			
			function userDataCookieMustBeUpdated() {
				return (/ssouud/).test(document.location.search);
			}			
			
			var delayBeforeInsertingImages = 500; // we don't want to halt everything while waiting for the images to load
			if (tdc.login.isLoggedIn()) {
				jQuery(function(){
					setTimeout(function(){
						var obSSOCookieChangedByWebGate = tdc.cookie.get('ObSSOCookie') != tdc.cookie.get('ObSSOCookie2');
						var allDomains = _getSupportedDomains();
						jQuery.each(allDomains, function(){
							var src = location.protocol +  '//' + _loginSiteName + '.' + this + '/update/';
							if (userDataCookieMustBeUpdated()) {
								src += '?ssouud';
							}
							if (obSSOCookieChangedByWebGate) {
								src += (src.indexOf('?') == -1) ? '?' : '&';
								src += 'r=' + Math.random();
							}
							jQuery('#sso_logout_form_images').append('<img border="0" src="' + src + '" width="1" height="1"');
						});
					}, delayBeforeInsertingImages);
				});		
			} else 	if (_configuration['forceLoggedOut']) {		
				jQuery(function(){
					setTimeout(function(){
						var domainsToLogOut = _configuration['forceLoggedOut'] ? _getSupportedDomains() : otherDomains();
						jQuery.each(domainsToLogOut, function(){
							var src = location.protocol +  '//' + _loginSiteName + '.' + this + '/update/?logout';
							jQuery('#sso_logout_form_images').append('<img border="0" src="' + src + '"');					
						});
						//jQuery('#sso_logout_form_images').append('<img border="0" src="http://musik.tdconline.dk/servlets/2452306090224Dispatch/19/jspinclude?file=/index.jsp&page=logout"');					
					}, delayBeforeInsertingImages);
				});		
			}
			
			var html = '<span id="sso_logout_form_images"></span>';
			if (returnHtml) {
				return html;	
			} else {
				document.write(html);	
			}
		};
		
		var _writeHiddenFields = function(returnHtml) {
			if (typeof(returnHtml) != 'boolean') {
				returnHtml = false;
			}
			var html = '';
			if (tdc.login.isLoggedIn()) {
				html += '<input type="hidden" name="logout_target" value="' + this.logoutTarget + '" />';
			} else {
				html += '<input type="hidden" name="login_target" value="' + this.loginTarget + '" />';
			}
			if (returnHtml) {
				return html;
			} else {
				document.write(html);
			}
		};

		var _isDisabledBecauseOfBrowser = function() {
			var ret = false;
			// disabled older IEs than 5 and IE on Mac
			if (tdc.browser.isie && (tdc.browser.getVersion() < 5 || tdc.browser.onmac)) {
				ret = true;
			// disabled older IEs than 5.5
			} else if (tdc.browser.isie && tdc.browser.getVersion() == 5 && tdc.browser.getVersionSub() < 5) {
				ret = true;
			// disabled older Operas then 7
			} else if (tdc.browser.isopera && tdc.browser.getVersion() < 7) {
				ret = true;
			// disabled older Netscapes than 5
			} else if (tdc.browser.isnetscape && tdc.browser.getVersion() < 5) {
				ret = true;
			// disabled browsers that doesn't support cookies
			} else if (!tdc.browser.hasCookies) {
				ret = true;
			}
			return ret;
		};
		
		
		var _secondLevelAndTopLevelDomain = function(domain)	{
		    var m = domain.match(new RegExp('[^.]+\\.[^.]+$'));
		    return m[0];
		};
		
		var _getSupportedDomains = function() {
			if ((new RegExp(';(test|udv)')).test(tdc.cookie.get('CoreIdTest'))) {
				return ['tdk.dk'];
			}
			return ['tdc.dk', 'tdconline.dk', 'yousee.dk'];
		};
		
		var _redraw = function () {
			var links = [];
			if (tdc.login.isLoggedIn()) {
			} else {
				if (_configuration.newUserUrl) {
					links.push({'name':'Opret TDC Login', 'url':_configuration.newUserUrl});
				}
				if (_configuration.forgotPasswordUrl) {
					links.push({'name':'Glemt password?', 'url':_configuration.forgotPasswordUrl});
				}
				if (_configuration.aboutTdcLoginUrl) {
					links.push({'name':'Om TDC Login', 'url':_configuration.aboutTdcLoginUrl});
				}			
			}
			jQuery.each(tdc.login.isLoggedIn() ? _configuration.extraLoggedInLinks : _configuration.extraLoggedOutLinks, function(){
				links.push(this);
			});
			jQuery.each(_linkRedrawCallbacks, function(){				
				this(links, _configuration.linkTarget, _configuration.loggedInInfo,  _configuration.loggedOutInfo);
			});
		};
		var _addJavascriptToLoginBoxes = function() {
				var templateArguments = tdc.login.loginBoxTemplateArguments();	
			
				jQuery('.t_login_box_addjs form, form.t_login_box_addjs').each(function(){
					var form = jQuery(this);
					if (!templateArguments.isLoggedIn) {
						form.submit(function(){
								var name = form.find(':input[name=usr_name]').val();
								if (!name || name == 'Brugernavn') {
									alert("Du har ikke udfyldt noget Brugernavn");
									return false;
								}
								var password = form.find(':input[name=usr_password]').val();
								if (!password) {
									alert("Du har ikke udfyldt noget Password");
									return false;
								}
								
								return true;
							})
							.attr('action', templateArguments.loginUrl);
						form.find(':input[name=usr_name]')
							.blur(function(){								
								if (this.value == '') {
									this.value = 'Brugernavn';
									jQuery(this).removeClass("t_focus");
								}
							})
							.focus(function(){
								jQuery(this).addClass("t_focus");
								if (this.value == 'Brugernavn') {
									this.value = '';
								}								
							});
						
						form.find(':input[name=usr_name]').each(function() {
							if (this.value == '') {
								if (templateArguments.rememberedUsername != 'null') {
									this.value = templateArguments.rememberedUsername ? templateArguments.rememberedUsername : 'Brugernavn';
								}
							}
						});
							
						form.find(':input[name=usr_password_fake]').show().focus(function(){
							jQuery(this).hide();
							form.find(':input[name=usr_password]').show().get(0).focus();
						});						
						form.find(':input[name=usr_password]').hide().blur(function(){
							if (this.value == '') {
								jQuery(this).hide();
								form.find(':input[name=usr_password_fake]').show();
							}
						});
						if (templateArguments.rememberedUsername) {
							form.find(':input[name=remember_username]').attr('checked','checked');
							form.find(':input[name=usr_name]').addClass("t_focus");
						}
						
					} else {
						form.attr('action', templateArguments.logoutUrl);						
					}

				});
			
		};
		if (typeof(jQuery) == 'function') {
			jQuery(_redraw); // redraw loginbox when page is ready
			jQuery(_addJavascriptToLoginBoxes);
		}
		
		return {		
			/*
			 * public methods
			 */		
			
			setLoginTarget : function(value){
				jQuery('.t_login_box :input[name=login_target]').val(value.toString()); // not sound
				_configuration.loginTarget = value.toString();
			},
			
			setLogoutTarget : function(value){
				jQuery('.t_login_box :input[name=logout_target]').val(value.toString());  // not sound
				_configuration.logoutTarget = value.toString();
			},

			setLinkTarget : function(value){
				jQuery('.t_login_box a').attr('target', '_' + value);  // not sound
				_configuration.linkTarget = value;
			},

			setNewUserUrl : function(value){
				_configuration.newUserUrl = value;
				_redraw();
			},
			
			setForgotPasswordUrl : function(value){
				_configuration.forgotPasswordUrl = value;
				_redraw();
			},
			
			
			setOptionsUrl : function(value){
				_configuration.optionsUrl = value;
				_redraw();
			},
			
			setAboutTdcLoginUrl : function(value){
				_configuration.aboutTdcLoginUrl = value;
				_redraw();
			},
			
			addLoggedOutLink : function(name, url){
				_configuration.extraLoggedOutLinks.push({'name':name, 'url':url});
				_redraw();
			},

			addLoggedInLink : function(name, url){
				_configuration.extraLoggedInLinks.push({'name':name, 'url':url});
				_redraw();
			},

			addRedrawCallback : function (callback) {
				_linkRedrawCallbacks.push(callback);			
			},
			
			setLoggedInInfo : function(html) {
				_configuration.loggedInInfo = html;
				_redraw();
			},
			
			setLoggedOutInfo : function(html) {
				_configuration.loggedOutInfo = html;
				_redraw();
			},
			
			setForceLoggedOut : function(value) {
				_configuration.forceLoggedOut = true;
				_redraw();
			},
			
			/**
			 * Return a map with data and funtions used to draw login/logout boxes
			 *
			 * In case of login the form must post the fields usr_name, usr_password and optionally remember_username
			 */
			loginBoxTemplateArguments : function() {
				var templateArguments;
				var allDomains = _getSupportedDomains();
				var defaultDomain = allDomains[0];

				if ((new RegExp(';test')).test(tdc.cookie.get('CoreIdTest'))) {
					defaultDomain = 'loginsitetest.tdk.dk';
				} else if ((new RegExp(';udv')).test(tdc.cookie.get('CoreIdTest'))) {
					defaultDomain = 'loginsiteudv.tdk.dk';
				}					

				var loginUrl        = 'https://' + defaultDomain + '/login/';					
				var logoutUrl       = (location.protocol == "https:" ? "https://" :"http://") + defaultDomain + '/logout/';
				for (var i=0; i<allDomains.length; i++) {						
					if (_configuration.loginTarget.indexOf(allDomains[i]) != -1) {
						loginUrl        = 'https://' + _loginSiteName + '.'  + allDomains[i] + '/login/';
					}
					if (_configuration.logoutTarget.indexOf(allDomains[i]) != -1) {
						logoutUrl       = (location.protocol == "https:" ? "https://" :"http://") + _loginSiteName + "." + allDomains[i] + '/logout/';
					}
				}
	
				templateArguments = {
					'isLoggedIn'                       : tdc.login.isLoggedIn(),
					'isDisabledBecauseOfBrowser'       : _isDisabledBecauseOfBrowser(),
					'isLoginSystemTemporarilyDisabled' : tdc.login.isLoginSystemTemporarilyDisabled(),
					'userName'                         : tdc.login.getUsername(), //Try to get the login name from the cookie
					'rememberedUsername'               : tdc.cookie.get("SsoRememberedUserName"),
					'loginUrl'                         : loginUrl,
					'logoutUrl'                        : logoutUrl,
					'writeHiddenSsoImagesFunction'     : _writeHiddenSsoImages,
					'writeHiddenFieldsFunction'        : _writeHiddenFields
				};

				for (var key in _configuration) {
					if (typeof(key) != 'function') {
						templateArguments[key] = _configuration[key];
					}
				}		
				
				return templateArguments;
			},
			
			getUsername : function() {
				var name = "";
				var s = tdc.cookie.get("SsoSessionData");
				if (s) {
					name = s.substring(0, s.indexOf(";"));
				}
				return name;
			},

			isLoginSystemTemporarilyDisabled : function() {
				return false;
			},
			isLoggedIn : function() {
				return !!tdc.cookie.get('ObSSOCookie') && tdc.cookie.get('ObSSOCookie') != 'loggedoutcontinue' && !_configuration['forceLoggedOut'];
			},
			setUseLoginsitePet : function(useLoginsitePet) {
				_loginSiteName = useLoginsitePet ? 'loginsitepet.pp' : 'loginsite';
			}
		};		
	}();
})();



function popup(aURL, aWidth, aHeight, aWindowname) {
	tdc.popup(aURL, aWidth, aHeight, aWindowname);
}

function getEle(aId) {
	return tdc.element.getId(aId);
}

function getTHQ() {
	return tdc.getTHQ();
}

function setTDCRef(obj,csref) {
	return tdc.stats.setref(obj, csref);
}
function entity_encode (str) {  
    return str ? str.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;") : str; 
}
