(function() {
$(document).ready(function() {
	$('.gallery').carousel( {
		pagination: true, 
		effect: 'no',
		autoSlide: true,
		autoSlideInterval: 5000,
		animSpeed: 50,
		nextBtn: '<a></a>',
		prevBtn: '<a></a>',
		nextBtnInsert: 'insertAfter',
		prevBtnInsert: 'insertAfter',
		btnsPosition: 'inside',
		paginationPosition: 'inside',
		loop: true
	} );

  var get_objects = function() {
    var cookie = $.cookie("saved-objects");
    var objs = [];
    
    //if(!$.isEmptyObject(cookie))
    if(cookie != null && cookie != 'undefined')
      objs = cookie.split('|');

  	return objs;
  }
  
  var save_objects = function(objs) {
  	var ser = null;
  	if(objs)
    	ser = objs.join('|');
    $.cookie("saved-objects", ser, { expires: 7, path: '/', domain: 'www.skordefest.ax' })
  }
  
  $("a.save-object").click(function() {
	var objs = get_objects();
    var obj = $(".entry-title a", $(this).parent().parent());
	var href = obj.attr("href");

	if(objs.join('|').match(href))
		return false;
	
    objs[objs.length] = href+"="+obj.text();

	save_objects(objs);
    render();

    //return false;
  });

  $("a.remove-object").click(function() {
	var objs = get_objects();
    var obj = $(".entry-title a", $(this).parent().parent());
	var href = obj.attr("href");

    objs = $.grep(objs, function(val){
    	return !val.match('^'+href+'=.*');
    });

	save_objects(objs);
    render();

    //return false;
  });
    
  var render = function() {
	var objs = get_objects();

    $("#saved-objects ul").html('');
    
    if(objs.length == 0) {
    	$('<li class="none">Du har inte lagt till någon gård till din gårdslista.</li>').appendTo($("#saved-objects ul"));
    	return;
    }
    
    $(objs).each(function(key, val){
    	val = val.split('=');
    	var li = $('<li><a class="object" href="'+val[0]+'">'+val[1]+'</a><a class="remove" href="">&nbsp;</a></li>').appendTo($("#saved-objects ul"));
    	
    	$('.remove', li).click(function(){
			var objs = get_objects();
		    var href = $(this).siblings(".object:first").attr('href');
		    
		    objs = $.grep(objs, function(val){
		    	return !val.match('^'+href+'=.*');
		    });
		    
			save_objects(objs);
		    render();
		
		    return false;
    	})
    });
  }
  
  render();

  
  $.fn.savedObjects = function( method ) {
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist.' );
		}

	};
	
	var methods = {
		urlIsSaved : function( url ) {
			var objs = get_objects();
			return !objs.join('|').match(url)
		}
	}

});
})()

