/**
 * Forsikringsguiden Application
 * @author	 		Netcompany - mel
 * @created			25-04-2006 21:00 
 * @revised			12-10-2007 16:39
*/
var App = {
	
	_$:function(s){ return document.getElementById(s)!=null?document.getElementById(s):false; },
	$:function (o){
		if(typeof o=="string"){
			var s=o.split("|"),a=[];
			if(s.length==1) return App._$(s[0]);
			for(var i=0; i<s.length; i++) a.push(App._$(s[i]));
			o=a;
		}
		return o; 
	},

	extend:function(o,p){ // TODO: is this used anywhere?
		var p=p?p:this;
		for(var i in o) p[i]=o[i];
	},
			
	show:function(o){
		var o=App.$(o),d="block";
		if(!App.Browser.msie){ // normalize display value for table elements
			switch(o.nodeName){
				case "TR":
					d = "table-row";
					break;
				case "TD":
					d = "table-cell";
					break;
				case "TABLE":
					d = "table";
					break;
				case "TBODY":
					d = "table-row-group";
					break;
			}
		}
		this.setCss(o,{display:d});
		return o;
	},
	
	hide:function(o){
		var o = App.$(o);
		if(o.length>1){
			for(var i=0; i<o.length; i++) this.setCss(o[i],{display:"none"}); 
			return o; 
		} else {
			this.setCss(o,{display:"none"});
		}
		return o;
	},

	toggle:function(o){
		var d=o.style.display=="block"||o.style.display==""?"none":"block";
		this.setCss(o,{display:d});
		return o;
	},
	
	toggleTableRow:function(o){
		var showClass = App.Browser.mozilla ? "table-row":"block";
		var toggleClass = o.style.display == "none" ? showClass : "none";
		this.setCss(o,{display:toggleClass});
		return o;
	},

	empty:function(o){ // TODO: is this used anywhere?
		var o = App.$(o);
		o.innerHTML = "";
		return o;
	},

	fill:function(o,c){ // TODO: is this used anywhere?
		var o = App.$(o);
		o.innerHTML = App.$(c).innerHTML;
		return o;
	},

	getCss:function(o,s){
		var o=App.$(o),r,n;
		if(o.currentStyle){ // ie
			var n = s.split("-");
			for(var i=1; i<n.length; i++) n[i] = n[i].charAt(0).toUpperCase()+n[i].substr(1);
			r=o.currentStyle[n.join("")];
		} else if(document.defaultView && document.defaultView.getComputedStyle){ // ff, saf
			r=document.defaultView.getComputedStyle(o,null).getPropertyValue(s);
		} else { // fallback
			r=o.style[s];
		}
		return r;
	},

	setCss:function(o,s){
		var o=App.$(o);
		if (o) {
			for(var p in s){
				var n = p.split("-");
				for(var i=1; i<n.length; i++) n[i] = n[i].charAt(0).toUpperCase()+n[i].substr(1);
				o.style[n.join("")]=s[p];
			}
		}
	},
	
	addClass:function(o,s){
		var o=App.$(o);
	    App.removeClass(o,s);
	    o.className=(o.className+" "+s).trim();
	    return o;
	},

	removeClass:function(o,s){
		var o=App.$(o);
		o.className = o.className.replace(s,"").trim();
	    return o;
	},
	
	classContains:function(o,s){
		var o=App.$(o),ss=s.split("|");
		for(var i=0; i<ss.length; i++) if(o.className.indexOf(ss[i])!=-1) return true;
		return false;
	},
		
	getAbsLeft:function (o){
		var iY = 0;
		while(o.offsetParent){
			iY += o.offsetLeft;
			o = o.offsetParent;
		}
		return iY;
	},

	getAbsTop:function (o){
		var iX = 0;
		while(o.offsetParent){
			iX += o.offsetTop;
			o = o.offsetParent;
		}
		return iX;
	},
	
	// TODO: refactor with shorter var names
    getPageSize: function (){
	    var xScroll,yScroll,scrollLeft,scrollTop;
    	
		if (self.pageYOffset){ // all except Explorer
			scrollLeft = self.pageXOffset;
			scrollTop = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict
			scrollLeft = document.documentElement.scrollLeft;
			scrollTop = document.documentElement.scrollTop;
		} else if (document.body){ // all other Explorers
			scrollLeft = document.body.scrollLeft;
			scrollTop = document.body.scrollTop;
		}
	    if (window.innerHeight && window.scrollMaxY) {	
		    xScroll = document.body.scrollWidth;
		    yScroll = window.innerHeight + window.scrollMaxY;
	    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		    xScroll = document.body.scrollWidth;
		    yScroll = document.body.scrollHeight;
	    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		    xScroll = document.body.offsetWidth;
		    yScroll = document.body.offsetHeight;
	    }

	    var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
			scrollLeft = document.body.scrollLeft;
	    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		    windowWidth = document.documentElement.clientWidth;
		    windowHeight = document.documentElement.clientHeight;
	    } else if (document.body) { // other Explorers
		    windowWidth = document.body.clientWidth;
		    windowHeight = document.body.clientHeight;
	    }	
    	
	    // for small pages with total height less then height of the viewport
	    if(yScroll < windowHeight){
		    pageHeight = windowHeight;
	    } else { 
		    pageHeight = yScroll;
	    }

	    // for small pages with total width less then width of the viewport
	    if(xScroll < windowWidth){	
		    pageWidth = windowWidth;
	    } else {
		    pageWidth = xScroll;
	    }
	    return {pW:pageWidth,pH:pageHeight,wW:windowWidth,wH:windowHeight,scL:scrollLeft,scT:scrollTop};
    },
	scrollLowerColumns:function(){
	    scrollPos = App.$("col-xx-large").scrollLeft;
	    App.$("col-xx-large2").scrollLeft = scrollPos;
	    window.console.log(scrollPos);
	},
	scrollUpperColumns:function(){
	    scrollPos = App.$("col-xx-large2").scrollLeft;
	    App.$("col-xx-large").scrollLeft = scrollPos;
	    window.console.log(scrollPos);
	},

	/**
	 * A method to easily create new DOM objects and populate them with attributes
	 * @param	{String} sType The type of HTML element to create
	 * @param	{Object} oConfig An object with attributes to attach to the created element
	 * @returns 	The newly created element
	*/
	createElement:function (sType,oConfig){
		var elm = document.createElement(sType);
		for(p in oConfig){
			if(p == "CSSClass"){
				elm.className = oConfig[p];
			} else if(p == "content"){
				try {
					elm.innerHTML = oConfig[p];
				} catch(e){}
			} else if(p == "parent"){
				// do nothing
			} else {
				elm.setAttribute(p,oConfig[p]);
			}
		}
		if(oConfig.parent){
			App.$(oConfig.parent).appendChild(elm);
		} else {
			document.body.appendChild(elm);
		}
		return elm;
	},

	/**
	 * A method to add an event to the onload handler without overwriting prevoiusly set functions
	 * @param	{Function} f The function that is to be attached to the onload queue
	*/
	addLoadEvent:function (f){
		var a = window.onload;
		if(typeof window.onload != "function"){
			window.onload = f;
		} else {
			window.onload = function() {
				a(); f();
			};
		}
	},
	
	getElementsByClassName:function(p,s,t){
		var n,r=[];
		if(t){
			n=p.getElementsByTagName(t.toUpperCase());
		} else {
			n=p.getElementsByTagName("*");
			if(n.length<=0) n=document.all;
		}
		if(n.length>0){
			for(var i=0;i<n.length;i++){
				var t="#"+n[i].className+"#",x="[ |#]"+s+"[ |#]";
				if(t.match(new RegExp(x))){ r.push(n[i]); }
			}
			return r;
		} else {
			return false;
		}
	},
	
	Cache:{
		get:function(s){return this[s];}, 
		set:function(k,v){this[k]=v;},
		init:function(){
			this.set("topZIndex",1000);
			this.set("imagePath","/Style%20Library/Images/fg/");
			this.set("styleLibraryPath","/_layouts/fg/css/");
			this.set("swfPath","/fg/swf/");
			this.set("contentImagesPath","/fg/images/");
		}
	},
	
	Browser:{
		safari:/webkit/.test(navigator.userAgent.toLowerCase()),
		opera:/opera/.test(navigator.userAgent.toLowerCase()),
		msie:/msie/.test(navigator.userAgent.toLowerCase()) && !/opera/.test(navigator.userAgent.toLowerCase()),
		mozilla: /mozilla/.test(navigator.userAgent.toLowerCase()) && !/(compatible|webkit)/.test(navigator.userAgent.toLowerCase())
	},
	
	BrowserVersion: function() {
			version = navigator.appVersion.match(/[\d\.]+/);
			return (version.length > 0) ? version[0] : null;
	},
	
	Page: {
		/**
		 * onDOMContentLoaded, kudos jquery
		*/
		Loader:{
			readyList:[],
			add:function(f){
				App.Page.Loader.readyList.push(f);
			},
			run:function (){
				if(App.Page.Loader.readyList.length>0){
					for(var i=0; i<App.Page.Loader.readyList.length; i++){
						if(typeof App.Page.Loader.readyList[i] === "function"){
							App.Page.Loader.readyList[i].apply(document);
						}
					}
				}
			},
			prepare:function(){
				if(App.Browser.mozilla||App.Browser.opera){
					document.addEventListener("DOMContentLoaded",App.Page.Loader.run,false);
				} else if(App.Browser.msie){
					document.write("<scr" + "ipt id=__ie_init defer=true " + "src=//:><\/script>");
					var script = document.getElementById("__ie_init");
					if(script) 
						script.onreadystatechange = function(){
							if(this.readyState!="complete") return;
							this.parentNode.removeChild(this);
							App.Page.Loader.run();
						};
					script = null;
				} else if(App.Browser.safari){
					var safariTimer = setInterval(function(){
						if (document.readyState=="loaded"||document.readyState=="complete"){
							clearInterval(safariTimer);
							safariTimer = null;
							App.Page.Loader.run();
						}
					},10);
				} else {
					App.addLoadEvent(App.Page.Loader.run);
				}
			}	
		},
		
		setEntranceLinks:function (){
			
			if(!App.Cache.get("editmode")){
				var p = App.getElementsByClassName(document,"entrance"); //get products
				for(var i=0; i<p.length; i++){
					var o = p[i];
					App.addClass(o,"linkcursor");
					o.setAttribute("index",(i+1));
					
					//var img = o.getElementsByTagName("IMG")[0];
					//App.addClass(img,"stretch");
					
					// Get the first link in the webpart and add it's href-att. as a custom prop. to the current <div>
					var aLinks = o.getElementsByTagName("A");
					if(aLinks[0]){ var aTemp = aLinks[0]; o.setAttribute("href",aLinks[0].getAttribute("href")); o.linkref = aTemp; }
									
					// event mouseover
					o.onmouseover = function (e){ 
						try { window.status = this.getAttribute("href"); } catch(e){ /*console.log("Could not set status text."); */} 
						App.addClass(this,"ent-"+this.getAttribute("index")+"-over");
					}
	
					// event mouseout
					o.onmouseout = function (){ 
						try { window.status = window.defaultStatus; } catch(e){}
						App.removeClass(this,"ent-"+this.getAttribute("index")+"-over");
					}
	
					// event click
					o.onclick = function (){ 
						document.location.href = this.getAttribute("href"); 
					}
				}
			}
		}, // @App.Page.setCampaignLinks
		
		createAccessiblePopupLinks:function (){
			var aElms = App.getElementsByClassName(document,"popup");
			var dims = {
			    dict:{w:510,h:520},
			    def:{w:100,h:100},
			    conditions:{w:800,h:800}
			};
			var currentDims;
			for(var i=0; i<aElms.length; i++){
				var o=aElms[i];
				var sHref = o.getAttribute("href");
				o.setAttribute("savedHrefAtt",sHref); // save the href attribute so we can use it in the window.open()
				o.onclick = function (){
					if(sHref != "#" && sHref != ""){
						if(!win){
						    if(o.className.indexOf("dict") != -1){
						        currentDims = "dict";
						    } else {
						        currentDims = "def";
						    }
							var win = window.open(this.getAttribute("savedHrefAtt"),"FP","width="+dims[currentDims].w+",height="+dims[currentDims].h);
						} else {
							win.focus();
						}
						return false; 
					}
				};
			}
		}, // @App.Page.createAccessiblePopupLinks
		
		Tables:{		
			zebratize:function (){
				var oTables = App.getElementsByClassName(document,"stripes");
				for(var i=0; i<oTables.length; i++){
					var oTbodys = oTables[i].getElementsByTagName("TBODY");
					for(var j=0; j<oTbodys.length; j++){
						for(var k=0; tr=oTbodys[j].getElementsByTagName("TR")[k]; k++){
							tr.className = k%2==0?"odd":"even";
						}
					}
				}
			},
			ScrollableTable:{
				init:function (){
					if(App.$("comparison")){ this.resizeColumnWidth(); this.resizeHeight(); }
				},
				resizeHeight:function(){
					var oTbody1 = App.$("comparison-table-1").getElementsByTagName("TBODY");
					var oTbody2 = App.$("comparison-table-3").getElementsByTagName("TBODY");
					if (oTbody1.length > 0 && oTbody2.length > 0) {
						var oTr1 = oTbody1[0].getElementsByTagName("TR");
						var oTr2 = oTbody2[0].getElementsByTagName("TR");
						for(var i=0; i<oTr1.length; i++){
							g1 = oTr1[i].offsetHeight;
							g2 = oTr2[i].offsetHeight;
							if (g1 > g2) {
								oTr2[i].style.height = g1+"px";
							} else if (g2 > g1) {
								oTr1[i].style.height = g2+"px";
							}
						}
						
						//hack to adjust when css height and offset height differs after setting css height
						if (oTbody1 != null && oTbody1.length > 0 && oTbody2 != null && oTbody2.length > 0) {
							var oTr1 = oTbody1[0].getElementsByTagName("TR");
							var oTr2 = oTbody2[0].getElementsByTagName("TR");
							for(var i=0; i<oTr1.length; i++){
								g1 = oTr1[i].offsetHeight;
								g2 = oTr2[i].offsetHeight;
								if (g1 > g2) {
									oTr2[i].style.height = g1+"px";
								} else if (g2 > g1) {
									oTr1[i].style.height = g2+"px";
								}
							}
							
							for (var i=0; i<oTr1.length; i++) {
								var cssHeight1 = App.getCss(oTr1[i], "height").match(/\d+/);
								if (cssHeight1 != null && cssHeight1.length > 0) {
									var offsetHeight1 = oTr1[i].offsetHeight;
									if (offsetHeight1 > cssHeight1[0]) {
										oTr1[i].style.height = cssHeight1[0] - (offsetHeight1 - cssHeight1[0]);
									}
								}
								
								if (oTr2[i].offsetHeight != oTr1[i].offsetHeight) {
									oTr1[i].style.height = oTr2[i].offsetHeight;

									var cssHeight1 = App.getCss(oTr2[i], "height").match(/\d+/);
									if (cssHeight1 != null && cssHeight1.length > 0) {
										var offsetHeight1 = oTr1[i].offsetHeight;
										if (offsetHeight1 > cssHeight1[0]) {
											oTr1[i].style.height = cssHeight1[0];
										}
									}
								}
							} 
						} 
					}
					h1 = App.$("comparison-table-1").offsetHeight;
					h2 = App.$("comparison-table-3").offsetHeight;
					h = Math.max(h1,h2);
					App.$("comparison-mask-1").style.height = h + "px";
					App.$("comparison-mask-3").style.height = h + "px";
				},
				
				resizeColumnWidth:function(){
					showNumCols = 3;
					widthContainerElementId = "col-xx-large";
					lowerwidthContainerElementId = "col-xx-large2";
					heightContainerElementId = "comparison-mask-2";
					heightContainerElementId2 = "comparison-mask-3";
					
					viewWidth = App.getCss(widthContainerElementId, "width").match(/\d+/)[0];
					cols = App.$("r2a").getElementsByTagName("th");
					
					if (App.Browser.msie && App.BrowserVersion() == "4.0") {							
						colWidth = (cols.length <= showNumCols) ? (viewWidth/cols.length)-5 : viewWidth/showNumCols-35; 
					} else {
						colWidth = (cols.length <= showNumCols) ? (viewWidth/cols.length) : viewWidth/showNumCols-35; 
					}
					
					for (i = 0; i < cols.length; i++) {
						App.setCss(cols[i], {width:colWidth + "px"});
					}
					
					cols2 = App.$("comparison-table-3").getElementsByTagName("td");
					for (i = 0; i < cols2.length; i++) {
					    //Padding is 9 px
						App.setCss(cols2[i], {width:colWidth-9 + "px"});
					}
					
					if (cols.length > showNumCols) {
						App.$(widthContainerElementId).style.overflow = "scroll";
						App.$(lowerwidthContainerElementId).style.overflow = "scroll";
						App.$(widthContainerElementId).onscroll = App.scrollLowerColumns;
						App.$(lowerwidthContainerElementId).onscroll = App.scrollUpperColumns;
						leftHeaderHeight = App.$("r1").offsetHeight;
						if (App.Browser.msie) {
							if (App.BrowserVersion() == "4.0") { //special handling for IE6
								App.$("r1").childNodes[0].style.height = (leftHeaderHeight+11) +"px";
						    } else {
								App.$("r1").style.height = (leftHeaderHeight+8) +"px";
							}
						} else {
						    App.$("r1").style.height = (leftHeaderHeight+17) +"px";
						}
						App.$(lowerwidthContainerElementId).style.overflow = "scroll";
					}
				}
			},
			highlightOnMouseEvents:function(o){
				var oTables = App.getElementsByClassName(document,"js-addevents");
				//window.console.log(oTables.length)
				for(var i=0; i<oTables.length; i++){
					for(var k=0; tr=oTables[i].getElementsByTagName("TR")[k]; k++){
						if(tr.className.indexOf("even")!=-1||tr.className.indexOf("odd")!=-1){
							tr.onmouseover = function (){ App.addClass(this,"over"); };
							tr.onmouseout = function (){ App.removeClass(this,"over"); }; 
						}
					}
				}
			},
			ColorizeComparisonHeaders:function(){
				var compHeaders = App.getElementsByClassName(document, 'comparison-criteria-header', 'tr');
				for (var i=0; i<compHeaders.length; i++) {
					if (App.Browser.msie) {
						nextRows = Element.nextSiblings(compHeaders[i]);
					} else {
						nextRows = compHeaders[i].nextSiblings();
					}
					if (nextRows.length > 0) {
						bgColor = nextRows[0].getStyle('background-color');
						compHeaders[i].style.backgroundColor = bgColor;
					}
				}
			}						
		}, // @App.Page.createAccessiblePopupLinks
					
		Cookie:{
			create:function(name,value,days){
				if(days){
					var date = new Date();
					date.setTime(date.getTime()+(days*24*60*60*1000));
					var expires = "; expires="+date.toGMTString();
				} else {
					expires = "";
				}
				document.cookie = name+"="+value+expires+"; path=/";
			},
			read:function(name){
				var nameEQ = name + "=";
				var ca = document.cookie.split(';');
				for(var i=0; i<ca.length; i++){
					var c = ca[i];
					while (c.charAt(0)==' ') c = c.substring(1,c.length);
					if(c.indexOf(nameEQ)==0) return c.substring(nameEQ.length,c.length);
				}
				return null;
			}
		}, // @App.Page.Cookie
		
		Print:{
			
		}, // @App.Page.Print
		
		ModalMask:{
			create:function(){
				if(!App.$("modalmask")){
				//image path changed from contentimage to imagepath
					var o = App.createElement("DIV",{id:"modalmask",content:"<img src='"+App.Cache.get("imagePath")+"modalmask.gif' />"});
					App.addClass(document.body,"modalenabled");
					App.Page.ModalMask.resize("modalmask");
					window.onresize = window.onscroll = function (){
						App.Page.ModalMask.resize("modalmask");
					}
				}
			},
			destroy:function (){
				var o = App.$("modalmask");
				if(o) try { document.body.removeChild(o); } catch(e){ /*window.console.log(e.message); */}
				App.removeClass(document.body,"modalenabled"); // used to hide <select>'s in ie6.css
				window.onresize = null;
				window.onscroll = null;
			},
			resize:function (s){
				var o = App.$(s);
				// TODO: not quite crossbrowser safe measurements
				o.style.height = document.body.offsetHeight + "px";
				o.style.width = document.body.offsetWidth + "px";
			}
		},
			
		Tooltip:{
			initialized:false,
			currentLayer:null,
			currentLayerText:null,
			init:function (){
				// always remove existing instances of the container to prevent multible instances
				if(App.$("nc-js-tooltip-container")) document.body.removeChild(App.$("nc-js-tooltip-container")); 
				var oContainer 	= App.createElement("DIV",{id:"nc-js-tooltip-container"});
				var oInner1 	= App.createElement("DIV",{CSSClass:"inner1",parent:oContainer});
				var oInner2 	= App.createElement("DIV",{CSSClass:"inner2",parent:oInner1});
				var oH4	 		= App.createElement("H4", {CSSClass:"tooltip",parent:oInner2,content:"Ordforklaring"});
				var oText 		= App.createElement("DIV",{id:"nc-js-tooltip-text",CSSClass:"text",parent:oInner2});
				var oImg 		= App.createElement("IMG",{id:"nc-js-tooltip-close",parent:oH4,src:App.Cache.get("imagePath")+"icon_close.gif",alt:"",title:""});
				
				this.currentLayer 		= oContainer;
				this.currentLayerText 	= oText;
				if(this.currentLayer){
					App.$("nc-js-tooltip-close").onclick = App.Page.Tooltip.destroy;
					App.$("nc-footer").onclick = App.Page.Tooltip.destroy;
					App.Page.Selects.zIndexFix.create({appendToDiv:this.currentLayer});
					var aTTImg = App.getElementsByClassName(document,"nc-js-tooltip-img");
					var aTTT = App.getElementsByClassName(document,"tooltip-text");
					var curImg,assoText;
					for(var i=0; i<aTTImg.length; i++){
						curImg = aTTImg[i];
						curImg.assoTextObj = aTTT[i];
						curImg.onclick = function (){
							App.Page.Tooltip.show({thisRef:this,grabContentFrom:this.assoTextObj}); 
						};
						try { App.hide(aTTT[i]); } catch(e){}
					}
					
				    
					
					this.initialized = true;
				}
			},
			show:function (oConfig){
				if(!this.initialized) this.init();
				App.Cache.set("topZIndex",App.Cache.get("topZIndex")+1);
				this.currentLayerText.innerHTML = App.$(oConfig.grabContentFrom).innerHTML;
				App.setCss(this.currentLayer,{left:(App.getAbsLeft(oConfig.thisRef)+oConfig.thisRef.width+1)+"px",top:(App.getAbsTop(oConfig.thisRef)-1)+"px",display:"block",zIndex:App.Cache.get("topZIndex")});
				if ((this.currentLayer.offsetTop + this.currentLayer.offsetHeight) > App.getPageSize().wH) App.setCss(this.currentLayer, {top:(App.getPageSize().wH-this.currentLayer.offsetHeight-1)+"px"})
				App.Page.Selects.zIndexFix.adjustIframeOnResize({parent:this.currentLayer});
				if(oConfig.modal) App.Page.ModalMask.create();
				return false;
			},
			destroy:function (){
				App.hide(App.Page.Tooltip.currentLayer);
			}
		}, // @App.Page.Tooltip
		
		ConfirmSupplierConditions:{
			initialized:false,
			containerId:"js-supplier-container",
			ClickMonitor:{
				_clicks:[],
				_limit:6,
				add:function(c){
					this._clicks.push(c);
				},
				init:function(){
					//console.log("init()")
					if(App.$("getlist")){
						var a = App.$("getlist").getElementsByTagName("INPUT");
						for(var i=0; i<a.length; i++){
							if(a[i].type == "checkbox"){
								// TODO: skal sættes på checkboxe uden nogle conditions eller ekstra spg: a[i].onclick = App.Page.ConfirmSupplierConditions.ClickMonitor.check;
								if(a[i].checked){ this.add(a[i]); }
							}
						}
						//console.log("Init clicks.length: "+this._clicks.length)
					}
				},
				check:function(errorMsg){
					//console.log("check")
					if(App.$("getlist")){
						App.Page.ConfirmSupplierConditions.ClickMonitor._clicks.length = 0;
						var a = App.$("getlist").getElementsByTagName("INPUT");
						for(var i=0; i<a.length; i++){
							if(a[i].type == "checkbox" && a[i].checked){
								App.Page.ConfirmSupplierConditions.ClickMonitor._clicks.push(a[i]);
								if(App.Page.ConfirmSupplierConditions.ClickMonitor._clicks.length>App.Page.ConfirmSupplierConditions.ClickMonitor._limit){
									//alert("Du kan ikke vælge flere end "+App.Page.ConfirmSupplierConditions.ClickMonitor._clicks+" selskaber");
									if(typeof(errorMsg)!='undefined') // Otherwise "undefined" will be printed when 7 suppliers are selected
									  alert(errorMsg);
									return false;
								}
							}
						}
						//console.log(App.Page.ConfirmSupplierConditions.ClickMonitor._clicks.length);
					}
				}
			},
			init:function (){
				App.Page.ConfirmSupplierConditions.ClickMonitor.init();

				// create HTML skeleton for the layer
				if(!App.$(this.containerId)){
					var oContainer 	= App.createElement("DIV",{id:this.containerId});
					App.Page.Selects.zIndexFix.create({appendToDiv:oContainer});
					var oInner1 	= App.createElement("DIV",{CSSClass:"inner1",parent:oContainer});
					var oInner2 	= App.createElement("DIV",{CSSClass:"inner2",parent:oInner1});
					var oLogo 		= App.createElement("DIV",{CSSClass:"logo",parent:oInner2});
					var oImg 		= App.createElement("IMG",{id:"js-confirmlayer-logo",parent:oLogo,src:App.Cache.get("imagePath")+"logos/kommune.gif",alt:"",title:""});
					var oText 		= App.createElement("DIV",{id:"js-confirmlayer-text",CSSClass:"text",parent:oInner2});
					var oBtnWrap1 	= App.createElement("DIV",{CSSClass:"text-block",parent:oInner2});
					var oBtnWrap2 	= App.createElement("DIV",{CSSClass:"buttons",parent:oBtnWrap1});
					var oBtnYes 	= App.createElement("INPUT",{type:"button",CSSClass:"button",value:"Ja",parent:oBtnWrap2,id:"btnYes"});
					var oBtnNo 		= App.createElement("INPUT",{type:"button",CSSClass:"button",value:"Nej",parent:oBtnWrap2,id:"btnNo"});
				}
	
				var oSuppliers = App.getElementsByClassName(document,"js-supplier"); // alle <div> med class = js-supplier dvs. alle suppliers med ekstra spg.
				for(var i=0; i<oSuppliers.length; i++){
					oSupplier = oSuppliers[i];
					oSupplier.grabTextFrom = "js-supplier-text-"+i; // find ud af hvilken <div> teksten til popuppen skal tages fra
					oSupplier.img  = oSupplier.getElementsByTagName("IMG")[0]; // lav reference til det første billede i <div>'en, som er logoet
					oSupplier.cb  = oSupplier.getElementsByTagName("INPUT")[0]; // lav reference til checkboxen i <div>'en
					oSupplier.cb.supplier = oSupplier; // lav en reference på checkboxen til den <div> den er inde i, så den kan bruges senere i dens click-event
					oSupplier.cb.onclick = function (){
						App.Page.ConfirmSupplierConditions.ClickMonitor.check();
						if(this.checked){ // vi kommer herind hvis checkboxen *ikke* er checked onload
							App.$(App.Page.ConfirmSupplierConditions.containerId).supplier = this.supplier; // lav reference til checkboxens
							App.Page.ConfirmSupplierConditions.show(this); // kør metoden show(), som viser laget
						} else { // herind hvis checkboxen *er* checked
							var sFunc = this.supplier.getAttribute("fireFuncton"); // find den custom attribut "fireFunction" som er .net's postback-funktion
							eval(sFunc); // evaluer den som javascript dvs. den bliver eksekveret her
						}
					};
					try { App.hide(conf.curText); } catch(e){}
				}
				this.initialized = true;
			},
			show:function (oThis){ // oThis referes to the checkbox
				if(!this.initialized) this.init();
				App.Cache.set("topZIndex",App.Cache.get("topZIndex")+1);
				App.$("js-confirmlayer-text").innerHTML = App.$(oThis.supplier.grabTextFrom).innerHTML;
				App.setCss(App.Page.ConfirmSupplierConditions.containerId,{left:(App.getAbsLeft(oThis))+"px",top:(App.getAbsTop(oThis)-1)+"px",display:"block",zIndex:App.Cache.get("topZIndex")});
				try { App.$("js-confirmlayer-logo").src = oThis.supplier.img.src; } catch(e) { /*console.log("TODO: set image src of logo images"); */}

				//sørg for at kassen altid er placeret over folden
				var confirmSupplierBox =  $(App.Page.ConfirmSupplierConditions.containerId);
				if ((confirmSupplierBox.offsetTop + confirmSupplierBox.offsetHeight) > App.getPageSize().wH) App.setCss(App.Page.ConfirmSupplierConditions.containerId, {top:(App.getPageSize().wH-confirmSupplierBox.offsetHeight-1)+"px"})
				
				App.$("btnYes").onclick = function (){
					// ved klik på ja-knappen så find vores postback-funktion og eksekver den
					var sFunc = App.$(App.Page.ConfirmSupplierConditions.containerId).supplier.getAttribute("fireFuncton");
					eval(sFunc);
					App.Page.ConfirmSupplierConditions.destroy(); // slet popup laget
				};
				App.$("btnNo").onclick = function (){
					// ved klik på nej-knappen
					App.$(App.Page.ConfirmSupplierConditions.containerId).supplier.cb.checked = false; // være sikker på at den checkbox der blev klikket forbliver ikke checked
					App.Page.ConfirmSupplierConditions.destroy(); // skjul popup laget
				}
				// a little gardening 
				App.Page.Tooltip.destroy();
				App.Page.Selects.zIndexFix.adjustIframeOnResize({parent:App.$(App.Page.ConfirmSupplierConditions.containerId)});
				App.Page.ModalMask.create();
				return false;
			},
			destroy:function (){
				App.hide(App.Page.ConfirmSupplierConditions.containerId);
				App.Page.ModalMask.destroy();
			}
		}, // @App.Page.ConfirmSupplierConditions

		Dictionary:{
			openAnswer:"",
			clearText:function(){
				this.value="";
				this.onfocus = null; // only clear the initial text the first time you focus or else it will mess up the autocompletion
			},
			LocalData:{
				_data:[],
				_dataRef:[],
				get:function(){ return this._data; },
				add:function(d){ this._data.push(d); },
				addRef:function(d){ this._dataRef.push(d); }
			},
			onAutoCompleterSelect:function(e,b){
				var a=App.$("dict-r").getElementsByTagName("A"); 
				for(var i=0; i<a.length; i++){ 
					if(e.value.trim()==a[i].innerHTML.trim()){ 
						new Effect.ScrollDivTo('dict-r',a[i],{offset:8}); 
						a[i].onclick(); 
						return false;
					}
				}
			},
			onQuestionExpand:function(){ 
				if(App.Page.Dictionary.openAnswer!=""&&App.Page.Dictionary.openAnswer!=this.a) App.hide(App.Page.Dictionary.openAnswer); 
				App.toggle(this.a); 
				App.Page.Dictionary.openAnswer = this.a; 
				var l = this.a.getElementsByTagName("A");
				for(var i=0; i<l.length; i++){
					l[i].onclick = function (){
						for(var j=0; j<App.Page.Dictionary.LocalData._dataRef.length; j++){
							if(this.innerHTML===App.Page.Dictionary.LocalData._dataRef[j].innerHTML){
								new Effect.ScrollDivTo('dict-r',App.Page.Dictionary.LocalData._dataRef[j],{offset:8});
								App.Page.Dictionary.LocalData._dataRef[j].onclick();
							}
						}
						return false;
					};
				}
				return false; 
			},
			init:function(){
				if(App.$("dict")){
					// hide all answers, add click events to word links
					var a=App.$("dict").getElementsByTagName("LI");
					for(var i=0; i<a.length; i++){ 
						var l=a[i].getElementsByTagName("A"),d=a[i].getElementsByTagName("DIV");
						var q=d[0],an=d[1],l=l[0];
						this.LocalData.add(l.innerHTML);
						this.LocalData.addRef(l);
						l.a=an;
						l.onclick = this.onQuestionExpand;
						App.hide(an);
					}
					
					// add click events to alphabet links and check if there is word(s) matching the letter in the results. If false then add a "diabled" class.
					var a=App.$("dict-a").getElementsByTagName("A"); 
					for(var i=0; i<a.length; i++){ 
						var c=App.$("dict-r").getElementsByTagName("A"),m=false;
						for(var j=0; j<c.length; j++){
							if(a[i].innerHTML.trim()===c[j].innerHTML.trim()){ m=true; }
						}
						if(!m) App.addClass(a[i],"d");
						
						a[i].onclick = function (){
							var b=App.$("dict-r").getElementsByTagName("A"); 
							for(var j=0; j<b.length; j++){
								if(b[j].parentNode.nodeName == "H2"){
									if(this.innerHTML.trim() === b[j].innerHTML.trim()){ 
										new Effect.ScrollDivTo('dict-r',b[j],{offset:8}); 
									} 
								} 
							}	
							return false;
						}
					}
					try { App.$("ac").getElementsByTagName("INPUT")[0].onfocus = this.clearText; App.$("ac").getElementsByTagName("INPUT")[0].onkeypress = function (e){ return cancelSubmit(e); } } catch(e){}
					function cancelSubmit(e) {
						if(!e) var e=window.event;
						if(e.keyCode==13){
							return false;
						}
				 	}
				}
			}
		},
		
		LocationDetector:{
			init:function (){
				var isAdmin = /Administration/.test(document.location.href);
				var isEditMode = App.$("editmode-on");
				var b = document.getElementsByTagName("BODY")[0];
				if(isAdmin) b.className = new String(b.className+" admin").trim();
				if(isEditMode){
					App.Cache.set("editmode",true);
				}
			}
		},

		Flash:{
			embedResults:function (flashMovieUrl, name, width, height){
				var so = new SWFObject(flashMovieUrl, name, width, height, "8", "#ffffff");
		        so.addParam("allowScriptAccess", "sameDomain");
		        so.addParam("allowFullScreen", "false");
		        so.addParam("quality", "high");
		        so.addParam("flashvars", "sequence_id=" + name); 			
				so.useExpressInstall('../../Style Library/images/swf/expressinstall.swf');
				so.write("flashcontent");
			},
			Sifr:{
				init:function (){
					if(typeof sIFR == "function"){
						var swfSrc = App.Cache.get("swfPath")+"foundrymonoline.swf";
						var swfSrcBold = App.Cache.get("swfPath")+"foundrymonoline_bold.swf";
						sIFR.replaceElement(named({sSelector:".header h1",sFlashSrc:swfSrcBold,sColor:"#333333",sWmode:"transparent"}));
						
						sIFR.replaceElement(named({sSelector:".ent-1 h3",sFlashSrc:swfSrcBold,sColor:"#325662",sWmode:"transparent"}));
						sIFR.replaceElement(named({sSelector:".ent-2 h3",sFlashSrc:swfSrcBold,sColor:"#3a6734",sWmode:"transparent"}));
						sIFR.replaceElement(named({sSelector:".ent-3 h3",sFlashSrc:swfSrcBold,sColor:"#927511",sWmode:"transparent"}));
						sIFR.replaceElement(named({sSelector:".ent-4 h3",sFlashSrc:swfSrcBold,sColor:"#975529",sWmode:"transparent"}));
						sIFR.replaceElement(named({sSelector:".ent-5 h3",sFlashSrc:swfSrcBold,sColor:"#852d2c",sWmode:"transparent"}));
						
						sIFR.replaceElement(named({sSelector:".infos h4",sFlashSrc:swfSrcBold,sColor:"#222222",sWmode:"transparent"}));
					};
				}
			}
		}, // @App.Page.Flash

		Selects:{
			comparisonChanger:function (){
				var o = App.getElementsByClassName(document,"cc","select"); // cc == comparison-changer
				if(o){
					/*
					LessThan = 		1, 	rød 	.lg-1	{ background-color:#e54f2a; }
					EqualTo = 		2, 	grå 	.lg-2	{ background-color:#c8c8c5; }	
					LargerThan = 	3,	grøn	.lg-3	{ background-color:#73ca77; }
					Note = 			4 	gul		.lg-4	{ background-color:#fad219; }
					LargerLessThan = 			5 	orange		.lg-5	{ background-color:#f88017; }
					*/
					var m = [0,"lg-1","lg-2","lg-3","lg-4","lg-5"]; // map the classnames to values in select
					var c = "lg lg-s "; //prefix news classname with this
					for(var i=0; i<o.length; i++){
						var s = o[i].parentNode.getElementsByTagName("SPAN")[0];
						App.$(s).className = c+m[o[i].value]; // set className on pageload
						o[i].sId = s.id;
						o[i].onchange = function (){
							App.$(this.sId).className = c+m[this.value];
						}
					}
				}
			},
			zIndexFix:{
				create:function (o){
					// ie 6 iframe/select fix
					var oIf = App.createElement("IFRAME",{CSSClass:"ie6fix",src:App.Cache.get("styleLibraryPath")+"blank.html"});
					oIf.style.width = o.appendToDiv.offsetWidth + "px";
					oIf.style.height = o.appendToDiv.offsetHeight + "px";
					o.appendToDiv.appendChild(oIf);
				},
				adjustIframeOnResize:function (o){
					var oIf = o.parent.getElementsByTagName("IFRAME");
					if(oIf[0]){
						oIf[0].style.height = o.parent.offsetHeight + "px";
						oIf[0].style.width = o.parent.offsetWidth + "px";
					}
				}
			}
		},  // @App.Page.Selects
		
		Accident:{
			init:function() {
				//do initial hiding
				hides = [	'toggle01',
							'outer11', 'outer12', 'inner11', 'inner12', 'toggle11', 
							'outer21', 'outer22', 'inner21', 'inner22', 'toggle22',
							'outer31', 'outer32', 'inner31', 'inner32', 'toggle32'];
				all = hides.concat(['toggle02', 'toggle12', 'toggle21', 'toggle31']);
				if (App.Page.Accident.StateKeeper.hasState(all)) {
					App.Page.Accident.StateKeeper.keepState(all);
				} else {
					//do initial hiding
					this.hide(hides);
				}
			},
			unhide:function (o) {
				for(i=0;i<o.length; i++) {
					var obj = App.$(o[i]);
					if (obj) {
						App.show(obj);
						App.Page.Accident.StateKeeper.addState(o[i], 'visible');
					}
				}
			},
			hide:function (o) {
				for(i=0;i<o.length; i++) {
					var obj = App.$(o[i]);
					if (obj) {
					  App.hide(obj);
					  App.Page.Accident.StateKeeper.addState(o[i], 'hidden');
					}
				}
			},
			StateKeeper: {
				keepState:function(o) {
					for (i=0; i<o.length; i++) {
						state = App.Page.Cookie.read(o[i]);
						if (state == 'hidden') {
							App.hide(o[i]);
						}/* else if (state == 'visible') {
							App.show(o[i]);
						}*/
					}
				},
				addState: function(name, value) {
					App.Page.Cookie.create(name, value);
				},
				hasState: function(o) {
					hasState = false;
					for (i=0; i<o.length; i++) {
						state = App.Page.Cookie.read(o[i]);
						hasState = hasState || (state != null);
					}
					return hasState;
				}
			}
		},
		
		LibPrototype:{
			catchDrop:function (o){
				/*var a = App.getElementsByClassName(App.$(o.id),"srt-outer","DIV");
				window.console.log(a)
				for(var i=1; i<=a.length; i++){
					//a[i-1].style.zIndex = "";
				}*/
			}
		},
		
		start:function (){
			
			App.Cache.init();
			App.Page.Selects.comparisonChanger();
			App.Page.LocationDetector.init();
			App.Page.setEntranceLinks();
			App.Page.Flash.Sifr.init();
			App.Page.Tables.zebratize();
			App.Page.Tables.ScrollableTable.init();
			App.Page.Tables.highlightOnMouseEvents();
			App.Page.Tables.ColorizeComparisonHeaders();
			App.Page.Tooltip.init();
			App.Page.ConfirmSupplierConditions.init();
			App.Page.Dictionary.init();
			App.Page.createAccessiblePopupLinks();
			App.Page.Accident.init();
			
		} // @App.Page.start
	} // @App.Page
} // @App

/**
 * Initialize the page
*/
App.Page.Loader.prepare();
App.Page.Loader.add(App.Page.start);

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/,"");
}
Array.prototype.inArray = function (s){
  for(var i=0; i<this.length; i++){
	if(this[i]==s){
	  return true;
	}
  }
  return false;
};
if(typeof Array.prototype.push == "undefined"){
	Array.prototype.push = function (k){
		this[this.length] = k;
		return this.length;
	};
}
if(!window.console || !console){
	window.console = {};
	window.console.log = function (s){ /*alert(s);*/ }
}

var Zuul = {
  stateKeeper:[],
  add:function (s){
	if(!Zuul.stateKeeper.inArray(s)){
		Zuul.stateKeeper.push(s);
	}
  },
  onPostBack:function(){
	console.log(Zuul.stateKeeper.length)
	for(var i=0; i<Zuul.stateKeeper.length; i++){
		try { App.$(Zuul.stateKeeper[i]).onclick(); } catch(e){}
	}
  }
};
