$(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();
	});
	
	/* DBPEDIA OVERLAY */
    
    var sparqlTpl = 'select distinct * where { '
		            + 'OPTIONAL { <<%= uri %>> rdfs:label ?l FILTER( langMatches( lang(?l), "<%- lang %>" ) ) }. '
		            + 'OPTIONAL { <<%= uri %>> dbpedia-owl:thumbnail ?t }. '
		            + 'OPTIONAL { <<%= uri %>> dbpedia-owl:abstract ?a FILTER( langMatches( lang(?a), "<%- lang %>" ) ) }. '
		            + 'OPTIONAL { <<%= uri %>> dbpedia-owl:wikiPageRedirects ?r }. '
		            + 'OPTIONAL { ?r rdfs:label ?lr FILTER( langMatches( lang(?lr), "<%- lang %>" ) ) }. '
		            + 'OPTIONAL { ?r dbpedia-owl:thumbnail ?tr }. '
		            + 'OPTIONAL { ?r dbpedia-owl:abstract ?ar FILTER( langMatches( lang(?ar), "<%- lang %>" ) ) }. '
		            + '}',
        $overlay = $(".dbpedia-overlay"),
        hovering = null,
        anchor = null,
        $win = $(window),
        dbpediaCache = {},
        $overlayImg = $overlay.find("img"),
        $h2 = $overlay.find("h2"),
        $abstract = $overlay.find(".dbpedia-abstract"),
        $source = $overlay.find(".dbpedia-source a");
    
    function setDbpediaBoxAnchor(a) {
        anchor = a || null;
        if (anchor) {
            recentreDbpediaBox();
        }
    }
    
    function recentreDbpediaBox() {
        if (!anchor) { return; }
        var ovw = $overlay.outerWidth(),
            ovh = $overlay.outerHeight(),
            refbox;
        switch (anchor.type) {
            case "dom":
                var $refdiv = anchor.selector,
                    refoff = $refdiv.offset(),
                    refw = $refdiv.outerWidth(),
                    refh = $refdiv.outerHeight(),
                    refx = refoff.left,
                    refy = refoff.top;
                refbox = { left: refx, right: refx + refw, top: refy, bottom: refy + refh };
            break;
            case "box":
                refbox = anchor.box;
            break;
            case "callback":
                refbox = anchor.callback();
            break;
        }
        if (!refbox) { return; }
        if (!refbox.right) { refbox.right = refbox.left; }
        if (!refbox.bottom) { refbox.bottom = refbox.top; }
        refbox.hcentre = (refbox.left + refbox.right) / 2;
        switch (anchor.positioning) {
            case "side":
                var showLeft = (refbox.right + ovw) > $win.width();
                css = { left: showLeft ? (refbox.left - ovw) : (refbox.right), top: refbox.top };
            break;
            case "bottom":
                css = { left: refbox.hcentre - ovw / 2, top: refbox.bottom };
            break;
            case "vertical":
            default:
                var showAbove = (refbox.bottom + ovh) > ($win.height() + $win.scrollTop());
                css = { left: refbox.hcentre - ovw / 2, top: showAbove ? refbox.top - ovh : refbox.bottom };
        }
        if (css) {
            css.left = Math.max(5, Math.min($win.width() - ovw - 5, css.left));
            $overlay.css(css);
        }
    }
    
	function showDbpediaBox(dbpediaUri) {
        if (!dbpediaUri) {
            return;
        }
        hovering = dbpediaUri;
        $overlay.hide();
        $overlayImg.attr("src","");
        var uriData = dbpediaCache[dbpediaUri];
        if (!uriData) {
            getUriData(dbpediaUri);
            return;
        }
        $overlay.show().attr("data-dbpedia-uri", dbpediaUri);
        if (uriData.t || uriData.tr) {
            $overlayImg.attr("src",uriData.t || uriData.tr).show();
        } else {
            $overlayImg.hide();
        }
        var label = uriData.l || uriData.lr || "",
            wkUrl = "http://fr.wikipedia.org/";
        if (label) {
            wkUrl += "wiki/" + encodeURI(label.replace(/ /g,'_'));
        } 
        $h2.text((uriData.l && uriData.lr) ? (uriData.l + " → " + uriData.lr) : label);
        $abstract.text((uriData.a || uriData.ar || "").replace(/^(.{240,260})\s.+$/,'$1…').substr(0,261));
        $source.attr("href", wkUrl);
        recentreDbpediaBox();
    }
	
	function getUriData(dbpediaUri) {
        if (typeof dbpediaCache[dbpediaUri] !== "undefined") {
            return;
        }
        var sparqlEndpoint = dbpediaUri.replace(/\/resource\/.*$/,'/sparql'),
            query = sparqlTpl.replace(new RegExp("<%= uri %>", "g"), decodeURI(dbpediaUri)).replace(new RegExp("<%- lang %>", "g"), "fr");
        dbpediaCache[dbpediaUri] = false;
        $.getJSON(sparqlEndpoint, {
            query: query,
            format: "application/sparql-results+json"
        }, function(data) {
            if (!data.results || !data.results.bindings || !data.results.bindings.length) {
                return;
            }
            var res = data.results.bindings[0], cacheData = {};
            for (var k in res) {
                if (res.hasOwnProperty(k)) {
                    cacheData[k] = res[k].value;
                }
            }
            dbpediaCache[dbpediaUri] = cacheData;
            if (hovering === dbpediaUri) {
                showDbpediaBox(dbpediaUri);
            }
        });
    }
	
	function hideDbpediaBox() {
        hovering = null;
        setTimeout(function() {
            if (!hovering) {
                $overlay.hide();
                setDbpediaBoxAnchor();
            }
        }, 0);
    }
    
    function bindDbpediaBox(selector, defaultUri) {
        var $sel = $(selector);
        $sel.off("mouseenter mouseleave");
        $sel.mouseenter(function(e) {
            var $this = $(this);
            setDbpediaBoxAnchor({ selector: $this, type: "dom", positioning: "vertical" });
            var dbpediaUri = $this.attr("data-dbpedia-uri") || defaultUri;
            if (!dbpediaUri || dbpediaUri === "None") {
                return;
            }
            showDbpediaBox(dbpediaUri);
        });
        $sel.mouseleave(hideDbpediaBox);
    }
        
    $overlay.hover(function() {
        var $this = $(this),
            dbpediaUri = $this.attr("data-dbpedia-uri");
        if (dbpediaUri) {
            hovering = dbpediaUri;
        }
    }, hideDbpediaBox);
    
    $overlay.find(".dbpedia-close").click(function() {
        hideDbpediaBox();
        return false;
    });
    
    window.dbpediaBox = {
        bind: bindDbpediaBox,
        hide: hideDbpediaBox,
        show: showDbpediaBox,
        setAnchor: setDbpediaBoxAnchor,
        recentre: recentreDbpediaBox
    };
    
    /* END DBPEDIA OVERLAY MANAGEMENT */
	
	// TAG IT
	if($('.tag-it').length){
		var keywordsTagIt = $('.tag-it').tagit({
			allowSpaces : true,
			tagSource: function(search, showChoices){
                $.ajax({
                	url : "http://fr.wikipedia.org/w/api.php",
                    dataType: "jsonp",
                    data : {
                        action: "opensearch",
                        search: search.term,
                        format: "json",
                        limit: 10
                    },
                    success:function(data){
                    	var datas = data[1];
                    	var n = datas.length;
                    	var choices = [];
                    	for(var i=0;i<n;i++){
                    		var l = data[1][i];
                    		var l_uri = l.replace(new RegExp(" ","g"),"_");
                    		choices.push({ label:l, value:( 'http://fr.wikipedia.org/wiki/' + l_uri), dbpedia_uri: ('http://fr.dbpedia.org/resource/' + l_uri) });
                    	}
                        showChoices(choices);
                    }
                });
            },
			autocomplete: {
	            focus: function(e, ui) {
                    showDbpediaBox(ui.item.dbpedia_uri);
                    setDbpediaBoxAnchor({type: "dom", selector: $(e.target).autocomplete("widget"), positioning: "side"});
	            },
	            close: function(e, ui){
	            	hideDbpediaBox();
	            }
	        },
            beforeTagAdded: function(event, ui) {
                if($(ui.tag.children()[0]).hasClass("tagit-label")){
                	var tagit_label = $(ui.tag.children()[0]).html();
                	if(tagit_label.substr(0, 29) == 'http://fr.wikipedia.org/wiki/'){
                		var label = tagit_label.substr(29).replace(new RegExp("_","g")," ");
                		$(ui.tag.children()[0]).html(label + ' <a href="' + tagit_label + '" target="_blank"><span class="logo_wikipedia f-right">&nbsp;</span></a>');
                	}
                }
                hideDbpediaBox();
            },
            beforeTagRemoved: function(event, ui) {
                // test if tag label is wikipedia url
                if($(ui.tag.children()[0]).children().length>0){
                	var $a_tag = $($(ui.tag.children()[0]).children()[0]);
                	if($a_tag.attr("href").substr(0, 29) == 'http://fr.wikipedia.org/wiki/'){
                		// Before removing, turn label into url
                		$(ui.tag.children()[0]).html($a_tag.attr("href").replace(new RegExp(" ","g"),"_"));
                	}
                }
            }
		});
		$('.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