$(function(){

//masonry
	var masonry465 = $('.masonry-465');
	masonry465.masonry({
	  columnWidth: 465,
	  itemSelector: '.item-masonry',
	  gutter : 20
	});

	var masonry225 = $('.masonry-225');
	masonry225.masonry({
	  columnWidth: 225,
	  itemSelector: '.item-masonry',
	  gutter : 16
	});

//popin
	$('.open-popin').bind('click', function(e){
		e.preventDefault();
		var target = $(this).attr('href');
		$('.popin-wrap').fadeIn(function(){
			$(target).show();
		});
	});

	$('.close-popin, .popin-wrap').bind('click', function(e){
		e.preventDefault();
		e.stopPropagation();
		$('.popin-wrap').fadeOut(function(){
			$('.popin').hide();
		});
	});

	$('.popin').bind('click', function(e){
		e.stopPropagation();
	});
//tag it
	if($('.tag-it').length){
		var keywordsTagIt = $('.tag-it').tagit({
			allowSpaces : true
		});
		$('.list-key-add a').bind('click', function(e){
			e.preventDefault();
			keywordsTagIt.tagit("createTag", $(this).attr('data-tag'));
		});
	}


	
	// add item to collection behaviour
	$('.additemtocollection').bind('click', function(e){
		// When an item meant to be added to a collection is clicked,
		// we fill the form in the add-to-collection div
		$('#add-to-collection .item-type').val($(this).attr('data-type'));
		$('#add-to-collection .item-id').val($(this).attr('data-id'));
	});
	// modify item in collection behaviour
	$('.modifyitemincollection').bind('click', function(e){
		$('#modify-item .item-pk').val($(this).attr('data-pk'));
		$('#modify-item .item-description').val($(this).attr('data-description'));
	});
	
	
	$(".ajax-form").submit(function(e) { // On submit Ajax Form
	    var formel = $(this);
	    $.ajax({
	        url: formel.attr("action"),
	        type: formel.attr("method"),
	        data: formel.serialize(),
	        success: function(text) {
	        	// different behaviour if we add or modify an item
	        	if(text=="modifyok"){
	        		// modify
	        		$('.popin-wrap').fadeIn(function(){
	                    $(".modifyitem-success").show();
	                });
	        		// update text. $("item{{ item.pk }}") is the <div> with the text as <p> and <a data-description>
	        		var item_pk = $('#modify-item .item-pk').val();
	        		var item_desc = $('#modify-item .item-description').val();
	        		$("#item" + item_pk).find("a").attr("data-description", item_desc);
	        		$("#item" + item_pk).find("p").html(item_desc.replace(/\n/g, '<br />'));
	        	}
	        	else{
	        		// add
	                $('.popin-wrap').fadeIn(function(){
	                    $(".additem-success").show();
	                });
	                $(".additem-success .collection-url").attr("href", text);
                }
	        },
            error: function() {
                $('.popin-wrap').fadeIn(function(){
                    $(".additem-error").show();
                });
            }
	    });
	    formel.parents(".popin").hide();
	    return false;
	});

});//ready