// addLoadEvent function
function addLoadEvent(fn) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = fn;
    } else {
        window.onload = function() {
            oldonload();
            fn();
        }
    }
}
addLoadEvent(init);

// Init function
function init() {
    // Code to run after window.onLoad
    initMenu('mrorDateList');

    if (window.initLightbox) {
        initLightbox();
    }

    initCalendars();
    initNewsletters();
    initPhotoAlbumsArchive();
}

// pageHit function
function pageHit(){
	p = escape(document.location.href);
	rfr = escape(document.referrer);
	if (rfr == "undefined"){ rfr = "";}
	sx = screen.width;
	sy = screen.height;
	sc = (navigator.appName.indexOf("Microsoft") > -1) ? screen.colorDepth : screen.pixelDepth;
	src = 'stats.php?p=' + p + '&rfr=' + rfr + '&sx=' + sx + '&sy=' + sy + '&sc=' + sc;
	src = '<img style="position:absolute;left:-10px;top:-10px;" src="' + src + '" width="1" height="1" border="0" alt="" />';
	document.getElementById('counter').innerHTML = src;

}
addLoadEvent(pageHit);

// initMenu function
function initMenu(oMenuID) {
    var oMenu = document.getElementById(oMenuID);

    if (!oMenu) {
        var aMenus = getElementsByClassName(oMenuID);

        var i = aMenus.length;
        while (i--) {
            buildMenu(aMenus[i]);
        }
    } else {
        buildMenu(oMenu);
    }
}

// buildMenu function
function buildMenu(oMenu) {
    var aLis = oMenu.getElementsByTagName('*');

    var i = aLis.length;
    while (i--) {
        if(aLis[i + 2] != null){
            if (aLis[i + 2].className == 'submenu' && (aLis[i + 3].tagName == 'UL' || aLis[i + 3].tagName == 'OL')) {
                aLis[i + 1].oLi = aLis[i];
                aLis[i + 1].oUl = aLis[i + 3];
                aLis[i + 1].onclick = function () {
                    if (this.oLi.className == '') {
                        this.oLi.className = 'open';
                        this.oUl.style.display = 'block';
                    } else {
                        this.oLi.className = '';
                        this.oUl.style.display = 'none';
                    }

                    this.blur();

                    return false;
                }
            }
        }
    }
}

// initPhotoAlbumsArchive function
function initPhotoAlbumsArchive () {
    var aPhotoAlbumsArchive = getElementsByClassName('photoAlbumsModule-archive');

    var i = aPhotoAlbumsArchive.length;

    while (i--) {
        buildPhotoAlbumArchive(aPhotoAlbumsArchive[i]);
    }
}

// buildPhotoAlbumArchive function
function buildPhotoAlbumArchive (oArchive) {
    var oToggle = getElementsByClassName('openClose');

    if (oToggle != null) {
        var oList = oArchive.getElementsByTagName('ul');

        oToggle[0].oList = oList[0];
        oToggle[0].onclick = function () {
            if (this.oList.style.display == 'block') {
                this.oList.style.display = 'none';
            } else {
                this.oList.style.display = 'block';
            }

            this.style.display = 'none';

            return false;
        }
    }
}

// initCalendar function
function initCalendars() {
    var aCalendars = $(document).getElements('.calendarModule');

    if (aCalendars != null) {
        var i = aCalendars.length;
        while (i--) {
            var oMonthSpan = aCalendars[i].getElements('.month');

            oMonthSpan[0].onmouseover = function () {
                chooseMonthCalendar(this);
            }

            oMonthSpan[0].onmouseout = function () {
                if (window.oTimeoutCalenderChooseMonthPopup !== undefined) {
                    clearTimeout(oTimeoutCalenderChooseMonthPopup);
                }

                oTimeoutCalenderChooseMonthPopup = setTimeout (function () { closeChooseMonthPopup(); }, 500);
            }

            oMonthSpan[0].onclick = function () {
                return false;
            }

            buildCalendar(aCalendars[i]);
        }
    }
}

// buildCalendar function
function buildCalendar(oCalendar) {
    var aDls = oCalendar.getElementsByTagName('dl');

    var i = aDls.length;
    while (i--) {
        var aChildNodes = aDls[i].childNodes;

        var oDt = null;
        var oDd = null;
        for (var y = 0; y < aChildNodes.length; y++) {
            if (aChildNodes[y].tagName == 'DT') {
                oDt = aChildNodes[y];
            } else if (aChildNodes[y].className == 'calendarInfobox') {
                oDd = aChildNodes[y];
            }

            if (oDt != null && oDd != null) {
                oDt.contents = oDd.innerHTML;
                oDt.onmouseover = function () {
                    if (window.oTimeoutCalenderPopup !== undefined) {
                        clearTimeout(oTimeoutCalenderPopup);
                    }
                    closeCalendarPopup();

                    var oBody = document.getElementsByTagName("body").item(0);

                    var oCalendarInfobox = document.createElement("div");
                    oCalendarInfobox.setAttribute('id','calendarInfobox');
                    oCalendarInfobox.innerHTML = this.contents;
                    oBody.appendChild(oCalendarInfobox);

                    var oCalendarInfoboxArrow = document.createElement("div");
                    oCalendarInfoboxArrow.setAttribute('id','calendarInfoboxArrow');
                    oBody.appendChild(oCalendarInfoboxArrow);

                    var aPos = findPos(this);

                    oCalendarInfobox.style.left = aPos[0] - oCalendarInfobox.clientWidth - 18 - 5 + "px";
                    oCalendarInfobox.style.top = aPos[1] - (oCalendarInfobox.clientHeight / 2) + "px";

                    oCalendarInfoboxArrow.style.left = aPos[0] - 5 - 9 + "px";
                    oCalendarInfoboxArrow.style.top = aPos[1] + 4  + "px";

                    oCalendarInfobox.onmouseover = function () {
                        if (window.oTimeoutCalenderPopup !== undefined) {
                            clearTimeout(oTimeoutCalenderPopup);
                        }
                    }

                    oCalendarInfobox.onmouseout = function () {
                        oTimeoutCalenderPopup = setTimeout (function () { closeCalendarPopup(); }, 500);
                    }
                }

                oDt.onmouseout = function () {
                    if (window.oTimeoutCalenderPopup !== undefined) {
                        clearTimeout(oTimeoutCalenderPopup);
                    }

                    oTimeoutCalenderPopup = setTimeout (function () { closeCalendarPopup(); }, 500);
                }

                oDt.onclick = function () {
                    return false;
                }

                // Reset
                oDt = null;
                oDd = null;
            }
        }
    }
}

// closeCalendarPopup function
function closeCalendarPopup () {
    var oBody = document.getElementsByTagName("body").item(0);

    var oCalendarInfobox = document.getElementById('calendarInfobox');

    if (!oCalendarInfobox) {
        return false;
    }

    var oCalendarInfoboxArrow = document.getElementById('calendarInfoboxArrow');

    oBody.removeChild(oCalendarInfobox);
    oBody.removeChild(oCalendarInfoboxArrow);
}

// chooseMonthCalendar function
function chooseMonthCalendar (oMonthSpan) {
    if (window.oTimeoutCalenderChooseMonthPopup !== undefined) {
        clearTimeout(oTimeoutCalenderChooseMonthPopup);
    }
    closeChooseMonthPopup();

    var oBody = document.getElementsByTagName("body").item(0);

    var oCalendarMonthBox = document.createElement("div");
    oCalendarMonthBox.setAttribute('id','calendarMonthBox');
    oCalendarMonthBox.innerHTML = oMonthSpan.lastChild.innerHTML;
    oCalendarMonthBox.style.display = "block";

    oBody.appendChild(oCalendarMonthBox);

    var aPos = findPos(oMonthSpan);

    oCalendarMonthBox.style.left = aPos[0] - 22 + "px";
    oCalendarMonthBox.style.top = aPos[1] + 13 + "px";

    oCalendarMonthBox.onmouseover = function () {
        if (window.oTimeoutCalenderChooseMonthPopup !== undefined) {
            clearTimeout(oTimeoutCalenderChooseMonthPopup);
        }
    }

    oCalendarMonthBox.onmouseout = function () {
        oTimeoutCalenderChooseMonthPopup = setTimeout (function () { closeChooseMonthPopup(); }, 500);
    }

    oMonthSpan.onclick = null;
}

// closeChooseMonthPopup function
function closeChooseMonthPopup () {
    var oBody = document.getElementsByTagName("body").item(0);

    var oCalendarMonthBox = document.getElementById('calendarMonthBox');

    if (!oCalendarMonthBox) {
        return false;
    }

    oBody.removeChild(oCalendarMonthBox);
}

// findPos function
function findPos(obj) {
    var curleft = curtop = 0;

    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }

    return [curleft,curtop];
}

// Ajax request nieuwsbrief
function initNewsletters() {

    var aNewsletterModules = $$('.newsletterModule');

    var i = aNewsletterModules.length;
    while (i--) {
        if (aNewsletterModules[i].getElement('form').hasClass('subscribeForm')) {
            new Newsletter(aNewsletterModules[i].getProperty('id'));
        }
    }
}

var Newsletter = new Class({
    initialize:         function (sModuleId) {
                            this._sModuleId = sModuleId;

                            $(sModuleId).getElement('form').addEvent('submit', this.sendRequest.bind(this));
                        },

    sendRequest:        function (e) {
                            new Event(e).stop();

                            new Request.JSON({
                                url:        'nieuwsbrief/register/submit/',
                                onRequest:  this.onRequestHandler.bind(this),
                                onSuccess:  this.onSuccessHandler.bind(this),
                                onFailure:  this.onFailureHandler.bind(this)
                            }).post($(this._sModuleId).getElement('form'));
                        },

    onRequestHandler:   function () {
                            $(this._sModuleId).getElement('form').setStyle('display', 'none');
                            $(this._sModuleId).getFirst('.ajaxResponse').setStyle('display', 'none');
                            $(this._sModuleId).getFirst('.ajaxLoader').setStyle('display', 'block');
                        },

    onFailureHandler:   function () {
                            $(this._sModuleId).getElement('form').setStyle('display', 'block');
                            $(this._sModuleId).getFirst('.ajaxResponse').setStyle('display', 'block');
                            $(this._sModuleId).getFirst('.ajaxLoader').setStyle('display', 'none');

                            $(this._sModuleId).getFirst('.ajaxResponse').empty();
                            $(this._sModuleId).getFirst('.ajaxResponse').appendText('Fout bij het verzenden van het formulier.');
                        },

    onSuccessHandler:   function (oResponseText) {
                            $(this._sModuleId).getFirst('.ajaxResponse').setStyle('display', 'block');
                            $(this._sModuleId).getFirst('.ajaxLoader').setStyle('display', 'none');


                            $(this._sModuleId).getFirst('.ajaxResponse').empty();

                            if (oResponseText.success) {
                                $(this._sModuleId).getElement('form').setStyle('display', 'none');
                                $(this._sModuleId).getFirst('.ajaxResponse').appendText(oResponseText.msg);
                            } else {
                                $(this._sModuleId).getElement('form').setStyle('display', 'block');
                                $(this._sModuleId).getFirst('.ajaxResponse').innerHTML = 'Foutmelding: <br />' + oResponseText.msg;
                            }
                        }
});

/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};

function initExternalLinks() {
    if (!document.getElementsByTagName) {
        return;
    }

    var aLinks = document.getElementsByTagName("a");
    for (var i=0; i < aLinks.length; i++) {
        var anchor = aLinks[i];
        if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
            anchor.target = "_blank";
        }
    }
}
addLoadEvent(initExternalLinks);
