Page = function() {
	this.init();
	this.lastLink = null;
}

Page.prototype.dispatchDeeplink = function(action) {
    if ( action == "info_tilsagn" ) {
        new_customer_info_campaign.show("pledge");
    }else if ( action == "info_tak_for_dit_tilsagn" ) {
		gstatCallMeChangeBank();
		roiCallMePledgeReceipt();
                        tstat("Har du skiftet bank?","Har du skiftet bank? - tilsagn bekræftet","Velkommen,Har du skiftet bank,Tak for dit tilsagn"
					,{'events':"event52"
					});
        json(
            "page",
            {pageId:"455"},
            bind(this.showPage, this),
            function(){}
        );
    }else if ( action == "savings" ) {
        savings_page.show();
    }else if ( action == "bms" ) {
        bms_page.show();
    }
}

Page.prototype.refresh = function() {
	var links = $$("a[href*=action=]");
	if (links.length) {
		for (var i = 0; i < links.length; i++) {
			this.hookLink(links[i]);
			if (links[i].href.match(/.*ne\.calculation.*/)) {
				links[i].id = 'ne-calc-menu-link';
			}
		}
	}
}
Page.prototype.hookLink = function(link) {
	if (!getNodeAttribute(link, "hooked")) {
				connect(link,"onclick", bind(this.loadPage,this,link));
				setNodeAttribute(link, "onclick", "return false;");
				setNodeAttribute(link, "hooked", true);
			}
}
Page.prototype.menuHoverOn = function(elem){
	//not final just test
	//elem.childNodes[1].style.cssText="display:block;";
	this.menuHideAll();
	showElement(elem.childNodes[1]);
	return false;
}
Page.prototype.menuHoverOff = function(elem){
	//not final just test
	//hideElement(elem.childNodes[1]);
	return false;	
}

Page.prototype.menuHideAll = function(){
	map(function(e){hideElement(e);},$$('#menu > div > ul > li > ul'));
}
Page.prototype.init = function() {
	// catch all links
	this.refresh();
	
	//mouse over for sub-sub-menu
	var second_level = $$("#menu li > ul > li");
	
	if (second_level && second_level.length > 0) {
		updateNodeAttributes(second_level, {onmouseover:"return thepage.hoverMenu(this, true);", onmouseout:"return thepage.hoverMenu(this, false);"});
	}
	
	
	//mouse over for sub-menu
	//var menu_headers=$$("#menu ul > li[class*=p]") //$$('#menu > div > ul > li'); $('menu').firstChild.firstChild.childNodes;
	//updateNodeAttributes(menu_headers, {onmouseover:"return thepage.menuHoverOn(this);"}); //, onmouseout:"callLater(1,thepage.menuHoverOff,this)"
		
	//Menu arrows
	map(function(e){
				insertSiblingNodesBefore(e.parentNode.firstChild
				,IMG({'style':"float:right;margin: 5px 2px 0 0",'src':"resources/images/context_bullet.gif",'width':"5px",'height':"5px"}));
			}
		,$$("#menu ul ul ul"));
	
	checkDefinitions();
	if (parseQueryString(document.location.search).pi) {
		lookup.fetchAndShowBranch();
	}
}
Page.prototype.hoverMenu = function (li, show) {
	var ul = getFirstElementByTagAndClassName("ul", null, li);
	if (!ul) return;
	if (show) {
		if (this.shown && this.shown != ul) {
			this.hideMenu(this.shown);
		}
		this.shown = ul;
		addElementClass(ul, "displayed");
		var timeout = getNodeAttribute(ul, "hide_timeout");
		if (timeout) window.clearTimeout(timeout);
	} else {
		base = this;
		setNodeAttribute(ul, "hide_timeout", window.setTimeout(function() { base.hideMenu(ul); }, 350));
	}
}
Page.prototype.hideMenu = function(ul) {
	removeElementClass(ul, "displayed");
	var timeout = getNodeAttribute(ul, "hide_timeout");
	if (timeout) window.clearTimeout(timeout);
}
Page.prototype.getLink = function(id) {
	return "page?action=page&pageId="+id;
}
Page.prototype.loadPageById = function(id) {
	json(
		"page",
		{pageId:id}, 
		bind(this.showPage, this)
	);
	return false;
};
Page.prototype.loadInnerPage=function(id){
	json(
		"page",
		{pageId:id}, 
		bind(this.showInnerPage, this)
	);
	return false;
}
Page.prototype.showInnerPage = function (result){
	//log("showinnerpage called");
	
	try{
		this.headline = result.headline;
		setNodeAttribute("mainpage","class", "");
		
		//stat call for this special page
		//tstat("Artikler",""+result.headline,"Velkommen,Artikler,"+result.headline,null);
		//tk_forsidebanne_hbh.swf
		//add conditional that allows flash element to avoid a reload
		
		//if the content is already there, no need to reconstruct it
		if (!$('innerpage_flash')){
		    replaceChildNodes("mainpage"
				,H1({id:"mainheader"},"Header for 10 gode råd here")
				,DIV({id:"innerpage_flash",style:"height:200px;margin-bottom:10px"},"flash goes here")
				,H1({id:"innerpage_header"})
				,DIV({id:"page"})
			);
		}
		
		//make sure flash doesnt reload
		if (!this.innerflash_loaded){
			var so = new SWFObject("resources/flash/tk_forsidebanne_hbh.swf", "innerpage_flash", "100%", "100%", "0", "#FFFFFF");
			so.addParam("wmode", "transparent");
			so.write("innerpage_flash");
			this.innerflash_loaded=true;
		}
		
		//To ensure html content is parsed and content is refreshed
		$("page").innerHTML = result.contents;
		$("innerpage_header").innerHTML=result.headline;
		
		if (!$('testlink')){
			insertSiblingNodesAfter("innerpage_flash",A({'style':"margin-bottom:10px",'class':"a_dot_link",'href':"#",'onclick':"thepage.loadInnerPage(333);return false;"},"link 2"));
			insertSiblingNodesAfter("innerpage_flash",A({'id':"testlink",'class':"a_dot_link",'href':"#",'onclick':"thepage.loadInnerPage(400);return false;"},"link 1"));
			
		}
		/*
		//context and footer
		var context=this.buildContext(result);
		insertSiblingNodesAfter("page",context);
		insertSiblingNodesAfter("context",footer(result.pageId, result.headline));
		this.adjustContext();		
		*/
		if(!$('footer')) insertSiblingNodesAfter("page",footer(result.pageId, result.headline));
		else replaceChildNodes("footer",footer(result.pageId, result.headline));
		
	}catch(e){
		log(e);
	}
}
Page.prototype.processLoadPage = function(parms,a,callback) {
	if (!parms.action) {
		return;
	}	
	try {

		if ($('tell_afriend')) {
			removeElement('tell_afriend');
		}
		
		lookup.bookMode = false;
		externalStat(parms.action,parms.pageId);
		//var extid = parseQueryString(document.location.search).extid;
		/*
		if (extid){
			this.external=true;
			this.externalname=lookup.getBankName(extid);
			log("lol"+this.externalname);
		}else{
			log("no extid");			
		}
		*/
		switch (parms.action) {
		case "page":
			json(
				"page",
				{pageId:parms.pageId}, 
				bind(this.showPage, this),
				callback
			);
			break;
		case "ne.calculation":
			clearHighlight();
			var current_menu = $$("a[class=current_menu]");
			var current_submenu = $$("a[class=current_submenu]");
			for (var i = 0; i < current_menu.length; i++) {
				removeElementClass(current_menu[i], 'current_menu');
			}
			for (i = 0; i < current_submenu.length; i++) {
				removeElementClass(current_submenu[i], 'current_submenu');
			}
			if (a) {
				try{removeElementClass($$("li[class$=p10] ul")[0],'collapsed');}catch(e){}
				try{setNodeAttribute($$("li[class$=p10] a")[0], "class", "current_menu");}catch(e){}
				try{setNodeAttribute('ne-calc-menu-link', "class", "current_submenu");}catch(e){}
			}
			ne_model.state.init();
			break;
		case "user_forgotpass":
			myplanner.showForgotPass();
			break;
		case "user_login":
			myplanner.showLogin();
			break;
		case "user_edit":
			myplanner.showSettings();
			break;
		case "user_create":
			break;
		case "lookup_zip":

			lookup = new Lookup("lookup_map");
			lookup.showSearchByZip();
			lookup.origination = "Deeplink";
			break;
		case "lookup_list":
                    alert("page.js - switch");
			lookup.showSearchByList();
			lookup.origination = "Deeplink";
			break;
		case "lookup_address":
			lookup.showSearchByAddress();
			lookup.origination = "Deeplink";
			break;
		case "user_removehistorylink":
			myplanner.removeHistoryLink(a.parentNode, parms.id);
			break;
		case "user_removesavedlink":
			myplanner.removeSavedLink(a.parentNode, parms.id);
			break;
		case "user_removeinsterestedlink":
			myplanner.removeInterestedLink(a.parentNode, parms.id);
			break;
		case "brochure":
			brochure.show({});
			break;
		case "search":
			if (parms.pos) {
				search.drawResults(parms.pos);
			} else {
				search.searchRequest(parms.q,parms.pos);
			}
			break;
		case "bank_book_documents":
			bank_book.loadDocList();
			break;
		case "loan_new":
		case "my_expenses":
		case "loan_equity":
		case "loan_rescheduling":
		case "quotations":
			//old calc for external embedding
			var extid = parseQueryString(document.location.search).extid;
			if (extid!=undefined && parms.action=="loan_new"){
				calc.run("loan_new");
				break;				
			}
			if (extid!=undefined && parms.action =="quotations"){
				quotations.run($$("a[href$=quotations]")[0]);
				break;				
			}
						
			// create array of potential external links
			var externalCalculations = [
				{'caption': 'Nyt lån', 'url': 'https://netbank.totalkredit.dk/netbank/newLoanCalculation.do'},
				{'caption': 'Hvad har jeg råd til at købe?', 'url': 'https://netbank.totalkredit.dk/netbank/budgetView.do'},
				{'caption': 'Omlægning', 'url': 'https://netbank.totalkredit.dk/netbank/laanomlaegning.do'},
				{'caption': 'Friværdi', 'url': 'https://netbank.totalkredit.dk/netbank/equityCalculation.do'},
				{'caption': 'Kursliste', 'url': 'https://netbank.totalkredit.dk/netbank/showStockExchange.do'}
			];
			//
			// then open the correct one while recording page-name for stats
			var ctext="";
			var index;
			switch (parms.action) {
			case "loan_new":
				if (parms.backpageload)	thepage.loadPageById(333); //so theres an article underneath the overlay
				index = 0;
				ctext = "Nyt boliglån";
				gso_newloan();
				break;
				
			case "my_expenses":
				if (parms.backpageload)	thepage.loadPageById(333); //so theres an article underneath the overlay
				index = 1;
				ctext = "Hvad har jeg råd til?";
				gso_afford();
				break;
				
			case "loan_rescheduling":
				if (parms.backpageload)	thepage.loadPageById(333); //so theres an article underneath the overlay
				index = 2;
				ctext = "Låneomlægning";
				gso_reschedule();
				break;
				
			case "loan_equity":
				if (parms.backpageload)	thepage.loadPageById(333); //so theres an article underneath the overlay
				index = 3;
				ctext = "Beregn friværdi";
				gso_equity();
				break;
				
			case "quotations":
				if (parms.backpageload)	thepage.loadPageById(419); //so theres an article underneath the overlay
				index = 4;
				ctext = "Kurslister";
				break;
			}
			GB_showPage(externalCalculations[index].caption, externalCalculations[index].url);
			// record stats
			tstat("Beregning",ctext,"Velkommen,Beregning,"+ctext,null);
			// break main switch
			break; 	 
		case "campaign":
			campaign.show('bedrehjem');
			break;
		case "bank_book":
			bank_book.show();
			break;
		case "frontpage":
			frontpage.run();
			break;
		case "user.calc":
			calc.restoreSaved(parms.id);
			break;
		case "test_equity":
			calc.run('loan_equity');
			break;
		case "test_rescheduling":
			calc.run('loan_rescheduling');
			break;
		case "test_expenses":
			calc.run('my_expenses');
			break;	
		case "calc_rules":
			calc.showRules();
			break;
		case "info":
			new_customer_info_campaign.show('default');
			break;
		case "info_tilsagn":
			new_customer_info_campaign.show('pledge');
			break;
		case "info_tak_for_dit_tilsagn":
			json(
				"page",
				{pageId:"455"}, //test is 428
				bind(this.showPage, this),
                                callback
			);
						gstatCallMeChangeBank();
                        tstat("Har du skiftet bank?","Har du skiftet bank? - tilsagn bekræftet","Velkommen,Har du skiftet bank,Tak for dit tilsagn"
					,{'events':"event52"
					});
			break;
		case "savings":
			savings_page.show();
			this.updateLocation("Top 10 besparelser!", "savings");
			break;
		case "bms":
			bms_page.show();
			break;			
		default:
			console.debug("action is "+parms.action);
			break;
		}
	} catch (e) {
                console.debug("Load error occured: "+e.name);
                console.debug("Load error occured: "+e.message);
	}
	return false;
};
Page.prototype.loadPage = function(a, callback) {
	this.lastLink = a;
	var href = getNodeAttribute(a, "href");
	var parms = parseQueryString(href.substring(href.indexOf("?")+1));
	return this.processLoadPage(parms,a,callback);
}
Page.prototype.showPage = function(result) {
	try {
		this.headline = result.headline;
		lookup.bookMode = false;
		setNodeAttribute("mainpage","class", "");
		var menu_parents = setMenuLinkHighlight(result.pageId);
		// for stats
		if (menu_parents == null) {
			// not in menu
			menu_parents = ["Uden for menu"];	
		}
		// push headline
		menu_parents.push(result.headline);
		// reduce to single value
		var stat_title = reduce(function(a,b) {return a+" :: "+b}, menu_parents, "Artikler");
		tstat("Artikler",""+result.headline,"Velkommen,Artikler,"+result.headline,null);
		
		replaceChildNodes("mainpage", H1({id:"mainheader"}), DIV({id:"page"}));
		$("mainheader").innerHTML = result.headline;
		result.headline.replace(/\&amp\;/,'&');
		var context=this.buildContext(result);
		$("page").innerHTML = result.contents;
		
		insertSiblingNodesAfter("page",context);
		insertSiblingNodesAfter("context",footer(result.pageId, result.headline));
		
		hideDefinition();
		checkDefinitions();
		this.changeBanner(result.banner);
		myplanner.refresh();
		var a = getElementsByTagAndClassName("a",null,"page");
		for (var i = 0; i < a.length; i++ ){
			if (a[i].href && a[i].href.indexOf("page?action") == -1) {
				a[i].target = "_blank";
			}
		}
		toolbox(result.pageId, result.headline)
		this.updateLocation(result.headline, "page", "pageId=" + result.pageId);
		//this.addMetaTag("description","description text");
		this.refresh();
		$("header").scrollIntoView(true);
		this.adjustContext();
	} catch (e) {
		log (e);
	}
}

Page.prototype.addMetaTag=function(key,value){
	var themeta=document.createElement("meta");
	themeta.setAttribute("name",key);
	themeta.setAttribute("content",value);
	document.getElementsByTagName("head")[0].appendChild(themeta);
}

Page.prototype.buildContext=function(result){
		var contexts = result.contexts;
		var context = '';
		if (result.contextVisible && contexts) {
			context = DIV({id:"context"}
				,DIV({'class':"context-box",'id':"context-related"}
					,DIV({'class':"hd_rel",'style':"width:100%"})
					,map(
						function(e){
							 if (e.id!=result.pageId){
							 	//log("ENAME: "+e.name);
							 	return DIV({'class':"elem",'style':"overflow:hidden"}
											,A({href:e.url,hooked:true,onclick:"return thepage.loadFromContext(this,'hd_rel')"}, e.name.replace("&amp;","&"))
										);
								}		
						}
						,contexts[0].links
					)
				)
				,(contexts.length == 2 && contexts[1].links ? 
					DIV({'class':"context-box",'id':"context-siblings"}
						,DIV({'class':"hd_int",'style':"width:100%"})
						,map(
							function(e){
							 if (e.id!=result.pageId)
							 	return DIV({'class':"elem",'style':"overflow:hidden"}
											,A({href:e.url,hooked:true,onclick:"return thepage.loadFromContext(this,'hd_rel')"}, e.name)
										);
							}
							,contexts[1].links
						)
					)
					: DIV({'class':"context-box",'id':"context-siblings",'style':"margin:0;padding:0"}
						,H1({'style':"margin:0;padding:0"},"")
					)		
				)
				,DIV({id:"context-clear"})
			);
		}
		return context;
}

Page.prototype.adjustContext = function (){
	//measures height of context boxes and adjusts border
	var left = getElementDimensions('context-related').h;
	var right = getElementDimensions('context-siblings').h;
	
	var bstyle="1px solid #BDB6AA";
	
	if (right > left){
		$('context-siblings').style.borderLeft=bstyle;
	}else{
		$('context-related').style.borderRight=bstyle;		
	}
}
Page.prototype.loadFromContext = function(a, type) {
	var cb = null;
	switch (type) {
	case "hd_rel":
		cb = function(result) { tstat("Kontekstmenu", "Mere om dette emne - "+result.headline,"Velkommen,Artikler,Kontekstmenu,Mere om dette emne,"+result.headline) };
		break;
	case "hd_int":
		cb = function(result) { tstat("Kontekstmenu", "Interessant for dig - "+result.headline,"Velkommen,Artikler,Kontekstmenu,Interessant for dig,"+result.headline) };
		break;
	}
	return thepage.loadPage(a, cb);
}
Page.prototype.changeBanner = function(banner) {
	if (banner.substring(banner.lastIndexOf('.') + 1) === "swf") {
		var so = new SWFObject(banner, "", "508", "98", "8", "#ffffff");
		so.addParam("wmode", "transparent");
		so.write("banner")
	} else {
		replaceChildNodes("banner", IMG({'src':banner,'alt':"Banner"}));
	}
}
Page.prototype.deeplink = function() {
	// detect if fragment based deeplink (highest priority)
	// when found log stat AND invoke appropriate function 
	// to render the contents of the deeplinked page
	if (location.hash && /action=([^+&]+)/.test(location.hash)) {
		var act = /action=([^+&]+)/.exec(location.hash);
		switch (act[1]) {
			
			case "loan_new":
				tstat("Beregning","Nyt boliglån","Velkommen,Beregning,Nyt boliglån",null);
				calc.run("loan_new");
				return;
				
			case "page":
				// get id of page and load it
				var id = parseInt(location.hash.substring(location.hash.indexOf("pageId=") + "pageId=".length));	
				if (!isNaN(id)) {
					externalStat("page",id);
					// showPage invokes stat, don't do it manually
					json("page", {'pageId':id}, bind(this.showPage, this));
				}
				return;
		}
		
		// return anyway as some lib probably picks up the hash in remaining cases
		return;
	}
		
	
	// some unknown stat logging - probably not needed?
	if (parseQueryString(location.search).partner) {
		tstat("Partnerlink",parseQueryString(location.search).partner);
	}
	
	
	// detect if query based deeplink (second priority)
	// when found invoke stat but DO NOT do anything 
	// - page will be correctly rendered from server
	if (location.search && /action=([^+&]+)/.test(location.search)) {
		var act = /action=([^+&]+)/.exec(location.search);
		switch (act[1]) {
			case "lookup_address":
			case "lookup_list":
			case "lookup_zip":
				tstat("Find din nærmeste rådgiver","Find din nærmeste rådgiver","Velkommen,Find din nærmeste rådgiver",null);
				return;	
			case "campaign":
				tstat("Kampagne","Julekort 2008","Velkommen,Kampagne,Julekort 2008")
				return;
			case "page":
				var headline = scrapeText($("mainheader"));
				tstat("Velkommen",""+headline,"Velkommen,"+headline,null);
				return;
			case "loan_new":
				tstat("Beregning","Nyt boliglån","Velkommen,Beregning,Nyt boliglån",null);
				return;
			case "loan_rescheduling":
				tstat("Beregning","Låneomlægning","Velkommen,Beregning,Låneomlægning",null);
				return;
			case "loan_equity":
				tstat("Beregning","Beregn friværdien","Velkommen,Beregning,Beregn friværdien",null);
				return;
			case "my_expenses":
				tstat("Beregning","Hvad har jeg råd til?","Velkommen,Beregning,Hvad har jeg råd til?",null);
				return;
			case "ne.calculation":
				// no specific stat here, necalc.js does that for us
				// simple return to avoid front page stat hit
				return;
			case "info_tak_for_dit_tilsagn":
				// no specific stat here, necalc.js does that for us
				// simple return to avoid front page stat hit
				return;
			case "info_tilsagn":
				// no specific stat here, necalc.js does that for us
				// simple return to avoid front page stat hit
				return;

		}
	}
	
	
	// only here if directly to frontpage
	tstat("Velkommen","Forside","Velkommen,Forside",null);
	externalStat("frontpage");
};
Page.prototype.updateLocation = function(title, action, sub) {
	
	// set document title
	//document.title = "Totalkredit.dk - "+title;
	document.title=title + " - Totalkredit.dk";
	
	// action string
	var act = "action=" + action + (sub ? "&" + sub : "");
	
	// if main header is present
	if ($("mainheader")) {
		// create new link node and connect empty handler
		var link = A({'href':"page?" + act,'class':"headline_link"}, scrapeText("mainheader"));
		connect(link, "onclick", function(e) { e.stop(); });
		// replace text node with link node
		replaceChildNodes("mainheader", link);
	}

	// update history
	hist.add(act);
}
/* footer */
function footer(id,headline,calculation,extra_links) {
	var div = DIV({'id':"footer"});
	var ul = UL();
	if (id) {
		appendChildNodes(
			ul,
			li_img_href(
				"Mail siden til en ven",
				"footer_mail.gif",
				"return showTellAFriend(this," + id + ", '" + headline + "', false);"
			)
		);
	}
	if (id && myplanner.isLogged()) {
		appendChildNodes(ul,
			li_img_href("Gem siden i din boligmappe","footer_save.gif","return savePage(" + id +");"));
	}
	if (calculation && myplanner.isLogged() && !calc.externalviewer) {
		appendChildNodes(ul,
			li_img_href("Gem beregningen","footer_save.gif","return calc.saveCalculation(this);"));
	}
	appendChildNodes(ul,li_img_href("Skriv siden ud","footer_print.gif","tstatPrint(this);print();return false;"));
	appendChildNodes(div,ul);
	appendChildNodes(div,
		DIV({
				'style'	:"margin: 6px 6px 0 6px;"
			},
			A({
					'href'		:"#",
					'style'		:"margin-right: 16px;",
					'onclick'	:"$('header').scrollIntoView(true); return false;"
				},
					"Til toppen"
			),
			extra_links
		)
	);
	return div;
}
function toolbox(id,headline,calculation,hideprint) {
	var text = $("mainheader").innerHTML;
	replaceChildNodes("mainheader","");
	if (id) {
		appendChildNodes(
			"mainheader",
			img_href(
				"Mail siden til en ven",
				"footer_mail.gif",
				"return showTellAFriend(this,'" + id + "', '" + headline + "', true);"
			)
		);
	}
	if (id && myplanner.isLogged()) {
		appendChildNodes("mainheader",
			img_href("Gem siden i din boligmappe","footer_save.gif","return savePage('" + id +"');"));
	}
	if (calculation && myplanner.isLogged()) {
		appendChildNodes("mainheader",
			img_href("Gem beregningen","footer_save.gif","return calc.saveCalculation(this);"));
	}
	if (hideprint != true) {
		appendChildNodes("mainheader",
			img_href("Skriv siden ud","footer_print.gif","print() ;return false;"),
			text
		);
		$("mainheader").innerHTML = text;
	} else {
		appendChildNodes("mainheader",
			text
		);
		$("mainheader").innerHTML = text;
	}

}

function savePage(id) {
	//stat("Boligmappe :: Gem artikel :: "+thepage.headline);
	tstat("Boligmappe","Gem artikel - "+thepage.headline,null);
	
	json(
		"user.save.page",
		{"page_id":id},
		bind(myplanner.refresh,myplanner)
	);
	return false;
}

function img_href(alt,src,onclick) {
	return A({
			'href'		:"#",
			'onclick'	: (onclick ? onclick : "")
		},
		IMG({alt:alt,src:"resources/images/"+src})
	);
}
function li_img_href(alt,src,onclick) {
	return LI(null,
		A({
				 'href'		:"#"
				,'onclick'	: onclick
			},
			IMG({'alt':alt, 'titel':alt, src:"resources/images/"+src})
		)
	);
}
/* end footer */
/* boxes */

function findPos(obj) { // return absolute position of $obj
	if (typeof obj == "string") obj = $(obj);
	
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}
/*
 * Show small floating box with help message, request for message
 * 
 * @param {Element}	elem - element under which box will be shown
 * @param {String} key	 - key to fetch message 
 */
function showHelp(elem,key,position) {
	/*
	json(
	    	"help",
	    	{'key':key},
		bind(showHelpBox,this,elem,position)
	);
	*/
	jsonRequest(
	     {"key":key}
		,bind(showHelpBox,this,elem,position)
	    ,"help"
	);
	return false;
}
/*
 * Show small floating box with help message
 * 
 * @param {Element} elem  - element under which box will be shown
 * @param {String}  title - box title
 * @param {Element} body  - help message to show, can be html
 * 
 * Set node attribute on element {onmouseover,onclick}:"return showHelpBox(this,'title','body');"
 */
function showHelpBox(elem,position,response) {
	var box = getElement("help_box");
	if (!box) {
		box = DIV(
			{'id':'help_box'},
			DIV(
				{'id':'help_box_inside'}
			),
			IFRAME(),
			IMG({'src':'resources/images/bottum_shadow.gif'},null)
		);
		appendChildNodes("mainpage", box);
	}
	if (typeof(elem) == "string") {
		elem = $(elem);
	}
	setNodeAttribute(elem,"onmouseout","return hideHelp();");
	var pos = findPos(elem);
	box.style.top = pos[1] + elem.offsetHeight + 2;
	if (position) {
		box.style.left = pos[0] + elem.offsetWidth - 192;
	} else {
		box.style.left = pos[0] + elem.offsetWidth + 2;
	}
	box.style.display = 'block';
	replaceChildNodes("help_box_inside",
		DIV(
		{'id':"help_box_icon"},
			IMG({'src':'resources/images/white_help.gif'},null)
		),
		IMG({'src':'resources/images/close_button.gif','onclick':'hideHelp();','width':10,'height':9},null),
		response.result,
		// append break if text is too small - to ensure two lines
		response.result.length < 40 ? [BR(),BR()] : null
	);
	fixBoxPos(box,elem);
	//
	return false;
}
function fixBoxPos(box,elem) {
//	doFixBoxPos(box,elem);
//	setTimeout(partial(doFixBoxPos,box,elem),1);
}
function doFixBoxPos(box,elem) {
	// check if box goes outside the height of the viewport
	// - quite complex and has to handle scroll etc. 
	// - for some reason (absolute and fixed stuff) scroll offset can only be found through
	// (10-main.y)/2
	try {
		var bottom_y_of_help_box = (10-getElementPosition("main").y)/2 +getElementPosition(box,getElementPosition("main")).y + getElementDimensions(box).h;
		var height_of_viewport = getViewportDimensions().h;
		if (bottom_y_of_help_box > height_of_viewport) {
			// box is outside, move up by height of box plus height of elem plus 4
			box.style.top = bottom_y_of_help_box - (2*getElementDimensions(box).h + getElementDimensions(elem).h + 4);
		}
	} catch (e) {
		log (e.message);
	}
	
	// check if box goes outside the right of the viewport
	// - simpler as we do not use horizontal scroll
	try {
		var right_x_of_help_box = getElementPosition(box).x + getElementDimensions(box).w;
		var width_of_viewport = getViewportDimensions().w;
		if (right_x_of_help_box+40 > width_of_viewport) {
			// box is outside, move left by width of box plus width of elem plus 4
			box.style.left = right_x_of_help_box - (2*getElementDimensions(box).w + getElementDimensions(elem).w + 4);
		}
	} catch (e) {
		log (e.message);
	}
}
function showError(elem,key) {
	jsonRequest(
	     {"key":key}
		,bind(showErrorBoxJson,this,elem)
	    ,"help"
	);
	
	return false;
}
function showErrorBoxJson(elem, result) {
	showErrorBox(elem, result.result);
}
function showErrorBox(elem, body) {
	var box = getElement("error_box");
	if (!box) {
		box = DIV(
			{'id':'error_box'},
			DIV(
				{'id':'error_box_inside'}
			),
			IFRAME(),
			IMG({'src':'resources/images/bottum_shadow.gif'},null)
		);
		appendChildNodes("mainpage", box);
	}
	if (typeof(elem) == "string") {
		elem = getElement(elem);
	}
	setNodeAttribute(elem,"onmouseout","$('error_box').style.display = 'none';");
	var pos = findPos(elem);
	box.style.top = pos[1] + elem.offsetHeight + 2;
	box.style.left = pos[0] + elem.offsetWidth + 2;
	
	//fix for embedded calc (to avoid overflowing, add more cases here or make a generic function for it)
	try{
	if (elem.id && elem.id=="heat_consumption") box.style.left=(parseInt(box.style.left)-120)+"px";
	}catch(E){}
	
	
	box.style.display = 'block';
	replaceChildNodes("error_box_inside",
		IMG({'src':'resources/images/close_button.gif','onclick':'$("error_box").style.display = "none";','width':10,'height':9},null),
			DIV({'id':"help_box_icon"},IMG({'src':'resources/images/warning_icon.gif'},null)),
			body
	);
	fixBoxPos(box,elem);
	return false;
}
// private for showHelpBox() do not call this function
function hideHelp() {
	getElement("help_box").style.display = 'none';
	return true;
}
// search for acronyms and create onmouseover
function checkDefinitions() {
	try {
		var acr, acrs = $$("acronym[title]");
		for (var i = 0; i < acrs.length; i++) {
			acr = acrs[i];
			if (!hasParentByTagName(acr, "a")) {
				if (acr.parentNode.className != "p_title"){ 
					var a = A({"href":"#", "class":"dictionary_word","onclick":"return false;"}, acr.firstChild.nodeValue);
					//log("class: "+(acr.parentNode.className));
					insertSiblingNodesAfter(acr, a); 
					var hook = partial(showDefinitionHook, a, acr.firstChild.nodeValue, getNodeAttribute(acr, "title"));
					removeElement(acr);
					connect(a, "onmouseover", hook);
				}else{
					insertSiblingNodesAfter(acr, ""+acr.firstChild.nodeValue); 
					removeElement(acr);
					//log("element removed");					
				}	
			}
		}
	} catch (e) {
		//log(e);
		//myonerror(e);
	}
}
function messageBox(elem, message, callback) {
	var form = FORM({},
		DIV(
			null,
			INPUT({
				'type'		:"text",
				'id'		:"name"
			}),
			LABEL(null,message),
			BR()
		),
		DIV(null,
			INPUT({'type':"submit",'value':"Gem",'class':"submit"}),
			INPUT({'type':"button",'value':"Anullér",'class':"submit",'onclick': "removeElement('calc_name') ;return false;"}),
			SPAN({'class':"error",'id':"calc_name_error"})
		)
	);
	connect(form, 'onsubmit', callback);
	var div = DIV({'id':"calc_name"},
		DIV({'class':"inside"},
			form
		),
		DIV(null,
			IMG({
					'style'	:"width: 305px; height: 3px;" ,
					'src'	:"/TKdk/resources/images/bottum_shadow.gif"
				}
			)
		)
	);
	var pos = findPos(elem);
	div.style.left = pos[0] + elem.offsetWidth - 312;
	div.style.top  = pos[1] + elem.offsetHeight - 4;
	
	appendChildNodes('main', div);
	return false;
}




function showDefinitionHook(elem, word, definition) {
	buildDefinitionBox(elem);
	showDefinitionBox(elem, {query:word, result:definition});
};
function buildDefinitionBox(elem) {
	var box = getElement("definition_box");
	var box_inside = null;
	if (!box) {
		box_inside = DIV({'id':'definition_box_inside'},null);
		box =
			DIV(
				{'id':'definition_box'},
				box_inside,
				IFRAME(),
				IMG({'src':'resources/images/bottum_shadow.gif'},null)
			);
		appendChildNodes("mainpage", box);
		// don't position yet - happens in showDefinitionBox
		// when contents has been filled in
	} else {
		box_inside = getElement("definition_box_inside");
	}
	
	connect(elem, "onmouseout", hideDefinition);
}
/* 
 * Request servlet for word definion, and show in small floating, closable box
 * 
 * @param {Element} elem - element under which box will be shown
 * @param {String}  word - the word for which we request definition
 * 
 * Set node attribute on element {onmouseover,onclick}:"return showDefinition(this,$word);"
 */
function showDefinition(elem,word) { 
	buildDefinitionBox(elem);
	json("dict_search", {'query':word}, bind(this.showDefinitionBox,this,elem));
	return false;
};
// private for showDefinition() do not call this function
function hideDefinition() {
	var box = getElement("definition_box");
	if (box) {
		box.style.display = 'none';
	}
	return true;
}
// private for showDefinition() do not call this function
function showDefinitionBox(elem,def) {
	replaceChildNodes("definition_box_inside",H4(null,IMG({'src':'resources/images/close_button.gif','onclick':'hideDefinition();','width':10,'height':9},null),def.query),def.result);
	
	// fix box position
	var footerpos;
	
	if ($('footer'))footerpos = findPos("footer");
	if ($('nefooter')) footerpos=findPos("nefooter");
	
	var pos = findPos(elem);
	var box = $("definition_box");
	// first show
	setStyle(box, {'display':'block'});
	// then set top and left constrained to page box
	var styles = 
		{"top":
			Math.min(
				footerpos[1] - box.offsetHeight, 
				pos[1] + elem.offsetHeight + 2
			)
		,"left":
			Math.min(
				footerpos[0] + $("mainpage").offsetWidth - 180, 
				pos[0] + elem.offsetWidth + 2
			)
		};
	setStyle(box,styles);
	
	return false;
}
function validateEmail(email) {
	var objRegExp  = /(^[a-z]([a-z_\-\.0-9]*)@([a-z\-_\.0-9]*)([.][a-z]{3})$)|(^[a-z]([a-z\-_\.]*)@([a-z\-_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;
	return objRegExp.test(email);
}
function tellAFriend(id,necalc) {
	var f = getElementsByTagAndClassName("form",null,"tell_afriend")[0];
	if (!validateEmail(f.friend_email.value)
	 && !validateEmail(f.email.value)
	 && f.friend_name.value == ""
	 && f.name.value == ""
	 ) {
		replaceChildNodes("email_message","Vær venlig at udfylde alle felter.");
		return false;
	}
	//stat("Send til ven :: "+f.headline.value);
	//tstat("Send til ven",""+f.headline.value,"Send til ven,"+f.headline.value,null);
	//do stats
	roiFriend();
	tstatSendFriend("Send til ven",""+f.headline.value,"Send til ven");
	json(
		"tell.friend",
		{
			'friend_email' 	:f.friend_email.value,
			'friend_name' 	:f.friend_name.value,
			'email' 		:f.email.value,
			'name'			:f.name.value,
			'content'		:f.tcontent.value,
			'id'			:id,
			'headline'		:f.headline.value,
			'necalc'		:necalc
		},
		bind(tellAFriendSendCallback, this)
	);
	return false;
}
function tellAFriendSendCallback() {
	$("friend_name").value = "";
	$("friend_email").value = "";
	replaceChildNodes("email_message"
			,"Din besked er blevet sendt."
			,BR(),"Angiv en ny e-mail-adresse, hvis du vil sende til flere. Hvis ikke, kan du lukket vinduet ved at klikke på krydset i hjørnet."
	);
}
function showTellAFriend(elem,id,headline,top,necalc) {
	var callTxt = "return tellAFriend('" + id + "'," + (necalc ? 'true' : 'false') + ");"
	var div = DIV({'id':"tell_afriend"},
		DIV({'class':"inside"},
			H1({
					'id'			:"tell_afrien_header"
				},
				INPUT({
					'type'		:"image",
					'src'		:"resources/images/close_button.gif",
					'onclick'	:"removeElement('tell_afriend'); return false;",
					'class'		:"help"
				}),
				INPUT({
					'type'			:"image",
					'src'			:"resources/images/white_help.gif",
					'onmouseover'	:"return showHelp(this,'help.email.send');",
					'class'			:"close",
					'onclick'		:"return false;"
				}),
				"Send siden til en ven"
			),
			FORM({
					'onsubmit'	:callTxt
				},
				INPUT({
					'type'	:"hidden",
					'value'	:headline,
					'id'	:"headline"
				}),
				DIV(
					null,
					INPUT({
						'type'		:"text",
						'id'		:"friend_name"
					}),
					LABEL(null,"Din vens navn: "),
					BR()
				),
				DIV(
					null,
					INPUT({
						'type'		:"text",
						'id'		:"friend_email"
					}),
					LABEL(null,"Din vens e-mail-adresse: "),
					BR()
				),
				DIV(
					null,
					INPUT({
						'type'		:"text",
						'id'		:"name",
						'value'		: myplanner.getName()
						
					}),
					LABEL(null,"Dit navn: "),
					BR()
				),
				DIV(
					null,
					INPUT({
						'type'		:"text",
						'id'		:"email",
						'value'		: myplanner.getEmail()
					}),
					LABEL(null,"Din e-mail-adresse: "),
					BR()
				),
				DIV(null,
					TEXTAREA({'id':"tcontent",'cols':40, 'rows':5}),
					BR()
				),
				DIV(null,
					INPUT({'type':"submit",'value':"Send",'class':"submit"}),
					SPAN({'class':"error",'id':"email_message"})
				)
			)
		),
		DIV(null,
			IMG({
					'class'	:"bottom_shadow_mail" ,
					'src'	:"/TKdk/resources/images/bottum_shadow.gif"
				}
			)
		)
	);
	var pos = findPos(elem);
	if (top) {
		div.style.left = pos[0] + elem.offsetWidth - 360;
		div.style.top  = pos[1] + elem.offsetHeight;
		//setElementPosition(div, new MochiKit.Style.Coordinates(p[0] - 360, p[1] + 16));
	} else {
		div.style.left = pos[0] + elem.offsetWidth - 360;
		div.style.top  = pos[1] + elem.offsetHeight - 280;
		//setElementPosition(div, new MochiKit.Style.Coordinates(p[0] - 360, p[1] - 234));
	}
	
	appendChildNodes('main', div);

	
	return false;
}
function colapseMenu() {
	for(var i = 1; i < 20; i++) {
		var li = getFirstElementByTagAndClassName("li",'p'+i,'menu');
		if (li) {
			setElementClass(getFirstElementByTagAndClassName("ul", null, li),"collapsed");
			setElementClass(getFirstElementByTagAndClassName("a", null, li),"");
		}
	}
}
function clearHighlight() {
	var links = getElementsByTagAndClassName('a',null,getFirstElementByTagAndClassName('li','p1','menu'));
	for (var i = 0; i < links.length; i++) {
		removeElementClass(links[i], "current_menu");
		removeElementClass(links[i], "current_submenu");
	}
}
function setMenuLinkHighlight(id) {
	clearHighlight();
	var a = null;
	if (thepage.lastLink && thepage.lastLink.id && thepage.lastLink.id == "pg_"+id) {
		a = thepage.lastLink;
	} else {
		a = $("pg_"+id);
	}
	if (a) {
		var menu = null;
		var sub_menu = null;
		var sub_sub_menu = null;
		
		//clear highlighting
		elements = getElementsByTagAndClassName("a", null, "menu");
		for (var i = 0; i < elements.length; i++) {
			setNodeAttribute(elements[i], "class", "");
		}
		
		if (a.name) {
			var sub = a.name.split("_");
			menu = $("pg_"+sub[1]);
			if (sub.length > 2) {
				if (sub[1] == sub[2]) {
					sub_menu = document.getElementsByName('par_'+sub[1])[0];
				} else {
					sub_menu = $("pg_"+sub[2]);
				}
				sub_sub_menu = a;
			} else {
				sub_menu = a;			
			}
		} else {
			menu = a;
		}
		if (menu) {
			setNodeAttribute(menu, "class", "current_menu");
		}
		if (sub_menu) {
			setNodeAttribute(sub_menu, "class", "current_submenu");
		}
		if (sub_sub_menu) {
			setNodeAttribute(sub_sub_menu, "class", "current_submenu");
		}
		;
		
		var child_ul = getFirstElementByTagAndClassName("ul", null, menu.parentNode);
		if (child_ul && !sub_menu) {
			toggleElementClass("collapsed", child_ul);
		}
		if (sub_menu && sub_menu.parentNode && sub_menu.parentNode.parentNode && sub_menu.parentNode.parentNode.className == "collapsed") {
			toggleElementClass("collapsed", child_ul);
		}
		
		// array for list of parents only
		var parents = [];
		if (menu && menu != a) parents.push(trim(scrapeText(menu)));
		if (sub_menu && sub_menu != a) parents.push(trim(scrapeText(sub_menu)));
		return parents;
	}
	return null;
}

function moveIt(e) {
	if (!pos) {
		pos = {};
		pos.top =  e.clientY - p[1];
		pos.left = e.clientX - p[0];
	}
	getElement("tell_afriend").style.top =  e.clientY - pos.top;
	getElement("tell_afriend").style.left = e.clientX - pos.left;
}

function stopDrag(e) {
	document.releaseEvents(Event.MOUSEMOVE);
	document.releaseEvents(Event.MOUSEUP);
	var header = getElement("tell_afrien_header");
	document.onmousemove = null;
	document.onmouseup = null;
	header.style.cursor = "";
	pos = null; 
}

function startDrag() {
	/*
	if(!isIe) {
		var header = getElement("tell_afrien_header");
		header.style.cursor = "move";
		document.onmousemove= moveIt;
		document.onmouseup = stopDrag;
		document.captureEvents(Event.MOUSEMOVE);
		document.captureEvents(Event.MOUSEUP);
		p = findPos(getElement("tell_afriend"));
	}
	*/
}

function hasParentByTagName(node, tag) {
	if (!tag) return node.parentNode != null;
	tag = tag.toUpperCase();
	for (;node && node.tagName; node = node.parentNode) {
		if (node.tagName.toUpperCase() == tag)
			return true;
	}
	return false;
}


var p = null;
var pos = null;
function externalStat(action, id) {
	switch(action) {
	case "page":	
		switch(id) {
			case "333":
				ADFtrack(7642,24695,['']);
				break;	
			case "176":
				ADFtrack(7642,24704,['']);
			 	break;
			 case "192":
			 	ADFtrack(7642,24705,['']);
			 	break;
			 case "223":
			 	ADFtrack(7642,24706,['']);
			 	break;
			 case "246":
			 	ADFtrack(7642,24707,['']);
			 	break;
			 case "261":
			 	ADFtrack(7642,24708,['']);
			 	break;
			}
		break;
	case "frontpage":
		ADFtrack(7642,24694,['']);
		break;
	}
}
var isIe = document.all;
/* end boxes */
addLoadEvent(function () {
	try {
		// create global 'thepage' object
		thepage = new Page();
		
		// examine deeplink in order to log stats 
		// and/or redirect user to page
		thepage.deeplink();
		
		// then initialize history watcher
		// (deeplink has now been examined properly)
		hist.initialize();

	} catch (e) {
		log(e);
	}
});
