/**
* @fileOverview All JS-code for groenhorst.nl
* @author Wouter Bos
* @since 1.0 - 2010-8-23
* @version 1.0 - 2010-8-23
*/

if (typeof (nl) == "undefined") {
    /**
    * @namespace Top Level Domain
    */
    var nl = {}
}

/**
* @namespace Domain name and container for simple public functions
*/
nl.groenhorst = (function() {
    /* Start public */
    return {
        /**
        * Add Flash Spotlight to page
        * @param {String} swfUrl URL of SWF
        * @param {String} flashContainer ID of the DOM element where the SWF will be placed in
        * @requires swfobject
        * @requires jQuery
        * @example
        * nl.groenhorst.AddAnimationHeader("/flash/animationHeader.swf", "FlashSpotlight")
        */
        AddAnimationHeader: function(swfUrl, flashContainer) {
            var flashvars = {};
            //flashvars.xmlConfigURL = "/Estate/Flash/Spotlight/config.xml"
            var params = {};
            params.wmode = "transparent";
            var attributes = {};

            if (swfobject.getFlashPlayerVersion().major >= 9) {
                swfobject.embedSWF(swfUrl + "?random=" + Math.random(), flashContainer, "770", "160", "9.0.0", "/flash/expressInstall.swf", flashvars, params, attributes);
            }
        },

        /**
        * Adds accordion widget to a defenition list (dl)
        * @param {String} selector jQuery selector that selects the dl element
        * @requires jQuery
        * @example
        * nl.groenhorst.SetAccordion("dl.informatieaccordeon")
        */
        SetAccordion: function(selector) {
            jQuery(selector).addClass("js_accordion")
            jQuery(selector).find("dd:gt(0)").hide()
            jQuery(selector).find("dt").click(function() {
                if (jQuery(this).next("dd").is(":hidden")) {
                    jQuery(this).siblings("dd").slideUp(400);
                    jQuery(this).next("dd").slideDown(600);
                }
            })
        },

        /**
        * Avoids IE bug in menu
        * @requires jQuery
        * @example
        * nl.groenhorst.FixHeaderBugIE()
        */
        FixHeaderBugIE: function(selector) {
            if (jQuery.browser.msie == true) {
                jQuery('div.horizontaleMenubalk ul.level1 li.level1').bind('mouseenter', function() {
                    jQuery(this).find('ul.level3').hide()
                })
                jQuery('div.horizontaleMenubalk ul.level1 li.level1 li.level2').bind('mouseenter', function() {
                    jQuery(this).find('ul.level3').show()
                })
                jQuery('div.horizontaleMenubalk ul.level1 li.level1 li.level2').bind('mouseleave', function() {
                    jQuery(this).find('ul.level3').hide()
                })
            }
        },

        /**
        * Positions left menu level 3
        * @requires jQuery
        * @example
        * nl.groenhorst.FixLeftMenu()
        */
        FixLeftMenu: function(selector) {
            jQuery('div.linkerMenu li.level2').one('mouseenter', function() {
                var width = jQuery(this).innerWidth()
                jQuery(this).find('> ul').css('left', width)
            })
        }
    }
    /* End public */
})();






/**
* @namespace Adds watermark to an input box
*/
nl.groenhorst.Watermark = (function() {
    var collection
    var config = {
        watermarkText: "Zoek en vind"
    }

    function addWatermark(el) {
        jQuery(el).val(config.watermarkText)
        jQuery(el).addClass("watermark")
    }

    /* Start public */
    return {
        /**
        * Initialize watermark functionality
        * @param {String|Object} selector jQuery selector
        * @requires jQuery
        * @example
        * nl.groenhorst.Watermark.Init("input.searchBox")
        */
        Init: function(selector) {
            collection = jQuery(selector)

            addWatermark(collection)

            jQuery(collection).focus(function() {
                if (jQuery(this).val() == config.watermarkText) {
                    jQuery(collection).val("")
                    jQuery(collection).removeClass("watermark")
                }
            })

            jQuery(collection).blur(function() {
                if (jQuery(this).val() == "") {
                    addWatermark(this)
                }
            })
        }
    }
    /* End public */
})();









/**
* @namespace Adds highlighting to container
*/
nl.groenhorst.Highlighting = (function() {

	function DoHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) {

		// the highlightStartTag and highlightEndTag parameters are optional
		if ((!highlightStartTag) || (!highlightEndTag)) {
			highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
			highlightEndTag = "</font>";
		}

		// find all occurences of the search term in the given text,
		// and add some "highlight" tags to them (we're not using a
		// regular expression search, because we want to filter out
		// matches that occur within HTML tags and script blocks, so
		// we have to do a little extra validation)
		var newText = "";
		var i = -1;
		var lcSearchTerm = " " + searchTerm.toLowerCase();
		var lcBodyText = " " + bodyText.toLowerCase();

		searchTerm = " " + searchTerm;
		bodyText = " " + bodyText;

		while (bodyText.length > 0) {
			i = lcBodyText.indexOf(lcSearchTerm, i + 1);
			if (i < 0) {
				newText += bodyText;
				bodyText = "";
			} else {
				// skip anything inside an HTML tag
				if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
					// skip anything inside a <script> block
					if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
						newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
						bodyText = bodyText.substr(i + searchTerm.length);
						lcBodyText = bodyText.toLowerCase();
						i = -1;
					}
				}
			}
		}

		return newText;
	}

	/* Start public */
	return {
		/**
		* Highlight Search Terms
		* @param {String} search text
		* @param {Boolean} treat as phrase
		* @param {String} highlight start tag
		* @param {String} highlight end tag
		* @param {String} container class
		* @requires jQuery
		* @example
		* nl.groenhorst.Highlighting.HighlightSearchTerms("zoekterm", false, "<strong>", "</strong>", "zoekresultaatSummary")";
		*/
		HighlightSearchTerms: function(searchText, treatAsPhrase, highlightStartTag, highlightEndTag, containerClass) {

			// if the treatAsPhrase parameter is true, then we should search for 
			// the entire phrase that was entered; otherwise, we will split the
			// search string so that each word is searched for and highlighted
			// individually
			if (treatAsPhrase) {
				var searchArray = [searchText];
			} else {
				var searchArray = searchText.split(" ");
			}

			// loop through all the containers
			jQuery("." + containerClass).each(function() {
				var bodyText = jQuery(this).html();

				// loop through all search terms
				for (var i = 0; i < searchArray.length; i++) {
					bodyText = DoHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
				};

				jQuery(this).html(bodyText);
			});

			return true;
		}
	}
	/* End public */
})();









/**
* @namespace Mail-a-friend form management
*/
nl.groenhorst.mailAFriend = (function() {
    var popupConfig = {
        animationSpeed: 250,
        windowSelector: "#DivPopupWindowMailAFriend",
        backgroundSelector: "#DivPopupBackgroundMailAFriend"
    }

    function openPopup() {
        var popup = new Estate.Popup(popupConfig);
        popup.Open();
    }


    /* Start public */
    return {
        /**
        * Initialize Mail-a-friend
        * @param {String|Object} selector jQuery selector
        * @requires jQuery
        * @example
        * nl.groenhorst.mailAFriend.Init("input.searchBox")
        */
        Init: function(selector) {
            jQuery(document).ready(function() {
                jQuery(selector).bind('click', function(event) {
                    openPopup()
                    event.preventDefault()
                })

                if (jQuery('div.divPopupWindowMailAFriendConfirm').size() > 0) {
                    openPopup()
                }
            })
        }
    }
    /* End public */
})();






/**
* @namespace Sets class on odd menu items
*/
nl.groenhorst.EvenMenuItem = (function() {

    /**
    * Sets class on odd menu items
    * @requires jQuery
    * @example
    * nl.groenhorst.EvenMenuItem.Init()
    */
    return {
        Init: function() {
            jQuery("ul.linkermenu li.level1:even").addClass("evenLi");
            jQuery("table.contactlocatieoverzicht tr:even").addClass("evenRow");
        }
    }

})();





/**
* @namespace Pages through a list vertically
* @constructor
* @requires jQuery 
* @since 1.0 - 2010-10-04
* @version 1.0 - 2010-10-04
* @param {String} rootSelector jQuery selector. It should always the <ul>
* @param {Number} arg_animationIntervalSpeed The time between the transitions in milliseconds
* @example
* var newsTicker = new nl.groenhorst.newsTicker('ul.foo')
* newsTicker.Run()
*/
nl.groenhorst.newsTicker = function(rootSelector, arg_animationIntervalSpeed) {
    var error
    error = Estate.Check.ArgumentsCount(arguments.length, 2);
    if (error != "") throw new Error(error);

    config = {
        root: null,
        rootSelector: "",
        animationSpeed: 700,
        animationIntervalSpeed: arg_animationIntervalSpeed
    }
    var pageCount = 0
    var pageIndex = 0
    var ul
    var intervalAnimation

    config.rootSelector = rootSelector
    config.root = jQuery(config.rootSelector)

    function page() {
        var alt
        if (pageIndex < pageCount) {
            alt = parseInt(Estate.StringTools.RemoveMeasurement(jQuery(ul).find('li:eq(' + pageIndex + ')').css('padding-top')))
            jQuery(ul).animate({ scrollTop: jQuery(ul).find('li:eq(' + pageIndex + ')').position().top + alt + jQuery(ul).scrollTop() }, config.animationSpeed, "easeInOutQuint")
            pageIndex++
        } else {
            jQuery(ul).animate({ scrollTop: jQuery(ul).find('li').last().position().top = jQuery(ul).find('li').last().height() + jQuery(ul).scrollTop() }, config.animationSpeed, "easeInOutQuint")
            jQuery(ul).animate({ scrollTop: 0 }, 0, "easeInOutQuint")
            pageIndex = 0
        }
    }

    function animate() {
        intervalAnimation = setInterval(function() { page() }, config.animationIntervalSpeed)
    }

    /* Start public */
    /**
    * Initializes the pager
    * @example
    * var newsTicker = new nl.groenhorst.newsTicker('div.foo')
    * newsTicker.Run()
    */
    this.Run = function() {
        var allLiHeight = 0
        jQuery(config.root).find('li').each(function() {
            allLiHeight += jQuery(this).outerHeight()
        })
        var ulMaxHeight = Estate.StringTools.RemoveMeasurement(jQuery(config.root).find('ul').css('max-height'))
        if (allLiHeight > ulMaxHeight) {
            ul = jQuery(config.root).find('ul')
            pageCount = jQuery(ul).find('li').size()
            jQuery(ul).find('li').first().css('padding-top', ulMaxHeight + "px")
            jQuery(ul).find('li').last().css('padding-bottom', ulMaxHeight + "px")

            jQuery(ul).scrollTop(Estate.StringTools.RemoveMeasurement(jQuery(ul).find('li').first().css('padding-top')))
            animate()
        }
    }
    /* End public */
};












/**
* @namespace Extracts the value of title attributes in <dfn> tags and add
* them into the tag itself. A tooltip can be created with the new markup.
* 
* @requires jQuery 
* @since 1.0 - 2010-10-04
* @version 1.0 - 2010-10-04
* @example
* nl.groenhorst.definitionTooltip.Run()
*/
nl.groenhorst.definitionTooltip = (function() {
    var error
    error = Estate.Check.ArgumentsCount(arguments.length, 0);
    if (error != "") throw new Error(error);


    /* Start public */
    /**
    * Alters all <dfn> and its content
    * @example
    * nl.groenhorst.definitionTooltip.Run()
    */
    return {
        Run: function() {
            jQuery('dfn').each(function() {
                jQuery(this).prepend('<span class="tooltip"><span><span>' + jQuery(this).attr('title') + '</span></span></span>')
                jQuery(this).removeAttr('title')
                if (jQuery(this).find('span.tooltip').height() > 20) {
                    jQuery(this).find('span.tooltip').addClass('wide')
                }
            })
        }
    }
    /* End public */
})();




function encodeURL(url) {
    var newUrl = url
    if (newUrl.indexOf(" ") > 0) {
        newUrl = encodeURIComponent(newUrl)
    }
    newUrl = newUrl.replace(/%2f/ig, "/");
    return newUrl
}






/**
* @namespace Opens videolink in iframe popup
* 
* @requires jQuery 
* @since 1.0 - 2010-10-07
* @version 1.0 - 2010-10-07
* @example
* nl.groenhorst.videoPopup.Init('div.foo')
*/
nl.groenhorst.videoPopup = (function() {
    var error
    error = Estate.Check.ArgumentsCount(arguments.length, 0);
    if (error != "") throw new Error(error);

    var popupConfig = {
        animationSpeed: 500,
        windowSelector: '#DivPopupWindowVideo',
        backgroundSelector: '#DivPopupBackgroundVideo',
        windowPosition: 'dynamic'
    }

    function insertPopupCode() {
        if (jQuery(popupConfig.windowSelector).size() == 0) {
            var popupCode = ''
            popupCode += '<div id="' + popupConfig.windowSelector + '" class="divPopupWindow divPopupWindowVideo">'
            popupCode += '	<div class="close" title="Sluiten"></div>'
            popupCode += '	<iframe frameborder="0"></iframe>'
            popupCode += '</div>'
            popupCode += '<div id="' + popupConfig.backgroundSelector + '" class="divPopupBackground divPopupBackgroundVideo"></div>'

            jQuery('form:first').append(popupCode)
        }
    }

    /* Start public */
    /**
    * Sets events for popup
    * @param {String} rootSelector jQuery selector
    * @example
    * nl.groenhorst.videoPopup.Init('div.foo')
    */
    return {
        Init: function(selector) {
            jQuery(selector).find('a').bind('click', function(event) {
                insertPopupCode()
                jQuery(popupConfig.windowSelector).find('iframe').attr('src', jQuery(this).attr('href'))
                var popup = new Estate.Popup(popupConfig);
                popup.Open()

                event.preventDefault()
                event.stopPropagation()
            })
        }
    }
    /* End public */
})();

/**
* @namespace Opens cursuslink in iframe popup
* 
* @requires jQuery 
* @since 1.0 - 2010-10-07
* @version 1.0 - 2010-10-07
* @example
* nl.groenhorst.cursusPopup.Init('div.foo')
*/
nl.groenhorst.cursusPopup = (function() {
    var error
    error = Estate.Check.ArgumentsCount(arguments.length, 0);
    if (error != "") throw new Error(error);

    var popupConfig = {
        animationSpeed: 500,
        windowSelector: '#DivPopupWindowCursus',
        backgroundSelector: '#DivPopupBackgroundCursus',
        windowPosition: 'dynamic'
    }

    function insertPopupCode() {
        if (jQuery(popupConfig.windowSelector).size() == 0) {
            var popupCode = ''
            popupCode += '<div id="' + popupConfig.windowSelector.replace('#', '') + '" class="divPopupWindow divPopupWindowCursus">'
            popupCode += '	<div class="close" title="Sluiten"></div>'
            popupCode += '	<div class="innerDivPopupWindow popupContentCursus"></div>'
            popupCode += '</div>'
            popupCode += '<div id="' + popupConfig.backgroundSelector.replace('#', '') + '" class="divPopupBackground divPopupBackgroundCursus"></div>'

            jQuery('form:first').append(popupCode)
        }
    }

    /* Start public */
    /**
    * Sets events for popup
    * @param {String} rootSelector jQuery selector
    * @example
    * nl.groenhorst.cursusPopup.Init('div.foo')
    */
    return {
        Open: function(url) {
            insertPopupCode();
            jQuery(popupConfig.windowSelector).find('div.popupContentCursus').empty();
            var popup = new Estate.Popup(popupConfig);

            url = encodeURL(url);

            jQuery(popupConfig.windowSelector).find('div.popupContentCursus').load(url + ' #popupContent', function() {
                popup.Open();

                jQuery('.popupCursusToevoegen').each(function() {
                    var urlArray = jQuery(this).attr('href').split("?");
                    var urlTemp = '' + document.location;

                    if (urlTemp.indexOf("?")> 0) {
                        var locationArray = urlTemp.split("?");
                        urlTemp = locationArray[0];
                    }
                    
                    var urlTemp = urlTemp + "?" + urlArray[1];
                    jQuery(this).attr('href', urlTemp);
                })
            });
        }
    }
    /* End public */
})();



