/* EVENTS FUNCTIONS
-----------------------------------------------------*/
var cheatingTop = 0;

function getCleanUrl(u) {
	var parts = u.split("/");
	var h = parts.length;
	return parts[h-1];
}

function resort(el) {
	var h = 20;
	var list = $$('.article');
	list.each(function(e) {
		if(e.getStyle('z-index') >= h) h = parseInt(e.getStyle('z-index'))+1;
	});
	el.setStyle('z-index', h);
}

function addPopUp(req) {
	var data = eval('(' + req + ')');
	if (!$(data.story.id)) {
		var d = new Element('div').injectInside(document.body);
		d.className = 'vevent article section';
		d.setStyle('top',cheatingTop+20);
		d.id = data.story.id;
		var b = new Element('div').injectInside(d);
		b.className = 'body';
		var content = '<img src="/images/close-window.gif" style="position:absolute; cursor:pointer; top:4px; left:320px;" onclick="Close(\''+data.story.id+'\');" />';
		content += '<h2><span class="summary">'+data.story.headline+'</span></h2><p>';
		content += data.story.date+'<br />';
		if(data.story.fstart) content += '<abbr title="'+data.story.fstart+'" class="dtstart">'+data.story.start+'</abbr> - ';
		if(data.story.fend) content += '<abbr title="'+data.story.fend+'" class="dtend">'+data.story.end+'</abbr><br />';
		if(data.story.location) content += 'Location: <abbr title="'+data.story.location+'" class="location">'+data.story.location+'</abbr></p>';
		if(data.story.body) content += '<span class="description">'+data.story.body+'</span></p>';
		var f = 0;
		if (data.story.files[f]) {
			content	+= '<h3>Related File';
			if (data.story.files[1]) content += 's';
			content += '</h3><ul>';
			while (data.story.files[f]) {
				content += 	'<li><a href="/files/calendar/'+data.story.files[f]+'" onclick="window.open(this.href); return false;">'+data.story.files[f]+'</a></li>';
				f++;
			}
			content += '</ul>';
		}
		b.innerHTML = content;
		var f = new Element('div').injectInside(d);
		f.className = 'foot';
					
		var h2 = $E('#'+d.id+' h2');			
		new Drag.Move(d, {handle:h2, onStart:resort });
		var h = 20;
		var list = $$('.article');
		list.each(function(e) {
			if(e.getStyle('z-index') >= h) h = parseInt(e.getStyle('z-index'))+1;
		});
		d.setStyle('z-index', h);
	}
	return false;
}

function Close(id) {
	var c = $(id);
	document.body.removeChild(c);	
}

function runInit() {
	var list = $$('#list a');
	list.each(function(el) {
		el.onclick = function(e) {
			cheatingTop = el.getTop();
			var u = getCleanUrl(el.href);
			pageTracker._trackPageview('/calendar/'+u);
			var myAjax = new Ajax( '/ajax-get-data.php', { postBody:'action=calendar&cID='+u, onComplete:addPopUp }).request();
			return false;	
		}
	});
}

window.addEvent('domready', function() {
	var g = $E('form input[type=submit]');	
	if (g) g.style.display = 'none';
	
	runInit();
});
