// D4WScript.js - All sort of very usefull script functions and code
//
// convert all characters to lowercase to simplify testing
var agt=navigator.userAgent.toLowerCase();

var is_Mac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;		// Client is MAC?
var is_IEmac = ((document.all)&&(is_Mac)) ? true : false;						// IE-alike on MAC?

// *** BROWSER VERSION ***
// Note: On IE5/6/7/8, these return 4, so use is_ie5up to detect IE5.
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);
// Note: Opera and WebTV spoof Navigator.  We do strict client detection.
// If you want to allow spoofing, take out the tests for opera and webtv.
var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
	&& (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1) && (agt.indexOf('chrome/')==-1)
	&& (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));

var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie4up = (is_ie && (is_major >= 4));
var is_ie4down = (is_ie && (is_major <= 4));		// IE4 and less
var is_ie7up = (is_ie && (is_major >= 7));

var is_ff = (agt.indexOf("firefox/") != -1);
var is_ff1up = (is_ff && (is_major >= 1));

var is_opera = (agt.indexOf("opera") != -1);
var is_opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
var is_opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
var is_opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
var is_opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
var is_opera6 = (agt.indexOf("opera 6") != -1 || agt.indexOf("opera/6") != -1);
var is_opera6less = (is_opera2 || is_opera3 || is_opera4 || is_opera5 || is_opera6);

var is_chrome = ((agt.indexOf("chrome/") != -1) && (agt.indexOf("opera") == -1));

// Is StyleSheet?		HTMLLinkElement.getAttribute("rel").indexOf("style") != -1
// Title:				HTMLListElement.getAttribute("title")
// Is Alt?				HTMLLinkElement.getAttribute("rel").indexOf("alt") != -1
function setActiveStyleSheet(title) {
	var i, a;
	title = ''+title;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			if(a.getAttribute("title").substring(0,title.length) == title) {
				a.disabled = false;
			}
			else if (a.getAttribute("title") != "Cascading menu") {		// Cascading menu met rust laten!
				a.disabled = true;
			}
		}
	}
}
function getActiveStyleSheet()
{
	var i, a;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel").indexOf("style") != -1 &&
			a.getAttribute("title") &&
			a.getAttribute("title") != "Cascading menu" &&
			!a.disabled) {
			return a.getAttribute("title");
		}
	}
	return null;
}
// General functions for use in our html code
function Info()
{
;	// Does nothing
}
function D4WCanBeModal()
{
	if (is_opera6less || is_chrome) {
		return false;
	}
	if (typeof(showModalDialog) == "undefined") {
		return false;
	}
	return true;
}
// lTop and/or lLeft = -2 then centered
// lWidth and/ord lHeight = -2 then 100%
function D4WShowModalDialog(sURL, sName, lTop, lLeft, lWidth, lHeight, sRefresh, sIsResizable)
{
	if (sIsResizable == null || sIsResizable == '') {
		sIsResizable = 'no';
	}
	if (lWidth == -2) {
		if (window.screen) {
			lWidth = screen.availWidth;
		}
	}
	if (lHeight == -2) {
		if (window.screen) {
			lHeight = screen.availHeight;
		}
	}
	var myWindow;
	myWindow = null;
	if (D4WCanBeModal()) {
		var sFeats = "status:yes;center:yes;resizable:"+sIsResizable+";";
		if (lTop >= 0) {
			sFeats = sFeats+"dialogTop:"+lTop+"px;";
		}
		else if (lTop == -2) {
			sFeats = sFeats+"dialogTop:center;";
		}
		if (lLeft >= 0) {
			sFeats = sFeats+"dialogLeft:"+lLeft+"px;";
		}
		else if (lLeft == -2) {
			sFeats = sFeats+"dialogLeft:center;";
		}
		if (lWidth >= 0) {
			sFeats = sFeats+"dialogWidth:"+lWidth+"px;";
		}
		else if (lWidth == -2) {		// 100%!
			sFeats = sFeats+"dialogWidth:100%;";
		}
		if (lHeight >= 0) {
			sFeats = sFeats+"dialogHeight:"+lHeight+"px;";
		}
		else if (lHeight == -2) {		// 100%!
			sFeats = sFeats+"dialogHeight:100%;";
		}
		// Normally no scrollbar, unless content is larger than window
		sFeats = sFeats+"scroll:yes;";
//    myWindow = window.open(sURL);
		myWindow = showModalDialog(sURL,self,sFeats);
		if(sRefresh == 'true') {
			window.history.go(0);
		}
//      D4WShowDialog(sURL, sName, lTop, lLeft, lWidth, lHeight);
	}
	else {
		// Anders start de andere modal dialog functie :)
		myWindow = D4WShowDialog(sURL, sName, lTop, lLeft, lWidth, lHeight);
	}
	return myWindow;
}
// lTop and/or lLeft = -2 then centered
// lWidth and/ord lHeight = -2 then 100%
// Let op: Houd geen rekening met Modal state
function D4WShowDialog(sURL, sName, lTop, lLeft, lWidth, lHeight)
{
	if (lWidth == -2) {
		if (window.screen) {
			lWidth = screen.availWidth;
		}
	}
	if (lHeight == -2) {
		if (window.screen) {
			lHeight = screen.availHeight;
		}
	}
	var sFeats = "toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,modal=yes";	// modal=yes does work sometimes :-)
	if (lTop >= 0) {
		sFeats = sFeats+",top="+lTop+"px";
	}
	else if (lTop == -2) {
//		sFeats = sFeats+",top=centered";
		if (window.screen) {
			var hght = lHeight;
			if (hght <= 0) {
				hght = screen.availHeight;
			}
			sFeats = sFeats+",top="+(screen.availHeight-hght)/2+"px";
		}
	}
	if (lLeft >= 0) {
		sFeats = sFeats+",left="+lLeft+"px";
	}
	else if (lLeft == -2) {
//		sFeats = sFeats+",left=centered";
		if (window.screen) {
			var wdt = lWidth;
			if (wdt <= 0) {
				wdt = screen.availWidth;
			}
			sFeats = sFeats+",left="+(screen.availWidth-wdt)/2+"px";
		}
	}
	if (lWidth >= 0) {
		sFeats = sFeats+",width="+lWidth+"px";
	}
	else if (lWidth == -2) {		// 100%!
		sFeats = sFeats+",width=100%";
	}
	if (lHeight >= 0) {
		sFeats = sFeats+",height="+lHeight+"px";
	}
	else if (lHeight == -2) {		// 100%!
		sFeats = sFeats+",height=100%";
	}
	// Normally no scrollbar, unless content is larger than window
	sFeats = sFeats+",scrollbars=yes";
	var myWindow;
	myWindow = window.open(sURL,sName,sFeats);
	if (!myWindow) {
		alert('Window kan niet worden geopend; Is er een popup blokker geinstalleerd? Probeer dan te klikken met de Ctrl-toets ingedrukt');
		return null;
	}
	if (!myWindow.opener) {
		myWindow.opener = self;
	}
	myWindow.focus();
	// Om modal te maken: In de Info.htm file de volgende blur moet op de body worden gezet: <BODY onBlur="if (!D4WCanBeModal()) {this.focus();}">
	return myWindow;
}

// -- Elements --
function D4WEnableElement(lId, bEnable)
{
	// document.getElementById(lId).
	document.getElementById(lId).disabled = !bEnable;
}
function D4WReadOnlyElement(lId, bReadOnly)
{
	// document.getElementById(lId).
	document.getElementById(lId).readOnly = bReadOnly;
}
// -- Layers --
function D4WLoadLayer(lId, sHtml)
{
	document.getElementById(lId).innerHTML = sHtml;
}
function D4WShowLayer(lId)
{
	if (is_ie || is_ff1up) {
	// IE / firefox 1.x+
	//					display
	//						""				Shown
	//						"none"		Hidden
		document.getElementById(lId).style.display = "";
	}
	// N6
	//					visibility
	//						visible		Object is visible
	//						hidden		Object is hidden
	else {
		document.getElementById(lId).style.visibility = "visible";
	}
}
function D4WHideLayer(lId)
{
	if (is_ie || is_ff1up) {
	// IE
	//					display
	//						""				Shown
	//						"none"		Hidden
		document.getElementById(lId).style.display = "none";
	}
	// N6
	//					visibility
	//						visible		Object is visible
	//						hidden		Object is hidden
	else {
		document.getElementById(lId).style.visibility = "hidden";
	}
}
function D4WIsLayerVisible(lId)
{
	var ret = false;
	if (is_ie || is_ff1up) {
	// IE
	//					display
	//						""				Shown
	//						"none"		Hidden
		ret = (document.getElementById(lId).style.display == "");
	}
	else {
	// N6
	//					visibility
	//						visible		Object is visible
	//						hidden		Object is hidden
		ret = (document.getElementById(lId).style.visibility != "hidden");
	}
	return ret;
}
function D4WToggleLayer(lId)
{
	if (D4WIsLayerVisible(lId)) {
		D4WHideLayer(lId);
	}
	else {
		D4WShowLayer(lId);
	}
}
function D4WSelectIconNormal(lId)
{
	document.getElementById(lId).style.cursor = "default";
	//document.getElementById(lId).style.cursor = "crosshair";
}
function D4WSelectIconHand(lId)
{
	if (is_ie) {
		document.getElementById(lId).style.cursor = "hand";
	}
	else if (is_nav) {
		document.getElementById(lId).style.cursor = "pointer";
	}
	else {
		document.getElementById(lId).style.cursor = "crosshair";
	}
}
// -- D4W vars 'n stuff --
var strD4WRoot = '..';
function SetD4WRoot(s)
{
	strD4WRoot = s;
}
function GetD4WRoot()
{
	return strD4WRoot;
}
function D4WRootApp(s)
{
	var ret;
	ret = strD4WRoot+"/"+s+"/"+s+".php";
	return ret;
}
// -- Info dialogs --
// WerkderdenBon info
function D4WInfoWerkderdenbon(ID)
{
	D4WShowModalDialog(D4WRootApp('D4WInfoWerkderdenbon')+"?action=1&ID="+ID, "InfoWerkderdenBon", -2, -2, 780, 700, 'no');
}
// Deelcalculatie-detail info
function D4WInfoDeelcalculatieDetail(DI)
{
	D4WShowModalDialog(D4WRootApp('D4WInfoDeelCalculatie')+"?action=2&DI="+DI, "InfoDeelCalculatie", -2, -2, 780, 680, 'no');
}
// Deelcalculatie info, show prices?
function D4WInfoDeelcalculatieEx(DI, bSP)
{
	D4WShowModalDialog(D4WRootApp('D4WInfoDeelCalculatie')+"?action=1&DI="+DI+"&SP="+bSP+"&w=200&h=200", "InfoDeelCalculatie", -2, -2, 780, 680, 'no');
}
function D4WInfoDeelcalculatie(DI)
{
	D4WInfoDeelcalculatieEx(DI,1);
}

function D4WInfoDeelcalculatieEx3(DI, Action, bSP)
{
	D4WShowModalDialog(D4WRootApp('D4WInfoDeelCalculatie')+"?action="+Action+"&DI="+DI+"&SP="+bSP+"&w=200&h=200", "InfoDeelCalculatie", -2, -2, 780, 680, 'no');
}

function D4WUpdateOrderZak(DI, Action)
{
	D4WInfoDeelcalculatieEx3(DI, Action, 1);
}
function DetailedArtInfo(AI)
{
	D4WShowModalDialog(D4WRootApp('D4WInfoArtikel')+"?AI="+AI+"&w=200&h=200", "Artikelinfo", -2, -2, 700, 650, 'no');
}
function DetailedVrdInfo(VI)
{
	D4WShowModalDialog(D4WRootApp('D4WInfoVrdArtikel')+"?VI="+VI+"&w=200&h=200", "Artikelinfo", -2, -2, 700, 650, 'no');
}
function DetailedBinariesInfo(BI, AI)
{
	D4WShowModalDialog(D4WRootApp('D4WInfoBinary')+"?BI="+BI+"&AI="+AI+"&w=200&h=200", "Documentinfo", -2, -2, 700, 650, 'no');
}
function SelectImage(id,rid,st,omid)
{
	D4WShowDialog(D4WRootApp('D4WSelectImage')+"?ID="+id+"&RID="+rid+"&OMID="+omid+"&st="+st, "SelectImage", -2, -2, 700, 650);
}
function DetailedCartInfo(LT, VI, BI, AI)
{
// LT=0=VrdArtikel
//    1=RepOrder
//    2=VarDoc
//    3=Artikel
	if (LT==0) {
		DetailedVrdInfo(VI);
	}
	else if (LT==2 && BI > 0) {
		//DetailedBinariesInfo(BI, VI);
		DetailedBinariesInfo(BI, AI);
	}
	else if (LT==3 || (LT==2 && BI <= 0)) {
		DetailedArtInfo(AI);
	}
}
function AboutBox()
{
	D4WShowModalDialog(D4WRootApp('D4WAppAbout'), "AboutBox", -2, -2, 470, 785, 'no');
}
function OnClickImage(lId)
{
	if (lId == '' || lId <= 0) {	// <= 0 = not available and not clickeable
		return false;
	}
	return true;
}
function OnOverImage(lId)
{
	OnOverImageEx(lId, '');
}
function OnOverImageEx(lId, postfix)
{
	if (lId == '' || lId <= 0) {	// <= 0 = not available and not clickeable
		D4WSelectIconNormal('ShowImage_'+lId+postfix);
	}
}
function D4WGetFrameFromParent(strFrameName, startparent, lLevelsLeft)
{
	if (strFrameName == '' || lLevelsLeft <= 0) {	// Also check recursion depth
		return null;
	}
	if (startparent.frames != null && startparent.frames[strFrameName] != null) {
		return startparent.frames[strFrameName];
	}
	if (startparent.parent != null) {
		return D4WGetFrameFromParent(strFrameName, startparent.parent, lLevelsLeft-1);
	}
	return null;
}
function D4WAddFooter(strFooter, strFrameName, bShowWhenFramesOnly)
{
	D4WUpdateFooter(strFooter, strFrameName, bShowWhenFramesOnly);
}
function D4WRefreshFrame(strFrameName, levelIsMenuframe)	// level 0 = geen menu, 1 = basic menu, 2 = force menu(part 0)
{
	var pFrame;
	pFrame = D4WGetFrameFromParent(strFrameName, parent, 5);	// max 5 levels deep
	if (pFrame == null) {
		pFrame = this;
	}
	if (levelIsMenuframe > 0) {			// Menu heeft een aparte afhandeling..
		if (levelIsMenuframe == 1) {
			// Doe hier niets :)
			//szOld = pFrame.location.href;
			//szNew = szOld.replace(/Menu.php/gi, 'Menu2.php');
			//pFrame.location.href = szNew;
		}
		else {		// level 2 of hoger is een force!
			szOld = pFrame.location.href;
			szNew = szOld.replace(/Menu2.php/gi, 'Menu.php');
			pFrame.location.href = szNew;
		}
		return;
	}
	// for nice smooth transition: reload and set href to itself
	pFrame.location.reload();
	var a;
	a = pFrame.location.href;
	pFrame.location.href = a;
}
function D4WRedirectFrame(strFrameName, strNewURL)
{
	var pFrame;
	pFrame = D4WGetFrameFromParent(strFrameName, parent, 5);	// max 5 levels deep
	if (pFrame == null) {
		pFrame = this;
	}
	pFrame.location.href = strNewURL;
}
function D4WUpdateFooter(strFooter, strFrameName, bShowWhenFramesOnly)
{
	var pFrame;
	pFrame = D4WGetFrameFromParent(strFrameName, parent, 5);	// max 5 levels deep
	var elem;
	elem = null;
	if (pFrame != null) {
		elem = pFrame.document.getElementById('strFooter');
	}
	else {
		if (!bShowWhenFramesOnly) {
			elem = document.getElementById('strFooter');
		}
	}
	if (elem != null) {
		elem.innerHTML = strFooter;
	}
}
function D4WgetXMLHttpRequest()
{
	var xhr = false;
	if (window.XMLHttpRequest) {
		xhr = new window.XMLHttpRequest;
	}
	else {
		try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
		catch (e) {
			try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
			catch (e2) {
				try { xhr = new XMLHttpRequest(); }
				catch (e3) {
					xhr = false;
				 }
			}
		}
	}
	return xhr;
}
function D4WPostURLRequest(url, params)
{
	var xhr;
	var bErr = false;
	xhr = D4WgetXMLHttpRequest();
	if (!xhr) {
		bErr = true;
	}
	else {
		xhr.open("POST", url, false);
		//Send the proper header information along with the request
		xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xhr.setRequestHeader("Content-length", params.length);
		if (!document.all) {
			xhr.setRequestHeader("Connection", "close");
		}
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					//received: xhr.responseText;
				}
				else {
					bErr = true;
					//Status code: xhr.status
				}
			}
		}
		xhr.send(params);
	}
	return bErr;
}
function D4WGetViewPort() {
	var h = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight;
	var w = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
	return { width: w, height: h }
}
// Lightbox stuff - <!D4WLightboxHTML> should be put right under the <body> tag!
function D4WOpenLightbox() {
	// Set full screen height to body height
	var offsetHeight = document.getElementsByTagName('body').item(0).offsetHeight;  // document.getElementsByTagName('body').item(0).clientHeight;
	var docHeight = document.getElementsByTagName('body').item(0).scrollHeight;  //document.height;
	var windowiHeight = window.innerHeight;
	if (typeof windowiHeight == 'undefined') {
		// innerHeight is NOT supported by IE!
		windowiHeight = D4WGetViewPort().height;
	}
	var scrHeight = offsetHeight;
	if (docHeight > scrHeight) {
		scrHeight = docHeight;
	}
	if (windowiHeight > scrHeight) {
		scrHeight = windowiHeight;
	}
	document.getElementById("idFullScreen").style.height = scrHeight + 'px';
	document.getElementById("idFullScreen").style.display = "inline";
	document.getElementById("idD4WLightbox").style.display = "inline";
}
function D4WCloseLightbox() {
	document.getElementById("idD4WLightbox").style.display = "none";
	document.getElementById("idFullScreen").style.display = "none";
}
function URLDecode(strEncoded)
{
	return unescape(strEncoded);
}
function URLEncode(strUnEncoded)
{
	return escape(strUnEncoded);
}
function D4WShowDataPage(strPage, strTarget)
{
	if (strTarget == '_blank') {	// Forced on a new page
		var myWindow;
		myWindow = window.open(strPage);
		if (!myWindow) {
			alert('Window kan niet worden geopend; Is een popup blokker geinstalleerd? Probeer te klikken met de Ctrl-toets ingedrukt');
			return;
		}
		if (!myWindow.opener) {
			myWindow.opener = self;
		}
		myWindow.focus();
		return;
	}
	var pFrame;
	pFrame = D4WGetFrameFromParent(strTarget, parent, 5);	// max 5 levels deep!!
	if (pFrame != null) {
		var bSet;
		bSet = false;
		try {
			var strDecoded;
			strDecoded = URLDecode(strPage);
///// Todo: Check for redir page?
			// Indien redirpage then param with default page
			if (strDecoded.substr(strDecoded.lastIndexOf("/D4WAppRedir.php")) == "/D4WAppRedir.php") {
				//strDecoded += "?defpage="+URLEncode(pFrame.location.href);
				// Reload same page :-)
				strDecoded = pFrame.location.href;
			}
/////
			if (pFrame.location.href == strPage || pFrame.location.href == strDecoded) {
				//alert('Same page found; skip refresh :-)');
				bSet = false;
			}
			else {
				bSet = true;
			}
		}
		catch (e) { // Error, so just assume to set it!
			bSet = true;
			if (strPage == '') {	// Indien geen pagina gegeven, dan niets doen...
				bSet = false;
			}
		}
		if (bSet) {
			try {
				pFrame.location.href = strDecoded;
			}
			catch (e) {
				alert('Internal error: Cannot change to other page.');
			}
		}
	}
	else {
		alert('Internal error: No frames');
	}
}
function ChangeClass(Elem, newClassName)
{
	Elem.className = newClassName;		// TODO: Gaat soms fout in IE?
}
function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2)
{
  var x = Math.round(num * Math.pow(10,dec));
  if (x >= 0) {
    n1=n2='';
  }
  var y = (''+Math.abs(x)).split('');
  var z = y.length - dec; if (z<0) z--;
  for(var i = z; i < 0; i++) {
    y.unshift('0');
    y.splice(z, 0, pnt);
  }
  while (z > 3) {
    z-=3;
    y.splice(z,0,thou);
  }
  var r = curr1+n1+y.join('')+n2+curr2;
  return r;
}
// -- Something Borrowed --
// MM_ Support functions; disable if you have your own way ;)
function MM_preloadImages()
{
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].length > 0 && a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d)
{
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}
function MM_swapImgRestore()
{
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_swapImage()
{
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
// -- End Something Borrowed --

