var KPWindowsSocketTimeout = 20000;
var KPWindowsSocketTimeoutHandler = function(){
	alert("Socket Timeout");
	window.location.reload(true);
}
var KPWindowRemoveBorders = false;
var KPWindowUseFade = true;
var KPWindow = new Array();
var KPWindowHistoryList = Array();
var KPWindowProgressList = Array();
//KPWindow constructor
function KPWindowInit(){
	//load background
	if(getCookie('KPWindowSettingsBackGround'))
		document.getElementsByTagName('body')[0].style.backgroundImage = "url("+getCookie('KPWindowSettingsBackGround')+")";
	if(getCookie('KPWindowRemoveBorders') == 'true')
		KPWindowRemoveBorders = true;
	else
		KPWindowRemoveBorders = false;
	
	KPWindowNotifyUserLoading();
	var KPWindowCssRules = getCssRules();
	var x;
	var KPWindowScreenWidth = getViewPortWidth();
	var KPWindowScreenHeight = getViewPortHeight();
	//static elements counters
	iBTw=0; iBLw=0; iA1w=0; iB1w=0; iC1w=0; iA2w=0; iB2w=0; iC2w=0; iA3w=0; iB3w=0; iC3w=0; iA4w=0; iB4w=0; iC4w=0; iA5w=0; iB5w=0; iC5w=0; iBRw=0; iBBw=0;
	iBTh=0; iBLh=0; iA1h=0; iB1h=0; iC1h=0; iA2h=0; iB2h=0; iC2h=0; iA3h=0; iB3h=0; iC3h=0; iA4h=0; iB4h=0; iC4h=0; iA5h=0; iB5h=0; iC5h=0; iBRh=0; iBBh=0;
	var KPWindowStartBorderIsLeft = false;
	//alert(KPWindowCssRules.length+" - "+KPWindowCssRules.item(2));
	//for(x in KPWindowCssRules){
	for(x = 0; x<KPWindowCssRules.length; x++){
		if(KPWindowCssRules.item(x).selectorText && KPWindowCssRules.item(x).selectorText.toLowerCase().match('kpwindow')){
			if(KPWindowCssRules[x].selectorText.toLowerCase().match('kpwindowstartborder') && KPWindowCssRules.item(x).style.left == '1px'){
				KPWindowStartBorderIsLeft = true;
			}
			var KPWindowElementId = KPWindowCssRules.item(x).selectorText.toLowerCase().split("#")[1];
			var KPWindowElement = document.getElementById(KPWindowElementId);
			//alert(KPWindowElementId + ' - '+KPWindowElement);
			if(KPWindowElement){
				switch(KPWindowElementId){
					//calculate borders
					case 'kpwindowbordertop':
						/*if(KPWindowRemoveBorders){
							iBTw = 0;
							iBTh = 0;
							break;
						}*/
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)	
							iBTw = parseInt(KPWindowCssRules.item(x).style.width);
						else
							iBTw = KPWindowScreenWidth;
						if(KPWindowRemoveBorders)
							iBTh = 30;
						else if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iBTh = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iBTh = (parseInt(KPWindowCssRules.item(x).style.height) * KPWindowScreenHeight)/100;
						break;
					case 'kpwindowborderbottom':
						if(KPWindowRemoveBorders){
							iBBw = 0;
							iBBh = 0;
							break;
						}
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iBBw = parseInt(KPWindowCssRules.item(x).style.width);
						else
							iBBw = KPWindowScreenWidth;
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iBBh = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iBBh = (parseInt(KPWindowCssRules.item(x).style.height) * KPWindowScreenHeight)/100;
						break;	
					case 'kpwindowborderleft':
						//border left and right defs should be in bottom of css because this calc is dependand on other window heights when borders are defined in %.
						if(KPWindowRemoveBorders){
							iBLw = 0;
							iBLh = 0;
							break;
						}
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iBLw = parseInt(KPWindowCssRules.item(x).style.width);
						else
							iBLw = (parseInt(KPWindowCssRules.item(x).style.width) * KPWindowScreenWidth)/100;
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iBLh = parseInt(KPWindowCssRules.item(x).style.height);
						else
							if (KPWindowStartBorderIsLeft)
								iBLh = (parseInt(KPWindowCssRules.item(x).style.height) * (iBTh + iA1h + iA2h + iA3h + iA4h + iA5h + iBBh))/100;
							else
								iBLh = (parseInt(KPWindowCssRules.item(x).style.height) * (iA1h + iA2h + iA3h + iA4h + iA5h))/100;
						break;
					case 'kpwindowborderright':
						if(KPWindowRemoveBorders){
							iBRw = 0;
							iBRh = 0;
							break;
						}
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iBRw = parseInt(KPWindowCssRules.item(x).style.width);
						else
							iBRw = (parseInt(KPWindowCssRules.item(x).style.width) * KPWindowScreenWidth)/100;
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iBRh = parseInt(KPWindowCssRules.item(x).style.height);
						else
							if (!KPWindowStartBorderIsLeft)
								iBRh = (parseInt(KPWindowCssRules.item(x).style.height) * (iBTh + iA1h + iA2h + iA3h + iA4h + iA5h + iBBh))/100;
							else
								iBRh = (parseInt(KPWindowCssRules.item(x).style.height) * (iA1h + iA2h + iA3h + iA4h + iA5h))/100;
						break;
					case 'kpwindowa1':
						//count static defined heights in css for al windows
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iA1w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iA1h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iA1h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iA1h+iA2h+iA3h+iA4h+iA5h)))/100);
							//this is needed to calculate the correct border left and right height. This also wil be excluded correctly in % calc in next switch.
						break;
					case 'kpwindowb1':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iB1w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iB1h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iB1h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iB1h+iB2h+iB3h+iB4h+iB5h)))/100);
						break;
					case 'kpwindowc1':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iC1w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iC1h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iC1h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iC1h+iC2h+iC3h+iC4h+iC5h)))/100);
						break;
					case 'kpwindowa2':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iA2w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iA2h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iA2h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iA1h+iA2h+iA3h+iA4h+iA5h)))/100);
						break;
					case 'kpwindowb2':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iB2w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iB2h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iB2h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iB1h+iB2h+iB3h+iB4h+iB5h)))/100);
						break;
					case 'kpwindowc2':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iC2w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iC2h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iC2h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iC1h+iC2h+iC3h+iC4h+iC5h)))/100);
						break;
					case 'kpwindowa3':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iA3w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iA3h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iA3h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iA1h+iA2h+iA3h+iA4h+iA5h)))/100);
						break;
					case 'kpwindowb3':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iB3w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iB3h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iB3h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iB1h+iB2h+iB3h+iB4h+iB5h)))/100);
						break;
					case 'kpwindowc3':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iC3w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iC3h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iC3h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iC1h+iC2h+iC3h+iC4h+iC5h)))/100);
						break;
					case 'kpwindowa4':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iA4w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iA4h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iA4h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iA1h+iA2h+iA3h+iA4h+iA5h)))/100);
						break;
					case 'kpwindowb4':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iB4w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iB4h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iB4h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iB1h+iB2h+iB3h+iB4h+iB5h)))/100);
						break;
					case 'kpwindowc4':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iC4w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iC4h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iC4h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iC1h+iC2h+iC3h+iC4h+iC5h)))/100);
						break;
					case 'kpwindowa5':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iA5w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iA5h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iA5h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iA1h+iA2h+iA3h+iA4h+iA5h)))/100);
						break;
					case 'kpwindowb5':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iB5w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iB5h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iB5h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iB1h+iB2h+iB3h+iB4h+iB5h)))/100);
						break;
					case 'kpwindowc5':
						if(KPWindowCssRules.item(x).style.width.indexOf("%") < 0)
							iC5w = parseInt(KPWindowCssRules.item(x).style.width);
						if(KPWindowCssRules.item(x).style.height.indexOf("%") < 0)
							iC5h = parseInt(KPWindowCssRules.item(x).style.height);
						else
							iC5h = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh+iC1h+iC2h+iC3h+iC4h+iC5h)))/100);
						break;				
				}
			}
		}	
	}
	//alert(KPWindowStartBorderIsLeft+' - '+iBTh+' - '+iBLh+' - '+iA1h+' - '+iB1h+' - '+iC1h+' - '+iA2h+' - '+iB2h+' - '+iC2h+' - '+iA3h+' - '+iB3h+' - '+iC3h+' - '+iA4h+' - '+iB4h+' - '+iC4h+' - '+iA5h+' - '+iB5h+' - '+iC5h+' - '+iBRh+' - '+iBBh);
	for(x = 0; x<KPWindowCssRules.length; x++){
		if(KPWindowCssRules.item(x).selectorText && KPWindowCssRules.item(x).selectorText.toLowerCase().match('kpwindow')){
			var KPWindowElementId = KPWindowCssRules.item(x).selectorText.toLowerCase().split("#")[1];
			var KPWindowElement = document.getElementById(KPWindowElementId);
			if(KPWindowElement){
				//alert(KPWindowElementId+": width:"+KPWindowCssRules.item(x).style.width+": height:"+KPWindowCssRules.item(x).style.height);
				switch(KPWindowElementId){
					case 'kpwindowbordertop':
						KPWindow[0] = KPWindowElement;
						if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
							KPWindowElement.style.position = 'absolute';
							KPWindowElement.style.top = '0px';
							KPWindowElement.style.height = iBTh+'px';
							if(KPWindowStartBorderIsLeft){
								KPWindowElement.style.left = iBLw+'px';
								KPWindowElement.style.width = (iBTw-iBLw-iBRw)+'px';
							} else {							
								KPWindowElement.style.left = '0px';
								KPWindowElement.style.width = iBTw+'px';
							}
						}
						break;
					case 'kpwindowborderbottom':
					KPWindow[2] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.height = iBBh+'px';
						KPWindowElement.style.top = (KPWindowScreenHeight-iBBh)+'px';
						if(KPWindowStartBorderIsLeft){
							KPWindowElement.style.left = iBLw+'px';
							KPWindowElement.style.width = (iBBw-iBLw-iBRw)+'px';
						} else {
							KPWindowElement.style.left = '0px';
							KPWindowElement.style.width = iBBw+'px';
						}
					}
						break;
					case 'kpwindowborderleft':
					KPWindow[3] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						//console.log('kpwindowborderleft');
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.left = '0px';
						KPWindowElement.style.width = iBLw+'px';
						if(KPWindowStartBorderIsLeft){
							KPWindowElement.style.top = '0px';
							KPWindowElement.style.height = iBLh+'px';
						} else {
							KPWindowElement.style.top = document.getElementById('kpwindowbordertop').style.height;
							KPWindowElement.style.height = iBLh+'px';
						}
					}
						break;
					case 'kpwindowborderright':
					KPWindow[1] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.left = KPWindowScreenWidth - iBRw;
						KPWindowElement.style.width = iBRw+'px';
						if(KPWindowStartBorderIsLeft){
							KPWindowElement.style.top = '0px';
							KPWindowElement.style.height = iBRh+'px';
						} else {
							KPWindowElement.style.top = document.getElementById('kpwindowbordertop').style.height;
							KPWindowElement.style.height = iBRh+'px';
						}
					}
						break;
					case 'kpwindowa1':
					KPWindow[4] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = '0px';
						KPWindowElement.style.left = '0px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}	
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowb1':
					KPWindow[5] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = '0px';
						KPWindowElement.style.left = parseInt(document.getElementById('kpwindowa1').style.width)+parseInt(document.getElementById('kpwindowa1').style.left)+'px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowc1':
					KPWindow[6] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = '0px';
						KPWindowElement.style.left = parseInt(document.getElementById('kpwindowb1').style.width)+parseInt(document.getElementById('kpwindowb1').style.left)+'px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}	
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowa2':
					KPWindow[7] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowa1').style.height)+parseInt(document.getElementById('kpwindowa1').style.top)+'px';
						KPWindowElement.style.left = '0px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowb2':
					KPWindow[8] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						iTop = parseInt(document.getElementById('kpwindowb1').style.top);
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowb1').style.height)+iTop+'px';
						KPWindowElement.style.left = parseInt(document.getElementById('kpwindowa2').style.width)+parseInt(document.getElementById('kpwindowa2').style.left)+'px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}	
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowc2':
					KPWindow[9] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowc1').style.height)+parseInt(document.getElementById('kpwindowc1').style.top)+'px';
						KPWindowElement.style.left = parseInt(document.getElementById('kpwindowb2').style.width)+parseInt(document.getElementById('kpwindowb2').style.left)+'px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}	
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowa3':
					KPWindow[10] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowa2').style.height)+parseInt(document.getElementById('kpwindowa2').style.top)+'px';
						KPWindowElement.style.left = '0px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowb3':
					KPWindow[11] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowb2').style.height)+parseInt(document.getElementById('kpwindowb2').style.top)+'px';
						KPWindowElement.style.left = parseInt(document.getElementById('kpwindowa3').style.width)+parseInt(document.getElementById('kpwindowa3').style.left)+'px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowc3':
					KPWindow[12] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowc2').style.height)+parseInt(document.getElementById('kpwindowc2').style.top)+'px';
						KPWindowElement.style.left = parseInt(document.getElementById('kpwindowb3').style.width)+parseInt(document.getElementById('kpwindowb3').style.left)+'px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowa4':
					KPWindow[13] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowa3').style.height)+parseInt(document.getElementById('kpwindowa3').style.top)+'px';
						KPWindowElement.style.left = '0px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowb4':
					KPWindow[14] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowb3').style.height)+parseInt(document.getElementById('kpwindowb3').style.top)+'px';
						KPWindowElement.style.left = parseInt(document.getElementById('kpwindowa4').style.width)+parseInt(document.getElementById('kpwindowa4').style.left)+'px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowc4':
					KPWindow[15] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowc3').style.height)+parseInt(document.getElementById('kpwindowc3').style.top)+'px';
						KPWindowElement.style.left = parseInt(document.getElementById('kpwindowb4').style.width)+parseInt(document.getElementById('kpwindowb4').style.left)+'px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowa5':
					KPWindow[16] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowa4').style.height)+parseInt(document.getElementById('kpwindowa4').style.top)+'px';
						KPWindowElement.style.left = '0px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowb5':
					KPWindow[17] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowb4').style.height)+parseInt(document.getElementById('kpwindowb4').style.top)+'px';
						KPWindowElement.style.left = parseInt(document.getElementById('kpwindowa5').style.width)+parseInt(document.getElementById('kpwindowa5').style.left)+'px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowc5':
					KPWindow[18] = KPWindowElement;
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = parseInt(document.getElementById('kpwindowc4').style.height)+parseInt(document.getElementById('kpwindowc4').style.top)+'px';
						KPWindowElement.style.left = parseInt(document.getElementById('kpwindowb5').style.width)+parseInt(document.getElementById('kpwindowb5').style.left)+'px';
						if(KPWindowCssRules.item(x).style.width.indexOf("%") > -1){
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * (KPWindowScreenWidth-(iBLw+iBRw)))/100)+'px';
						} else {
							KPWindowElement.style.width = KPWindowCssRules.item(x).style.width;
						}
						if(KPWindowCssRules.item(x).style.height.indexOf("%") > -1){	
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * (KPWindowScreenHeight-(iBTh+iBBh)))/100)+'px';
						} else {
							KPWindowElement.style.height = KPWindowCssRules.item(x).style.height;
						}
					}
						break;
					case 'kpwindowscrollpane':
					if(!KPWindowLoadUserSettingsWindow(KPWindowElementId)){
						KPWindowElement.style.position = 'absolute';
						KPWindowElement.style.top = document.getElementById('kpwindowbordertop').style.height;
						KPWindowElement.style.left = document.getElementById('kpwindowborderleft').style.width;
						KPWindowElement.style.width = (KPWindowScreenWidth-iBLw-iBRw)+'px';
						KPWindowElement.style.height = (KPWindowScreenHeight-iBTh-iBBh)+'px';
					}
						break;					
					default:
						if(KPWindowCssRules.item(x).style.width != '' && KPWindowCssRules.item(x).style.height != ''){
							/*KPWindowElement.style.top = '0px';
							KPWindowElement.style.left = '0px';
							KPWindowElement.style.width = ((parseInt(KPWindowCssRules.item(x).style.width) * KPWindowScreenWidth)/100)+'px';
							KPWindowElement.style.height = ((parseInt(KPWindowCssRules.item(x).style.height) * KPWindowScreenHeight)/100)+'px';
							KPWindowElement.style.position = 'absolute';*/
						}
						break;					
				}
				//alert(KPWindowElementId+' top:'+KPWindowElement.style.top+' left:'+KPWindowElement.style.left+' width:'+KPWindowElement.style.width+' height:'+KPWindowElement.style.height);
			}
			//alert(x+" "+KPWindowCssRules.length);
		}	
	}
	/*
	KPWindowSaveUserSettingsWindow("kpwindowb1");
	KPWindowLoadUserSettingsWindow("kpwindowb1");
	*/
	KPWindowNotifyUserDoneLoading();
}
function KPWindowLoadUserSettingsWindow(windowName){
	var cookieString = getCookie('KPWindowSettings'+windowName);
	var KPWindowElement = document.getElementById(windowName);
	if(cookieString == null || cookieString == "" || KPWindowElement == null){
		return false;
	}
	var settings = cookieString.split(";");
	KPWindowElement.style.position = settings[0].split("=")[1];//0
	KPWindowElement.style.top = settings[1].split("=")[1];//1
	KPWindowElement.style.left = settings[2].split("=")[1];//2
	KPWindowElement.style.width = settings[3].split("=")[1];//3
	KPWindowElement.style.height = settings[4].split("=")[1];//4
	KPWindowElement.style.zIndex = settings[5].split("=")[1];//5
	if(typeof(settings[6].split("=")[1]) != 'undefined')//ms feature
		KPWindowElement.style.visibility = settings[6].split("=")[1];//6
	return true;
}
function KPWindowSaveUserSettingsWindow(windowName){
	var KPWindowElement = document.getElementById(windowName);
	if(KPWindowElement == null){
		return;
	}
	var cookieString = "";
	cookieString += "position="+KPWindowElement.style.position+";";//0
	cookieString += "top="+KPWindowElement.style.top+";";//1
	cookieString += "left="+KPWindowElement.style.left+";";//2
	cookieString += "width="+KPWindowElement.style.width+";";//3
	cookieString += "height="+KPWindowElement.style.height+";";//4
	cookieString += "zIndex="+KPWindowElement.style.zIndex+";";//5
	cookieString += "visibility="+KPWindowElement.style.visibility+";";//6
	setCookie('KPWindowSettings'+windowName,cookieString,99);
}
//no window reset on resize for desktop env 
window.onresize=KPWindowInit;
//Test case
function KPWindowTest(){
	alert("start test!");	
	//KPWindow test case
	setTimeout("KPWindowShowOverlayHtml('<p><center><h1>Test Case 1: Overlay</h1></center></p>');", 2000);
	setTimeout("KPWindowShowOverlayHtml('<center><br><div style=\"width: 90%; height:90%; border-style: solid; background: gray; text-align: center;\"><h1>Overlay!</h1></div></center>');", 4000);
	setTimeout("KPWindowHideOverlay();",6000);
	setTimeout("KPWindowShowOverlayHtml('<p><center><h1>Test Case 2: Loading</h1></center></p>');", 8000);
	setTimeout("KPWindowNotifyUserLoading();",10000);
	setTimeout("KPWindowNotifyUserDoneLoading();",14000);
	setTimeout("KPWindowHideOverlay();",14000);
	setTimeout("KPWindowShowOverlayHtml('<p><center><h1>Test Case 3: Resize</h1></center></p>');", 14000);
	setTimeout("window.resizeBy(-200,-200);",16000);
	//setTimeout("KPWindowShowOverlayHtml('<p><center><h1>Test Case 4: Replace CSS</h1></center></p>');", 17000);
	//setTimeout("KPWindowSwitchCSS('./css/kpwindow_dashboard.css');",19000);
	setTimeout("KPWindowShowOverlayHtml('<p><center><h1>Test Done</h1></center></p>');", 19000);
	setTimeout("KPWindowHideOverlay();",21000);//*/
}

function KPWindowLoadParseStr(url, windowId, sourceId){
	//fill in escaped vars from input fields
	url = parseStr( url, 1, sourceId);
	KPWindowLoad(url, windowId);
}

//KPWindow api - load window innerHTML
function KPWindowLoad(url, windowId, addHistory){
	if (KPWindowGetInProgress(windowId) == true)
	{
		return false;
	}
	else
	{
	   KPWindowSetInProgress(windowId,true);
	}  	
	
  if(typeof addHistory=='undefined') addHistory=true;
  require(["dojo/domReady!"],function(){
  	if(addHistory && !(typeof KPWindowHistory === 'undefined')) {
  		KPWindowHistory.add(url,windowId);
  	}
	KPWindowClearElement('tempContentDiv');

	//if no cmode defined, add cmode	
	if(url.indexOf("cmode")<0 && windowId.indexOf("kpwindow")<0){
		url += "&cmode="+windowtype_to_cmode[windowId];
	}
	
	//if windowId is no actual kpwindow, translate alias to windowId
	if(windowId.indexOf("kpwindow")<0){
		windowId = windowtype_to_location[windowId];
	}
	
	if(windowId == "kpwindowoverlay" || windowId == "kpwindowoverlaybody") {
		KPWindowShowOverlay(url);
	} else {
		opacity(windowId, 100, 0, 500);
		//cleanupWidgets(windowId);
		KPWindowNotifyUserLoading();
		KPWindowCleanUpIncludes(windowId);
		KPWindowAddHistory(windowId,url);
		
		require(["dojo/domReady!"],function(ready){
			
			Sarissa.updateContentFromURI(url+"&contenttype=text/xml", document.getElementById(windowId), null, KPWindowOnloadCallback);
			});
		//setTimeout('Sarissa.updateContentFromURI("'+url+'"+"&contenttype=text/xml", document.getElementById("'+windowId+'"), null, KPWindowOnloadCallback);',1);
	}
  });
}

function checkAndSetTarget(trgt, ddDiagTarget){
	//set target
	var subField = ( getForm(trgt).elements[ 'target' ] ) ? 'target' : ( getForm(trgt).elements[ 'subButton' ] ) ? 'subButton' : undef;
	if( getForm(trgt).elements[ subField ] )
	{
		if( getForm(trgt).elements[ subField ].type )
		{
			if( getForm(trgt).elements[ subField ].type == 'hidden' )
			{
				getForm(trgt).elements[ subField ].value = ddDiagTarget;
				//document.getElementById('my').submit(); // post
				//KPWindowDoPost(trgt);
				return true;
			}
		}
		return false;
	}
	else
	{
		// Do not no how to submit both target and subButton are not defined.
		alert( 'Kan niet submitten zowel target als subButton zijn niet gedefinieerd.');
		return false;
	}	
}

//post a form in a KPWindow and load the returned result.
function KPWindowDoPost(windowId, target, noResult){

	if(noResult == undefined || noResult == null) {
		noResult = false;	
	}
	
	if (KPWindowGetInProgress(windowId) == true)
	{
		return false;
	}
	else
	{
	   KPWindowSetInProgress(windowId,true);
	}  	
	if(!checkAndSetTarget(windowId, target)){
		return false;	
	}
	
	if(!KPWindowComponentRunOnsubmit(windowId)){
		return false;	
	}
	
	//check dojo formManger if form is valid
	require(["dijit/registry"], function(registry){
		if(!registry.byId(getForm(windowId).id).validate()){
			return false;
		}
	});
	
	//if windowId is no actual kpwindow, translate alias to windowId
	if(windowId.indexOf("kpwindow")<0){
		windowId = windowtype_to_location[windowId];
	}
	
	if(windowId == "kpwindowoverlaybody"){
		opacity("kpwindowoverlay", 100, 0, 500);
	} else {
		//KPWindowGetHistory(windowId,windowId);
		opacity(windowId, 100, 0, 500);
	}
	KPWindowNotifyUserLoading();
	KPWindowCleanUpIncludes(windowId);
	if(noResult) {
		//TODO load/destroy issue formmanger
		setTimeout("Sarissa.updateContentFromForm(getForm('"+windowId+"'), document.getElementById('"+windowId+"'), null, null);",1);
		//Sarissa.updateContentFromForm(getForm(windowId), document.getElementById(windowId), null, null);
	}
	else {
		//TODO load/destory issue formmanger
		setTimeout("Sarissa.updateContentFromForm(getForm('"+windowId+"'), document.getElementById('"+windowId+"'), null, KPWindowOnloadCallback);",1);
		//Sarissa.updateContentFromForm(getForm(windowId), document.getElementById(windowId), null, KPWindowOnloadCallback);
	}
	return false;
}
//KPWindow api - overlay
function KPWindowShowOverlay(url){
	//alert(url);
	//changeOpac(0, 'kpwindowoverlay');
	if(url.indexOf("cmode")<0)
	{
		url+='&cmode=kpwindow_dialogborder_overlay';
	}
	KPWindowNotifyUserLoading();
	//window.scroll(0,0);
	//cleanupWidgets('kpwindowoverlay');	
	KPWindowCleanUpIncludes('kpwindowoverlay');
	KPWindowAddHistory('kpwindowoverlay',url);
	Sarissa.updateContentFromURI(url+"&contenttype=text/xml", document.getElementById('kpwindowoverlay'), null, KPWindowOnloadCallback);
	document.getElementById('kpwindowoverlay').style.visibility = "visible";
	//opacity('kpwindowoverlay', 0, 90, 500);
	addPlaceHolders();
	//KPWindowNotifyUserDoneLoading();
}
function KPWindowShowOverlayHtml(htmlText){
	KPWindowNotifyUserLoading();
	window.scroll(0,0);
	document.getElementById('kpwindowoverlay').innerHTML = htmlText;
	//changeOpac(0, 'kpwindowoverlay');
	document.getElementById('kpwindowoverlay').style.visibility = "visible";
	KPWindowNotifyUserDoneLoading();
	opacity('kpwindowoverlay', 0, 90, 500);
	addPlaceHolders();
}
function KPWindowHideOverlay(){
	opacity('kpwindowoverlay', 90, 0, 500);
	removePlaceHolders();
	cleanupWidgets('kpwindowoverlay');	
	//TODO load/destory issue formmanager
	setTimeout('document.getElementById("kpwindowoverlay").style.visibility = "hidden";KPWindowClearElement("kpwindowoverlay");',1);
	//document.getElementById("kpwindowoverlay").style.visibility = "hidden";
	//KPWindowClearElement("kpwindowoverlay");
}
//window history

function KPWindowAddHistory(windowId, windowUrl){
	
	if(windowUrl == null || windowUrl.indexOf("endstream") > 0 || windowUrl.indexOf("skipkpwindowhistory") > 0) {
		console.log('skip to history '  + windowId + '  ' + windowUrl);
		return;
	}
	
	if(windowId.indexOf('kpwindowoverlaybody')>-1){
		windowId = 'kpwindowoverlay';	
	}
	if(typeof(KPWindowHistoryList[windowId]) == 'undefined'){
		KPWindowHistoryList[windowId] = Array();
	}
	
	console.log('add to history '  + windowId + '  ' + windowUrl);
	KPWindowHistoryList[windowId].push(windowUrl)
}
function KPWindowGetHistory(windowId){
	
	if(windowId.indexOf('kpwindowoverlaybody')>-1){
		windowId = 'kpwindowoverlay';	
	}
	if(typeof KPWindowHistoryList[windowId] != 'undefined'){
		if(KPWindowHistoryList[windowId].length > 1){
			KPWindowHistoryList[windowId].pop();
			ans = KPWindowHistoryList[windowId].pop();
			console.log('get history for ' + windowId + '  ' + ans);
			return ans;
		} else {
			return KPWindowHistoryList[windowId][0];
		}
	} else {
		//return current url if history is not defined.
		return window.location.href.replace('&cmode=easy_dialog','');
	}
}
function KPWindowHistoryBack(e1){
	targetid = KPWindowFindParent(e1).getAttribute('id');
	if(targetid.indexOf('kpwindowoverlaybody')>-1){
		targetid = 'kpwindowoverlay';	
	}
	if(targetid.indexOf('kpwindowoverlay')==-1){
		KPWindowLoad(KPWindowGetHistory(targetid),targetid);
	} else {
		if(KPWindowHistoryList[targetid].length <= 1){
			KPWindowHideOverlay();
		} else {
			KPWindowShowOverlay(KPWindowGetHistory(targetid));
		}
	}
}
function KPWindowChangeCmode(e1){
	targetid = KPWindowFindParent(e1).getAttribute('id');
	if(targetid.indexOf('kpwindowoverlay')==-1){
		var lasturl = ""+KPWindowHistoryList[targetid][KPWindowHistoryList[targetid].length-1];
		if(lasturl.indexOf("_edit")<0){
			lasturl = lasturl+"_edit";
		} else {
			lasturl = lasturl.replace(/_edit$/,"");
		}
		KPWindowLoad(lasturl,targetid);
	}
}

//refresh all windows
function KPWindowRefresh(steps){
	if(steps == null || steps == "undefined"){
		//alert(document.getElementsByTagName('form')[0].id);
		steps =1;
	}
	for(x in KPWindowHistoryList){
		if(x.indexOf('kpwindow')>-1 && x.indexOf('kpwindowoverlay')==-1 && KPWindowHistoryList[x].length>0){
			if(document.getElementById(x) != null){
				//alert("refresh "+x+" - "+KPWindowHistoryList[x][KPWindowHistoryList[x].length-1]);
				/* this is bad functionality. You never want to send ALL windows back 2 steps.
				This is implementen to prevent loading of a deleted instance. Instead of this we will check if thhe instance is deleted on load if so, 
				it will forward to the instance lists of its context.
				TODO check navigation delete.
				tmpsteps = steps;
				if(tmpsteps > 1 && KPWindowHistoryList[x].length > 1) {
					KPWindowHistoryList[x].pop();
					tmpsteps--;
				}*/
				KPWindowLoad(KPWindowHistoryList[x][KPWindowHistoryList[x].length-1]+'&P_NOFOCUS=1',x);
			} else {
				//dynamic generated divframe, need to remove from History ouside this loop... 
				//other wise it skips a element.
			}
		}
	}
}
function KPWindowRefreshWindow(windowid){
	if(document.getElementById(windowid) != null){
		//alert(windowid);
		//alert("refresh "+windowid+" - "+KPWindowHistoryList[windowid][KPWindowHistoryList[windowid].length-1]);
		
		KPWindowLoad(KPWindowGetHistory(targetid),windowid);
	}
}
//remove / add borders in kpwindow rendering
function KPWindowBordersSwitch(){
	if(KPWindowRemoveBorders){
		KPWindowRemoveBorders = false;
	} else {
		KPWindowRemoveBorders = true;
	}
	setCookie('KPWindowRemoveBorders',KPWindowRemoveBorders,99);
	KPWindowInit();
}
//remove previous included javascript for this window
function KPWindowCleanUpIncludes(windowId){
	while(document.getElementById(windowId+"include") != null){
		getParent(document.getElementById(windowId+"include")).removeChild(document.getElementById(windowId+"include"));
	}
}

//dom update callback function
function KPWindowOnloadCallback(oForm, oTargetElement, e, rawSource){
	//TODO load/destory issue formmanager
	//require(["dojo/ready"], function(ready){
	//	ready(function(){
			//cleanupWidgets(oTargetElement.id);
			KPWindowSetInProgress(oTargetElement.id,false);
			//alert(new XMLSerializer().serializeToString(oForm));
			//check for update errors (sarissa xml parse errors)
			if(typeof(e)!='undefined'){
				if(typeof(rawSource)=='undefined'){
					rawSource = '';
				}
				KPWindowError(e,rawSource);
			} else {
				//DEBUG: alert all loaded content
				//alert(new XMLSerializer().serializeToString(oTargetElement));
				//check for todo items
				if(KPWindowComponentToDo(oTargetElement)){
					KPWindowLoad(KPWindowToDoList.shift(), oTargetElement.getAttribute('id'));	
				}
				//check for forwards
				KPWindowComponentForward(oTargetElement);

				//scroll in to view
				if(typeof oForm == 'string' && oForm.indexOf('&P_FOCUSRESET=1') != -1){
					window.scroll(0,0);
				}else if(typeof oForm != 'string' || oForm.indexOf('&P_NOFOCUS=1') == -1){
					require(["dojo/window"], function(win){
					  win.scrollIntoView(oTargetElement);
					});
					
					/*alternative smooth scrolling
					require(["dojox/fx/scroll","dojo/dom"], function(scroll,dom){
						dojox.fx.smoothScroll({
							node: oTargetElement,
							win: dom.byId('kpwindowscrollpane'),
							duration: 300
						}).play();
					});*/
				}
						
				//run includes js components
				KPWindowRunComponentJS(oTargetElement);
				//check for end stream
				KPWindowComponentEndstream(oTargetElement);
				//check for screen refresh
				KPWindowComponentRefresh(oTargetElement);
				//register component onsubmit
				KPWindowComponentRegisterOnsubmit(oTargetElement);
				//Create Dijit Form
				KPWindowRunDojo(oTargetElement);
			}
			//remove loading screen
			KPWindowNotifyUserDoneLoading();
			//this if oTargetElement is not rfemoved from dom by other thread and fade new element back in.
			if(oTargetElement != null){
				if(oTargetElement.id == "kpwindowoverlaybody"){
					setTimeout("opacity('kpwindowoverlay', 0, 100, 100);",100);
				} else {
					setTimeout("opacity('"+oTargetElement.id+"', 0, 100, 100);",100);
				}
				//reload deactivated window list
				if(oTargetElement.style.visibility == 'hidden' && document.getElementById('windowlist')){
					//KPWindowRefreshWindow(KPWindowFindParent(document.getElementById('windowlist')).id);	
					KPWindowWindowRestoreList(document.getElementById('windowlist'));
				}
			}
	//	 });
	//});
}
var KPWindowToDoList = Array();
//add the url in the value of the name=component_todo elements to the todo list
function KPWindowComponentToDo(oTargetElement){
	todoEls = document.getElementsByName('component_todo');
	ret = false;
	
	//FIX TODO LIST HACK voor Roko
	//Reset todo list 
	//if(todoEls.length > 0)
		//KPWindowToDoList = Array();
	
	for(i = todoEls.length; i>0; i--){
		if(todoEls[0] && todoEls[0].value && todoEls[0].value != ''){
			//alert(i+' TODO:'+todoEls[0].value);
			KPWindowToDoList.push(todoEls[0].value);
			ret = true;
		}
		getParent(todoEls[0]).removeChild(todoEls[0]);
	}
	return ret;
}
//forward the kpwindows to the url in the value of the name=component_forward elements
function KPWindowComponentForward(oTargetElement){
	var	ret = false;
	//console.debug("processing forwards for ",oTargetElement);
	require(["dojo/query"],function(query){
		//forwardEls = document.getElementsByName('component_forward');
		forwardEls = query("input[name=\"component_forward\"]",oTargetElement);
		//console.debug("detected forwards",forwardEls);
		for(i = 0; i<forwardEls.length; i++){
			if(forwardEls[i] && forwardEls[i].value && forwardEls[i].value != ''){
				//console.debug("forwarding url,id",forwardEls[i].value, forwardEls[i].getAttribute('target'));
				//alert(i+' KPWindowLoad('+forwardEls[0].value+', '+forwardEls[0].getAttribute('target')+')');
				KPWindowLoad(forwardEls[i].value, forwardEls[i].getAttribute('target'));
				ret = true;
			}
			//TODO safari
			if(typeof(forwardEls[i]) != 'undefined' && forwardEls[i] != null){
				getParent(forwardEls[i]).removeChild(forwardEls[i]);
			}
		}
	});
	return ret;
}
//check for a compnent with name=component_endstream, if so, load next todo item or close/re-initialize window
function KPWindowComponentEndstream(oTargetElement){
	endEls = document.getElementsByName('component_endstream');
	if(endEls.length > 0){
		//alert("endstream "+oTargetElement.getAttribute('id'));
		KPWindowsOnSubmit[oTargetElement.getAttribute('id')] = new Array();
		if(typeof(endEls[0]) != 'undefined'){
			getParent(endEls[0]).removeChild(endEls[0]);
		}
		if(KPWindowToDoList.length > 0){
			KPWindowLoad(KPWindowToDoList.shift(), oTargetElement.getAttribute('id'));
		} else {
			x = oTargetElement.getAttribute('id');
			if(x.indexOf('kpwindow')>-1 && x.indexOf('kpwindowoverlay')==-1){
				//KPWindowLoad(KPWindowHistoryList[x][0],x);
				
				KPWindowLoad(KPWindowGetHistory(oTargetElement.getAttribute('id')),oTargetElement.getAttribute('id'));
			} else if (x.indexOf('kpwindowoverlay')>-1){
				KPWindowHideOverlay();
			}
		}
		return true;
	}
	return false;
}
//check for a compnent with name=component_refresh, if so, refresh all kpwidnows
function KPWindowComponentRefresh(oTargetElement){
	refresEls = document.getElementsByName('component_refresh');
	
	if(refresEls.length > 0){
		steps = refresEls[0].value;
		if(typeof(refresEls[0]) != 'undefined'){
			getParent(refresEls[0]).removeChild(refresEls[0]);
		}
		KPWindowRefresh(steps);
	}
}
//include name=component_js_include and run name=componenent_onload
function KPWindowRunComponentJS(oTargetElement){
require(["dojo/ready"],function(ready){
ready(function(){
	//load requested script files and remove refering hidden input
	//<script type="text/javascript" src="../script/dd_paging_table.js"></script>
	onloadElements = document.getElementsByName('component_js_include');
	for(x=0; x<onloadElements.length;){
		if(typeof(onloadElements[x]) != 'undefined' && 
		typeof(onloadElements[x].tagName) != 'undefined' && 
		onloadElements[x].tagName.toLowerCase() == 'input' &&
		KPWindowFindParent(onloadElements[x]) == oTargetElement ){
			//WARNING: if component js is already loaded the current load window will depend on 
			//the already loaded script. if this script is a include from a other kpwindow 
			//it can happen that the script gets unloaded with the unload of the other kpwindow 
			//before the windows wich also uses this script is unloaded... 
			//need more advanced include management for this.
			if(!KPWindowIsComponentJSLoaded(onloadElements[x].value)){
				try{
					scriptLink = document.createElement('script');
					scriptLink.language = 'javascript';
					scriptLink.type = 'text/javascript';
					scriptLink.src = onloadElements[x].value;
					scriptLink.setAttribute('id', oTargetElement.id+"include");
					document.getElementsByTagName("head")[0].appendChild(scriptLink);
				}catch(e){
					KPWindowError(e,onloadElements[x].value);
				}
			}
			getParent(onloadElements[x]).removeChild(onloadElements[x]);
		} else {
			x++;
		}
	}
	//execute onlad element and remove them
	onloadElements = document.getElementsByName('component_onload');
	//console.log("component_onload count:"+onloadElements.length);
	for(x=0; x<onloadElements.length;){
		//console.log(KPWindowFindParent(getParent(onloadElements[x])).id +'-'+ oTargetElement.id);
		//console.log(KPWindowFindParent(getParent(getParent(onloadElements[x]))).id +'-'+ oTargetElement.id);
		if(typeof(onloadElements[x]) != 'undefined' && 
		typeof(onloadElements[x].tagName) != 'undefined' && 
		onloadElements[x].tagName.toLowerCase() == 'input' && 
		!KPWindowIsTemplate(onloadElements[x]) && ( 
			KPWindowFindParent(onloadElements[x]) == oTargetElement || 
			KPWindowFindParent(getParent(getParent(onloadElements[x]))) == oTargetElement
		)
		){
			//TODO niet oTargetElement overschrijven in een loop
			//oTargetElement = KPWindowFindParent(onloadElements[x]);
			targetWindow = KPWindowFindParent(onloadElements[x]);
			try{
				if(!Sarissa._SARISSA_IS_IE && !Sarissa._SARISSA_IS_SAFARI){
							//console.debug(onloadElements[x]);
							eval(onloadElements[x].value);

//					window.setTimeout( onloadElements[x].value,1000 );
					
					/*
					scriptLink = document.createElement('script');
					scriptLink.language = 'javascript';
					scriptLink.type = 'text/javascript';
					//console.log("exec: "+onloadElements[x].value);
					scriptLink.innerHTML = onloadElements[x].value;
					scriptLink.setAttribute('id', targetWindow.id+"include");
					//document.getElementsByTagName("head")[0].appendChild(scriptLink);
					if (window.execScript){        	
    					window.execScript(onloadElements[x].value);
    				}
	    			else {
	    				 window.setTimeout( onloadElements[x].value,1000 );
	    			}
	    			*/
				} else {
					//timeout needed for IE/Safari otherwise it did nog load his header includes yet :s and trim needed cause IE get's confused by \r and \n...
					//also no error catching for IE because of that...
					//alert('eval("'+trimJS(onloadElements[x].value)+'");');
							console.debug(onloadElements[x].value);
							eval(onloadElements[x].value);
					//setTimeout('eval("'+trimJS(onloadElements[x].value)+'");',1000);
				}
			}catch(e){
				KPWindowError(e,onloadElements[x].value);
			}
			if (onloadElements[x]!=null) {
				getParent(onloadElements[x]).removeChild(onloadElements[x]);
			}
		} else {
			x++;
		}
	}
});
});
}

var KPWindowsOnSubmit = new Array();
function KPWindowComponentRegisterOnsubmit(oTargetElement){
	onsubmitElements = document.getElementsByName('component_onsubmit');
	KPWindowsOnSubmit[oTargetElement.id] = new Array();
	for(x=0; x<onsubmitElements.length;){
		if(typeof(onsubmitElements[x]) != 'undefined' && 
		typeof(onsubmitElements[x].tagName) != 'undefined' && 
		onsubmitElements[x].tagName.toLowerCase() == 'input' &&
		KPWindowFindParent(onsubmitElements[x]) == oTargetElement ){
				KPWindowsOnSubmit[oTargetElement.id][KPWindowsOnSubmit[oTargetElement.id].length] = onsubmitElements[x].value;
				getParent(onsubmitElements[x]).removeChild(onsubmitElements[x]);
		} else {
			x++;
		}
	}
}

function KPWindowComponentRunOnsubmit(windowId){
	//check dojo forms
	var dojoAnswer = false;
	require(["dijit/registry"],function(reg){
		var formObj=getForm(windowId);
		var isvalid=true;
		if (formObj)
		{
			var formWdg=reg.byId(formObj.id);
			if (formWdg) {
				isvalid=formWdg.validate();
			}
		} 
		else	
		{
			isvalid=true;
		}
		dojoAnswer=isvalid;
	});
	
	if (!dojoAnswer) return false;
	//check other stuff
	var KPwindowsOnSubmitAnswer = false;
	onsubmitElements = KPWindowsOnSubmit[windowId];
	if(typeof onsubmitElements != 'undefined'){
		for(x=0; x<onsubmitElements.length; x++){
			eval('KPwindowsOnSubmitAnswer='+onsubmitElements[x]);
			if(KPwindowsOnSubmitAnswer != true){
				return false;
			}
		}
	}
	return true;
}

//check if element is hidden
function KPWindowIsTemplate(obj){
	while(typeof(obj.id) == 'undefined' || !obj.id.substr(0,12).match('row_template')){
		obj = obj.parentNode ? obj.parentNode : obj.parentElement;
		//alert(obj+" "+obj.id);
		if(obj == null){
			return false;
		}
	}
	return true;
}
//check if a Component script is already loaded.
function KPWindowIsComponentJSLoaded(src){
	scriptElements = document.getElementsByTagName("script");
	for(y = 0; y < scriptElements.length; y++){
		if(typeof(scriptElements[y]) != 'undefined' && scriptElements[y].getAttribute("src")==src){
			return true;	
		}
	}
	return false;
}
//find KPWindow wich obj belongs to.
function KPWindowFindParent(obj){
	if(obj == null)
		return null;
	while(typeof(obj.className) == 'undefined' || !obj.id.match('kpwindow')){
		objold = obj;
		obj = getParent(obj);
		//if original object has no parrent but a domnode, its a dojo widget, find parent of domNode from dojo widget.
		if(obj == null && typeof objold.domNode != 'undifined' ){
			obj = KPWindowFindParent(getParent(objold.domNode));
		}
		if(obj == null){
			//alert("return null "+objold+" "+objold.id);
			return null;
		}
	}
	if(obj.id == "kpwindowoverlaybody"){
		obj = KPWindowFindParent(getParent(obj));
	}
	//alert(obj+" "+obj.id);
	return obj;
}

function getParent(obj){
	return obj.parentNode ? obj.parentNode : obj.parentElement;	
}
//find KPWindow wich obj belongs to. FUNCTION REPLaced by getForm
/*function KPWindowFindParentForm(obj){
	//alert(obj+" "+obj.method);
	while(typeof(obj.method) == 'undefined'){
		
		obj = obj.parentNode ? obj.parentNode : obj.parentElement;
		//alert(obj);
		if(obj == null){
			return null;
		}
	}
	alert(obj+" ");
}*/

//swicht kpwindow layout css file.
function KPWindowSwitchCSS(srcStr){
	//<link rel="stylesheet" type="text/css" href="./css/kpwindow.css" id="kpwindowcsstag"></link>
	head = document.getElementsByTagName("head")[0];
	cssLinkOld = document.getElementById('kpwindowcsstag');
	//alert(srcStr+' == '+cssLinkOld.href);
	if (cssLinkOld != null && cssLinkOld.href.match(srcStr)) {
		return;
	}
	cssLink = document.createElement('link');
	cssLink.type = 'text/css';
	cssLink.rel = 'stylesheet';
	cssLink.href = srcStr;
	cssLink.id = "kpwindowcsstag";
	//KPWindowClear(); problem, removes parent node. and should not be done by css loader.
	if (cssLinkOld != null) {
		head.replaceChild(cssLink,cssLinkOld);
	}
	KPWindowWaitForCSSLoading();
}
//Wait until css file is load before continuing to rerender kpwindow
function KPWindowWaitForCSSLoading(){
	if(getCssRules() == null || getCssRules().length == 0){
		setTimeout('KPWindowWaitForCSSLoading();',50);
	} else {
		KPWindowInit();
	}
}
//clear all KPWindow contents
function KPWindowClear(){
	//KPWindowClearElement(document.getElementById('kpwindowbordertop'));
	KPWindowClearElement('kpwindowborderleft');
	KPWindowClearElement('kpwindowborderright');
	KPWindowClearElement('kpwindowborderbottom');
	KPWindowClearElement('kpwindowa1');
	KPWindowClearElement('kpwindowa2');
	KPWindowClearElement('kpwindowa3');
	KPWindowClearElement('kpwindowa4');
	KPWindowClearElement('kpwindowa5');
	KPWindowClearElement('kpwindowb1');
	KPWindowClearElement('kpwindowb2');
	KPWindowClearElement('kpwindowb3');
	KPWindowClearElement('kpwindowb4');
	KPWindowClearElement('kpwindowb5');
	KPWindowClearElement('kpwindowc1');
	KPWindowClearElement('kpwindowc2');
	KPWindowClearElement('kpwindowc3');
	KPWindowClearElement('kpwindowc4');
	KPWindowClearElement('kpwindowc5');
}
//remove all childeren of element with id
function KPWindowClearElement(id){
	if(KPWindowHistoryList[id])
		KPWindowHistoryList[id] = Array();
	//setTimeout('while(document.getElementById("'+id+'") && document.getElementById("'+id+'").hasChildNodes()){document.getElementById("'+id+'").removeChild(document.getElementById("'+id+'").firstChild);};',500);	
	while(document.getElementById(id) && document.getElementById(id).hasChildNodes()){
		chyCtrl.cleanup(id);
		document.getElementById(id).removeChild(document.getElementById(id).firstChild);}
}
//deactivate window (minimize)
function KPWindowDeactivate(id){
	document.getElementById(id).style.visibility = 'hidden';
	if(document.getElementById('windowlist'))
		KPWindowWindowRestoreList(document.getElementById('windowlist'));//KPWindowRefreshWindow(KPWindowFindParent(document.getElementById('windowlist')).id);
	KPWindowSaveUserSettingsWindow(id);
}
//activate window (restore)
function KPWindowActivate(id){
	document.getElementById(id).style.visibility = 'visible';
	if(document.getElementById('windowlist'))
		KPWindowWindowRestoreList(document.getElementById('windowlist'));//KPWindowRefreshWindow(KPWindowFindParent(document.getElementById('windowlist')).id);
	KPWindowSaveUserSettingsWindow(id);
}
//generates a list of javascript links to activate deactivated windows
function KPWindowWindowRestoreList(parentelement){		
	if(parentelement == null)
		return;
	KPWindowClearElement('windowlist');
	for(i = 0; i < KPWindow.length; i++){
		//alert(KPWindow[i].style.visibility);
		if(KPWindow[i].style.visibility == 'hidden' && KPWindow[i].getElementsByTagName('div')[0]){
			windowLink = document.createElement('div');
			windowLink.setAttribute('name', KPWindow[i].id);
			windowLink.onclick = function(e1){ 
				sourceElement = e1 ? e1.target : event.srcElement;
				KPWindowActivate(sourceElement.getAttribute('name')); 
			};
			windowSub = document.createElement('a');
			windowSub.setAttribute('name', KPWindow[i].id);
			windowSub.onclick = function(e1){ 
				sourceElement = e1 ? e1.target : event.srcElement;
				KPWindowActivate(sourceElement.getAttribute('name')); 
			};
			windowSub.innerHTML = KPWindow[i].getElementsByTagName('div')[0].getAttribute('name');
			windowLink.appendChild(windowSub);
			parentelement.appendChild(windowLink);
		}
	}
}
//get form of kpwindow with windowId
function getForm(windowId){
	if(windowId == null || windowId == "undefined"){
		//alert(document.getElementsByTagName('form')[0].id);
		return document.getElementsByTagName('form')[0];
	} else {
		//alert(windowId);
		return document.getElementById(windowId).getElementsByTagName('form')[0];
	}
}
//Show error in overlay
function KPWindowError(e,rawSource){
	KPWindowShowOverlayHtml('<div style="background-color: silver; width: 80%; top: 10%; left: 10%; position: absolute; overflow-y: scroll; z-index: 98; opacity: 0.8;"><br/><br/><br/><center><font color="red" size="+2pt" style="word-wrap: break-word;">'+e+'<br/>stack:'+e.stack+'<br/><br/><b>Raw Source:</b><br/><br/>'+rawSource.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;")+'</font></center></div>');
}
//KPWindow api - loading
function KPWindowNotifyUserLoading(){
	document.getElementById("kpwindowloading").style.visibility = 'visible';
	opacity('kpwindowloading', 25, 50, 300);
	document.getElementsByTagName("body")[0].style.cursor = 'wait';	
}
function KPWindowNotifyUserDoneLoading(){
	opacity('kpwindowloading', 50, 25, 300);
	//TODO destroy/load issue formmanager
	setTimeout("document.getElementById(\"kpwindowloading\").style.visibility = 'hidden';document.getElementsByTagName(\"body\")[0].style.cursor = 'default';", 300);
	//document.getElementById("kpwindowloading").style.visibility = 'hidden';document.getElementsByTagName("body")[0].style.cursor = 'default';	
}
//KPWindow api - placeHolders
var dummyCount = 1;
//create dummy layer
function getDummy(){
	dropLayer = document.createElement('div');
	dropLayer.className = 'kpwindowplaceholder';
	dropLayer.id = 'placeholder'+dummyCount++;
	return dropLayer;
}
var placeHolders = new Array();
//replace all object tags with dummy layers
function addPlaceHolders(){
    /*list = document.getElementsByTagName("object");
    while(list.length > 0){
    	dummy = getDummy();
    	dummy.style.width = list[0].width;
    	dummy.style.height = list[0].height;
    	placeHolders[dummy.id] = list[0];
		getParent(list[0]).replaceChild(dummy, list[0]);
    }*/
}
//replace all dummy layers with original object tags
function removePlaceHolders(){
	for(k in placeHolders){
		console.debug("remove placeholder",k);
		if(placeHolders[k]!=null){
			dl = document.getElementById(k);
			if(dl != null){
				getParent(dl).replaceChild(placeHolders[k],dl);
				placeHolders[k] = null;
			}
		}
	}
	dummyCount = 1;
}

//=================cross browser api

var retry = 3;
//get css rules
function getCssRules(){
	count = document.styleSheets.length - 1;
	
	for(i=0; i<document.styleSheets.length; i++) {
	if 	(document.styleSheets[i].href != null && document.styleSheets[i].href.indexOf('kpwindow/kpwindow.css') > 0) {
			count = i;	
		}
	}
	
	try{
		if (document.styleSheets[count].cssRules){
			return document.styleSheets[count].cssRules;
		}else if (document.styleSheets[count].rules){
			return document.styleSheets[count].rules;
		}
	} catch(e) {
		//alert(e);
		//retry if ccs loading fails (for example user pushing a second buttons loading a diferent css before the fist was loaded)
		if(retry > 0){
			setTimeout('KPWindowInit();',500);
			retry--;	
		}
		return null;
	}
	retry = 3;
}
function getViewPortWidth(){
	if (window.innerWidth) {
		return window.innerWidth;
	}
	if (document.body.offsetWidth) {
  		return document.body.offsetWidth;
	}
}
function getViewPortHeight(){
	if (window.innerHeight) {
		return window.innerHeight;
	}
	if (document.body.offsetHeight) {
  		return document.body.offsetHeight;
	}
}
//fade opacity
function opacity(id, opacStart, opacEnd, millisec) {
    /*speed = Math.round(millisec / 100);
    timer = 0; 
    if(opacStart >= opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'"+id+"');",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++) {
            setTimeout("changeOpac(" + i + ",'"+id+"');",(timer * speed));
            timer++;
        }
    }*/
}
//change the opacity for different browsers
function changeOpac(opacity, id) {
 	object = document.getElementById(id);
 	if(object != null && KPWindowUseFade){
 		object = object.style;
	    object.opacity = (opacity / 100);
	    object.MozOpacity = (opacity / 100);
	    object.KhtmlOpacity = (opacity / 100);
	    object.filter = "alpha(opacity=" + opacity + ")";
 	}
}
//trim js string before eval, needed for IE(uw).
function trimJS(value) {
  value = value.replace(/^\s+/,'');
  value = value.replace(/\s+$/,'');
  value = value.replace(/\n/g,'');
  value = value.replace(/\r/g,'');
  value = value.replace(/\"/g,"\\\"");
  return value;
}
//figure out scroll bar with
function getScrollerWidth() {
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    scr.style.overflow = 'hidden';
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';
    scr.appendChild(inn);
    document.body.appendChild(scr);
    wNoScroll = inn.offsetWidth;
    scr.style.overflow = 'auto';
    wScroll = inn.offsetWidth;
    document.body.removeChild(
        document.body.lastChild);
    return (wNoScroll - wScroll);
}

/* needed from dd.js, mostly modified to fit kpwindow */
//hover functions should be replaced by css classes... unnessasairy code..

/*function clntSub( ddDiagTarget, trgt )
{ // Submit initiated from the client with support of targets ( submit another form then the one having the button defined )
  // The client submit button must have an associated hidden field ddDiagTarget so the receiver knows which button is pressed. 
  // For backwards compatibility a check in subButton is also made.
  	//opacity('kpwindowa1', 100, 0, 500);
  	KPWindowNotifyUserLoading();
  	var subField;
	//var obj = getTrgtObj( trgt ); ?????
	if( checkForm(getForm(trgt), trgt ) )
	{
		subField = ( getForm(trgt).elements[ 'target' ] ) ? 'target' : ( getForm(trgt).elements[ 'subButton' ] ) ? 'subButton' : undef;
		if( getForm(trgt).elements[ subField ] )
		{
			if( getForm(trgt).elements[ subField ].type )
			{
				if( getForm(trgt).elements[ subField ].type == 'hidden' )
				{
					getForm(trgt).elements[ subField ].value = ddDiagTarget;
					//document.getElementById('my').submit(); // post
					KPWindowDoPost(trgt);
				}
			}
		}
		else
		{
			// Do not no how to submit both target and subButton are not defined.
			alert( 'Kan niet submitten zowel target als subButton zijn niet gedefinieerd.');
		}
	}
}*/

/*function formSub( ddDiagTarget, trgt )
{ // Submit initiated from the client with support of targets ( submit another form then the one having the button defined )
  // The client submit button must have an associated hidden field ddDiagTarget so the receiver knows which button is pressed. 
  // For backwards compatibility a check in subButton is also made.
  	//opacity('kpwindowa1', 100, 0, 500);
  	//KPWindowNotifyUserLoading();
  	var obj, subField;
	obj = getTrgtObj( trgt );
		
	subField = ( obj.my.elements[ 'target' ] ) ? 'target' : ( obj.my.elements[ 'subButton' ] ) ? 'subButton' : undef;
	if( obj.my.elements[ subField ] )
	{
		if( obj.my.elements[ subField ].type )
		{
			if( obj.my.elements[ subField ].type == 'hidden' )
			{
				obj.my.elements[ subField ].value = ddDiagTarget;
				obj.my.submit(); // post
			}
		}
	}
	else
	{
		// Do not no how to submit both target and subButton are not defined.
		alert( 'Kan niet submitten zowel target als subButton zijn niet gedefinieerd.');
	}
}

function getTrgtObj( trgt )
{ // Get the obj of the target ( art!? )
	return( ( trgt ) ? ( ( trgt != 'parent' ) ? parent.frames[ trgt ] : this.parent ) : this.document );
}*/

/*obsolete function checkMandatory( trgt )
{ // Check the comma separated list of fields in the hidden field obligate for values
	var fldName, fldObj, stat = true, errMsg = "", flag = 0;
	//, obj = getTrgtObj( trgt ); ?????
	mVal = getForm(trgt).obligate.value;
	if( mVal != "" )
	{
		mandFields = mVal.split(",");
		for( var i=0; i < mandFields.length; i++ )
		{      
			fldObj = getForm(trgt)[ mandFields[ i ] ];
			if( fldObj.value == "" )
			{
				fldName = ( fldObj.label ) ? ( fldObj.label != '' ) ? fldObj.label : fldObj.name : fldObj.name;
				errMsg = errMsg + "Leeg verplicht veld: " + fldName + "\n";
				stat = false;
				if( flag == 0 )
				{
					fldObj.focus();
					flag = 1;
				}
			} 
		}
	}
	if( !stat )
	{
		alert( errMsg );
	}
	return stat;
}*/

function prosUrlPopup( curl , trgt)
{ // solve a dd url tag string and open a window for it
	popUrl = parseStr( curl, 1, trgt );
	if (popUrl.match(/.*(\.docx|\.doc|\.ppt|\.pptx|\.xls|\.xlsx)/g)){
		if (OpenInOffice(popUrl)){	
			return;
		}
	}
	ddWin = window.open( popUrl,'_new');
	ddWin.focus();
	
}

function parseStr( tagStr, escFlag, trgt )
{ // Find and replace the %% tags and replace it with the value if they are form fields.
  // If the escFlag is set to 1 the found values will be web escaped
require(["dijit/registry","dojo/domReady!"], function(reg) {
	escFlag = escFlag || 0;
	var obj = this.document, re = /%\w+%/g, res = tagStr.match( re ), fieldName, fieldObj;
	if( res )
	{ // yes found %tag(s)%
		for( var i = 0; i < res.length; i++ )
		{ // All found %%
			
			fieldName = res[ i ].substring( 1, res[ i ].length - 1 ); // Cut %%
			//alert(getForm(trgt).elements.length);
			if( getForm(trgt).elements[ fieldName ] )
			{ // Yes it is a form element 
				if( getForm(trgt).elements[ fieldName ].type )
				{ // Yes it is a form element with a type
					if( getForm(trgt).elements[ fieldName ].type == 'text' || getForm(trgt).elements[ fieldName ].type == 'hidden' || getForm(trgt).elements[ fieldName ].type == 'radio' )
					{
						fieldObj = getForm(trgt).elements[ fieldName ];
					}
					else if( getForm(trgt).elements[ fieldName ].type == 'select-one' || 
						getForm(trgt).elements[ fieldName ].type == 'select-multiple' )
					{ // limited support for select multiple only return the first element checked will be returned
						for( var ii = 0; ii < getForm(trgt).elements[ fieldName ].length; ii++ )
						{
							if( getForm(trgt).elements[ fieldName ][ ii ].selected )
							{
								fieldObj = getForm(trgt).elements[ fieldName ][ ii ];
							}
						}
					}
				} else if(reg.byId(fieldName)) {
					//check dijit reg
					var dojoObj=reg.byId(fieldName);
					tagStr = findAndRep( tagStr, res[ i ], ( escFlag == 1 ) ? escape( dojoObj.get("value") ) : dojoObj.get("value") );	
				}
				else if( getForm(trgt).elements[ fieldName ].length )
				{ // Yes it is a form element with possible more values for now only radio is supported
					for( var ii = 0; ii < getForm(trgt).elements[ fieldName ].length; ii++ )
					{
						if( getForm(trgt).elements[ fieldName ][ ii ].type == 'radio' )
						{ 
							if( getForm(trgt).elements[ fieldName ][ ii ].checked )
							{
								fieldObj = getForm(trgt).elements[ fieldName ][ ii ];
								break;
							}
								
						}
					}
				}
				if( fieldObj )
				{
					tagStr = findAndRep( tagStr, res[ i ], ( escFlag == 1 ) ? escape( fieldObj.value ) : fieldObj.value );
				}
			} 
		}
	}
});
return( tagStr );

}

function findAndRep( str, strFind, strRep )
{ // Love regexp... thanks Larry
	return( str.replace( new RegExp( strFind, 'g' ), strRep ) );
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function KPWindowsSetBackgound(inputel){
	//alert(inputel.value);
	//image = new Image();
	//image.src = inputel.value;
	document.getElementsByTagName('body')[0].style.backgroundImage = "url("+inputel.value+")";
	setCookie('KPWindowSettingsBackGround',inputel.value,99);
}

function KpwindowsConfirmDialog(answer,windowid) {
	if(answer){
		KPWindowDoPost(windowid,'');
	}
}

function KPWindowsResetWindows(){
	var theCookies = document.cookie.split(';');
	for(var i = 0; i<theCookies.length; i++){
		var cookieName = theCookies[i].split('=')[0];
		if(cookieName.indexOf('KPWindowSettings') != -1){
			setCookie(cookieName,"",-1);
		}
	}
	setCookie('KPWindowRemoveBorders',"",-1);
	KPWindowInit();
	KPWindowRefresh();
}

function KPWindowsMakeWindowsStatic(){
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowa1"));
	KPWindowSaveUserSettingsWindow("kpwindowa1");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowa2"));
	KPWindowSaveUserSettingsWindow("kpwindowa2");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowa3"));
	KPWindowSaveUserSettingsWindow("kpwindowa3");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowa4"));
	KPWindowSaveUserSettingsWindow("kpwindowa4");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowa5"));
	KPWindowSaveUserSettingsWindow("kpwindowa5");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowb1"));
	KPWindowSaveUserSettingsWindow("kpwindowb1");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowb2"));
	KPWindowSaveUserSettingsWindow("kpwindowb2");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowb3"));
	KPWindowSaveUserSettingsWindow("kpwindowb3");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowb4"));
	KPWindowSaveUserSettingsWindow("kpwindowb4");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowb5"));
	KPWindowSaveUserSettingsWindow("kpwindowb5");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowc1"));
	KPWindowSaveUserSettingsWindow("kpwindowc1");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowc2"));
	KPWindowSaveUserSettingsWindow("kpwindowc2");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowc3"));
	KPWindowSaveUserSettingsWindow("kpwindowc3");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowc4"));
	KPWindowSaveUserSettingsWindow("kpwindowc4");
	KPWindowsMakeWindowStatic(document.getElementById("kpwindowc5"));
	KPWindowSaveUserSettingsWindow("kpwindowc5");
}

function KPWindowsMakeWindowStatic(windowobj){
	var widthTest = window.getComputedStyle ? parseInt(window.getComputedStyle(windowobj,'').width+0)+'' : parseInt(windowobj.currentStyle.width+0)+'';
	var heightTest = window.getComputedStyle ? parseInt(window.getComputedStyle(windowobj,'').height+0)+'' : parseInt(windowobj.currentStyle.height+0)+'';
	if(widthTest == 'NaN' || widthTest == '0'){
		widthTest = '300';
	}
	if(heightTest == 'NaN' || heightTest == '0'){
		heightTest = '300';
	}
	windowobj.style.width = widthTest+'px';
	windowobj.style.height = heightTest+'px';
	windowobj.style.position = 'absolute';
}

function KPWindowsMaximize(obj){
	var windowobj = KPWindowFindParent(obj);
	if(windowobj.style.top == '0px' && windowobj.style.left == '0px' && windowobj.style.width == '100%' && windowobj.style.height == '100%'){
		KPWindowInit();
	} else {
		KPWindowsMakeWindowStatic(windowobj);
		KPWindowSaveUserSettingsWindow(windowobj.id);
		bringFront(windowobj);
		windowobj.style.top = '0px';
		windowobj.style.left = '0px';
		windowobj.style.width = '100%';
		windowobj.style.height = '100%';	
	}
}

function KPWindowRunDojo(elem)
{
	var elemForm=getForm(elem.id);
	if(elemForm)
	{
		require(["dojo/parser","dojo/dom"],function(parser,dom){
			parser.parse(dom.byId(elem.id));
		});
	}
		
}

function cleanupWidgets(windowId)
{
	//cleanup widgets is done by Controller.js inbetween post and content put
	//console.log('clear widgets for ' + windowId);
	require(["dojo/_base/array", "dijit/registry","dojo/dom"], function(array, registry,dom){
	    var windowWidgets = registry.findWidgets(dom.byId(windowId));
	    array.forEach(windowWidgets,function(item){
	    	item.destroyRecursive();
	    });
	    
	});
}

function verifyDelete( delete_target, e )
{	
	if ( confirm( 'Weet u zeker dat u dit onderdeel wilt verwijderen?' ) )
	{
    	// try to save
    	KPWindowDoPost( KPWindowFindParent(e).id, delete_target );
	}
}

function KPWindowSetInProgress(windowId,active){
	KPWindowProgressList[windowId]=active;
	
	console.log('KPWindowSetInProgress for ' + windowId + ' = ' + KPWindowProgressList[windowId]);
}

function KPWindowGetInProgress(windowId){
	var inArray=true;
	require(["dojo/_base/array"],function(array){
		if(array.indexOf(KPWindowProgressList,windowId)==-1)
		{
			inArray=false;
		} else {
			inArray=KPWindowProgressList[windowId];
		}
	});
	console.log('check in progress for '+ windowId + '= ' + inArray);
	return inArray;
}

function OpenInOffice(curl){
	var ffwin=document.getElementById("winFirefoxPlugin");
	if (ffwin && ffwin.EditDocument){
		ffwin.EditDocument(curl);
		return true	
	}

	if (window.ActiveXObject){		
		var s;
        s = new ActiveXObject("SharePoint.OpenDocuments.3");
        if (s == null)
            s = new ActiveXObject("SharePoint.OpenDocuments.2");
        if (s == null)
            s = new ActiveXObject("SharePoint.OpenDocuments.1");
        if (s == null)
			return false;       
        s.EditDocument(curl);
        return true;
    } else {
		return false;
	}
}