var offerteBoxBovenHover = false;
var offerteBoxBovenContainerNoHover = true;
var ongelezenOfferteDialog;
var levertijdenAanpassenDialog;
var momentDialog;

function levertijdenAanpassen(aantal) {
	if (popupdatum != vandaag) {
		updatePopupDatum()
		if (popupongelezenoffertes != "false") {
			levertijdenAanpassenDialog = new YAHOO.widget.SimpleDialog(
					'levertijdenaanpassen', {
						width : "400px",
						effect : {
							effect : YAHOO.widget.ContainerEffect.FADE,
							duration : 0.25
						},
						fixedcenter : true,
						modal : true,
						visible : false,
						draggable : false
					});
			levertijdenAanpassenDialog.setHeader("Leverdata aanpassen");
			levertijdenAanpassenDialog.setBody("U heeft " + aantal
					+ " overschreden leverdata.");
			var levertijdenAanpassenButtons = [ {
				text : "Sluiten",
				handler : ongelezenOfferteSluiten
			} ];
			levertijdenAanpassenDialog.cfg.queueProperty("buttons",
					levertijdenAanpassenButtons);
			levertijdenAanpassenDialog.render(document.body);
			levertijdenAanpassenDialog.show();
		}
	}
}

var ongelezenOfferteSluiten = function() {
	levertijdenAanpassenDialog.hide();
}

function updatePopupDatum() {
	var now = new Date();
	if (popupdatum == '') {
		YAHOO.util.Connect.asyncRequest("GET",
				"/media/snippets/popupdatum-invoeren?noCache=" + now.getTime(),
				null, "");
	} else {
		YAHOO.util.Connect.asyncRequest("GET",
				"/media/snippets/popupdatum-vernieuwen?noCache="
						+ now.getTime(), null, "");
	}
}

function bestelPopupInit() {
	bestelPopupDialog = new YAHOO.widget.SimpleDialog('bestelpopup', {
		width : "400px",
		effect : {
			effect : YAHOO.widget.ContainerEffect.FADE,
			duration : 0.25
		},
		fixedcenter : true,
		modal : true,
		visible : false,
		draggable : false
	});
	bestelPopupDialog.setHeader("Artikel toegevoegd");
	bestelPopupDialog
			.setBody("Het artikel is toegevoegd aan uw besteloverzicht<br /><input type=\"checkbox\" id=\"checkbestel\"  /> <label for=\"checkbestel\">Deze melding niet meer weergeven</label>");
	var bestelPopupButtons = [ {
		text : "Sluiten",
		handler : bestelPopupSluiten,
		isDefault : true
	} ];
	bestelPopupDialog.cfg.queueProperty("buttons", bestelPopupButtons);
	bestelPopupDialog.render(document.body);
}

function onUpdatePopupBestellen() {
	bestelPopupDialog.hide();
}

var bestelPopupSluiten = function() {
	if (document.getElementById('checkbestel').checked) {
//		var now = new Date();
//		var callback = {
//			success : onUpdatePopupBestellen
//		}
//		YAHOO.util.Connect.asyncRequest("GET",
//				"/media/snippets/popupbestellen-uitzetten?noCache="
//						+ now.getTime(), callback, "");
		bncAjaxConnection({
			url:"/media/snippets/popupbestellen-uitzetten",
			method:'GET',
			success : onUpdatePopupBestellen,
			argument : {
				redirect : redirect
			}
		});
		popupbestellen = 'false';
	} else {
		bestelPopupDialog.hide();
	}
}

function momentInit() {
	momentDialog = new YAHOO.widget.SimpleDialog('moment', {
		width : "400px",
		fixedcenter : true,
		modal : true,
		visible : false,
		draggable : false
	});
	momentDialog.setHeader("Moment a.u.b.");
	momentDialog.setBody("<div style=\"text-align: center;\"><img src=\"/media/afbeeldingen/layout/laden.gif\" alt=\"laden\" /></div>");
	momentDialog.render(document.body);
}

function ongelezenOfferte(aantal) {
	if (popupdatum != vandaag) {
		updatePopupDatum()
		if (popupongelezenoffertes != "false") {
			ongelezenOfferteDialog = new YAHOO.widget.SimpleDialog(
					'ongelezenofferte', {
						width : "400px",
						effect : {
							effect : YAHOO.widget.ContainerEffect.FADE,
							duration : 0.25
						},
						fixedcenter : true,
						modal : true,
						visible : false,
						draggable : false
					});
			if (aantal == "1") {
				ongelezenOfferteDialog.setHeader("Ongelezen offerte");
				ongelezenOfferteDialog
						.setBody("U heeft "
								+ aantal
								+ " ongelezen offerte.  Wilt u naar uw ontvangen offertes?<br /><input type=\"checkbox\" id=\"checkongelezenoffertes\"  /> <label for=\"checkongelezenoffertes\">Deze melding niet meer weergeven</label>");
			} else {
				ongelezenOfferteDialog.setHeader("Ongelezen offertes");
				ongelezenOfferteDialog
						.setBody("U heeft "
								+ aantal
								+ " ongelezen offertes.  Wilt u naar uw ontvangen offertes?<br /><input type=\"checkbox\" id=\"checkongelezenoffertes\"  /> <label for=\"checkongelezenoffertes\">Deze melding niet meer weergeven</label>");
			}
			var ongelezenOfferteButtons = [ {
				text : "Ja",
				handler: function(){
					closeOngelezenOfferte(true);
				}
			}, {
				text : "Nee",
				handler: function(){
					closeOngelezenOfferte(false);
				}
			} ];
			ongelezenOfferteDialog.cfg.queueProperty("buttons",
					ongelezenOfferteButtons);
			ongelezenOfferteDialog.render(document.body);
			ongelezenOfferteDialog.show();
		}
	}
}

var closeOngelezenOfferte = function(redirect) {
	if (document.getElementById('checkongelezenoffertes').checked) {
//		var now = new Date();
//		var callback = {
//			success : onUpdateCloseOngelezenOfferte,
//			argument : {
//				redirect : redirect
//			}
//		}
//		YAHOO.util.Connect.asyncRequest("GET",
//				"/media/snippets/ongelezen-offertes-uitzetten?noCache="
//						+ now.getTime(), callback, "");
		bncAjaxConnection({
			url:"/media/snippets/ongelezen-offertes-uitzetten",
			method:'GET',
			success : onUpdateCloseOngelezenOfferte,
			argument : {
				redirect : redirect
			}
		});
	} else {
		ongelezenOfferteDialog.hide();
		if (redirect == true) {
			document.location.href = '/offertes/ontvangen-offertes';
		}
	}
}

function onUpdateCloseOngelezenOfferte(o) {
	ongelezenOfferteDialog.hide();
	if (o.argument.redirect == true) {
		document.location.href = '/offertes/ontvangen-offertes';
	}
}

function bestel(productcode, aantal, prijs, showOfferteBox) {
	if (popupbestellen == 'false') {
		momentDialog.show();
		
	} else {
		bestelPopupDialog.show();
	}
	productcode = escape(productcode);

	// escape doet niks met +
	while (productcode.indexOf('+') != -1) {
		productcode = productcode.replace('+', '%2B');
	}

	if (aantal == null) {
		aantal = 1;
	}
	if (prijs != null) {
		// vertaal de escaped , (&#44;) in een .
		prijs = prijs.replace('&#44;', '.');
	}
	var now = new Date();
//	var callback = {
//		success : onLoadBestel,
//		argument: {showOfferteBox: showOfferteBox}
//	}
	var url = gateway
			+ "?appclass=nl.bnc.bncweb.system.applicatie.webshop.BWAppOfferte&json=1&menuid="
			+ menuid + "&ac=editofferte&fn=bestel&productcode=" + productcode
			+ "&aantal=" + aantal + ((prijs != null) ? "&prijs=" + prijs : "")
			+ "&activearea="+getActivearea()+"&noCache=" + now.getTime();
//	YAHOO.util.Connect.asyncRequest("GET", url, callback, "");
	bncAjaxConnection({
		url:url,
		method:'GET',
		success : onLoadBestel,
		argument: {showOfferteBox: showOfferteBox}
	});
}
function onLoadBestel(o) {
	var obj = eval("(" + o.responseText + ")");
	if (document.getElementById("tabcontentofferte") != null) {
		// offertepagina is open, deze opnieuw inlezen
		loadOfferteinhoud("view");
	}
	updateOverzicht(o.argument.showOfferteBox);
	if (popupbestellen == 'false') {
		momentDialog.hide();
	}
	if (obj["xml.error"] != null) {
		alert(obj["xml.error"]);
	}
}

function onMouseOverOfferteBoxBoven() {
	offerteBoxBovenHover = true;
	setTimeout(onMouseOverOfferteBoxBovenCheck,500);
}

function onMouseOverOfferteBoxBovenCheck() {
	if (offerteBoxBovenHover == true) {
		showOfferteBoxBoven();
		hideOfferteBoxBoven(3);
	}
}

function showOfferteBoxBoven() {
	document.getElementById('offerteBoxBoven').style.display = "block";
}

function hideOfferteBoxBoven(seconden) {
	seconden = (seconden) ? parseInt(seconden * 1000) : 0;
	setTimeout(doHideOfferteBoxBoven, seconden);
}

function onMouseOutOfferteBoxBovenContainer() {
	offerteBoxBovenContainerNoHover = true;
	doHideOfferteBoxBoven();
}

function doHideOfferteBoxBoven() {
	if (offerteBoxBovenContainerNoHover) {
		document.getElementById('offerteBoxBoven').style.display = 'none';
	}
}

var show = false;
function showOfferteOverzicht(savenr) {
//	var now = new Date();
//	var callback = {
//		success : onShowOfferteOverzicht
//	}
//	show = true;
//	YAHOO.util.Connect.asyncRequest("GET",
//			"/wobjects/overzichtje/offerteoverzicht?HttpProxy_savenr=" + savenr
//					+ "&noCache=" + now.getTime(), callback, "");
	bncAjaxConnection({
		url:"/wobjects/overzichtje/offerteoverzicht?HttpProxy_savenr=" + savenr,
		method:'GET',
		success : onShowOfferteOverzicht
	});
}
function onShowOfferteOverzicht(o) {
	if (show) {
		document.getElementById("offerteoverzicht").innerHTML = o.responseText;
		document.getElementById("offerteoverzicht").style.display = "block";
	}
}
function hideOfferteOverzicht() {
	show = false;
	document.getElementById("offerteoverzicht").style.display = "none";
}
function deleteOfferte(showOfferteBox) {
	var now = new Date();
	if(showOfferteBox==null) {
		showOfferteBox = true;
	}
//	var callback = {
//		success : onDeleteOfferte,
//		argument: { showOfferteBox: showOfferteBox }
//	}
//	YAHOO.util.Connect
//			.asyncRequest(
//					"GET",
//					gateway
//							+ "?appclass=nl.bnc.bncweb.system.applicatie.webshop.BWAppOfferte&ac=editofferte&fn=clearofferte&json=1&menuid="
//							+ menuid + "&activearea="+getActivearea()+"&noCache=" + now.getTime(), callback,
//					"");
	bncAjaxConnection({
		url:gateway+ "?appclass=nl.bnc.bncweb.system.applicatie.webshop.BWAppOfferte&ac=editofferte&fn=clearofferte&json=1&menuid="+ menuid + "&activearea="+getActivearea(),
		method:'GET',
		success : onDeleteOfferte,
		argument: { showOfferteBox: showOfferteBox }
	});
}
function onDeleteOfferte(o) {
	var obj = eval("(" + o.responseText + ")");
	if (obj["xml.error"] != null) {
		alert('onDeleteOfferte' + obj["xml.error"]);
	}
	onUpdateOverzicht(o);
	if (document.getElementById("tabcontentofferte") != null) {
		if (document.getElementById("emailadres") != null) {
			document.getElementById("emailadres").value = "";
		}
		if (document.getElementById("afleverbedrijfsnaam") != null) {
			document.getElementById("afleverbedrijfsnaam").value = "";
		}
		if (document.getElementById("aflevernaam") != null) {
			document.getElementById("aflevernaam").value = "";
		}
		if (document.getElementById("afleveradres") != null) {
			document.getElementById("afleveradres").value = "";
		}
		if (document.getElementById("afleverpostcode") != null) {
			document.getElementById("afleverpostcode").value = "";
		}
		if (document.getElementById("afleverplaats") != null) {
			document.getElementById("afleverplaats").value = "";
		}
		if (document.getElementById("afleverland") != null) {
			var aoptions = document.getElementById("afleverland").options;
			document.getElementById("afleverland").selectedIndex = -1;
			for ( var i = 0; i < aoptions.length; i++) {
				if (aoptions[i].value == "NL") {
					document.getElementById("afleverland").selectedIndex = i;
					break;
				}
			}
		}
		// offertepagina is open, deze opnieuw inlezen, ook onderwerp en e-mail
		// tekst leegmaken
		loadOfferteinhoud("view");
		if (document.getElementById("onderwerp") != null) {
			document.getElementById("onderwerp").value = "";
		}
		if (document.getElementById("HttpProxy_emailtekst") != null) {
			document.getElementById("HttpProxy_emailtekst").value = document.getElementById('emailhandtekening').value;
			tinyMCE.execCommand('mceRemoveControl', false, 'HttpProxy_emailtekst');
			tinyMCE.execCommand('mceAddControl', false, 'HttpProxy_emailtekst');
		}
		if (document.getElementById("tabofferte") != null) {
			offerteTabs.toggleTab('offerte');
		}
	}
}
function selectActivearea(activearea, showOfferteBox) {
	setCookie("activearea",activearea,null,"/");
	if (document.getElementById('HttpProxy_emailtekst') != null) {
		tinyMCE.execCommand('mceRemoveControl', false, 'HttpProxy_emailtekst');
	}	
	if (document.getElementById("pageId_offerte") != null && document.getElementById("newPageContainer").style.display == "block" && document.getElementById("pageId_offerte").style.display != "none") {
		// offertepagina is open, de pagina opnieuw inlezen
		document.location.href = '/#location='+escape('/offerte?op=makePrintable&noCache='+new Date().getTime()+'&HttpProxy_activearea=')+activearea;
	} else {
		ajaxSelectActivearea(activearea,showOfferteBox);
	}
}
function getActivearea() {
	var activearea = getCookie("activearea");
	if(activearea=="") {
		activearea = "0";
	}
	return activearea;
}
function ajaxSelectActivearea(activearea, showOfferteBox) {
	var now = new Date();
	var callback = {
		success : onUpdateOverzicht,
		argument: { showOfferteBox: showOfferteBox }
	}
	YAHOO.util.Connect
			.asyncRequest(
					"GET",
					gateway
							+ "?appclass=nl.bnc.bncweb.system.applicatie.webshop.BWAppOfferte&ac=editofferte&activearea="
							+ activearea + "&json=1&menuid=" + menuid
							+ "&noCache=" + now.getTime(), callback, "");
}
function resetGebruiker() {
	var now = new Date();
	var callback = {
		success : onResetGebruiker
	}
	YAHOO.util.Connect
			.asyncRequest(
					"GET",
					gateway
							+ "?appclass=nl.bnc.bncweb.system.applicatie.webshop.BWAppOfferte&ac=editofferte&fn=resetuser&json=1&menuid="
							+ menuid + "&activearea="+getActivearea()+"&noCache=" + now.getTime(), callback,
					"");
}
function onResetGebruiker(o) {
	selectActivearea(getActivearea(),true);
}
function updateOverzicht(showOfferteBox) {
	var now = new Date();
	if(showOfferteBox==null) {
		showOfferteBox = true;
	}
	var callback = {
		success : onUpdateOverzicht,
		argument: { showOfferteBox: showOfferteBox }
	}
	YAHOO.util.Connect
			.asyncRequest(
					"GET",
					gateway
							+ "?appclass=nl.bnc.bncweb.system.applicatie.webshop.BWAppOfferte&ac=editofferte&json=1&menuid="
							+ menuid + "&activearea="+getActivearea()+"&noCache=" + now.getTime(), callback,
					"");
}
function onUpdateOverzicht(o) {
	var obj = eval("(" + o.responseText + ")");
	if (obj["xml.error"] != null) {
		alert('onUpdateOverzicht' + obj["xml.error"]);
	}
	var boxes = YAHOO.util.Selector.query('.offerteOverzichtje');
	for ( var count = 0; count < boxes.length; count++) {
		var totaalprijs = YAHOO.util.Selector.query('.artikel-totaalprijs',
				boxes[count], true);
		if (totaalprijs) {
			totaalprijs.innerHTML = obj["xml.totaalbedrag.thousands_separator"];
		}
		var aantal = YAHOO.util.Selector.query('.artikel-aantal', boxes[count],
				true);
		if (aantal) {
			aantal.innerHTML = obj["xml.totaalaantal"]
					+ ((obj["xml.totaalaantal"] == 1) ? " artikel"
							: " artikelen");
		}
	}
	var offerteGebieden = YAHOO.util.Selector.query('.offerteGebieden');
	for ( var count = 0; count < offerteGebieden.length; count++) {
		var offerteGebiedenDivs = YAHOO.util.Selector.query('div', offerteGebieden[count]);
		for ( var countAreas = 0; countAreas < offerteGebiedenDivs.length; countAreas++) {
			if (obj["xml.activearea"] == countAreas) {
				offerteGebiedenDivs[countAreas].className = "actief";
			} else {
				offerteGebiedenDivs[countAreas].className = "";
			}
		}
	}
	if (obj["xml.verkoopofferte"] != null && obj["xml.verkoopofferte"] == true) {
		if (document.getElementById("offerteboxdebiteurnaam") != null) {
			document.getElementById("offerteboxdebiteurnaam").innerHTML = obj["xml.users.debnaam"];
			document.getElementById("offerteboxgebruikernaam").innerHTML = obj["xml.users.volledigenaam"];
			document.getElementById("offerteboxtelefoon").innerHTML = (obj["xml.users.telefoon"]!=null)?obj["xml.users.telefoon"]:obj["xml.debiteuren.telefoon"];
		}
	} else {
		if (document.getElementById("offerteboxdebiteurnaam") != null) {
			if (obj["xml.offerte_headers.afleverbedrijfsnaam"] != null) {
				document.getElementById("offerteboxdebiteurnaam").innerHTML = obj["xml.offerte_headers.afleverbedrijfsnaam"];
				document.getElementById("offerteboxgebruikernaam").innerHTML = obj["xml.offerte_headers.aflevernaam"];
			} else {
				document.getElementById("offerteboxdebiteurnaam").innerHTML = "niet-klant";
				document.getElementById("offerteboxgebruikernaam").innerHTML = "";
			}
			document.getElementById("offerteboxtelefoon").innerHTML = "";
		}
	}
	if (document.getElementById("offerteboxtotaalbedrag") != null) {
		document.getElementById("offerteboxtotaalbedrag").innerHTML = obj["xml.totaalbedrag.thousands_separator"];
		document.getElementById("offerteboxtotaalaantal").innerHTML = obj["xml.totaalaantal"];
	}
	if(o.argument.showOfferteBox) {
		showOfferteBoxBoven();
		hideOfferteBoxBoven(3);
	}
}

/**
 * ...
 */
function isVisibleStyle(style) {
	// Style object found for object ?
	if ((style !== null) && (style !== undefined)) {
		if ((style.display == 'none') || (style.visibility == 'hidden'))
			return false;
	}
	return true;
}

/**
 * Check if object (element) is visible, this will also check if the object is
 * in an invisible container (invisible parent). Returns: TRUE if visible, FALSE
 * if invisible.
 */
function isVisible(obj) {
	// Prevents infinite recursion, also document should always be visible.
	if (obj == document)
		return true;

	if (!obj || !obj.parentNode)
		return false;

	if (!isVisibleStyle(obj.style))
		return false;

	// Try the computed style in a standard way
	var style = null;
	if (window.getComputedStyle) {
		style = window.getComputedStyle(obj, "");
	} else {
		// Or get the computed style using IE's silly proprietary way
		style = obj.currentStyle;
	}
	if (!isVisibleStyle(style))
		return false;

	return isVisible(obj.parentNode);
}

YAHOO.util.Event.onDOMReady(initOverzichtje);

