(function() {

	function loadScript(sScriptUrl, fCallback) {
		var oScript 	= document.createElement('script');
		oScript.src 	= sScriptUrl;
		oScript.type 	= 'text/javascript';
		oScript.onload	= fCallback; // load calendar
		// load callback for IE<=8
		oScript.onreadystatechange = function() {
			if (this.readyState == 'loaded' || this.readyState == 'complete') {
				fCallback(); // load calendar
			}
		};
		document.getElementsByTagName('head')[0].appendChild(oScript);
	}

	var browser = function() {
		var ua = navigator.userAgent;
		return {
			ie: ua.match(/MSIE\s([^;]*)/)
		};
    }();

	var URL_BASE 		= 'http://www.hklimburg.nl/',
		months 			= ['januari','februari','maart','april', 'mei','juni','juli','augustus','september','oktober','november','december'],
		isLoaded 		= false,
		bCalCodeLoaded 	= false;

	function loadCalBinds(oCalWidget) {

		var toggleCalItem = function(oItem) {

			var oContent		= oItem.find('.cal-item-content'),
				oIntro			= oContent.children('.cal-item-text'),
				oExpand			= oContent.children('.cal-item-text-full'),
				oArrow			= oItem.find('.cal-item-arrow');


			if (oIntro.is('div:visible')) {
				oExpand.show();
				oIntro.hide();
				oItem.addClass('cal-item-active');
				oArrow.arrow({ width: 15, height: 8, direction: 'up'});
			} else {
				oContent.height('auto');
				oItem.removeClass('cal-item-active');
				oExpand.hide();
				oIntro.show();
				oArrow.arrow({ width: 15, height: 8, direction: 'down'});
			}

		};

		oCalWidget
			.delegate('.cal-item', 'click', function(e) {

				var oCurrObj 		= $(this),
					oHasTextFull 	= oCurrObj.find('.cal-item-text-full'),
					oCurrOpen 		= oCalWidget.find('.cal-item-text-full:visible').closest('.cal-item');

				if (oHasTextFull.length > 0) {
					if (oCurrOpen.length > 0 && oCurrOpen[0] != oCurrObj[0]) {
						toggleCalItem(oCurrOpen);
					}
					toggleCalItem(oCurrObj);
				}

			})
			.delegate('.cal-item-expandable', 'hover', function(e) {

				$(this).toggleClass('cal-item-expandable-hover');

			});
	}

	// CALENDAR WIDGET LOADER FUNCTIONS

	function loadCalStyle() {

		// load external stylesheet
		var linkElement 	= document.createElement('link');
		linkElement.href 	= URL_BASE+'modules/agenda/agenda.widget.css';
		linkElement.rel 	= 'stylesheet';
		linkElement.type 	= 'text/css';
        document.getElementsByTagName('head')[0].appendChild(linkElement);

		var rules = '',
			theme = oCalWidget.config.theme,
			newHeight = (oCalWidget.config.height == 'auto') ? oCalWidget.config.height : (parseInt(oCalWidget.config.height)-90)+'px';

		if (oCalWidget.config.showLine == 1) {
			rules += '#hvdk-agendaWidget-container div.cal-item { border-bottom: 1px dotted '+theme.main.lineColor+'; }';
		}

		rules += '\
			#hvdk-agendaWidget-container { \
				background-color: '+theme.container.background+'; \
				color: '+theme.container.color+'; \
			} \
			#hvdk-agendaWidget-container .hvdk-agendaWidget-footer a, #hvdk-agendaWidget-container .hvdk-agendaWidget-header a { color: '+theme.container.color+'; } \
			#hvdk-agendaWidget-container a { color: '+theme.link.color+'; } \
			#hvdk-agendaWidget-container a:hover { color: '+theme.link.hoverColor+'; } \
			#hvdk-agendaWidget-container div.hvdk-agendaWidget-content { \
				background-color: '+theme.main.background+'; \
				color: '+theme.main.color+'; \
				height: '+newHeight+'; \
			} \
			#hvdk-agendaWidget-container #cal-item-more { \
				background-color: '+theme.container.background+'; \
				border-bottom: 1px dotted '+theme.container.color+'; \
			} \
			#hvdk-agendaWidget-container div.cal-item-date { color: '+theme.main.dateColor+'; } \
			#hvdk-agendaWidget-container div.cal-item-expandable-hover { background-color: '+theme.main.hoverBackgroundcolor+';  } \
		';

		var styleElement 	= document.createElement('style');
        styleElement.type 	= 'text/css';
		styleElement.id 	= 'calWidgetStyle';
        if (browser.ie) {
			styleElement.styleSheet.cssText = rules;
        } else {
			var frag = document.createDocumentFragment();
			frag.appendChild(document.createTextNode(rules));
			styleElement.appendChild(frag);
        }

        document.getElementsByTagName('head')[0].appendChild(styleElement);

    };

	function makeDate(startDate, stopDate) {

		var startTimeStamp 	= new Date(startDate*1000),
			stopTimeStamp 	= new Date(stopDate*1000),
			showDate 		= '';
			
		startDate 		= startTimeStamp.getDate()+' '+months[startTimeStamp.getMonth()]+' '+startTimeStamp.getFullYear();
		stopDate 		= stopTimeStamp.getDate()+' '+months[stopTimeStamp.getMonth()]+' '+stopTimeStamp.getFullYear();

		if (startDate == stopDate) {
			var startTime	= startTimeStamp.getHours()+':'+((startTimeStamp.getMinutes() < 10) ? '0'+startTimeStamp.getMinutes() : startTimeStamp.getMinutes()),
				stopTime	= stopTimeStamp.getHours()+':'+((stopTimeStamp.getMinutes() < 10) ? '0'+stopTimeStamp.getMinutes() : stopTimeStamp.getMinutes());

			showDate = startDate+' '+startTime+' - '+stopTime;
		} else {
			showDate = startDate+' - '+stopDate;
		}

		return showDate;
	}

	function loadCalDate(calItem) {

		var htmlDate = '';

		if (oCalWidget.config.showDate == 1 && calItem.date != '') {

			var calDate = makeDate(calItem.startDate, calItem.stopDate);

			htmlDate = '<div class="cal-item-date">'+calDate+'</div>';
		}

		return htmlDate;
	}

	function svg(tag, attr) {
		var el = document.createElementNS("http://www.w3.org/2000/svg", tag || 'svg');
		if (attr) {
			$.each(attr, function(k, v) {
				el.setAttributeNS(null, k, v);
			});
		}
		return $(el);
	}

	function loadCalText(oConfig, calItem) {

		var htmlText = '';

		if (calItem.extendedText != '') {

			htmlText = '<div class="cal-item-text"> \
				'+calItem.text+' \
			</div> \
			<div class="cal-item-text-full"> \
				'+calItem.extendedText+' \
			</div> \
			<div class="cal-item-arrow" style="width:'+(oConfig.config.width - 85)+'px;"></div> \
			';
		} else {
			htmlText = '<div class="cal-item-text"> \
			  '+calItem.text+' \
			</div>';
		}

		return htmlText;
	}


	function loadCalItem(oConfig, calItem, sClass) {

		var html 	= '',
			div 	= document.createElement('div');

		html = ' \
			<div class="cal-item-image"> \
				<img src="'+calItem.image+'" /> \
			</div> \
			<div class="cal-item-content"> \
				'+loadCalDate(calItem)+' \
				<div class="cal-item-title">'+calItem.title+'</div> \
				'+loadCalText(oConfig, calItem)+' \
			</div> \
			<div class="clear"></div>';

		expandable 		= (calItem.extendedText != '') ? ' cal-item-expandable': '';

		div.id 			= 'cal-item-id-'+calItem.id;
		div.className 	= 'cal-item'+sClass+expandable;
		div.innerHTML 	= html;

		return div;
    }

	function loadCalEmpty() {

		var html 	= '',
			div 	= document.createElement('div');

		html = 'Geen agendaitems';

		div.id 			= 'cal-item-empty';
		div.innerHTML 	= html;

		return div;
    }

	function loadCalMoreDiscipline(footerData) {

		var html 	= '',
			div 	= document.createElement('div');

		html = footerData.discipline;

		div.id 			= 'cal-item-more';
		div.innerHTML 	= html;

		return div;
    }


	function loadCalHeader(headerData) {

		oCalWidget.widgetHeader.html(' \
			<div class="cal-header-image"><img src="'+headerData.image+'" title="'+headerData.cleanTitle+'"></div> \
			<div class="cal-header-title">Agenda <span class="cal-header-organisation">'+headerData.title+'</span></div> \
		');
	}

	function loadCalFooter(footerData) {

		oCalWidget.widgetFooter.html(' \
			<div class="cal-footer-image"><a href="'+URL_BASE+'" target="_blank"><img src="'+footerData.image+'" title="Huis voor de Kunsten" alt="HvdK Logo"/></a></div> \
			<div class="cal-footer-title">'+footerData.title+'</div> \
		');
		/*
		oCalWidget.widgetFooter.html(' \
			<div class="cal-footer-image"><img src="'+footerData.image+'" title="Huis voor de Kunsten" alt="HvdK Logo"/></div> \
			<div class="cal-footer-title">'+footerData.title+'</div> \
		');*/
	}

	function loadCalContent(callback) {

		var oConfig = { 'config' : oCalWidget.config };

		$.getJSON(URL_BASE+'modules/agenda/agenda.widget.php?&callback=?', oConfig, function(oCalData) {

			var numItems = oCalData.items.length;
			if (numItems > 0) {
				for(var i=0;i<numItems;i++) {
					var sClass = (i==(numItems-1)) ? ' cal-item-last' : '';
					oCalWidget.widgetContent.append(loadCalItem(oConfig, oCalData.items[i], sClass));
				}
			} else {
				oCalWidget.widgetContent.append(loadCalEmpty());
			}
			oCalWidget.widgetContent.append(loadCalMoreDiscipline(oCalData.footer));

			loadCalFooter(oCalData.footer);
			loadCalHeader(oCalData.header);
			callback();

		});

	}

	function loadCalCode() {
		if (bCalCodeLoaded === false) { // IE FIX multipleload
			var sCalCode = ' \
				<div id="hvdk-agendaWidget-container"> \
					<div class="hvdk-agendaWidget-header"></div> \
					<div class="hvdk-agendaWidget-content"></div> \
					<div class="hvdk-agendaWidget-footer"></div> \
				</div> \
			';

			$('#hvdk-agendaWidget').before(sCalCode);

			loadCalStyle();

			oCalWidget.widget 			= $('#hvdk-agendaWidget-container');
			oCalWidget.widgetHeader 	= oCalWidget.widget.find('.hvdk-agendaWidget-header');
			oCalWidget.widgetContent 	= oCalWidget.widget.find('.hvdk-agendaWidget-content');
			oCalWidget.widgetFooter		= oCalWidget.widget.find('.hvdk-agendaWidget-footer');

			oCalWidget.widget
				.height(oCalWidget.config.height)
				.width(oCalWidget.config.width);

			loadCalContent(function() {
				$('.cal-item-arrow').arrow({
					width: 15,
					height: 8,
					padding: 2
				});
			});

			bCalCodeLoaded = true;

			loadCalBinds(oCalWidget.widget);

		}

	}

	function jqueryLoadedInit() {
		loadScript(URL_BASE+'lib/common/js/jquery.arrow.js', loadCalCode);
	}

	/**
	 *	check if document is loaded
	 */

			// Dean Edwards/Matthias Miller/John Resig

			function init() {
			  // quit if this function has already been called
			  if (arguments.callee.done) return;

			  // flag this function so we don't do the same thing twice
			  arguments.callee.done = true;

			  // kill the timer
			  if (_timer) clearInterval(_timer);

			  // do stuff
			  if (typeof(jQuery) != 'undefined') {
					jqueryLoadedInit(); // load calendar widget if jquery is already loaded
				} else {
					loadScript(URL_BASE+'lib/common/js/jquery-1.4.2.min.js', jqueryLoadedInit);
				}
			};

			/* for Mozilla/Opera9 */
			if (document.addEventListener) {
			  document.addEventListener("DOMContentLoaded", init, false);
			}

			/* for Internet Explorer */
			/*@cc_on @*/
			/*@if (@_win32)
			  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
			  var script = document.getElementById("__ie_onload");
			  script.onreadystatechange = function() {
				if (this.readyState == "complete") {
				  init(); // call the onload handler
				}
			  };
			/*@end @*/

			/* for Safari */
			if (/WebKit/i.test(navigator.userAgent)) { // sniff
			  var _timer = setInterval(function() {
				if (/loaded|complete/.test(document.readyState)) {
				  init(); // call the onload handler
				}
			  }, 10);
			}

			/* for other browsers */
			window.onload = init;
	/**
	 *	check if document is loaded
	 */

})();

