/**
 * Javascript for the 'octv_events' extension.
 *
 * @author	Thomas Biller, Frank Kern <t.biller@online-congress.com, f.kern@online-congress.com>
 */


function timestampToDate(timestamp, format) {
	var dateFormat = format;
	var theDate = new Date(timestamp * 1000);
	
	var j = String(theDate.getDate());
	var d = j;
	if (d.charAt(1) == '') {
		d = '0' + d;
	}
	
	var n = theDate.getMonth();
	n = String(n + 1);
	m = n;
	if (m.charAt(1) == '') {
		m = '0' + m;
	}
	
	var Y = String(theDate.getFullYear());
	var y = Y.charAt(2) + Y.charAt(3);
	
	
	var G = String(theDate.getHours());
	var H = G;
	if (H.charAt(1) == '') {
		H = '0' + H;
	}
	
	var i = String(theDate.getMinutes());
	if (i.charAt(1) == '') {
		i = '0' + i;
	}
	
	
	dateFormat = dateFormat.replace(/j/g, j);
	dateFormat = dateFormat.replace(/d/g, d);
	dateFormat = dateFormat.replace(/n/g, n);
	dateFormat = dateFormat.replace(/m/g, m);
	dateFormat = dateFormat.replace(/Y/g, Y);
	dateFormat = dateFormat.replace(/y/g, y);
	dateFormat = dateFormat.replace(/G/g, G);
	dateFormat = dateFormat.replace(/H/g, H);
	dateFormat = dateFormat.replace(/i/g, i);
	
	return dateFormat;
}


/**
 * adds a click handler to all ankers with the class 
 *
 * @return	void
 */
function openLinkInNewWindow() {
	jQuery('a.octv_events-link-new-window').click(function(){
		window.open(this.href);
		return false;
	});
}


function toggleDescription(uid, openText, closeText) {
	jQuery('#description_'+uid).slideToggle("fast");
	jQuery('#togglebutton_'+uid).toggleClass("octv_events-description-close");
	
	if (jQuery('#toggledescription_'+uid).text() == openText) {
		jQuery('#toggledescription_'+uid).text(closeText);
	} else {
		jQuery('#toggledescription_'+uid).text(openText);
	}
}


function updateTeaser() {
	if (jQuery('.octv_events-teaser').size() != 1) return;
	
	var refreshId = setInterval(function() {
		var url2go2 = window.location.href;
		var anchorParts = url2go2.split("#");
		if (anchorParts.length > 0) {
			var withoutAnchor = anchorParts[0];
			if (withoutAnchor.indexOf("?") === -1) {
				withoutAnchor += "?";
			} else {
				withoutAnchor += "&";
			}
			withoutAnchor += "cachekiller="+new Date().valueOf();
			anchorParts[0] = withoutAnchor;
		}
		url2go2 = anchorParts.join("#");
		
		jQuery.ajax({
			url: url2go2,
			type: 'GET',
			dataType: 'html',
			success: function(data){
				var html2insert = jQuery('.octv_events-teaser', data);
				jQuery('.tx-octvevents-pi2').html(html2insert);
			}
		});
	}, 60000);
}


/**
 * do onLoad
 *
 * @return	void
 */
oldOnload = window.onload;
window.onload = function() {
	jQuery.noConflict();
	
	if (typeof(oldOnload) === "function") {
		oldOnload();
	}
	if (document.getElementById && document.createTextNode) {
		openLinkInNewWindow();
		
		updateTeaser();
	}
};

