$(document).ready(function() {

    // Set submenu indentation
    $("#sitemenu UL.lvl1 > LI").each(function() {
        $(this).find("UL").first().css("text-indent", $(this).attr("offsetLeft"));
    });

    // IE :focus hack
    if ($.browser.msie === true) {
        jQuery('input')
			.bind('focus', function() { $(this).addClass('ieFocusHack'); })
			.bind('blur', function() { $(this).removeClass('ieFocusHack'); });
    }

    $("#username").focus(function() { if ($(this).val() == "inlognaam") { $(this).val(""); } })
							.blur(function() { if ($(this).val() == "") { $(this).val("inlognaam"); } });
    $("#debtornumber").focus(function() { if ($(this).val() == "Debiteur") { $(this).val(""); } })
							.blur(function() { if ($(this).val() == "") { $(this).val("Debiteur"); } });

    $("#password").focus(function() { if ($(this).val() == "wachtwoord") { $(this).val(""); } })
							.blur(function() { if ($(this).val() == "") { $(this).val("wachtwoord"); } });
    $("#saddr").focus(function() { if ($(this).val() == "vertrekpunt") { $(this).val(""); $(this).removeClass("helptext"); } })
							.blur(function() { if ($(this).val() == "") { $(this).addClass("helptext"); $(this).val("vertrekpunt"); } });
    $("#startDate,#question").focus(function() { if ($(this).val() == $(this).attr("title")) { $(this).val(""); $(this).removeClass("helptext"); } })
							.blur(function() { if ($(this).val() == "") { $(this).addClass("helptext"); $(this).val($(this).attr("title")); } });

    $(".more_products LI").mouseover(function() { $(this).addClass("hover"); })
							.mouseout(function() { $(this).removeClass("hover"); });

    $("#sitefooter LI").mouseover(function() { $(this).addClass("active"); })
							.mouseout(function() { if (!$(this).hasClass("current")) $(this).removeClass("active"); });

    $("#frmContact").jqTransform();
    $("#login").jqTransform();

    if ($("#salonlocator").length > 0) {
        var so = new SWFObject(CONTENT_URL + "flash/SalonLocator.swf", "salonlocator", "650", "400", "9,0,0,0", "#FFFFFF");
        so.addVariable("projectURL", CONTENT_URL);
        so.addVariable("locations", CONTENT_URL + "xml/chronique.xml");
        so.addParam("allowFullScreen", "true");
        so.write("salonlocator");
    }

    $("#frmLogin-submit").click(function() { submitLogin(); });

    var newsTitle = $("#sitecontent .newsitem .title"); var height1 = newsTitle.attr("clientHeight") + parseInt(newsTitle.css("marginTop")) + parseInt(newsTitle.css("marginBottom"));
    var newsIntro = $("#sitecontent .newsitem .intro"); var height2 = (newsIntro.length > 0 ? newsIntro.attr("clientHeight") + parseInt((newsIntro.css("marginTop") == "auto" ? 0 : newsIntro.css("marginTop"))) + parseInt((newsIntro.css("marginBottom") == "auto" ? 0 : newsIntro.css("marginBottom"))) : 0);
    var newsBody = $("#sitecontent .newsitem .body"); var height3 = (newsBody.length > 0 ? newsBody.attr("clientHeight") + parseInt((newsBody.css("marginTop") == "auto" ? 0 : newsBody.css("marginTop"))) + parseInt((newsBody.css("marginBottom") == "auto" ? 0 : newsBody.css("marginBottom"))) : 0);
    $("#sitecontent .newsitem .right").css("overflow-y", height1 + height2 + height3 > 400 ? "scroll" : "hidden");

    //RECHTER MUIS UITZETTEN
    var message = "";
    ///////////////////////////////////
    function clickIE() { if (document.all) { (message); return false; } }
    function clickNS(e) {
        if
    (document.layers || (document.getElementById && !document.all)) {
            if (e.which == 2 || e.which == 3) { (message); return false; }
        }
    }
    if (document.layers)
    { document.captureEvents(Event.MOUSEDOWN); document.onmousedown = clickNS; }
    else { document.onmouseup = clickNS; document.oncontextmenu = clickIE; }
    document.oncontextmenu = new Function("return false")

    $('.forgotpass').click(function() {
        showforgotpass();
        return false;
    })

    $('.backtologin').click(function() {
        backtologin();
        return false;
    })


});

function showforgotpass() {
    $('#forgotPassword').show();
    $('#login').hide();
}

function backtologin() {
    $('#forgotPassword').hide();
    $('#login').show();
}

function showLogin() {
	toggleLoginStatus("submit");
}

function hideLogin() {
	if ((!$.browser.msie && $("#login INPUT:focus").length == 0) || ($.browser.msie && $("#login INPUT.ieFocusHack").length == 0)) {
		toggleLoginStatus("hidden");
	}
}

function trim(str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

var tr = null;
var tr2 = null;
var openMenuId = 0;
var menu = null;
function showSub(o, id) {
    // annuleer vertraging menu sluiten
//    if (tr) clearTimeout(tr); tr = null;
//    // niet openen van een ander hoofdmenu item, wanneer het openMenuId item open staat.
//    // timeout zodat als je er op blijft staan deze alsnog geopend wordt.
//    if (id) {
//        if (openMenuId != id && openMenuId != 0) {
//            tr2 = setTimeout(function test2() {
//                closeAll(o);
//                showSub(o, id);
//            }, 600);
//            return false;
//        }
//        // register openstaand menu
//        openMenuId = id;
    //    }

    if (tr) clearTimeout(tr); tr = null;


    // niet openen van een ander hoofdmenu item, wanneer het openMenuId item open staat.
    // timeout zodat als je er op blijft staan deze alsnog geopend wordt.

    if (id) {
        if (openMenuId != id && openMenuId != 0) {
            if (menu == 1) {
                tr2 = setTimeout(function test2() {
                    closeAll(o);
                    showSub(o, id);
                }, 600);
            } else {
                closeAll(o);
                showSub(o, id);
            }
            return false;
            menureset();

        }
        // register openstaand menu
        openMenuId = id;
        menureset();
    }

	// deactivate 'current' menu, only if $(o) has a child UL
	var o_ul = $(o).find("UL");
	if (o_ul.length > 0)
	{
		$("#sitemenu UL.current").each(function() {
			if (o_ul.find("#" + $(this).attr("id")).length == 0)
			{
				$(this).css("display", "none");
			}
		});
	}

	// hide login box
	if ((!$.browser.msie && $("#login INPUT:focus").length == 0) || ($.browser.msie && $("#login INPUT.ieFocusHack").length == 0)) {
		document.getElementById("login").style.display = "none";
		document.getElementById("frmLogin-sending").style.display = "none";
		document.getElementById("frmLogin-success").style.display = "none";
		document.getElementById("frmLogin-error").style.display = "none";
	}
	
	// activate
	$(o).addClass("active");
	$(o).find("IMG").first().addClass("active");
//	var img = $(o).find("IMG").first();
//	if ($(img).length > 0) {
//		var iDot = $(img).attr("src").lastIndexOf(".");
//		if (img.attr("src").substring(iDot - 2, iDot) != "_a")
//		{
//			img.attr("src", img.attr("src").substring(0, iDot) + "_a" + img.attr("src").substring(iDot));
//		}
//	}

	// open submenu
	if (o.children && o.children.length > 1)
	{
		var ul = o.children[1];
		if (ul && ul.style) {
			ul.style.display = (ul.className.indexOf("lvl3") > -1 ? "inline" : "block");
		}
	}
}

// wanneer hoofditem, sluit alles
function closeAll(o) {
    if ($(o).hasClass('mainItem')) {
        // reset openstaand menu        
        openMenuId = 0;
        $('.mainItem').each(function() {
            if (!$(this).hasClass('current')) {
                $(this).removeClass("active").find("IMG").first().removeClass("active");
                $(this).find('ul').hide();
            }
        });
    }
}

function reopenCurrentMenu(o) {
    $("#sitemenu UL.current").each(function() {
        $(this).css("display", $(this).hasClass("lvl3") ? "inline" : "block");
    });
}

function menuset() {
    menu = 1;
}

function menureset() {
    menu = null;
}


function hideSub(o, timeout) {
    // deactivate LI

    if (timeout) {
        // annuleer openen ander hoofdmenu
        if (tr2) clearTimeout(tr2); tr2 = null;
        // menu met vertraging sluiten
        tr = setTimeout(function test() {
            hideSub(o);
            reopenCurrentMenu(0);
        }, 1000);
        return false;
    } else {
        // wanneer hoofditem, sluit alles
        closeAll(o);
    }
    
    if (!$(o).hasClass("current")) {
            $(o).removeClass("active").find("IMG").first().removeClass("active");
    }
    
    // close submenu
    if (o.children && o.children.length > 1 && o.className.indexOf("loginlink") == -1) {
        var ul = o.children[1];
        if (ul && ul.style) {
            ul.style.display = "none";
        }
    }
}

//$.fn.reverse = [].reverse;
function toggleDownload(a, topLevelUL) {
	var openUL = $(a).next();
	var nrParents = $(a).parentsUntil("UL[id=" + $(topLevelUL).attr("id") + "]").length; // nrParents 1 (LI) = category, nrParents 3 (LI UL LI) = subcategory
	var closeULs = (nrParents == 1 ? $(topLevelUL).find("UL:visible") : $(a).parent().parent().find("UL:visible"));
	
	closeULs.each(function() {
		var closeUL = $(this);
		if (openUL[0] != closeUL[0])
			$(closeUL).animate({ height: ['toggle', 'swing'] }, 150, null, function() { $(closeUL).css("display", "none"); });
	});

	$(openUL).animate({ height: ['toggle', 'swing'] }, 150, null, null);
}

var togglingSub = false;
function toggleSub(a) {
	if (!togglingSub) {
		togglingSub = true;
		$(a).next().animate({ height: 'toggle' }, 1000);
		togglingSub = false;
	}
}

function showMerkOverlay(merkId) {
	$(".merk-overlay").each(function() {
		if (this.id == "merk-overlay-" + merkId) {
			$(this).removeClass("hidden");
		} else {
			$(this).addClass("hidden");
		}
	});
}

function hideMerkOverlays() {
	$(".merk-overlay").each(function() { $(this).addClass("hidden"); });
}

function getFlashMovie(movieName) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}

function filterBrands(brand) {
	var swf = getFlashMovie('salonlocator');
	if (swf) swf.filter(brand);
}

String.prototype.convertHTMLEntity = function() {
	var myString = this;
	myString = myString.replace('&', "&amp;");
	myString = myString.replace('<', "&lt;");
	myString = myString.replace('"', "&quot;");
	myString = myString.replace('©', "&copy;");
	myString = myString.replace('®', "&reg;");
	myString = myString.replace('«', "&laquo;");
	myString = myString.replace('»', "&raqou;");
	myString = myString.replace("'", "&apos;");
	return myString;
}

function updateLocationInfo(title, address, postalcode, city, telephone, email) {
	$("#salonlocator_address").html(
		"<p class=\"addrTitle\">" + title.convertHTMLEntity() + "</p>" +
		"<p>" + address.convertHTMLEntity() + "<br />" + postalcode + " " + city.convertHTMLEntity() + "</p>" +
		"<p>Tel: " + telephone + "<br />" + email + "</p>");
	//return true;
}

function submitLogin() {
	var result;
	if (formCheck('frmLogin')) {
		toggleLoginStatus("sending");
		$.ajax({
			type: "POST",
			url: PATH_LANG + "xml/Login",
			data: $("#frmLogin").serialize(),
			dataType: "html",
			async: false,
			success: function(data, status) {
				var dataSplit = data.split(',');
				if (dataSplit[0].toUpperCase() == "TRUE") {
					result = "success";
				}
				else
					result = "error";
			},
			error: function() {
				result = "error";
			}
		});
	} else {
		return false;

	}

	toggleLoginStatus(result);
	if (result == "success")
		redirect(dataSplit[1], 3000);
}

function redirect(url, timeout) {
	setTimeout(function() {
		$(location).attr("href", url);
	}, timeout);
}

var loginErrorVisible = false;
function toggleLoginStatus(status) {
	$("#login").css("display", status != "hidden" ? "block" : "none");
	$("#frmLogin").css("display", status == "submit" ? "block" : "none");
	$("#frmLogin-submit").css("display", status == "submit" ? "block" : "none");
	$("#frmLogin-sending").css("display", status == "sending" ? "block" : "none");
	$("#frmLogin-success").css("display", status == "success" ? "block" : "none");
	$("#frmLogin-error").css("display", status == "error" ? "block" : "none");
}

function formCheck(form) {
	var result = true;
	$(form).find("INPUT, SELECT").each(function() {
		var ruleAttr = (this.type == "select-one" || this.type == "select-multiple" ? "title" : "accesskey");
		var rule = ($(this).attr(ruleAttr) != undefined ? $(this).attr(ruleAttr).substring(1, $(this).attr(ruleAttr).length - 1).split(",")[0].split(":")[1] : "");
		if (!chckField(this, null, rule))
			result = false;
	});
	return result;
}

function chkField(o, e) {
	var ruleAttr = (this.type == "select-one" || this.type == "select-multiple" ? "title" : "accesskey");
	var rule = ($(o).attr(ruleAttr) != undefined ? $(o).attr(ruleAttr).substring(1, $(o).attr(ruleAttr).length - 1).split(",")[0].split(":")[1] : "");
	return chckField(o, e, rule);
}

function chckField(o, e, rule) {
	var onkeydown = (e != null);
	var requiredAttr = (o.type == "select-one" || o.type == "select-multiple" ? $(o).attr("title") : $(o).attr("accesskey"));
	var required = requiredAttr != undefined && requiredAttr != "";
	switch (o.type) {
		case "text":
			{
				if (required && !onkeydown) {
					// Field is required, and event = onblur()
					if (rule != undefined && rule != "") {
						// Validate field
						var r = getRuleRegex(rule);
						if (!r.test(trim(o.value))) {
							errorLayout(o, false, "Ongeldige " + rule + " waarde.");
							return false;
						} else {
							errorLayout(o, true, "");
							return true;
						}
					}
					// No rule specified, check if not empty
					if (trim(o.value) == "" || trim(o.value) == $(o).attr("title")) {
						errorLayout(o, false, "Verplicht");
						return false;
					}
				} else if (onkeydown) {
					return keyAllowed(e, rule);
				}
				errorLayout(o, true, "");
				return true;
				break;
			}
		case "textarea":
			{
				if (required && o.value == "") {
					errorLayout(o, false, "Verplicht");
					return false;
				} else {
					errorLayout(o, true, "");
					return true;
				}
				break;
			}
		case "radio":
		case "select-one":
		case "select-multiple":
			{
				if (required) {
					var nrSelected = (o.type == "radio" ? $(o).parent().find(":checked").length : $(o).find(":selected").length);
					if (nrSelected == 0 || o.value == "") {
						errorLayout(o, false, "Verplicht");
						return false;
					} else {
						errorLayout(o, true, "");
						return true;
					}
				}
				break;
			}
		default:
			break;
	}
	return true;
}

function getRuleRegex(rule) {
	switch (rule) {
		case "Decimal":				return /^(\-?[0-9]+[\,\.]+[0-9]+)+$/;
		case "Money":				return /^(\-?[0-9]+[\,\.]+[0-9]+)+$/;
		case "Integer":				return /^([0-9])+$/;
		case "Email":				return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		case "Letters":				return /^(\w)+$/;
		case "LettersAndNumbers":	return /^(\w\d)+$/;
		case "Date":				return /^([0-3]?[0-9]+)[\-\/]{1}([0-1]?[0-9]+)[\-\/]{1}([0-9]{4})$/;
		case "ZipcodeNL":			return /^[1-8]{1}[0-9]{3}[A-Za-z]{2}$/;
		case "PhoneNL":				return /^(0{1}\d{9})+$/;
	}
}

function keyAllowed(e, rule) {
	var k = (document.all ? e.keyCode : e.which);
	switch (rule) {
		case "Decimal":				return isControlKey(k) || isDecimalKey(k, e);
		case "Money":				return isControlKey(k) || isDecimalKey(k, e);
		case "Integer":				return isControlKey(k) || isNumberKey(k, e);
		case "Letters":				return isControlKey(k) || isAlphaKey(k);
		case "LettersAndNumbers":	return isControlKey(k) || isAlphaKey(k) || isNumberKey(k, e);
		case "Date":				return isControlKey(k) || isDateKey(k, e);
		case "ZipcodeNL":			return isControlKey(k) || isAlphaKey(k) || isNumberKey(k, e);
		case "PhoneNL":				return isControlKey(k) || isNumberKey(k, e);
	}
}

function isControlKey(k) {
	return (
		k == 8 || 				// (backspace)
		k == 9 || 				// (tab)
		k == 35 || 				// (home)
		k == 36 || 				// (end)
		k == 37 || 				// (left)
		k == 39 ||  			// (right)
		k == 46);				// (delete)
}

function isNumberKey(k, e) {
	return (
		(k > 47 && k < 58 && e.shiftKey != 1) || 	// 0-9
		(k >= 96 && k <= 105)						// (numpad keys)
	);
}

function isDecimalKey(k, e) {
	return (isNumberKey(k, e) || k == 46);			// 0-9.
}

function isAlphaKey(k) {
	return (
		(k >= 65 && k <= 90) ||						// A-Z
		(k >= 97 && k <= 122)						// a-z
	);
}

function isDateKey(k, e) {
	return (
		isNumberKey(k, e) ||						// 0-9
		k == 109 ||									// -
		k == 191									// /
	);
}

function errorLayout(o, OK, errorMessage) {
	if (OK)
		$("#check-" + (o.type == "radio" ? o.name : o.id)).removeClass("error").addClass("green");
	else
		$("#check-" + (o.type == "radio" ? o.name : o.id)).removeClass("green").addClass("error");
}
