﻿$.fn.hasAttr = function(name) {
	var ret = true;
	if (this.attr(name) == null)
		ret = false;
	if (this.attr(name) == undefined)
		ret = false;
	//alert(this.attr(name));
	return ret;
};

$(document).ready(function() {
	//alert(document.cookie);

	$("a.fancybox").fancybox({
		'width': 600, 'height': 500, 'overlayShow': true,
		'hideOnContentClick': false,
		'title': null,
		'titleShow': false
	});
	$("a.fancyboxi").fancybox({
		'type': 'iframe',
		'width': 600, 'height': 500, 'overlayShow': true,
		'hideOnContentClick': false,
		'title': null,
		'titleShow': false
	});
	$("a.fancyboxp").fancybox({
		'type': 'iframe',
		'width': 810, 'height': 600, 'overlayShow': true,
		'hideOnContentClick': false,
		'title': '',
		'titleShow': false
	});
	$("a.fancyboxf").fancybox({
		'type': 'iframe',
		'width': 610, 'height': 300, 'overlayShow': true,
		'hideOnContentClick': false,
		'title': null,
		'titleShow': false
	});

	$.ajaxSetup({
		type: "POST",
		dataType: "json",
		contentType: "application/json; charset=utf-8"
	});

	//$("#nonefounddiv").corner("20px");

	$('div.field-search-m').click(function() { $('input.input-search').focus(); });

	$('.AlphabetOtherPageCells').hover(function() { $(this).addClass('AlphabetOtherPageCellsHover'); }, function() { $(this).removeClass('AlphabetOtherPageCellsHover') });
	CheckIE6Warning();
	CheckReporting();
});

function CheckIE6Warning() {
	if ($.browser.msie && $.browser.version == "6.0") {
		var doneie6 = getCookie("IE6CHECK2");
		//doneie6 = "0";
		if (doneie6 != "1") {
			$("#ie6warning").show();
			$("#btnOKIE6").click(function() { $("#ie6warning").hide(); setCookie("IE6CHECK2", "1", 2); });
		}
	}
}

function isDecimal(str) {
	var rex = new RegExp("^(\\+|-)?[0-9][0-9]*(\\,[0-9]*)?$");
	return str.match(rex);
}
function isDecimalRange(str,van,tot) {
	if (isDecimal(str)) {
		str = str.replace(",", ".");
		var num = parseFloat(str);
		if (num < van)
			return false;
		if (num > tot)
			return false;
		return true;
	}
	else
		return false;
}
function isInteger(s) {
	return (s.toString().search(/^-?[0-9]+$/) == 0);
}
function isUnsignedInteger(s) {
	return (s.toString().search(/^[0-9]+$/) == 0);
}
/* email */
function IsValidEmail(value) {
	var rex = new RegExp("\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
	return value.match(rex);
}
/* phone */
/*function IsValidPhone(value) {
	if (value == '')
		return true;
	var rex = new RegExp("^((00|[+])(\\d{2}|0))?[ -/]?((\\d{2}[ -/]?\\d{7})|(\\d{3}[ -/]?\\d{6})|(\\d{4}[ -/]?\\d{6})|(6[ -/]?\\d{8}))$");
	return value.match(rex);
}*/
function IsValidPhone(value) {
	if (value == '')
		return true;
	var rex = new RegExp("[^0-9 -\/\(\)\+]");
	return !value.match(rex);
}

function CheckEmailField(selector) {
	if (IsValidEmail($(selector).val())) {
		$(selector).removeClass("invalid");
		return true;
	}
	else {
		$(selector).addClass("invalid");
		return false;
	}
}

function CloseFancy() {
	try { parent.$.fn.fancybox.close(); } catch (e) { }
	try { $.fn.fancybox.close(); } catch (e) { }
	try { $.fancybox.close(); } catch (e) { }
	try { parent.$.fancybox.close(); } catch (e) { }
}

function jQueryAjaxError(XMLHttpRequest, textStatus, errorThrown) {
	try {
		// get the .NET Exception from the JSON text
		var err = eval("(" + XMLHttpRequest.responseText + ")");
		//alert(err.Message + '\n\n_____________________\n\n' + err.StackTrace);
		ReportMessage(err.Message + '<br/><hr/>' + err.StackTrace);
	}
	catch (e) {
		// responseText is most likely not a valid JSON object - that's why eval isn't working

		if (XMLHttpRequest.status == 404) {
			// friendly alert
			alert(XMLHttpRequest.statusText);
		}
		else if (XMLHttpRequest.status == 500) {
			// output the html to the browser - less friendly - but required
			document.clear();
			document.write(XMLHttpRequest.responseText);
		}
		else {
			//alert('Unhandled status code ' + XMLHttpRequest.status + ': ' + XMLHttpRequest.statusText + '\n\n_____________________\n\n' + e);
			ReportMessage('Unhandled status code ' + XMLHttpRequest.status + ': ' + XMLHttpRequest.statusText + '<br/><hr/>' + e);
		}
	}
}

/**************/
$(document).ready(function() {

	var fs = getCookie("fs");
	if (fs == "3")
		SetSize3();
	else if (fs == "2")
		SetSize2();
	else
		SetSize1();

	$("li.size1 a").click(function(event) {
		SetSize1();
		event.preventDefault();
	});
	$("li.size2 a").click(function(event) {
		SetSize2();
		event.preventDefault();
	});
	$("li.size3 a").click(function(event) {
		SetSize3();
		event.preventDefault();
	});

});

function SetSize1() {
	$("li.size1 a").parent().siblings().removeClass("active");
	$("li.size1 a").parent().addClass("active");

	$("body").css("font-size", "62.5%");
	setCookie("fs", "1", 100);
}
function SetSize2() {
	$("li.size2 a").parent().siblings().removeClass("active");
	$("li.size2 a").parent().addClass("active");

	$("body").css("font-size", "65%");
	setCookie("fs", "2", 100);
}
function SetSize3() {
	$("li.size3 a").parent().siblings().removeClass("active");
	$("li.size3 a").parent().addClass("active");

	$("body").css("font-size", "70%");
	setCookie("fs", "3", 100);
}


// this deletes the cookie when called
function deleteCookie(c_name, path, domain) {
	if (getCookie(c_name) != '')
		document.cookie = c_name + "=" + 
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

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 trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function TryPrint() {
	if (window.print) {
		window.print();
	}
}

function fnTrapKD2(event,btnid) {
	if (document.all) {
		if (event.keyCode == 13) {
			event.returnValue = false;
			event.cancel = true;
			document.getElementById(btnid).click();
		}
	}
	else if (document.getElementById) {
		if (event.which == 13) {
			event.returnValue = false;
			event.cancel = true;
			document.getElementById(btnid).click();
		}
	}
	/*else if (document.layers) {
		if (event.which == 13) {
			event.returnValue = false;
			event.cancel = true;
			btn.click();
		}
	}*/
}
function ReportMessage(msg) {
	var rep = $("#reporting #reportingcontent");
	var h = rep.html(msg + '<br/>Refresh your browser ! Click <a href="/ecommerce">here</a>.');
	CheckReporting();
}
function CheckReporting() {
	var rep = $("#reporting #reportingcontent");
	var h = rep.html();
	if (h == null)
		return;
	h = trim(h);
	if (h != '') {
		$("#reporting").show();
		$("#reporting").dblclick(function() { $(this).hide(); });
	}
}
function CloseReporting() {
	var rep = $("#reporting #reportingcontent");
	var h = rep.html("");
	$("#reporting").hide();
}
var prodstocks = new Array();
function LoadStockTT(tooltip, node, settings) {
	try {
		var productid = settings.productid;
		var customerid = settings.customerid;
		var pstcks = prodstocks[productid];

		if (pstcks == null) {

			$.ajax({
				url: "/Ecommerce/Services/Tooltips.asmx/GetStockInfoHtml",
				data: "{'customerid':'" + customerid + "', 'productid':'" + productid + "'}",
				success: function(response) {
					pstcks = response.d;
					prodstocks[productid] = pstcks;
					$(tooltip).html(pstcks);
				},
				failure: LoadStockTTFailed,
				error: jQueryAjaxError
			});
		}
		else
			$(tooltip).html(pstcks);
	}
	catch (e) {
	}
}
function LoadStockTTFailed(error) {
}

function LoadPictureTT(tooltip, node, settings) {
	try {
		var productid = settings.productid;
		$.ajax({
			url: "/Ecommerce/Services/Tooltips.asmx/GetPictureHtml",
			data: "{'productid':'" + productid + "'}",
			success: function(response) { $(tooltip).html(response.d); },
			failure: LoadPictureTTFailed,
			error: jQueryAjaxError
		});
	}
	catch (e) {
	}
}
function LoadPictureTTFailed(error) {
}


var prodtooltips = new Array();
function LoadInfoTT(tooltip, node, settings) {
	try {
		var productid = settings.productid;
		var ptt = prodtooltips[productid];
		if (ptt == null) {
			$.ajax({
				url: "/Ecommerce/Services/Tooltips.asmx/GetProductTooltipHtml",
				data: "{'productid':'" + productid + "'}",
				success: function(response) {
					ptt = response.d;
					prodtooltips[productid] = ptt;
					$(tooltip).html(ptt);
				},
				failure: LoadInfoTTFailed,
				error: jQueryAjaxError
			});
		}
		else
			$(tooltip).html(ptt);
	}
	catch (e) {
	}
}
function LoadInfoTTFailed(error) {
}

/*ucLogin*****************/
function Login_Init() {
	var uid = $(userid).val();
	var pw = $(pwid).val();
	
	if (uid == '') {
		uid = getCookie("PUID");
		if (uid != '') {
			$(userid).val(uid);
			$(chkr1id).attr("checked", "checked");
		}

		if ($(userid).val() != '') {
			var rempw = getCookie('RPW');
			//alert(rempw);
			if (rempw.substring(0,2) == 'PW') {
				$(pwid).val(rempw);
				$(chkr2id).attr("checked", "checked");
			}
		}

	}
	if (getCookie("ACCEPT") == '1')
		$(chkid).attr("checked", "checked");
	Login_Refocus();
	$(userid).keypress(Login_HideForgot);
	$(pwid).keypress(Login_HideForgot);
	$(btnid).click(Login_CheckLogin);
	$(hlreaid).click(Login_Reactivate);
	$(hlforid).click(Login_SendPW);
	$(chkr1id).click(Login_ClickChk1);
	$(chkr2id).click(Login_ClickChk2);
	if ($(userid).val() != '')
		$("#login_forgot").show();

}
function Login_ClickChk1() {
	var r1 = $(chkr1id).is(":checked");
	var r2 = $(chkr2id).is(":checked");
	if (!r1) {
		$(chkr2id).attr("checked", "");
		$(chkr2id).attr("disabled", true);
		$(pwid).val('');
	}
	else
		$(chkr2id).attr("disabled", false);
}
function Login_ClickChk2() {
	var r2 = $(chkr2id).is(":checked");
	if (!r2)
		$(pwid).val('');
}

/************************************************************/
function Login_SendPW(event) {
	$("#login_msg1").hide();
	$("#login_msg2").hide();
	$("#login_msg3").hide();
	$("#login_pwsent").hide();
	$("#login_pwnotsent").hide();
	$("#login_loading").show();
	$("#login_button").hide();
	
	var txt = $(userid).val();
	if (txt != '') {

		$("#login_forgot").hide();
		$("#login_msg3").hide();

		try {
			$.ajax({
				url: "/Ecommerce/Services/Ajax.asmx/SendPw",
				data: "{'loginid':'" + txt + "'}",
				success: Login_SendPWDone,
				failure: Login_SendPWError,
				error: jQueryAjaxError
			});
		}
		catch (e) {
			alert('failed to call web service. Error: ' + e);
			$('#login_loading').hide();
			$("#login_button").show();
		}
	}
	event.preventDefault();
}
function Login_SendPWDone(response) {
	if (response.d=='')
		$("#login_pwsent").show();
	else
		$("#login_pwnotsent").show();
	$('#login_loading').hide();
	$("#login_button").show();
}
function Login_SendPWError(error) {
	alert('error: ' + error);
	$('#login_loading').hide();
	$("#login_button").show();
}
/************************************************************/
function Login_Reactivate(event) {
	$("#login_msg1").hide();
	$("#login_msg2").hide();
	$("#login_msg3").hide();
	$("#login_pwsent").hide();
	$("#login_pwnotsent").hide();
	$("#login_loading").show();
	$("#login_button").hide();

	var txt = $(userid).val();
	if (txt != '') {

		$("#login_forgot").hide();
		$("#login_msg3").hide();

		try {
			$.ajax({
				url: "/Ecommerce/Services/Ajax.asmx/Reactivate",
				data: "{'loginid':'" + txt + "'}",
				success: Login_ReactivateDone,
				failure: Login_ReactivateError,
				error: jQueryAjaxError
			});
		}
		catch (e) {
			alert('failed to call web service. Error: ' + e);
			$('#login_loading').hide();
			$("#login_button").show();
		}
	}
	event.preventDefault();
}
function Login_ReactivateDone(response) {
	$('#login_loading').hide();
	$("#login_button").show();
	alert(REACTIVATESENT);
}
function Login_ReactivateError(error) {
	alert('error: ' + error);
	$('#login_loading').hide();
	$("#login_button").show();
}
/************************************************************/

function Login_HideForgot() {
	$("#login_forgot").hide();
	$("#login_pwsent").hide();
	$("#login_pwnotsent").hide();
}
function Login_Refocus() {
	var txt = $(userid).val();
	var pw = $(pwid).val();
	var ia = $(chkid).is(":checked");
	txt = trim(txt);
	pw = trim(pw);
	if (txt == '')
		$(userid).focus();
	else if (pw == '')
		$(pwid).focus();
	else if (!ia)
		$(chkid).focus();
}
function Login_CheckLogin(event) {
	$(userid).removeClass("errorfield");
	$(pwid).removeClass("errorfield");
	$(chkid).parent().children().eq(1).removeClass("errorchk");
	$("#login_pwsent").hide();
	$("#login_pwnotsent").hide();
	$("#login_msg1").hide();
	$("#login_msg2").hide();
	$("#login_msg3").hide();
	var txt = $(userid).val();
	var pw = $(pwid).val();
	var ia = $(chkid).is(":checked");
	txt = trim(txt);
	pw = trim(pw);
	if (txt == '' || pw == '') {
		$("#login_msg2").show();
		event.preventDefault();
		if (txt == '')
			$(userid).addClass("errorfield");
		if (pw == '')
			$(pwid).addClass("errorfield");
	}
	else if (!ia) {
		$("#login_msg1").show();
		$(chkid).parent().children().eq(1).addClass("errorchk");
		event.preventDefault();
	}
	else {
		setCookie("ACCEPT", "1", 100);

		var r1 = $(chkr1id).is(":checked");
		var r2 = $(chkr2id).is(":checked");

		if (!r1)
			r2 = false;
		if (r1)
			setCookie("PUID", txt, 100);
		else
			setCookie("PUID", "");

/*        if (r2)
			setCookie("RPW", "1", 100);
		else
			setCookie("RPW", "");*/

		//$(userid).attr("readonly", true);
		//$(pwid).attr("readonly", true);
		//$(btnid).attr("disabled", true);
	}
	Login_Refocus();
}
/*************************/
function SetLang(langcode, lcid) {
	//alert(langcode + ' ' + lcid);
	deleteCookie("Language");
	setCookie("Language", langcode,100);
	deleteCookie("LCID");
	setCookie("LCID", ''+lcid,100);
}
/*ucLint*******************************************************/
function BookmarkAction(add, cb) {
	alert(cb + ' ' + add + ' ' + location.href + ' ' + location.pathname);

}
function HistoryAction(add, cb) {
	//alert(cb + ' ' + add);
	document.location.href = location.pathname + '?H=' + add;
}

function RemoveFixed(num) {
	//CallPageMethod("ClearFixed", onSuccess, onFail, "dummy", "dummyvalue");
	if (num == 1)
		HideFixed1();
	else if (num == 2)
		HideFixed2();
}

function HideFixed1() {
	HideFixed2();
	$("#btnclearfixed").hide();
	$(".input-fixed").hide();
	$(hidfixedclearedSelector).val("1");
	backurl1 = '';
}
function HideFixed2() {
	$("#btnclearfixed2").hide();
	$(".input-fixed2").hide();
	$(hidfixedclearedSelector).val("2");
	backurl2 = '';
}

function onSuccess(result) {
	//alert(result.d);
}

function onFail(result) {
	//alert(result.d);
}

function CallPageMethod(methodName, onSuccess, onFail) {
	var args = '';
	var l = arguments.length;
	if (l > 3) {
		for (var i = 3; i < l - 1; i += 2) {
			if (args.length != 0)
				args += ',';
			args += '"' + arguments[i] + '":"' + arguments[i + 1] + '"';
		}
	}
	var loc = window.location.href;
	loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "default.aspx" : loc;
	$.ajax({ type: "POST",
		url: loc + "/" + methodName,
		data: "{" + args + "}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: onSuccess,
		fail: onFail
	});
}
var showerrorcount = 0;
function CheckSearchArg(event) {
	var sa = $(searchtxt).val();
	sa = sa.replace('*', '');
	if (sa.length == 0) {
		//event.preventDefault();

		if (backurl2 != '') {
			//alert('redirect to backurl2');
			document.location = backurl2;
			return;
		}
		if (backurl1 != '') {
			//alert('redirect to backurl1');
			document.location = backurl1;
			return;
		}
		//alert('redirect to home');
		document.location = 'Default.aspx';
	   
		return false;
	}
	/*if (sa.length < 3) {
		jAlert(tooshort, CHEYNSNV);
		return false;
	}
	else */if (true){
		foundlonger = false;
		arr_words = sa.split(" ");
		for (ii = 0; ii < arr_words.length; ii++) {
			if (arr_words[ii].length > 2 || IsStartWord(arr_words[ii]))
				foundlonger = true;
		}
		if (!foundlonger) {
			jAlert(tooshort, CHEYNSNV);
			return false;
		}
	}
	return true;
}
function IsStartWord(w) {
	for (var i=0;i<startwords.length;i++)
	{
		if (w.toUpperCase() == startwords[i])
			return true;
	}
	return false;
}
//wijziging filter setting
function ChangeFilter() {
	deleteCookie("SEFI");
	setCookie("SEFI", $(cbSearchFilter).val(), 100);
}

function InitLint() {
	if ($(hidfixedclearedSelector).val() == "1") {
		HideFixed1();
		HideFixed2();
	}
	if ($(hidfixedclearedSelector).val() == "2")
		HideFixed2();

	//if (history.previous == null) {
	if (false) {
		$("#divHistoryPrev").removeClass("prevon");
		$("#divHistoryPrev").addClass("prevoff");
		$("#divHistoryPrev").click(function() { Hist(); });
	}
	else {
		$("#divHistoryPrev").removeClass("prevoff");
		$("#divHistoryPrev").addClass("prevon");
		$("#divHistoryPrev").click(function() {
			$("#divHistoryPrev").removeClass("prevon");
			$("#divHistoryPrev").addClass("prevoff");
			history.back();
		});
	}

	//if (history.next == null) {
	if (false) {
		$("#divHistoryNext").removeClass("nexton");
		$("#divHistoryNext").addClass("nextoff");
		$("#divHistoryNext").click(function() { Hist(); });
	}
	else {
		$("#divHistoryNext").removeClass("nextoff");
		$("#divHistoryNext").addClass("nexton");
		$("#divHistoryNext").click(function() {
			$("#divHistoryNext").removeClass("nexton");
			$("#divHistoryNext").addClass("nextoff");
			history.forward();
		});
	}

	/*	$(searchtxt).keypress(function(e) {
	if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
	e.preventDefault();
	$(searchbtn).click();
	return true;
	}
	});*/

	//$(cbSearchFilter).click(ChangeFilter);

	//$(searchbtn).click(function(e) { return CheckSearchArg(e); });

	if ($(hidSearchFilter).val() != '0')  //all (not)
	{
		$('#searchbarnav li#filter').addClass('active');
	}

	$(filterknop).click(ToggleSearchFilter);
	$("#mnuSearchFilter ul li").hover(function() { $(this).addClass("active"); }, function() { $(this).removeClass("active"); });
	$("#mnuSearchFilter ul li").click(SetSearchFilter);
	$('body').click(HideSearchFilter);
	$("#searchbarnav li#toggle1").hover(function() { $(this).addClass("toggle1hover"); }, function() { $(this).removeClass("toggle1hover"); });
	$("#searchbarnav li#toggle2").hover(function() { $(this).addClass("toggle2hover"); }, function() { $(this).removeClass("toggle2hover"); });
	$("#searchbarnav li#filter").hover(function() { $(this).addClass("filterhover"); }, function() { if (!filtervis) $(this).removeClass("filterhover"); });

	SetDefaultButton(searchtxt, searchbtn);
	SetDefaultButton(qitxt, qibtn);
}

function SetSA(txt, b, g) {
	if (txt!='')
		$(searchtxt).val(txt);

	if (b == 0)
		HideFixed1();
	else if (g == 0)
		HideFixed2();

/*    if ($(".input-fixed").val() == "")
		HideFixed1();
	else if ($(".input-fixed2").val() == "")
		HideFixed2();*/
}

//init via hidSearchFilter
function SetSearchFilter(e) {
	$(hidSearchFilter).val($(this).attr('kind'));
	ToggleSearchFilter(e);
	if ($(hidSearchFilter).val() == '3')  //courante
		$(btnFilterCourant).trigger("click");
	else if ($(hidSearchFilter).val() == '0')  //all
		$(btnFilterAll).trigger("click");
	else
		pb();
}

function HideSearchFilter() {
	if (filtervis) {
		$("#mnuSearchFilter").hide();
		filtervis = false;
		$("#searchbarnav li#filter").removeClass("filterhover");
	}
}

function ToggleSearchFilter(e) {
	if (filtervis) {
		$("#mnuSearchFilter").hide();
		filtervis = false;
		return;
	}
	//get the position of the placeholder element
	var pos = $(filterknop).offset();
	var width = $(filterknop).width();
	var height = $(filterknop).height();
	//show the menu directly over the placeholder
	//$("#mnuSearchFilter").css({ "left": (pos.left + width) + "px", "top": pos.top + "px" });
	$("#mnuSearchFilter").css({ "left": (pos.left) + "px", "top": (pos.top + height + 4) + "px" });
	$("#mnuSearchFilter").show();
	filtervis = true;

	e.stopPropagation();

} 

/**ucSorter****************************************************/
function SortBy(fieldname) {
	var newUrl;
	//return false;
	if (document.location.href.indexOf('?') > 0) {
		var curUrl = document.location.href.split("?");
		var params = curUrl[1].split("&");
		var newparams = '';
		var i;
		for (i = 0; i < params.length; i++) {
			if (params[i].indexOf('so=') == 0) {

			}
			else {
				if (newparams != '')
					newparams += '&';
				newparams = newparams + params[i];
			}
		}
		if (newparams != '')
			newparams += '&';
		newparams = newparams + 'so=' + fieldname;
		newUrl = curUrl[0] + '?' + newparams;
	}
	else
		newUrl = document.location.href + '?so=' + fieldname;

	if (newUrl != document.location.href)
		document.location.href = newUrl;
	return false;
}
/**ucBasketList***************************************************/
function InitUcBasketList() {
	if ($(".basketlineitem").length > 0) {
		$(".basketlineheader").remove().insertBefore(".basketlineitem:eq(0)").show();
	}
	else {
		$(".basketlineheader").remove();
	}
	$("div.basketlineitem").hover(function() {
		$(this).toggleClass("hover");
	},
	function() {
		$(this).toggleClass("hover");
	});
}
function CheckUseTemplate() {
	if (ItemsInBasket > 0) {
		msg = CONFIRMBASKETOVERWRITE;
		msg = msg.replace("%%C%%", ItemsInBasket);
		return confirm(msg);
	}
	else
		return true;
}
function CheckDeleteTemplate() {
	return confirm(CONFIRMDELETETEMPLATE);
}
function CheckUseDeleteTemplate() {
	if (ItemsInBasket > 0) {
		msg = CONFIRMBASKETOVERWRITE2;
		msg = msg.replace("%%C%%", ItemsInBasket);
		return confirm(msg);
	}
	else
		return true;
}

/**ucCustomerList***************************************************/
var OTpopupVis = false;
function InitUcCustomerList() {
	if ($(".customerlineitem").length > 0) {
		$(".customerlineheader").remove().insertBefore(".customerlineitem:eq(0)").show();
	}
	else {
		$(".customerlineheader").remove();
	}
	$("div.customerlineitem").hover(function() {
		$(this).toggleClass("hover");
	},
	function() {
		$(this).toggleClass("hover");
	});
	$('body').click(HideOTpopup);
}
function HideOTpopup() {
	if (OTpopupVis) {
		//$('body').unbind('click.OTpopup');
		$("#OTpopup").hide();
		OTpopupVis = false;
	}
}
/**ucuserList***************************************************/
function InitUcUserList() {
	if ($(".userlineitem").length > 0) {
		$(".userlineheader").remove().insertBefore(".userlineitem:eq(0)").show();
	}
	else {
		$(".userlineheader").remove();
	}
	$("div.userlineitem").hover(function() {
		$(this).toggleClass("hover");
	},
	function() {
		$(this).toggleClass("hover");
	});
}
/**ucResults********************************************************/
//this code moves the <div class="productlineheader"> to just above the first <div class="productline">
var someinputfocus = false;
var donepromowarning = '';
function InitUcResults() {
	if ($(".productline").length > 0) {
		$(".resultproductdivh").remove().insertBefore(".resultmerkdiv:eq(0)").show();
		$(".resultproductdivh .productlineheader").show();
	}
	else {
		$(".resultproductdivh").remove();
	}
	/*if ($(".productline").length > 0) {
		$(".productlineheader").remove().insertBefore(".productline:eq(0)").show();
	}
	else {
		$(".productlineheader").remove();
	}*/

	//$(".productline:odd").addClass("altern");

	$("div.productline div.txt input").numeric();

	$("div.productline div.txt input").focus(function() { $(this).addClass("focused"); someinputfocus = true; $(this).parent().parent().addClass("hover"); });
	$("div.productline div.txt input").blur(function() { $(this).removeClass("focused"); someinputfocus = false; $(this).parent().parent().removeClass("hover"); });
	$("div.productline div.txt input").each(CheckUcResultsQuantity);
	$("div.productline div.txt input").bind("change keyup", CheckUcResultsQuantityCP);    //PROMO warning
	$("div.productline").hover(function() {
		if (!someinputfocus) $(this).addClass("hover");
		//$(this).find('img.imgNoFav').show();
	},
	function() {
		if (!someinputfocus) $(this).removeClass("hover");
		//$(this).find('img.imgNoFav').hide();
	});

	//default button instellen:
	SetDefaultButton("div.productline div.txt input", btnAdd);

	//$(btnAdd).click(AddManyToBasket);
}

function SetDefaultButton(txtselector, btnselector) {
	var eventtocatch = 'keypress';
	//if (BrowserDetect.browser.toLowerCase().indexOf('chrome') >= 0)
	//    eventtocatch = 'keyup';
	$(txtselector).live(eventtocatch, function (e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {

			$(btnselector).click();
			return false;
		}
		else {
			return true;
		}
	}
	);
	
	}
function CheckUcResultsQuantityCP(e) {
		var prid = $(this).attr("oo");
		var pid = $(this).attr("pid");
		if ((prid != 0) && !PromoWarningDone(pid)) {
			//DoPromoWarning(pid);
		}
	return CheckUcResultsQuantity2(e, $(this));
}

function CheckUcResultsQuantity(e) {
	return CheckUcResultsQuantity2(e, $(this));
}
function CheckUcResultsQuantity2(e,$txt) {
	var moq = $txt.attr('mi');
	var maq = $txt.attr('ma'); //maximum (indien PurchaseBlocked)
	var res = $txt.attr('rs');
	if (res == null)
		res = 0;
	if (($txt.val() == null) || ($txt.val() == '') || ($txt.val() == '0')) {
		$txt.removeClass("invalid");
		return true;
	}
	return ValidateAmount2($txt, null, moq, res, 0, 0, maq);
}
function DoPromoWarning(pid) {
	donepromowarning = donepromowarning + pid + ",";
	jConfirm(PROMOWARNING1, CHEYNSNV, function(r) {
		if (r) OpenPromoBox(pid);
	});
}
function PromoWarningDone(pid) {
	return (donepromowarning.indexOf('' + pid + ',', 0) > -1);
}
function OpenPromoBox(pid, onclosefunc) {
	$.fancybox({
		'href': '/ecommerce/Popup/Promotion.aspx?pid='+pid,
		'title': 'Promotion',
		'type': 'iframe',
		'autoScale': false,
		'width': 800, 'height': 600, 'overlayShow': true,
		'hideOnContentClick': false,
		'onClosed': onclosefunc
	});
}

/**************************************************************/
/*Haspels.aspx*/

function InitHaspelList() {
	if ($(".haspelline").length > 0) {
		$(".haspellineheader").remove().insertBefore(".haspelline:eq(0)").show();
	}
	else {
		$(".haspellineheader").remove();
	}

	$("div.haspelline").hover(function() {
		$(this).addClass("hover");
		//$(this).find('img.imgNoFav').show();
	},
	function() {
		$(this).removeClass("hover");
		//$(this).find('img.imgNoFav').hide();
	});

	/*$("div.haspelline:odd").addClass("altern");
*/
	/*$("div.haspelline:even").hover(function() {
	$(this).toggleClass("hover");
	},
	function() {
	$(this).toggleClass("hover");
	});*/
	$("#XlsIcon").show();

	//nu de adres-icon tooltips regelen
	$("div.haspelline .adricon").wTooltip({ className: 'wtt', style: false, content: true, callBefore: LoadHaspelAdresTT });
}

var lastttverif = '';
var lastttid = 0;
var lasttthtml = '';

function LoadHaspelAdresTT(tooltip, node, settings) {
	try {
		var haspelid = parseInt($(node).attr("haspelid"));

		if (haspelid == lastttid && VerifCode == lastttverif) {
			$(tooltip).html(lasttthtml);
		}
		else {
			$(tooltip).html("Loading...");
			$.ajax({
				url: "/Ecommerce/Services/Tooltips.asmx/GetHaspelAddressHtml",
				data: "{'verifcode':'" + VerifCode + "', 'haspelid':'" + haspelid + "'}",
				success: function(response) { $(tooltip).html(response.d); lastttverif = VerifCode; lastttid = haspelid; lasttthtml = response.d; },
				failure: function(error) { $(tooltip).html("Haspel " + haspelid + " " + error); },
				error: function(error) { $(tooltip).html("Haspel " + haspelid + " " + error); }
				//error: jQueryAjaxError
			});
		}
	}
	catch (e) {
	}
}

function CheckHaspels(chk) {
	//alert(chk);
	$(".haspelline .chk input").each(function() { this.checked = chk.checked; });
}

function CheckHaspelsFound() {
	var count = 0;
	$(".haspelline .chk input").each(function() {
		count++;
	});
	return (count > 0);
};

function NumHaspelsSelected() {
	var count = 0;
	$(".haspelline .chk input").each(function() {
		if ($(this).is(":checked"))
			count++;
	});
	return count;
}

function CheckHaspelsSelected() {
	var count = NumHaspelsSelected();
	if (count > 0)
		return true;
	else {

		jAlert(NOHASPELSMSG, CHEYNSNV);
		return false;
	}
}

function GetSelectedHaspels() {
	var hasps = '';
	$(".haspelline .chk input").each(function() {
		if ($(this).is(":checked")) {
			hasps = hasps + $(this).parent().attr("haspelid") + ";";
		}
	});
	return hasps;
}

function HaspelPrint() {
	if (!CheckHaspelsFound()) {
		return;
	}

	$.fancybox({
		'href': '/ecommerce/Print/Haspels.aspx',
		'title': 'Haspels',
		'type': 'iframe',
		'autoScale': false,
		'width': 800, 'height': 600, 'overlayShow': true,
		'hideOnContentClick': false,
		'onClosed': function() {
			//do something here
		}
	});
}
/*framed pages*************************************************************/
function pageY(elem) {
	return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
}

function resizeIframe() {
	var buffer = 20 + 5; //scroll bar buffer 
	var height = document.documentElement.clientHeight;
	height -= pageY(document.getElementById('OrderTracing')) + buffer;
	height = (height < 0) ? 0 : height;
	document.getElementById('OrderTracing').style.height = height + 'px';
	//resizeDebug(); 
} 
/**************************************************************/
function OrderTracingPrint() {
	//alert('Klik het print-icoon in de hoofding van de af te drukken lijst');
	document.getElementById('OrderTracing').contentWindow.TryPrint();
	//$("#OrderTracing").contentWindow.TryPrint();
	return false;
}
/**************************************************************/
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'); if (z < 0) z = 1; y.splice(z, 0, pnt); if (y[0] == pnt) y.unshift('0'); while (z > 3) { z -= 3; y.splice(z, 0, thou); } var r = curr1 + n1 + y.join('') + n2 + curr2; return r; }
/**************************************************************/
/*product.aspx*/

function InitPacking(sel, txt, num) {
	if (num > 0) {
		txt = txt + " " + num + " " + UNIT;
		$(sel).append("<div class='packitxt'>" + txt + "</div>");
		$(sel).addClass("active");
		$(sel).append("<div class='orangearrow'>&gt;&gt;</div>");
		$(sel).click(function() { SetTxtAmount(num, pric); });
		$(sel).show();
	}
	else
		$(sel).hide();
}
function InitProductDetail() {
	try {
		InitPacking("#packingA", TXT_PACKINGA, numA);
		InitPacking("#packingB", TXT_PACKINGB, numB);
		InitPacking("#packingC", TXT_PACKINGC, numC);
	}
	catch (ex) { };
	$(txtQuantity).numeric();
	$(txtQuantity).bind("change keyup", ValidateAmount);
	InitImages();
	ValidateAmount();

	SetDefaultButton(txtQuantity, btnAdd);

	// AP 0024
	if (acs == 0) {
		$('#pimages').protectContent({ allowRightContextMenu: false });
	}
	//$(btnAdd).click(AddToBasket1);
}

function InitImage(sel, url, eve) {
	if (url != '') {
		$(sel).append("<img src='" + url + "' alt=''/>");
		if (eve) {
			$(sel).click(SwapImage);
		}
	}
}
function SwapImage() {
	var temp1 = $(this).html();
	var temp2 = $("#prodimg1").html();
	$(this).html(temp2);
	$("#prodimg1").html(temp1);
}
function InitImages() {
	if (typeof img1 === 'undefined') img1 = '';
	if (typeof img2 === 'undefined') img2 = '';
	if (typeof img3 === 'undefined') img3 = '';
	if (typeof img4 === 'undefined') img4 = '';
	if (typeof img5 === 'undefined') img5 = '';
	if (typeof img6 === 'undefined') img6 = '';
	if (typeof img7 === 'undefined') img7 = '';
	InitImage("#prodimg1", img1, false);
	InitImage("#prodimg2", img2, true);
	InitImage("#prodimg3", img3, true);
	InitImage("#prodimg4", img4, true);
	InitImage("#prodimg5", img5, true);
	InitImage("#prodimg6", img6, true);
	InitImage("#prodimg7", img7, true);
	if ((img1 == '') && (img2 == '') && (img3 == '') && (img4 == '') && (img5 == '') && (img6 == '') && (img7 == '')) {
		$("div#pimages div.subtit").hide();
	}
}

function AddToBasket1() {
	if (ValidateAmount()) {
		var q = $(txtQuantity).val();
		var qi = parseInt(q, 10);
		var oo = $(txtQuantity).attr("oo");
		var ooprodok = true;
		if (oo == "1") {
			jConfirm(PROMOWARNING2, CHEYNSNV, function(r) {
				if (r) {
					$(btnAdd).hide();
					$("#loading").show();

					$.ajax({
						url: "/Ecommerce/Services/Ajax.asmx/AddToBasket",
						data: "{'verifcode1':'" + VerifCode1 + "','verifcode2':'" + VerifCode2 + "', 'productid':" + pid + ",'quantity':" + qi + "}",
						success: AddToBasketDone,
						failure: AddToBasketFailed,
						error: jQueryAjaxError
					});
				}
				else {
					OpenPromoBox(pid);
				}
			});
		}
		else {
			$(btnAdd).hide();
			$("#loading").show();

			$.ajax({
				url: "/Ecommerce/Services/Ajax.asmx/AddToBasket",
				data: "{'verifcode1':'" + VerifCode1 + "','verifcode2':'" + VerifCode2 + "', 'productid':" + pid + ",'quantity':" + qi + "}",
				success: AddToBasketDone,
				failure: AddToBasketFailed,
				error: jQueryAjaxError
			});
		}
	}
}

function AddToBasketDone(response) {
	var resp = response.d;
	if (resp.Success) {
		//jAlert(resp.Message, CHEYNSNV);
		UpdateBasketInfoHead();
	}
	else {
		alert(resp.Message);
	}
	$("#loading").hide();
	$(btnAdd).show();
}
function AddToBasketFailed(error) {
	$("#loading").hide();
	$(btnAdd).show();
	alert(error);
}
function ValidateAmount() {
	q = $(txtQuantity).val();
	qi = parseInt(q, 10);
	pricta = NetPrTa;
	pric = NetPr;

	if (qi >= numA && numA > 0) {
		pricta = NetPrTaA;
		pric = NetPrA;
	}
	if (qi >= numB && numB > 0) {
		pricta = NetPrTaB;
		pric = NetPrB;
	}
	if (qi >= numC && numC > 0) {
		pricta = NetPrTaC;
		pric = NetPrC;
	}

	return ValidateAmount2($(txtQuantity), $(btnAdd), MiOnQ, RestQ, pricta, pric, MaOnQ);
}
function ValidateAmount2($txt, $btn, moq, rest, priceta, pricenota,maq) {
	$txt.removeClass("invalid");
	if ($btn != null)
		$btn.removeClass("disabled");
	var ok = false;
	var q = $txt.val();
	var qi = parseInt(q, 10);

	if (pricenota>0.0)
		$("#yourup").html(formatNumber(pricenota, 4, '.', ',', '€ ', '', '', ''));
	if (priceta > 0.0)
		$("#yourupwt").html(formatNumber(priceta, 4, '.', ',', '€ ', '', '', ''));
	
	$("#yourtotal").html('');
	if (qi > 0) {
		if (moq > 0) {
			if ((qi % moq) == 0)
				ok = true;
			if (rest > 0) {
				if (rest == qi)
					ok = true;
				else {
					if (((qi - rest) % moq == 0) && (qi - rest > 0))
						ok = true;
					else {  //added 201011010
						if ((qi - Math.floor(qi / moq) * moq) <= rest)
							ok = true;
					}
				}
			}
		}
	}
	if (maq != 0 && qi > maq) {
		ok = false;
		tempmsg = ONGELDIGEQMA.replace("%MAQ%", maq);
		jAlert(tempmsg, CHEYNSNV);
	}
	if (ok) {

		if (priceta > 0.0) {
			var cp = priceta * qi;
			$("#yourtotal").html(formatNumber(cp, 4, '.', ',', '€ ', '', '', ''));
		}
		return true;
	}
	else {
		$txt.addClass("invalid");
		if ($btn != null)
			$btn.addClass("disabled");
		return false;
	}

}

function SetTxtAmount(num) {
	$(txtQuantity).val(num);
	$(txtQuantity).focus();
	ValidateAmount();
}

function UpdateFavIcon(productid, companyfav, personalfav) {

	if (companyfav) {
		$(imgFav).attr("src", "/Assets/large/FavB.png");
	}
	else if (personalfav) {
		$(imgFav).attr("src", "/Assets/large/FavY.png");
	}
	else {
		$(imgFav).attr("src", "/Assets/large/FavNo.png");
	}
}

/**************************************************************/

function NoEnter() {
	if (typeof (window.event) != "undefined") {
		if (window.event.keyCode == 13) {
			//window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
	}
}

/**************************************************************/

