/*
	Handles carousel and AJAX functionality
*/
function mycarousel_itemLoadCallback(carousel, state) {
	// Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }
    jQuery.get(
        makeUrl(),
        {
            first: carousel.first,
            last: carousel.last
        },
        function(xml) {
            mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, xml);
        },
        "xml"
    );
};

function mycarousel_itemAddCallback(carousel, first, last, xml)	{
    var $columns = jQuery('column', xml);
    carousel.size(parseInt($columns.length)); 

    $columns.each(function(i) {
    	
		var $items = jQuery('newsitem', this);
		tmp = '';
			$items.each(function(i) {
			tmp += mycarousel_getItemHTML(this, i);
		});
		carousel.add(i + 1, tmp);	
	});
};

/**
 * Item html creation helper.
 */
function mycarousel_getItemHTML(item, i) {
	if(i == 0){
		return '<h3>'+$('date', item).text()+'</h3><ul><li><span class="originaltime">'+$('time', item).text()+'</span><br/><a target="_top" href="'+$('url', item).text()+'">'+$('description', item).text()+'</a></li></ul>';
	}
	return '<ul><li><span class="originaltime">'+$('time', item).text()+'</span><br/><a target="_top" href="'+$('url', item).text()+'">'+$('description', item).text()+'</a></li></ul>';	
};

/**
 * Creates url to get data from
 */
function makeUrl(){
	urlStr = '';
	// Make the url to request including some params that the server will like
	for(key in urlVars){
		urlStr = urlStr + key + "=" + urlVars[key] + "&";
	}
	// Remove trailing &
	urlStr = urlStr.substr(0,urlStr.length-1);
	urlStr = "http://" + top.location.host + top.location.pathname + "/?" + encodeURI(urlStr);
	return urlStr;
}

jQuery(document).ready(function() {
    jQuery("#mycarousel").jcarousel({
        // Uncomment the following option if you want items
        // which are outside the visible range to be removed
        // from the DOM.
        // Useful for carousels with MANY items.
        //itemVisibleOutCallback: {onAfterAnimation: function(carousel, item, i, state, evt) { carousel.remove(i); }},
        
        itemLoadCallback: mycarousel_itemLoadCallback,
        scroll: 4
    });
    
});