$.jGrowl.defaults.position = 'center';
jQuery.extend(
	jQuery.expr[':'].Contains = function(a, i, m) { 
	  return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; 
	}
);
jQuery.extend(
	jQuery.expr[':'].contains = function(a, i, m) { 
	  return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; 
	}
);
$.fn.extend({
	toHTMLString: function() {
		return $("<div>").append(this.clone()).html();
	}
});

var flowerAngle;
var flowerRotateInterval = 100;
var flowerCookieName = "OnderstebovenWinkelmandje";
var personalMessage = "";
$(function() {
	if($(".datepicker").length > 0)
		$(".datepicker").datepicker({ dateFormat: "dd/mm/yy" }, $.datepicker.regional[ "nl" ]);

	if($(".datefilterpicker").length > 0)
		$(".datefilterpicker").datepicker({ dateFormat: "dd/mm/yy", onClose: function() { filterList() } }, $.datepicker.regional[ "nl" ]);
	
	var d = new Date();
	if((!$.browser.msie || ($.browser.msie && $.browser.version >= 9)) && d.getMonth()<11)	// not in december
		rotateFlower();
	
	initImageScroller();
	
	initTables();
	
	try {
		if(document.location.href.indexOf("&added=1") > 0)
			$.jGrowl("Het product werd toegevoegd aan het winkelmandje.", { life: 1500 });
	} catch (ex) {}
		
	$(".chkFilter").change(function () {
		$("#frmFilterWS").submit();
	})
	
	$("#wsTxtFilter").keypress(function (event) {
		if (event.which == 13)
			$("#frmFilterWS").submit();
	})
	
	$("#txtFilterBLcatalog").keyup(function (event) {
	    $("ul#catalog li").css("display", "none");
	    $("ul#catalog li:Contains('" + $(this).val() + "')").css('display', 'block');
		
	})
	
	$("#btnCompleteSB").click(function () {
		$("#frmBasket").submit();
	})
	
	$.ajaxSetup({
		error:function(x,e){
			if(x.status==0){
				alert('You are offline!!\n Please Check Your Network.');
			}else if(x.status==404){
				alert('Requested URL not found.');
			}else if(x.status==500){
				alert('Internel Server Error.');
			}else if(e=='parsererror'){
				alert('Error.\nParsing JSON Request failed.');
			}else if(e=='timeout'){
				alert('Request Time out.');
			}else {
				alert('Unknow Error.\n'+x.responseText);
			}
		}
	});		
});
function isDefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}
function rotateFlower() {
	if(flowerAngle == undefined) flowerAngle = 0;
	flowerAngle = flowerAngle + 0.5;
	if(flowerAngle > 360) flowerAngle -= 360;
	
    $(".bloem").css("-webkit-transform", "rotate(" + flowerAngle + "deg)");
    $(".bloem").css("-moz-transform", "rotate(" + flowerAngle + "deg)");
    $(".bloem").css("-o-transform", "rotate(" + flowerAngle + "deg)");
    $(".bloem").css("-ms-transform", "rotate(" + flowerAngle + "deg)");
	$(".bloem").css("transform", "rotate(" + flowerAngle + "deg)");
	setTimeout("rotateFlower()", flowerRotateInterval);
}
function setFBTargets() {
	$("#tblFB").find("a[href]").attr('target', 'wnd_fb_ondersteboven');
	$("#tblFB").find("a[href*='http://www.facebook.com/media/set/?']").remove();
}
function initImageScroller() {
	// photostack
	var $album = Math.random();
	$.each($("ul.imageScroller li img"), function(index, value) {
		$src = $(this).attr("src");
		$title = $(this).attr("title");
		$rel = "prettyPhoto[" + $album + "]";
		$link = $("<a href='" + $src + "' rel='" + $rel + "' title='" + $title + "'></a>");
		$link.html($(this).toHTMLString());
		$(this).replaceWith($link);
	});
	// select 3 images from the list randomly and generate a thumbnail image for it
	randomElements = $("ul.imageScroller li").get().sort(function(){ 
		return Math.round(Math.random())-0.5
	}).slice(0,3)
	
	var $alignment = $("ul.imageScroller").css("float");
	if($alignment == undefined || $alignment == null || $alignment == "" || $alignment == "none") $alignment = "left";
	var $thumbHtml = '<div class="thumbnail" style="float:' + $alignment + '">';
	$.each(randomElements, function(index, listitem) {
		var element = $(listitem).find("img");
		$thumbHtml += '<a href="#" linkedimage="' + escape($(element).attr("src")) + '">';
		$thumbHtml += '<img class="thumb' + (index + 1) + '" src="thumbnail.php?transparent=false&image=' + escape($(element).attr("src")) + '" alt="' + $(element).attr("alt") + '"';
		$thumbHtml += ' title="' + $(element).attr("title") + '" /></a>'
	})
	$thumbHtml += '</div>';
	
	$ppHtml = "";
	
	$("ul.imageScroller").css("display", "none");
	$("ul.imageScroller").next().prepend($thumbHtml);
	
	$("a[linkedimage]").click( function() {
		$('img[src="' + $(this).attr("linkedimage") + '"]').click();	
	});
	
	// prettyPhoto
	$.each($("img[rel^='prettyPhoto']"), function(index, value) {
		$src = $(this).attr("src");
		$src = $src.substr($src.indexOf("&image=") + 7);
		$title = $(this).attr("title");
		$rel = $(this).attr("rel");
		$link = $("<a href='" + $src + "' rel='" + $rel + "' title='" + $title + "'></a>");
		$link.html($(this).toHTMLString());
		$(this).replaceWith($link);
	});
	try {
	$("a[rel^='prettyPhoto']").prettyPhoto( { social_tools: false } );
	} catch(e) {}
	return;
}
function initTables() {
	return;
	if($('.scrollTable').length == 0)
		return;
// 1. grab a bunch of variables
    var $container = $('.scrollTable');
    var $headers = $container.find('h2');
    var zIndex = 2;
    var containerTop = $container.offset().top + parseInt($container.css('marginTop')) + parseInt($container.css('borderTopWidth'));
    var $fakeHeader = $headers.filter(':first').clone();
    
    // 2. absolute position on the h2, and fix the z-index so they increase
    $headers.each(function () {
       // set position absolute, etc
       var $header = $(this), height = $header.outerHeight(), width = $header.outerWidth();

       zIndex += 2;
       
       $header.css({
           position: 'absolute',
           width: $header.width(),
           zIndex: zIndex
       });
       
       // create the white space
       var $spacer = $header.after('<div />').next();
       $spacer.css({
           height: height,
           width: width
       });
    });
    
    // 3. bind a scroll event and change the text of the take heading
    $container.scroll(function () {
        $headers.each(function () {
            var $header = $(this);
            var top = $header.offset().top;
            
            if (top < containerTop) {
                $fakeHeader.text($header.text());
                $fakeHeader.css('zIndex', parseInt($header.css('zIndex'))+1);
            }
        });
    });
    
    // 4. initialisation
    $container.wrap('<div class="box" />');
    $fakeHeader.css({ zIndex: 1, position: 'absolute', width: $headers.filter(':first').width() }).attr("class","scrollTableHeader");
    $container.before($fakeHeader.text($headers.filter(':first').text()));
	
	return;
}
function filterList() {
	var $filterFields = $(".filter");
	var $constraints = new Array();
	
	$.each($filterFields, function (index, filterField) {
		if($.trim($(filterField).val()) != "")
			$constraints.push("div."+$(filterField).attr("colname")+":contains('" + $.trim($(filterField).val()) + "')");
	});
	
	var $constraint = "";
	if($constraints.length == 0)
		$("div.row").show();
	else
	{
		$("div.row").hide();
		if($constraints.length >= 1)
			$constraint = "$(\"" + $constraints[0] + "\").parent()";
		for($i=1; $i<$constraints.length; $i++) {
			$constraint += ".children(\"" + $constraints[$i] + "\").parent()";
		}
		eval($constraint + ".show()");
	}
	$results = $("div.row:not(:hidden)").length;
	$("div.scrollTableFoot").html('<strong>' + $results + '</strong> item' + ($results == 1 ? "" : 's') + ' gevonden');
	
	return;
}
function openBirthList(id) {
	document.location = "?page=geboortelijst&id=" + id;
}
function deleteBirthList(id) {
	if(confirm("Ben je zeker dat je deze geboortelijst wil verwijderen?"))
		document.location = "?action=deletelist&id=" + id;
}
function checkField($field) {
	if($.trim($field.val()) == "") {
		$field.addClass( "ui-state-error" );
		$field.focus();
		return false;
	} else
		return true;
}
function initDialog() {
	if($("#bl-dialog-form")) {
		var bValid			= true,
			bl_name  		= $("#name"),
			bl_fname 		= $("#fname"),
			bl_birthdate 	= $("#birthdate"),
			//bl_chkPrices 	= $("#chkPrices").attr("checked") == "checked" ? "1" : "0",
			//bl_chkGiftcards = $("#chkGiftcards").attr("checked") == "checked" ? "1" : "0",
			bl_allFields 		= $( [] ).add( bl_name ).add( bl_fname ).add( bl_birthdate );
		
		$("#bl-dialog-form").dialog({
			autoOpen: false,
			height: 250,
			width: 500,
			modal: true,
			buttons: {
				"Maak lijst aan": function() {
					bValid = true;
					bl_allFields.removeClass( "ui-state-error" );
					bValid = bValid && checkField(bl_name);
					bValid = bValid && checkField(bl_fname);
					bValid = bValid && checkField(bl_birthdate);
					
					if(bValid) {
						$("#createNewBL").submit();
						$( this ).dialog( "close" );
					}
				},
				"Annuleren": function() {
					bl_allFields.val( "" ).removeClass( "ui-state-error" );
					$( this ).dialog( "close" );
				}
			}
		});
	}
	if($("#btnCreateBL")) {
		$("#btnCreateBL").button()
			.click(function() {
				$( "#bl-dialog-form" ).dialog( "open" );
			});
	}
}
function exportBirthList(id) {
	window.open("export.php?id=" + id);
}
function filterBirthList() {
	var $filterFields = $(".filter");
	var $constraints = new Array();
	
	$.each($filterFields, function (index, filterField) {
		if($.trim($(filterField).val()) != "")
			$constraints.push("."+$(filterField).attr("colname")+":contains('" + $.trim($(filterField).val()) + "')");
	});
	
	var $constraint = "";
	if($constraints.length == 0)
		$(".row").show();
	else
	{
		$(".row").hide();
		if($constraints.length >= 1)
			$constraint = "$(\"" + $constraints[0] + "\").parent()";
		for($i=1; $i<$constraints.length; $i++) {
			$constraint += ".children(\"" + $constraints[$i] + "\").parent()";
		}
		eval($constraint + ".show()");
	}
	$results = $(".row:not(:hidden)").length;
	
	return;
}
function updateBLitem(method, itemid, column) {
	document.location = "?action=updateBL&itemid=" + itemid + "&column=" + column + "&method=" + method + "&referrer=" + escape(document.location.href);
	return false;
}
function removeBL(itemid, blid) {
	document.location = "?action=deleteBLitem&itemid=" + itemid + "&blid=" + blid + "&referrer=" + escape(document.location.href);
	return false;
}
function editBL(itemid, blid, blitemid) {
	var url = "product_details.php?id=" + parseInt(itemid, 10) + "&blid=" + parseInt(blid, 10)+ "&blitemid=" + parseInt(blitemid, 10);
	var dialog = $("#detailsDialog");
	if ($("#detailsDialog").length == 0)
		dialog = $('<div id="detailsDialog" title="Details product" style="display:hidden"></div>').appendTo('body');

	dialog.load( 
		url, 
		{}, 
		function(responseText, textStatus, XMLHttpRequest) { 
			dialog.dialog( { 
				modal: true, 
				width: '400',
				hide: "fadeOut",
				show: "fadeIn",
				resizable: false,
				buttons: {
					"Bewaren": function() {
						$("#frmEditBLItem").submit();
						$( this ).dialog( "close" );
					},
					"Annuleren": function() {
						$( this ).dialog( "close" );
					}
				}
			} );
		}
	);

	if(event) event.stopPropagation();
	window.event.cancelBubble = true;
	return false;
}
function clearShoppingCookie() {
	$.ajax({
		url: "?action=ClearShoppingBasket",
		success: function(data){
			$("li#liWinkelMandje").attr("style", "display:none");
			document.location = "?";
		}
	});
}
function addToBasket(btn, itemid, itemcount, BLid, size, color) {
	$(btn).attr("old_src", $(btn).attr("src")).attr("src", "images/loading.gif").addClass("loading").attr("width", "15").attr("height", "15");
	$.ajax({
		url: "?action=addToBasket&id=" + itemid + "&itemcount=" + itemcount + "&bl=" + BLid + "&size=" + size + "&color=" + color,
		success: function(data){
			$.jGrowl("Het product werd toegevoegd aan het winkelmandje.", 
			{ 
				life: 1000, 
				beforeClose:function(e,m) {
					$.ajax({
						url: "?action=updateShoppingBasket",
						success: function(data){
							eval(data);
							$("img.loading").attr("src", $(btn).attr("old_src")).removeAttr("width").removeAttr("height");
							$("li#liWinkelMandje").removeAttr("style");
						}
					});
				} 
			});
		}
	});
	return false;
}
function openShoppingBasket() {
	document.location = "?page=winkelmandje";
}
function openProductDetails(id) {
	if(parseInt(id, 10) == 0) {
		event.stopPropagation();
		window.event.cancelBubble = true;
		return false;
	} else {
		var url = "product_details.php?id=" + parseInt(id, 10);
		var dialog = $("#detailsDialog");
		if ($("#detailsDialog").length == 0)
			dialog = $('<div id="detailsDialog" title="Details product" style="display:hidden"></div>').appendTo('body');
	
		dialog.load( 
			url, 
			{}, 
			function(responseText, textStatus, XMLHttpRequest) { 
				dialog.dialog( { 
					modal: true, 
					width: 'auto',
					hide: "fadeOut",
					show: "fadeIn",
					resizable: false,
					buttons: {
						Ok: function() {
							$( this ).dialog( "close" );
						}
					} 
				} );
			}
		);
	
		//if(event != undefined) event.stopPropagation();
		//window.event.cancelBubble = true;
		return false;
	}
}
function comparator(a, b) {
    return parseInt(a[1]) > parseInt(b[1]);
}
function showCatProducts($blid) {
	var cat = $("#selShoppingCat").val();
	$( "#catalog li").detach();
	
	var $url = "category_products.php?category=" + cat;
	
	$.getJSON($url, function(data) {
		var items = [];
		$.each(data, function(text, id) {
			items.push("<li value='" + id + "-" + $blid + "'>" + text + "</li>");
		});
		$( "#catalog" ).html( items.join('') );
	}).success(function() { 
		$( "#catalog li" ).draggable({
			appendTo: "body",
			helper: "clone"
		});
		$( "table.geboortelijst .row, table.geboortelijst .foot" ).droppable({
			activeClass: "ui-state-default",
			hoverClass: "ui-state-hover",
			drop: function( event, ui ) {
				var item_bl = ui.draggable.attr("value");
				var url = "?action=addBLitem&itemid=" + item_bl + "&blid=" + $blid + "&referrer=" + escape(document.location.href + "&cat=" + $("#selShoppingCat").val());
				document.location = url;
				return false;
			}
		})
	});
}
function deleteWebshopItem($itemid) {
	if(confirm("Ben je zeker dat je dit item wil verwijderen?"))
		document.location = "?action=deleteWSitem&id=" + $itemid;
}
function editWebshopItem($itemid) {
	var url = "product_details.php?id=" + parseInt($itemid, 10);
	var dialog = $("#ws-dialog-form");
	if ($("#ws-dialog-form").length == 0)
		dialog = $('<div id="ws-dialog-form" title="Webshop Item" style="display:hidden"></div>').appendTo('body');

	dialog.load( 
		url, 
		{}, 
		function(responseText, textStatus, XMLHttpRequest) { 
			var ws_name  		= $("#ws_name"),
				ws_cat_sel		= $("#ws_cat_sel"),
				ws_cat_txt		= $("#ws_cat_txt"),
				//ws_brand		= $("#ws_brand"),
				//ws_color		= $("#ws_color"),
				//ws_size		= $("#ws_size"),
				ws_price		= $("#ws_price"),
				ws_allFields 	= $( [] ).add( ws_name ).add( ws_cat_sel ).add( ws_cat_txt ).add ( ws_price );
			dialog.dialog( { 
				height: 345,
				width: 400,
				modal: true, 
				buttons: {
					"Bewaren": function() {
						bValid = true;
						ws_allFields.removeClass( "ui-state-error" );
						bValid = bValid && checkField(ws_name);
						bValid = bValid && checkField(ws_cat_sel);
						if(ws_cat_sel.val() == "Nieuw")
							bValid = bValid && checkField(ws_cat_txt);
						bValid = bValid && checkField(ws_price);
						
						if(bValid) {
							$("#frmEditWSItem").submit();
							$( this ).dialog( "close" );
						}
					},
					"Annuleren": function() {
						ws_allFields.val( "" ).removeClass( "ui-state-error" );
						$( this ).dialog( "close" );
					}
				}
					} );
		}
	);
	return false;
}
function checkWSOption(selList) {
	if(selList.options[selList.selectedIndex].value == "new") {
		$("#ws_cat_sel").css("width", "32%");
		$("#ws_cat_txt").show().focus();
	}
	else {
		$("#ws_cat_sel").css("width", "70%");
		$("#ws_cat_txt").hide();
	}
}
function initWSbutton() {
	if($("#btnCreateWSitem")) {
		$("#btnCreateWSitem").button()
			.click(function() {
				editWebshopItem(0);
			});
	}
}
function showWS() {
	document.location = "?page=webshop&cat=" + $("#selWSFilterCat").val();
}
function changePage(page, cat) {
	document.location = "?page=webshop&p=" + page + "&cat=" + cat;
}
function clearWSfilter() {
	document.location = "?action=clearWSfilter";
}
function updateSBitemCount(field, operation, key) {
	//$fieldid = "#txtAmount_" + key;
	//$field = $($fieldid);
	$field = $(field).parent("td").parent("tr").find("input.SBtxt");
	$fieldval = parseInt($field.val().replace(".", "").replace(",", "."), 10);
	
	switch(operation) {
		case "delete":
			$fieldval = 0;
			//delete row from table
			$field.closest("tr").remove();
			break;
		case "increase":
			$fieldval ++;
			if($fieldval > 99) $fieldval = 99;
			break;
		case "decrease":
			$fieldval --;
			if($fieldval < 0) $fieldval = 0;
			break;
	}
	$field.val($fieldval);
	
	$itemCount = 0;
	$totalPrice = 0;
	
	$.each($(".trSBitem"), function() {
		$amountfield = $(this).find(".SBtxt")[0];
		$pricefield  = $(this).find(".spItemPrice")[0];
		$thisPricefield = $(this).find(".spTotal")[0];
		//$totalPrice += parseFloat($(this).val())
		
		$itemCount += parseInt($($amountfield).val(), 10);
		$price = parseFloat($($pricefield).html().replace(".", "").replace(",", "."));
		$thisTotalPrice = parseInt($($amountfield).val(), 10) * $price;
		$totalPrice += $thisTotalPrice;
		$($thisPricefield).html(formatCurrency($thisTotalPrice));
		//$totalPrice += parseInt($($amountfield).val(), 10) * parseFloat($($pricefield).html());
		
    });
	if($totalPrice == 0)
		clearShoppingCookie();
	
	$totalPrice = formatCurrency($totalPrice);
	
	$("#tdTotalAmount").html($itemCount + " item" + ($itemCount == 1 ? "" : "s"));
	$("#tdTotalPrice").html("&euro; " + $totalPrice);
}
function formatCurrency(number) {
	var numberStr = parseFloat(number).toFixed(2).toString();
	var numFormatDec = numberStr.slice(-2); /*decimal 00*/
	numberStr = numberStr.substring(0, numberStr.length-3); /*cut last 3 strings*/
	var numFormat = new Array;
	while (numberStr.length > 3) {
		numFormat.unshift(numberStr.slice(-3));
		numberStr = numberStr.substring(0, numberStr.length-3);
	}
	numFormat.unshift(numberStr);
	return numFormat.join('.')+','+numFormatDec; /*format 000.000.000,00 */
}
function checkLevFac($val) {
	if($val == "1")
		$("tr.trFacturatie").addClass("trNotVisible");
	else
		$("tr.trFacturatie").removeClass("trNotVisible");
}
function copyField(field) {
	var $fieldId = $(field).attr("id").replace("lev_", "fac_");
	var $targetField = $("#" + $fieldId);
	if($targetField.val() == "")
		$targetField.val($(field).val());
}
function TogglePersMsg(option) {
	switch(option)
	{
		case 1:
			$("tr#trPersonalMessage").css("display", "none");
			personalMessage = $("#MESSAGE").val();
			$("#MESSAGE").val("");
			break;
		case 2:
			$("tr#trPersonalMessage").css("display", "");
			personalMessage = $("#MESSAGE").val(personalMessage);
			break;
	}
}
function zet_emoticon(sIcon) {
	insertAtCursor(document.getElementById("txtTekst"), " "+sIcon+" ")
}
function insertAtCursor(myField, myValue) {
	//IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
		+ myValue
		+ myField.value.substring(endPos, myField.value.length);
	} else {
		myField.value += myValue;
	}
	myField.focus();
}
function gbReplyPopup(parentid) {
	$('#txtPARENTID').val(parentid);
	$('#txtNaam').val("Onderstebove");
	$('#txtMail').val("info@onderstebove.be");
	$( "#frmAddGBEntry" ).dialog( "open" );
}
function gbDeleteEntry(id) {
	confirm("Ben je zeker dat je dit bericht wil verwijderen?")
		document.location = "?page=gastenboek&action=deletegbentry&id=" + id;
}
function gbMarkEntryAsSpam(id) {
	confirm("Ben je zeker dat je dit bericht wil markeren als spam en verwijderen?\nDeze verzender zal dan geen berichten meer kunnen posten.")
		document.location = "?page=gastenboek&action=markgbentryasspam&id=" + id;
}
function resolveClientUrl(url) {
    if (url.indexOf("~/") == 0) {
        url = baseUrl + url.substring(2);
    }
    return url;
}
function openOrder(id) {
	$("#orderDetail").load("vieworder.php?id=" + parseInt(id, 10)).dialog({modal:true, position:'top', left:"50%", "margin-left":"-335px", width:670, title:"Details bestelling"});
}
function exportOrder(id) {
	window.open("exportorder.php?id=" + id);
}
function printElement(elem)
{
	printPopup($("#" + elem).html());
}
function printPopup(data) 
{
	var mywindow = window.open('', 'my div', 'height=400,width=600');
	mywindow.document.write('<html><head><title></title><style type="text/css">body {text-align:center;font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;font-size:13px;color:#5c7e3f;margin:0;width:100%;</style>');
	mywindow.document.write('</head><body >');
	mywindow.document.write(data);
	mywindow.document.write('</body></html>');
	mywindow.document.close();
	mywindow.print();
	mywindow.close();
	return true;
}
