/**
 * studio78.at javascript helper functions
 * @author roman.weinberger@studio78.at
 */

/** page setup **/

function s78_init() {
	// load news
	s78_add_rss('golem', 'golem_rss', 5);
	s78_add_rss('isc', 'isc_rss', 5);
	// if hash is set - load content
	s = window.location.hash.gsub('#','');
	if( s.length > 1 ) s78_load_content(s, 0);
}

/** cheap ajax functions **/

// show a loading image and load content from server
function s78_load_content(type, link) {
	new Effect.BlindUp('maincontent', {queue:'end', duration:0.6});
	new Effect.Appear('s78_loading', {duration:0.4,queue:'end', afterFinish: function() { 
			new Ajax.Updater('maincontent', type+'.html', { onComplete: s78_show_content });
		}
	});
	if( link != 0 ) link.blur();
	return false;
}

// callback for ajax request
function s78_show_content() {
	new Effect.Fade('s78_loading', {queue:'end', duration:0.4});
	new Effect.BlindDown('maincontent', {queue:'end',duration:0.6});
	initLightbox();
}


// insert an rss channel
function s78_add_rss(url, where_to_insert, element_count) {
	new Ajax.Request('getrss.php?feed='+url, 
					 { 
					 	method:'get', 
					 	onSuccess:function (t) { 
					 		showRSS(t.responseXML, where_to_insert, element_count); 
					 	}
					 });
}

/** tight javascript parser - thnx xml.com for hints **/

function RSS2Item(itemxml) {
	this.pubDate=0;
	var properties = new Array("title", "link", "description", "pubDate");
	var tmpElement = null;
	for (var i=0; i<properties.length; i++) {
		ele = itemxml.getElementsByTagName(properties[i])[0];
		if( ele != null )	
			eval("this."+properties[i]+"=ele.childNodes[0].nodeValue");
	}
}

function RSS2Channel(rssxml) {
	this.items = new Array();
	var itemElements = rssxml.getElementsByTagName("item");
	for (var i=0; i<itemElements.length; i++) {
		Item = new RSS2Item(itemElements[i]);
		this.items.push(Item);
	}
}

// render the rss channel
function showRSS(xml, element, c) {
	RSS = new RSS2Channel(xml);
	$(element).innerHTML = "";
	for (var i=0; i<c; i++) {
		html = '<li>&raquo; <a href="' + RSS.items[i].link + '">' + RSS.items[i].title.truncate(30) + '</a>';
		if( RSS.items[i].pubDate != 0 )
			html += '<br /><span>' + RSS.items[i].pubDate + '</span>';
		html += '</li>';
		$(element).innerHTML += html;
	}
	
	new Effect.BlindUp(element+'_loading', {queue:{position:'end', scope:'news'}});
	new Effect.BlindDown(element, {queue:{position:'end', scope:'news'}});
	
	return true;
}
