/**
 * @author Bramus! <bramus@netlash.com>
 */
jQuery(function(){

	// build mycarousel_itemList
	mycarousel_itemList = [];

	jQuery('#angels-jcarousel li').each(function(i) {

		var carouselObject = new Object();

		carouselObject.url = $(this).find('a').attr('href');
		carouselObject.title = $(this).find('a').attr('title');
		carouselObject.id = carouselObject.url.substring(carouselObject.url.lastIndexOf('/')+1, carouselObject.url.length);

		// hash hash!
		if (window.location.hash && (window.location.hash != '') && (window.location.hash + '.jpg' == '#' + carouselObject.id)) {
			$('#large').attr('src', carouselObject.url);
		}

		mycarousel_itemList.push(carouselObject);

	});

	// init Carousel
	jQuery('#angels-jcarousel').jcarousel({
		wrap: 'circular',
		itemVisibleInCallback: {onBeforeAnimation: mycarousel_itemVisibleInCallback},
		itemVisibleOutCallback: {onAfterAnimation: mycarousel_itemVisibleOutCallback}
	});

	// Rating
	jQuery('a.rater').click(function(){
		var name = $(this).attr('name');
		var parameterTokens = name.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5');
		var parameters = new Array();

		$(parameterTokens).each(function(i){
			var splitted = this.split("=");
			parameters[i] = splitted[1];
		});


	//function sndReq(vote,id_num,ip_num,units) {

		$('#unit_ul'+parameters[1]).html('<div class="loading"></div>');

		$.ajax({
			// URL to post to
			url:		'/ajax.php?module=angels&action=rating&language_id=1',

			// Method: get/post
			type:		'post',

			// What data do we expect to be returned?
			dataType:	'json',

			// Cache the url (best set to false!)
			cache:		false,

			// the data to post
			data:		$(this).attr('name'),

			// Success : call has been made and we have some data back!
			success:	function(json) {
				if (json.status.code == "error") {
					alert("There was an error! : " + json.status.text);
				} else {
					$('#unit_ul'+parameters[1]).html(json.content[1]);
					$('#rating-updater-ajax').html(''+json.content[2]+' votes');
				}
			},

			// Error : could not make the call
			error:		function(xhr,err,e) {
				alert( "XHR Error: " + err );
			}
		});

		return false;
	});
});

function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt)
{
	var idx = carousel.index(i, mycarousel_itemList.length);
	carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));

	// bind onclick
	jQuery('#angels-jcarousel > li > a').click(function(){
		jQuery('#large').attr('src', $(this).attr('href'));
		window.location.hash = $(this).attr('id').substr(0, $(this).attr('id').length-4);
		return false;
	});
};

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt)
{
	carousel.remove(i);
};

function mycarousel_getItemHTML(item)
{
	return '<a href="' + item.url + '" title="' + item.title + '" id="' + item.id +'"><img src="' + item.url.replace('large','square80') + '" width="80" height="80" alt="' + item.title + '" /></a>';
};
