/**
 * frontend javascript for calendar module, using ajax to load Event-Tooltips.
 * 
 * 2009-07-20 tomo: lazy loading details,
 * verbesserte ladefunktion, aktualisiert jetzt ggf offenes popup
 */
var cal_ajaxloaded = false;
var cal_lasttipuid = null;
var cal_ajaxpar = null;
var cal_tips = null;
var CAL_AJAXLOADING = '<div class="ajaxloading">&nbsp;</div>';
var cal_ajaxlinks = Array();
function cal_extractquery(urlstring, param) {
	var _pos1, _pos2, param_len, res_val;
	param = String(param);
	param_len = param.length;
	_pos1 = urlstring.indexOf(param + '=');
	if (_pos1 != -1) {
		_pos1 = _pos1 + param_len + 1;
		_pos2 = urlstring.indexOf('&', _pos1);
		// alternatively look for termination rewrite extension
		if (_pos2 == -1) {
			_pos2 = urlstring.indexOf('.phtml', _pos1);
		}
		// extract value on found positions.
		if (_pos2 == -1) {
			res_val = urlstring.slice(_pos1);
		} else {
			res_val = urlstring.slice(_pos1, _pos2);
		}
		return res_val;
	} else {
		// param not found!
		return false;
	}
	return false;
}
function cal_ajaxinit() {
	// console.log('initializing tooltips');
	cal_ajaxpar = Array();
	$$('a.calendarlink').each(function(element, index) {
		if (element.href) {
			var href = element.href;
			var caldate = cal_extractquery(href, 'calendardate');
			var eventids = cal_extractquery(href, 'eventids');
			var edata = {
			    eid : element.uid,
			    cal_ids : eventids,
			    cal_date : caldate
			};
			cal_ajaxpar.push(edata);
			var eventfunc = function() {
				cal_onTipHover(this);
			};
			element.addEvent('mouseover', eventfunc);
			element.store('hoverevent', eventfunc);
			element.store('tip:text', CAL_AJAXLOADING);
		}
	});
	// now create the tooltips
	cal_tips = new Tips('.calendarlink', {
	    className : 'calendartipz',
	    fixed : true,
	    hideDelay : 500,
	    showDelay : 50
	});
}
function cal_onTipHover(element) {
	// console.log('hover', element);
	// initialize loading if not allready done
	cal_lasttipuid = element.uid;
	if (!cal_ajaxloaded) {
		// console.log('ajax lazy loading event details......start.');
		var ajaxURL = '/include/inc_module/tmod_calendar/inc_act/cal_ajax.php';
		ajaxOPT = {
		    url : ajaxURL,
		    // link : 'ignore',
		    noCache : true,
		    method : 'post',
		    // secure: false,
		    // async : true,
		    onFailure : function() {
			    console.error('CAL AJAX Loading: failure');
		    },
		    onException : function() {
			    console.error('CAL AJAX Loading: exception occured');
		    },
		    onCancel : function() {
			    console.warn('CAL AJAX Loading: canceled');
		    },
		    onSuccess : function(responseJSON, responseText) {
			    // console.log('json on success');
			// console.log('responseText:' + responseText);
			cal_onAjaxResult(responseJSON);
			cal_ajaxloaded = true;
		}
		};
		// only one Request for all Tooltip Details
		var cAJAX = new Request.JSON(ajaxOPT);
		// and post the collected data
		var ajaxPAR = {
			caldata : cal_ajaxpar
		};
		cAJAX.post(ajaxPAR);
	} else {
		// tooltips allready loaded, do nothing...
		// console.log('CAL AJAX Details allready loaded.');
	}
}
function cal_onAjaxResult(responseJSON) {
	// console.info('CAL AJAX Loading: SUCCESS!!');
	/*
	 * IE7 & mootools somehow doe not properly decode nested associative arrays? workaround: return an array with std
	 * numeric keys and prepare associative array on the fly.
	 */
	var json_array = Array();
	responseJSON.each(function(element, index) {
		json_array[element.eid] = element;
	});
	$$('a.calendarlink').each(function(element, index) {
		if (json_array[element.uid]) {
			element.store('tip:title', json_array[element.uid].title);
			element.store('tip:text', json_array[element.uid].text);
		}
		// unregister hoverevent from element!
		    var hoverevent = element.retrieve('hoverevent');
		    element.removeEvent('mouseover', hoverevent);
		    // and remove the now unnecessary storage!
		    element.eliminate('hoverevent');
	    });
	// if a ' still loading ' tip is visible reinitialize it!
	// console.log(cal_tips.tip.getStyle('display'));
	if ('block' == cal_tips.tip.getStyle('display')) {
		$A(cal_tips.container.childNodes).each(Element.dispose);
		[ 'title', 'text' ].each(function(value) {
			// var content = element.retrieve('tip:' + value);
			    var lastElementUID = cal_lasttipuid;
			    var content = 'testext';
			    if (json_array[lastElementUID]) {
				    var content = json_array[lastElementUID][value];
			    }
			    if (!content)
				    return;
			    this[value + 'Element'] = new Element('div', {
				    'class' : 'tip-' + value
			    }).inject(this.container);
			    this.fill(this[value + 'Element'], content);
		    }, cal_tips);
	}
}
// finally start it... when the dom is ready
// we need to proof somehow if mootools is loaded, otherwise this causes an error in ie!
// alert (typeof (MooTools));
if (typeof MooTools != 'undefined') {
	window.addEvent('domready', function() {
		cal_ajaxinit();
	});
}