/* semantictree.js : We suppose that jquery, jquery ui, tag-it, jstree and smoothness theme have been loaded */
function init_autocomplete()
{
    // Wikipedia search management (new tag)
    $(".semantic-tree").autocomplete({
        source: function( request, response ) {
        	// We use "this" because there can be several autocomplete in the same form.
        	// this.element[0] is the input.
            var reg = $(this.element[0]).val();
            var url = $(this.element[0]).attr("data-url");
            var query = $(this.element[0]).attr("data-query");
            $.ajax({
            	url : url,
                data: {
                	query: query,
                	$reg: '"'+reg+'"',
                	$language: '"fr"'
                },
            	headers: { 
                    Accept: "application/sparql-results+json;charset=UTF-8"
            	},
                success: function( data ) {
                	response( $.map( data["results"]["bindings"], function( item ) {
                		//console.log(item["uri"]["value"] + " = " + item["label"]["value"]);
                		return {
                			label: item["label"]["value"],
                			value: item["label"]["value"] + " (" + item["uri"]["value"] + ")"
                		}
                    }));
                }
            });
        },
        select: function(event, ui) {
        	// We use "this" because there can be several autocomplete in the same form.
        	// this is the input.
        	// addSubjectText is like "label (uri)" so we get the chars inner the last brackets
        	uri = ui.item.value.match(/\(([^)]*)\)[^(]*$/)[1]
        	// First we update the uri/label dict
        	angular.element(this).scope().updateUriLabelDict(uri, ui.item.label);
        	// Angular does not listen to val() event so we update the model value manually:
            angular.element(this).controller('ngModel').$setViewValue(uri);
        },
        minLength: 2
    });  
}


function init_browse() {
	
	$( ".dialog-link" ).each(function() {
		var input_name = this.id.substr(12);
		
		// Link to open the dialog
		$( '#dialog-link-'+input_name ).click(function( event ) {
	        event.preventDefault();
			var input_name = this.id.substr(12);
			console.log("input_name 2 = " + input_name);
			console.log($( '#dialog-'+input_name ));
			$( '#dialog-'+input_name ).dialog( "open" );
	        //if(! $('#thesaurus_tree').is(":disabled")) {
	        //    $( ".dialog" ).dialog( "open" );
	        //}
	    });
		
	    $( '#dialog-'+input_name ).dialog({
	        autoOpen: false,
	        width: 400,
	        height: "auto",
	        maxHeight: 800,
	        resizable: false,
	        position: {my: "left top", at:"left bottom+5", of:$("#dialog-link-container-"+input_name), collision: 'none'},
	        open: function(event, ui) {
	        	// this is the span with class="dialog" and id="dialog-inputname"
	        	var input_name = this.id.substr(7);
	        	var url = $("#id_"+input_name).attr("data-url");
	            var root_query = $("#id_"+input_name).attr("data-root-query");
	            var childs_query = $("#id_"+input_name).attr("data-childs-query");
	            var child_count_query = $("#id_"+input_name).attr("data-child-count-query");
	            console.log("ICI 1");
	            $('#term-tree-'+input_name)
	                .jstree({
	                    themes: {
	                        theme: "apple",
	                        dots: true,
	                        icons: true
	                    },
	                    json_data: {
	                        ajax: {
	                        	url : url,
	                            data: function(node){
	                	            console.log("ICI 2");
	                            	var res = {};
	                                if(node.data) {
	                                    res.query = childs_query;
	                                    res.$root = node.data('uri');
	                                }                                
	                                else{
	                                	res.query = root_query;
	                                }                                
	                            	res.$language = '"fr"';
	                	            console.log("ICI 3");
	                	            console.log(res);
	                            	return res;
	                            },
	                        	headers: { 
	                                Accept: "application/sparql-results+json;charset=UTF-8"
	                            },
	                            success: function(json) {
	                	            console.log("ICI 4");
	                            	var b = json["results"]["bindings"];
	                            	var mytree = [];
	                            	var l = b.length;
	                            	for(var i=0;i<l;i++){
	                            		var uri = b[i]["uri"]["value"];
	                            		// We test if the uri has childs.
	                            		var nb = 0;
	                            		$.ajax({
	                            			url:url,
	                            			data:{
	                            				query: child_count_query,
	                            				$root: "<"+uri+">"
	                            			},
	        	                        	headers: { 
	        	                                Accept: "application/sparql-results+json;charset=UTF-8"
	        	                            },
	                            			async: false,
	                            			success:function(json_count){
	                            				nb = parseInt(json_count["results"]["bindings"][0]["nb"]["value"]);
	                            			}
	                            		});
	                            		// nb of child > 0 : state closed if yes, no state if not.
	                            		if(nb>0){
		                            		mytree.push({
			                            		"data" : { 
			                            			"title" : b[i]["label"]["value"] + " (" + nb + ") " + uri.substr(uri.lastIndexOf("/")+1),
			                            		},
			                            		"state" : "closed",
			                            		"metadata" : {uri: "<" + uri + ">", label:b[i]["label"]["value"]}
			                            		//"language" : "en"
			                            	});
	                            		}
	                            		else{
	                            			mytree.push({
			                            		"data" : { 
			                            			"title" : b[i]["label"]["value"] + " " + uri.substr(uri.lastIndexOf("/")+1),
			                            		},
			                            		"metadata" : {uri: "<" + uri + ">", label:b[i]["label"]["value"]}
			                            	});
	                            		}
	                            	}
	                	            console.log("ICI 5");
	                	            console.log(mytree);
	                            	return mytree;
	                            },
	                            error: function() {
	                            	console.log("FAIL");
	                                $(".jstree-loading").removeClass("jstree-loading").addClass("jstree-error").html("Error when loading tree");
	                            }
	                        },
	                        progressive_render: true
	                    },
	                    ui : {
	                        select_limit: 1,
	                        initially_select: $('#thesaurus_tree').val()?['node-term-'+$('#thesaurus_tree').val()]:[]
	                    },
	                    plugins : [ "themes", "json_data", "ui"]
	                });
	        },
	        close: function( event, ui ) {
	        	//console.log("close");
	        	// this is the span with class="dialog" and id="dialog-inputname"
	        	var input_name = this.id.substr(7);
	            $.jstree._reference($('#term-tree-'+input_name)).destroy();
	        },
	        buttons: [
	            {
	                text:  "Ok",
	                click: function() {
	    	        	// this is the span with id="dialog-inputname"
	    	        	var input_name = this.id.substr(7);
	                    selected = $.jstree._reference($('#term-tree-'+input_name)).get_selected();
	                    if(selected.length) {
	                        selected_node = $(selected[0]);
	                        // Update text input : val() if classical input, add tag to tagit instance if necessary
	                        if($('#id_'+input_name).hasClass("semantic-tree-tagit")){
	                        	$('#id_'+input_name).tagit("createTag", selected_node.data('label'));
	                        }
	                        else{
	                        	$('#id_'+input_name).val(selected_node.data('label'));
	                        }
	                        //$('#thesaurus_tree').data('term_tree_node',selected_node.data('term_tree_node'));
	                        //$('#thesaurus_tree').val(selected_node.data('term_tree_node').id).trigger('change');                        
	                    }
	                    $( this ).dialog( "close" );                    
	                }
	            },
	            {
	                text: "Cancel",
	                click: function() {
	                    $(this).dialog( "close" );
	                }
	            }
	        ]
	    });
	});
}

function init_tagit_autocomplete()
{
    // Semantic search management with tag-it feature
    $(".semantic-tree-tagit").tagit({
    	tagSource: function(request, response) {
        	// We use "this" because there can be several autocomplete in the same form.
        	// this.element[0] is the input.
            var url = $(this.element[0]).attr("data-url");
            var query = $(this.element[0]).attr("data-query");
            $.ajax({
            	url : url,
                data: {
                	query: query,
                	$reg: '"'+request.term+'"',
                	$language: '"fr"'
                },
            	headers: { 
                    Accept: "application/sparql-results+json;charset=UTF-8"
            	},
                success: function( data ) {
                	response( $.map( data["results"]["bindings"], function( item ) {
                		return {
                			label: item["label"]["value"],
                			value: item["uri"]["value"]
                		}
                    }));
                }
            });
        },
        allowSpaces: true
    });
}


$(document).ready(function(){
    init_autocomplete();
    init_browse();
    init_tagit_autocomplete();
});