/*  (C) Hradecon | http://hradecon.com   */

$(document).ready(function(){		
	jQuery('#first-carousel').jcarousel({
		// itemVisibleOutCallback: {onAfterAnimation: function(carousel, item, i, state, evt) { carousel.remove(i); }},
        itemLoadCallback: carouselItemLoadCallback
    });
	
	$('#first-carousel li').each(function(i){return hookStreamItems(i, $(this));});
	
	// slider handling
	var $back = $('<li class="back"></li>').appendTo($('#first-carousel'));
	jQuery('#first-carousel li').live('mouseover mouseout', function(event){
		var caption = $('.caption', this);
		var canvas = $('.canvasHolder', this);
		
		if (event.type == 'mouseover') {
			canvas.dequeue().animate({'opacity': 0.0}, 'fast').animate({'opacity': 0.0}, 'fast');
			
			$back.dequeue()
				 .animate({
					 left: this.offsetLeft
				 }, 700, 'easeOutBack');
			
			caption.stop().animate({'opacity': 0.5, 'height': '10%'}, 'fast');
			
			if (! $(this).hasClass('selected')) {
				var selected = $('#first-carousel .selected');
				selected.removeClass('selected');
				$(this).addClass('selected');
				selected.find('.canvasHolder').dequeue().animate({'opacity': 1.0}, 'fast').animate({'opacity': 1.0}, 'fast');
				selected.find('.caption').dequeue().animate({'opacity': 0.5, 'height': 0}, 'fast').animate({'opacity': 0.0}, 'fast');
			}
		}
	});
	
	jQuery('#video-carousel').jcarousel({
		itemLoadCallback: function(carousel, state){moreCarouselLoadCallback(carousel, state, 1, $('#lmil'));},
		initCallback: function(carousel){carouselExtHook(carousel, $('#lmil'));},
		buttonNextHTML: null,
        buttonPrevHTML: null
    });
	jQuery('#foto-carousel').jcarousel({
		itemLoadCallback: function(carousel, state){moreCarouselLoadCallback(carousel, state, 2, $('#lmir'));},
		initCallback: function(carousel){carouselExtHook(carousel, $('#lmir'));},
		buttonNextHTML: null,
        buttonPrevHTML: null
    });
	
	jQuery('#second-carousel').jcarousel({
    	scroll: 1,
		auto: 0.1,
		wrap: 'circular',
		animation: 16000,
		easing: 'linear'
    });
		 
	$('.item, .video').live('click', function() {
		var $content = $(this).parent().find('.dialog').html();
		var title = $(this).attr('title');
		var dialog = $('<div></div>').dialog({
			autoOpen: false,
			modal: true,  
			resizable: false,
			title: title, 
			width: 'auto', 
			height: 'auto', 
			draggable: true, 
			position: 'center'}).html($content);
		
		var url = $(this).attr('href');
		$.ajax({
			type: 'POST',
			url: url + '?format=html',
			data: {},
			success: function(msg){
				dialog.html(msg).dialog('open');
				$('.ad-gallery').adGallery({slideshow: {
				    enable: true,
				    autostart: true,
				    speed: 4000
				  },
				  effect: 'resize'});
			},
			complete: function(){
			},
			error: function(){
				dialog.html('Loading data from server just failed :(').dialog('open');
			}
		});
		
		return false;
	});
});

function carouselItemLoadCallback(carousel, state)
{
	var cnt = carousel.last - carousel.first + 1;
	if (carousel.has(carousel.last + cnt)) {
		return;
    }
	
	if ((carousel.last % cnt) != 0) {
		return;
	}
	
	var order = carousel.last + 1;
	var page = Math.floor((carousel.last / cnt) + 1);
	$.ajax({
		type: 'POST',
		url: $('#headerLeft a').attr('href') + 'tag/list/format/html/',
		data: {ids: '1,2', cnt: cnt, page: page},
		success: function(msg){
			var items = $('li', msg);
			items.each(function(i){
				carousel.add(order + i, $(this));
				return hookStreamItems(i, $(this));
			});
			if (carousel.first > 1) {
				// Set the size of the carousel
				carousel.size(carousel.size() + items.length);
			}
		},
		complete: function(){
		},
		error: function(){
			alert('AJAX error!');
		}
	});
}

function hookStreamItems(i, li) {
	var canvas = $('canvas', li);
	var image = canvas.parent().next();
	
	//IE hack
	if ($.browser.msie) {
		canvas.replaceWith($('<div class="alterCanvas"></div>'));
	} else {
		image.one('load', function() {
			// canvas handling after image is fully loaded
			var context = canvas[0].getContext('2d');
			context.drawImage(image[0], 0, 0);
			var imgd = context.getImageData(0, 0, this.width, this.height);
			var pix = imgd.data;
			for (var i = 0, n = pix.length; i < n; i += 4) {
				var grayscale = pix[i  ] * .3 + pix[i+1] * .59 + pix[i+2] * .11;
				pix[i  ] = grayscale;   // red
				pix[i+1] = grayscale;   // green
				pix[i+2] = grayscale;   // blue
				// alpha
			}
			context.putImageData(imgd, 0, 0);
			
			canvas.removeClass('empty');
	       })
	       .each(function() {
	    	   //Cache fix for browsers that don't trigger .load()
	    	   if(this.complete) $(this).trigger('load');
	       });
	}
}

function moreCarouselLoadCallback(carousel, state, type, handler)
{
	if (carousel.last < carousel.size()) {
		return;
	}
	
	var cnt = 5;
	$.ajax({
		type: 'POST',
		url: $('#headerLeft a').attr('href') + 'tag/list/format/html/',
		data: {ids: type, cnt: cnt, page: carousel.last + 1, template: 'text-star-item'},
		success: function(msg){
			if ($(msg).find('li').length > 0) {
				$('li', msg).each(function(i) {
					carousel.add(carousel.last + i + 1, msg);
			    });
				// Set the size of the carousel
				carousel.size(carousel.size() + 1);
			} else {
				var size = carousel.size();
				jQuery('a.next', handler).fadeOut();
				if (size <= 1) {
					jQuery('a.prev', handler).fadeOut();
				}
			}
		},
		complete: function(){
		},
		error: function(){
			alert('AJAX error!');
		}
	});
}

function carouselExtHook(carousel, handler) {
    var next = $('a.next', handler);
    var prev = $('a.prev', handler);
    
    prev.hide();
	next.bind('click', function() {
		carousel.next();
        if (carousel.first > 1) {
        	prev.fadeIn();
        }
        return false;
    });

    prev.bind('click', function() {
        carousel.prev();
        next.fadeIn();
        if (carousel.first == 1) {
        	$(this).fadeOut();
        }
        return false;
    });
};

