$(document).ready(function() {
	$('.mycarousel').each(function(idx, element){
		var e = $(element);
		e.data('firstElement', 0);
		var images = e.find('img');
		if(images.length > 3){
			e.jcarousel({
		        vertical: true,
				itemFirstInCallback:  mycarousel_itemFirstInCallback,
				initCallback:mycarousel_initCallback,
		        scroll: 3
			});
		}
		else{
			e.jcarousel({
				vertical: true,
		        scroll: 3,
				itemFirstInCallback:  mycarousel_itemFirstInCallback,
				initCallback:mycarousel_initCallback,
				buttonNextHTML: '',
		        buttonPrevHTML: ''
			});
		}
	});
	
	$('.small_images').click(function(){
		var cur_img = $(this).attr('src');
		var big_img = cur_img.replace(/Small/,"Big");
		$('.big_image').attr('src', big_img);
	});
	$('.categories-links').click(function(){
		var link = $(this);
		var href = link.attr('href').split("#");
		$.cookie('srb-link', href[1]);
		if(href[0] != ""){
			link.attr('href', href[0]);
			return true;
		}
		
		$('.gallery').addClass('hidden').each(function(idx, element){
			var e = $(element);
			var cur_id = link.attr('href').split("#")[1];
			if(e.hasClass(cur_id)){
				var ul = e.find('ul');
				var uh = ul.data('height');
				ul.height(ul.data('height'));
				e.removeClass('hidden');
				var i = e.find('img:eq(' + ul.data('firstElement') + ')');
				var img_name = i.attr('src');
				var big_img = img_name.replace(/Small/,"Big");
				$('.big_image').attr('src', big_img);
			}
		});
		return false;
	});
	
	function mycarousel_initCallback(carousel, b){
		var list = $(carousel.list).find('li');
		var carousel_container = $(carousel.list).closest('div.jcarousel-container-vertical');
		carousel.num = list.length;
		var gallery = carousel_container.closest('div.gallery');
		var hidden = false;
		if(gallery.hasClass('hidden')){
			hidden = true;
			gallery.removeClass('hidden');
		}
		var prev = carousel_container.find('.jcarousel-prev-vertical');
		var next = carousel_container.find('.jcarousel-next-vertical');
	
		var ul = carousel.list[0];
		var item = carousel_container.find('.jcarousel-item');
		var clip = carousel_container.find('.jcarousel-clip-vertical');
		var item_height = $(item).height();
		$(ul).data('height', (item_height + 20) * carousel.num);
		if(next.length){
			carousel_container.append("<div class = 'vertical-cursor'></div>");
			var cursor = carousel_container.find('div.vertical-cursor');
			carousel.clip_height = $(clip).height();
			carousel.height = carousel.clip_height - cursor.height();
			carousel.step = Math.floor(carousel.height/carousel.num * carousel.options['scroll']);
	
			if(carousel.step * 2 >= carousel.height) carousel.step = carousel.height;
			
			var next_btn_pos = parseInt(next.css('bottom').split('px')[0]);
			var prev_btn_pos = parseInt(prev.css('top').split('px')[0]);
			next.data('bottom_pos', next_btn_pos);
			prev.data('top_pos', prev_btn_pos);
			cursor.data('start_position', prev_btn_pos);
			cursor.data('stop_position', prev_btn_pos + carousel.height);
			cursor.css('top', prev_btn_pos + 'px');
			cursor.draggable({ axis: "y", containment:'parent', drag:function(evt, elem) {
				dragCallback(evt, elem, carousel, next, prev);
				}, start: function(evt, elem){
				startCallback(evt, elem, carousel, next, prev);
				}, stop: function(evt, elem){
				stopCallback(evt, elem, carousel, next, prev);
				}
			});
		}

		if(prev.length){
			prev.bind('click', function(){
				var h1 = Math.max(0, prev.height() - carousel.step) + 'px';
				var h2 = Math.min(next.height() + carousel.step, carousel.height) + 'px';
				var cur_pos = Math.max(parseInt(prev.data('top_pos')), parseInt(cursor.css('top').split('px')[0]) - carousel.step) + 'px';
				
				var idx = carousel.idx;
				
				carousel.idx = Math.max(0,  idx - carousel.options['scroll']);
				if(carousel.idx == 0){
					h1 = 0;
					h2 = carousel.height;
					cur_pos = cursor.data('start_position') + 'px';
				}
				cursor.css('top', cur_pos);
				prev.css('height', h1);
				next.css('height', h2);
			});
		prev.css('height', 0);
		carousel.idx = 0;
		}
		
		if(next.length){
			next.bind('click', function(){
				var h1 = Math.max(0, next.height() - carousel.step) + 'px';
				var h2 = Math.min(prev.height() + carousel.step, carousel.height) + 'px';
				var cur_pos = Math.min(carousel.height + parseInt(next.data('bottom_pos')), parseInt(cursor.css('top').split('px')[0]) + carousel.step) + 'px';

				var idx = carousel.idx;
				
				carousel.idx = Math.min(carousel.num - 1,  idx + carousel.options['scroll']);
				if(carousel.idx == (carousel.num - 1)){
					h2 = carousel.height;
					h1 = 0;
					cur_pos = cursor.data('stop_position') + 'px';
				}
				$('div#test').html("<p>cur_pos = " + cur_pos + "</p><p>idx_dopo = " + carousel.idx + "</p>");
				next.css('height', h1);
				prev.css('height', h2);
				cursor.css('top', cur_pos);
			});
		next.css('height', carousel.height + 'px');
		}
		
		if(hidden) gallery.addClass('hidden');
	}
	
	function dragCallback(evt, elem, carousel){
		var cursor = $(elem.helper.context);
		var start_position = cursor.data('start_position');
		var current_position = elem.position.top;
		var step = current_position - start_position;
		
		var idx = Math.floor(step/carousel.step) * carousel.options['scroll'];
		carousel.scroll(idx, false);
		carousel.idx = idx;
	};
	function startCallback(evt, elem, carousel){
		var next = carousel.buttonNext;
		var prev = carousel.buttonPrev;
		var cursor = $(elem.helper.context);
		cursor.data('previous_position', elem.originalPosition.top);
		cursor.data('next_h', next.height());
		cursor.data('prev_h', prev.height());
		next.css('background-image', 'url(images/slide_cursor.jpg)');
		next.height('300px');
		prev.height(0);
	};
	
	function stopCallback(evt, elem, carousel){
		var next = carousel.buttonNext;
		var prev = carousel.buttonPrev;
		var cursor = $(elem.helper.context);
		var h1 = cursor.css('top').split('px')[0] - prev.data('top_pos');
		var h2 = carousel.clip_height - cursor.height() - h1;
		var start_position = cursor.data('start_position');
		var current_position = elem.position.top;
		var step = current_position - start_position;
		if(carousel.idx == 0){
			h1 = 0;
			h2 = carousel.height;
			cursor.css('top', start_position + 'px');
		}
		if(carousel.idx == (carousel.num - 1)){
			h1 = carousel.height;
			h2 = 0;
			cursor.css('top', cursor.data('stop_position') + 'px');
		}
		next.css('background-image', 'url(images/next.jpg)');
		prev.css('height', h1 + 'px');
		next.css('height', h2 + 'px');
		
		var idx = Math.floor(step/carousel.step) * carousel.options['scroll'];
		carousel.scroll(idx, false);
	};
	
	function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
		$(carousel.list[0]).data('firstElement', idx - 1);
	};
	
	var link = $.cookie('srb-link');
	$('.categories-links').each(function(idx, element){
		var e = $(element);
		var href = e.attr('href').split("#")[1];
		if(href == link) $(this).trigger('click');
	});
	
	var cache = [];
	$('img').each(function(idx, element){
		var e = $(element);
		var src = e.attr('src');
		if(src.match(/Small/)){
			var cacheImage = document.createElement('img');
			cacheImage.src = src;
			cache.push(cacheImage);
			var big_img = src.replace(/Small/,"Big");
			cacheImage = document.createElement('img');
			cacheImage.src = big_img;
			cache.push(cacheImage);
		}
	});
});

jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
