var checkLangDesc=[];
var checkLangId=[];
var acceptablityArray =[];
var summaryDesc=[];
var inactiveDesc=[];
var clipboardCopyId,clipboardCopyIdLeft,clipboardCopyIdRight,clipboardCopyDetails,clipboardCopyIdLeftDetails,clipboardCopyIdRightDetails=null;
$(function() {
    $.extend($.fn.disableTextSelect = function() {
        return this.each(function() {
            $(this).mousedown(function() {
                return false;
            });
        });
    });
    $('.noSelect').disableTextSelect(); //No text selection on elements with a class of 'noSelect'
});

function conceptDetails(divElement, conceptId, options) {

    if (typeof componentsRegistry == "undefined") {
        componentsRegistry = [];
    }
    var panel = this;
	var perspective=panel.constructor.caller.name;
    this.temp="";
    this.type = "concept-details";
    this.conceptId = conceptId;
    this.divElement = divElement;
    this.options = jQuery.extend(true, {}, options);
    this.attributesPId = "";
    this.descsPId = "";
    this.relsPId = "";
    this.history = [];
    this.color = "white";
 //   panel.preferred = false;
 //   panel.acceptable = false;
 //   panel.included = false;
    this.lastGroup = null;
    this.subscription = null;
    var xhr = null;
    var xhrChildren = null;
    var xhrReferences = null;
    var xhrParents = null;
    var xhrMembers = null;
    var conceptRequested = 0;
    panel.subscriptionsColor = [];
    panel.subscriptions = [];
    panel.subscribers = [];
    var acceptability="all";  // for all dialect
	
	//Get the enum of language supported by csnoserv		
    $.ajaxSetup({
	async : false
     });  

	 $.getJSON(options.serverUrl+"/csnoserv/api/search/langrefset",
		function(result) {
		}).done(function(result) {
	 var i;
	 //store the language dialect Id in checkLangId array
	 checkLangId=[];
	//store the language dialect Description in checkLangDesc array
	 checkLangDesc=[];
	 for (i = 0; i < result.length; i++) {
		 //Store dialect other than us and uk (as the should always be present )in checkLangDesc,checkLangId
		 
		 if(result[i][1]!=="us" && result[i][1]!=="uk")
		 {
		checkLangId.push(result[i][0]);
		checkLangDesc.push(result[i][1]);
		 }
	}
});
	  $.ajaxSetup({
	async : true
}); 

    componentLoaded = false;
    $.each(componentsRegistry, function(i, field) {
        if (field.divElement.id == panel.divElement.id) {
            componentLoaded = true;
        }
    });
    if (componentLoaded == false) {
        componentsRegistry.push(panel);
    }


    this.getConceptId = function() {
        return this.conceptId;
    }

    this.getDivId = function() {
        return this.divId;
    }

    this.getNextMarkerColor = function(color) {
//console.log(color);
        var returnColor = 'black';
        if (color == 'black') {
            returnColor = 'green';
        } else if (color == 'green') {
            returnColor = 'purple';
        } else if (color == 'purple') {
            returnColor = 'red';
        } else if (color == 'red') {
            returnColor = 'blue';
        } else if (color == 'blue') {
            returnColor = 'maroon';
        } else if (color == 'maroon') {
            returnColor = 'green';
        }
//console.log(returnColor);
        globalMarkerColor = returnColor;
        return returnColor;
    }
    panel.markerColor = panel.getNextMarkerColor(globalMarkerColor);

    this.setupCanvas = function() {
    	
        panel.attributesPId = panel.divElement.id + "-attributes-panel";
        panel.descsPId = panel.divElement.id + "-descriptions-panel";
        panel.relsPId = panel.divElement.id + "-rels-panel";
        panel.childrenPId = panel.divElement.id + "-children-panel";
        panel.defaultTerm = "";
        $(divElement).html();
        var context = {
            divElementId: panel.divElement.id,
        };       
        $(divElement).html(JST["views/conceptDetailsPlugin/main.hbs"](context));
	//tooltip panel option
        $("#" + panel.divElement.id + "-configButton").tooltip({
            placement: 'left',
            trigger: 'hover',
            title: i18n_panel_options,
            animation: true,
            delay: 1000
        });  

	$("#" + panel.divElement.id + "-apply-button").click(function(){ 
                panel.updateCanvas();   //update canvas onclick of apply button
         });

        $("#" + panel.divElement.id + "-subscribersMarker").disableTextSelect();    
        $("#" + panel.divElement.id + "-subscribersMarker").hide();
        if (typeof panel.options.subscribersMarker != "undefined" && panel.options.subscribersMarker == false) {
            $("#" + panel.divElement.id + "-subscribersMarker").remove();
        }

        if (typeof i18n_panel_options == "undefined") {
            i18n_panel_options = "Panel options";
        }     

          $('#' + panel.divElement.id).click(function(event) {          
            if (!$(event.target).hasClass('glyphicon glyphicon-info-sign')) {            
                $('#' + panel.divElement.id).find('.more-fields-button').popover('hide');
            }                        
        }); 
         
        panel.updateCanvas();
        channel.publish(panel.divElement.id, {
            term: panel.term,
            module: panel.module,
            conceptId: panel.conceptId,
            source: panel.divElement.id
        });
     
        if (panel.subscriptions.length > 0 || panel.subscribers.length > 0){
            $("#" + panel.divElement.id + "-subscribersMarker").show();
        }
        $("#" + panel.divElement.id + "-ownMarker").css('color', panel.markerColor);
    }

    this.updateCanvas = function() {
        // Jump to ConceptDetails tab
        $('a[href="#fh-cd1_canvas-pane"]').tab('show');
	
	//check if inactive Button is checked
        if($("#"+ panel.divElement.id + "-displayInactiveDescriptionsOption").is(':checked'))
	{
		$.getJSON(options.serverUrl+"/csnoserv/api/search/search?term="+panel.conceptId+"&state=inactive",function(result){
                       
		}).done(function(result){
                  inactiveDesc = result; //fill arrya with inactive Description
                  
               });
        }else {
		inactiveDesc=[];        //set array to empty if unchecked
	}
	//check if Display Synonyms along with FSN and preferred terms
	if($("#"+ panel.divElement.id + "-displaySynonymsOption").is(':checked'))
	{
		inactiveDesc=[];
	}else {
	}
    	
//        $("#members-" + panel.divElement.id).html("");
        $("#home-children-cant-" + panel.divElement.id).html("");
        $('.more-fields-button').popover('hide');
         if (conceptRequested == panel.conceptId) {
            return;
        }
       	if(document.getElementById("dynamicbutton")!=null)
		{
	console.log(document.getElementById("dynamicbutton").remove());
		}
        $("#home-children-" + panel.divElement.id + "-body").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>");
        $('#' + panel.attributesPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>");
        $('#home-attributes-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>");
        $('#' + panel.descsPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>");
        $('#' + panel.relsPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>");
        $('#home-parents-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>");
        $('#home-roles-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>");
        $('#' + panel.childrenPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>");
        $("#diagram-canvas-" + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>");     

        // load attributes      
      
       xhr = $.getJSON(options.serverUrl+"/csnoserv/api/lookup/concept?id="+panel.conceptId+"&langrefset="+acceptability+"&callback=?", function (result) {
        }).done(function (result) {     
		//if perspective is other than Browsing or switchToResponsiveLayout
	  if(acceptability==="all" && perspective!=="switchToBrowsing" && perspective!=="switchToResponsiveLayout")
		  {
		   var tempList=[];
 
		   var index=0;
		   //get the list of refSetLangMember in concept in tempList
		   while(index < result.descriptions.length){
		         tempList.push(result.descriptions[index].refSetLangMember.refSetId);
			 index += 1;						
		   }
		   var flags = [], uniqueList = [], l = tempList.length, i;
 
		   // get unique list from tempList
		   for( i=0; i<l; i++) {
			   if( flags[tempList[i]]) continue;
			   	flags[tempList[i]] = true;
			   uniqueList.push(tempList[i] );
		   }
		   //acceptablityArray is use to store language supported by concept and load in dropdown of language
		   acceptablityArray =[];
		   	for (i = 0; i < uniqueList.length; i++) {
			  
			  for(l=0;l<checkLangId.length ;l++)
			  {
				  if(uniqueList[i]===checkLangId[l])
				  {
					  //language dialect Description should be store in capital
					  acceptablityArray .push(checkLangDesc[l].toUpperCase());
				  }
			  }
		  }	
		   	//acceptablityArray store fix language US,UK
		   	acceptablityArray.push("US");
		   	acceptablityArray.push("UK"); 		  
		   
		}
	  //If perspective is Browsing or switchToResponsiveLayout then each time load the acceptabilityArray as constant variable cant be used
	  else if(perspective==="switchToBrowsing" || perspective==="switchToResponsiveLayout" )
		  {
			   $.ajaxSetup({
				   async : false
			   });
		   
			   //Give call to csnoserv to load the language supported by that concept each time new language is selected by user
			  xhr = $.getJSON(options.serverUrl+"/csnoserv/api/lookup/concept?id="+panel.conceptId+"&langrefset=all&callback=?", function (result) {
		        }).done(function (resultAll) {
		        
		        	var tempList=[];

		        	var index=0;
		        	
		        	while(index < resultAll.descriptions.length){
		        		tempList.push(resultAll.descriptions[index].refSetLangMember.refSetId);
		        		index += 1;
		        	}
		        	var flags = [], uniqueList = [], l = tempList.length, i;

		        	for( i=0; i<l; i++) {
		        		if( flags[tempList[i]]) continue;
		        		flags[tempList[i]] = true;
		        		uniqueList.push(tempList[i] );
		        	}

		        	acceptablityArray =[];
		        	for (i = 0; i < uniqueList.length; i++) {
			  
		        		for(l=0;l<checkLangId.length ;l++)
		        		{
		        			if(uniqueList[i]===checkLangId[l])
		        			{
		        				acceptablityArray .push(checkLangDesc[l].toUpperCase());
		        			}
		        		}
		        	}		
		        	acceptablityArray.push("US");
		        	acceptablityArray.push("UK");  
		        	summaryDesc = resultAll.descriptions.slice(0);
		        	
		        });
				 $.ajaxSetup({
					 async : true
				 });
			   
		  }
		 
		 
            if(panel.conceptId==138875005)
            {

                var allDescriptions = result.descriptions.slice(0);

                var currentVersion;
                var pattern = /\d{8,8}/i;

                $.each(allDescriptions, function (i, field) {

                    var tempVersion = field.term;
                    tempVersion = tempVersion.match(pattern);
                    if( tempVersion != null ) {
                        currentVersion = tempVersion.toString();
                        return false;
                    }

                });
                //Date Format YYYY-MM-DD
                currentVersion = currentVersion.slice(0, 4) + "-" + currentVersion.slice(4, 6) + "-" + currentVersion.slice(-2);

                $("#currentversion").html("Release: "+currentVersion);
            }
            var firstMatch = result;
            xhr = null;
            panel.attributesPId = divElement.id + "-attributes-panel";
            panel.defaultTerm = firstMatch.fsn;
            var d = new Date();
            var time = d.getTime();         
            Handlebars.registerHelper('if_eq', function (a, b, opts) {
                if (opts != "undefined") {
                    if (a == b)
                        return opts.fn(this);
                    else
                        return opts.inverse(this);
                }
            });
                var context = {
                options: panel.options,
                firstMatch: firstMatch,
                divElementId: panel.divElement.id,
                edition: options.edition,
		acceptablityArray : acceptablityArray ,
		linkURL: document.URL.split("?")[0].split("#")[0] + "?perspective=full&conceptId1=" + firstMatch.conceptId + "&edition=" + panel.options.edition + "&release=" + panel.options.release + "&server=" + panel.options.serverUrl + "&langRefset=" + panel.options.langRefset,   
               // release: options.release,            
               // server: options.serverUrl,
               // langRefset: panel.options.langRefset,
                dataContentValue: document.URL.split("?")[0].split("#")[0]
            };

            $('#' + panel.attributesPId).html(JST["views/conceptDetailsPlugin/tabs/details/attributes-panel.hbs"](context));
            $('#' + 'share-link-' + panel.divElement.id).disableTextSelect();
            $('#' + 'share-link-' + panel.divElement.id).click(function (event) {
                setTimeout(function () {
                    $('#' + 'share-field-' + panel.divElement.id).select();
                }, 300);
            });
            
            // load home-attributes
            Handlebars.registerHelper('if_eq', function (a, b, opts) {
                if (opts != "undefined") {
                    if (a == b)
                        return opts.fn(this);
                    else
                        return opts.inverse(this);
                }
            });
         
            var context = {
                panel: panel,
                firstMatch: firstMatch,
                divElementId: panel.divElement.id,
                linkURL: document.URL.split("?")[0].split("#")[0] + "?perspective=full&conceptId1=" + firstMatch.conceptId + "&edition=" + panel.options.edition + "&release=" + panel.options.release + "&server=" + panel.options.serverUrl + "&langRefset=" + panel.options.langRefset
            };
            $('#home-attributes-' + panel.divElement.id).html(JST["views/conceptDetailsPlugin/tabs/home/attributes.hbs"](context));
            var state = {
                name: firstMatch.fsn,
                conceptId: firstMatch.conceptId,
            };
            var clientTerm = new ZeroClipboard( document.getElementById(panel.divElement.id + "-copy-term") );
            clientTerm.on( "ready", function( readyEvent ) {
                clientTerm.on( "copy", function (event) {
                    $("#" + panel.divElement.id + "-copy-icon").addClass("animated rubberBand");
                    window.setTimeout( function(){
                        $("#" + panel.divElement.id + "-copy-icon").removeClass('animated rubberBand');
                    }, 1000);
                    alertEvent("Term copied to clipboard", "info");
                    var clipboard = event.clipboardData;
                    clipboard.setData("text/plain", firstMatch.fsn);
                });
            } );
            var clientAll = new ZeroClipboard( document.getElementById(panel.divElement.id + "-copy-sctid-term") );
            clientAll.on( "ready", function( readyEvent ) {
                clientAll.on( "copy", function (event) {
                    $("#" + panel.divElement.id + "-copy-icon").addClass("animated rubberBand");
                    window.setTimeout( function(){
                        $("#" + panel.divElement.id + "-copy-icon").removeClass('animated rubberBand');
                    }, 1000);
                    alertEvent("SCTID and Term copied to clipboard", "info");
                    var clipboard = event.clipboardData;
                    clipboard.setData("text/plain", firstMatch.conceptId + " |" + firstMatch.fsn + "|");
                });
            } );
            var clientSctid = new ZeroClipboard( document.getElementById(panel.divElement.id + "-copy-sctid") );
            clientSctid.on( "ready", function( readyEvent ) {
                clientSctid.on( "copy", function (event) {
                    $("#" + panel.divElement.id + "-copy-icon").addClass("animated rubberBand");
                    window.setTimeout( function(){
                        $("#" + panel.divElement.id + "-copy-icon").removeClass('animated rubberBand');
                    }, 1000);
                    alertEvent("SCTID copied to clipboard", "info");
                    var clipboard = event.clipboardData;
                    clipboard.setData("text/plain", firstMatch.conceptId);
                });
            } );
            var clientLink = new ZeroClipboard( document.getElementById(panel.divElement.id + "-copy-link") );
            clientLink.on( "ready", function( readyEvent ) {
                clientLink.on( "copy", function (event) {
                    $("#" + panel.divElement.id + "-copy-icon").addClass("animated rubberBand");
                    window.setTimeout( function(){
                        $("#" + panel.divElement.id + "-copy-icon").removeClass('animated rubberBand');
                    }, 1000);
                    alertEvent("Link copied to clipboard", "info");
                    var clipboard = event.clipboardData;
                    clipboard.setData("text/plain", document.URL.split("?")[0].split("#")[0] + "?perspective=full&conceptId1=" + firstMatch.conceptId + "&edition=" + panel.options.edition + "&release=" + panel.options.release + "&server=" + panel.options.serverUrl + "&langRefset=" + panel.options.langRefset);
                });
            } );

            var clientTermDetails = new ZeroClipboard( document.getElementById(panel.divElement.id + "-copy-term-details") );
            clientTermDetails.on( "ready", function( readyEvent ) {
                clientTermDetails.on( "copy", function (event) {
                    $("#" + panel.divElement.id + "-copy-icon-details").addClass("animated rubberBand");
                    window.setTimeout( function(){
                        $("#" + panel.divElement.id + "-copy-icon-details").removeClass('animated rubberBand');
                    }, 1000);
                    alertEvent("Term copied to clipboard", "info");
                    var clipboard = event.clipboardData;
                    clipboard.setData("text/plain", firstMatch.fsn);
                });
            } );
            var clientAllDetails = new ZeroClipboard( document.getElementById(panel.divElement.id + "-copy-sctid-term-details") );
            clientAllDetails.on( "ready", function( readyEvent ) {
                clientAllDetails.on( "copy", function (event) {
                    $("#" + panel.divElement.id + "-copy-icon-details").addClass("animated rubberBand");
                    window.setTimeout( function(){
                        $("#" + panel.divElement.id + "-copy-icon-details").removeClass('animated rubberBand');
                    }, 1000);
                    alertEvent("SCTID and Term copied to clipboard", "info");
                    var clipboard = event.clipboardData;
                    clipboard.setData("text/plain", firstMatch.conceptId + " |" + firstMatch.fsn + "|");
                });
            } );
            var clientSctidDetails = new ZeroClipboard( document.getElementById(panel.divElement.id + "-copy-sctid-details") );
            clientSctidDetails.on( "ready", function( readyEvent ) {
                clientSctidDetails.on( "copy", function (event) {
                    $("#" + panel.divElement.id + "-copy-icon-details").addClass("animated rubberBand");
                    window.setTimeout( function(){
                        $("#" + panel.divElement.id + "-copy-icon-details").removeClass('animated rubberBand');
                    }, 1000);
                    alertEvent("SCTID copied to clipboard", "info");
                    var clipboard = event.clipboardData;
                    clipboard.setData("text/plain", firstMatch.conceptId);
                });
            } );
            var clientLinkDetails = new ZeroClipboard( document.getElementById(panel.divElement.id + "-copy-link-details") );
            clientLinkDetails.on( "ready", function( readyEvent ) {
                clientLinkDetails.on( "copy", function (event) {
                    $("#" + panel.divElement.id + "-copy-icon").addClass("animated rubberBand");
                    window.setTimeout( function(){
                        $("#" + panel.divElement.id + "-copy-icon").removeClass('animated rubberBand');
                    }, 1000);
                    alertEvent("Link copied to clipboard", "info");
                    var clipboard = event.clipboardData;
                    clipboard.setData("text/plain", document.URL.split("?")[0].split("#")[0] + "?perspective=full&conceptId1=" + firstMatch.conceptId + "&edition=" + panel.options.edition + "&release=" + panel.options.release + "&server=" + panel.options.serverUrl + "&langRefset=" + panel.options.langRefset);
                });
            } );
            
			//if perspective is  switchToBrowsing or switchToResponsiveLayout then we have two panel left panel and right panel which provides concept details
			if((perspective==="switchToBrowsing" || perspective==="switchToResponsiveLayout" ))
            	{
				//If full perspective clipboard object present destroy method is used
				if(clipboardCopyDetails)
					clipboardCopyDetails.destroy();
				if(clipboardCopyId)
					clipboardCopyId.destroy();
				//If panel contains bp-cd1_canvas i.e left panel so create new clipboard for left panel
            	if(panel.divElement.id.includes("bp-cd1_canvas"))
            		{
            		//If already clipboard object created for left panel destroy it and create new one.
						if(clipboardCopyIdLeft)
							clipboardCopyIdLeft.destroy();
            	 clipboardCopyIdLeft = new ClipboardJS("."+"clip-btn-copy-"+panel.divElement.id+"-id");

                clipboardCopyIdLeft.on('success', function(e) {
                	
                    if(e.trigger.innerText === "Copy SCTID")
                    	alertEvent("SCTID copied to clipboard","info");	
                    if(e.trigger.innerText === "Copy term")
                    	alertEvent("Term copied to clipboard", "info");
                    if(e.trigger.innerText === "Copy SCTID + term")
                    	alertEvent("SCTID and Term copied to clipboard", "info");
                    if(e.trigger.innerText === "Copy Link to share")
                    	alertEvent("Link copied to clipboard", "info");
                    e.clearSelection();
                });
            		
            	clipboardCopyIdLeft.on('error', function(e) {
                    console.error('Action:', e.action);
                    console.error('Trigger:', e.trigger);
                });
            	//If already clipboard object created for left panel detail tab destroy it and create new one.
				if(clipboardCopyIdLeftDetails)
					clipboardCopyIdLeftDetails.destroy();
				 clipboardCopyIdLeftDetails = new ClipboardJS("."+"clip-btn-copy-"+panel.divElement.id+"-details");

                clipboardCopyIdLeftDetails.on('success', function(e) {
                	
                    if(e.trigger.innerText === "Copy SCTID")
                    	alertEvent("SCTID copied to clipboard","info");	
                    if(e.trigger.innerText === "Copy term")
                    	alertEvent("Term copied to clipboard", "info");
                    if(e.trigger.innerText === "Copy SCTID + term")
                    	alertEvent("SCTID and Term copied to clipboard", "info");
                    if(e.trigger.innerText === "Copy Link to share")
                    	alertEvent("Link copied to clipboard", "info");
                    e.clearSelection();
                });
            		
            	clipboardCopyIdLeftDetails.on('error', function(e) {
                    console.error('Action:', e.action);
                    console.error('Trigger:', e.trigger);
                });
            }
            	//If panel contains bp-cd2_canvas i.e right panel so create new clipboard for right panel  	
            	else if(panel.divElement.id.includes("bp-cd2_canvas"))
            		{
            		//If already clipboard object created for right panel destroy it and create new one.
						if(clipboardCopyIdRight)
							clipboardCopyIdRight.destroy();
                 clipboardCopyIdRight = new ClipboardJS("."+"clip-btn-copy-"+panel.divElement.id+"-id");

                clipboardCopyIdRight.on('success', function(e) {
                	
                    if(e.trigger.innerText === "Copy SCTID")
                    	alertEvent("SCTID copied to clipboard","info");	
                    if(e.trigger.innerText === "Copy term")
                    	alertEvent("Term copied to clipboard", "info");
                    if(e.trigger.innerText === "Copy SCTID + term")
                    	alertEvent("SCTID and Term copied to clipboard", "info");
                    if(e.trigger.innerText === "Copy Link to share")
                    	alertEvent("Link copied to clipboard", "info");
                    e.clearSelection();
                });

                clipboardCopyIdRight.on('error', function(e) {
                    console.error('Action:', e.action);
                    console.error('Trigger:', e.trigger);
                });
              //If already clipboard object created for right panel detail tab destroy it and create new one.
				if(clipboardCopyIdRightDetails)
					clipboardCopyIdRightDetails.destroy();
			
				clipboardCopyIdRightDetails = new ClipboardJS("."+"clip-btn-copy-"+panel.divElement.id+"-details");

                clipboardCopyIdRightDetails.on('success', function(e) {
                	
                    if(e.trigger.innerText === "Copy SCTID")
                    	alertEvent("SCTID copied to clipboard","info");	
                    if(e.trigger.innerText === "Copy term")
                    	alertEvent("Term copied to clipboard", "info");
                    if(e.trigger.innerText === "Copy SCTID + term")
                    	alertEvent("SCTID and Term copied to clipboard", "info");
                    if(e.trigger.innerText === "Copy Link to share")
                    	alertEvent("Link copied to clipboard", "info");
                    e.clearSelection();
                });

                clipboardCopyIdRightDetails.on('error', function(e) {
                    console.error('Action:', e.action);
                    console.error('Trigger:', e.trigger);
                });
         		}
		}
			
		else{
			//if perspective is not switchToBrowsing or switchToResponsiveLayout then we have two panel left panel and right panel which provides concept details
			//If  clipboard object present for full perspective destroy method is used
				if(clipboardCopyId)
					clipboardCopyId.destroy();
             clipboardCopyId = new ClipboardJS('.'+'clip-btn-copy-'+panel.divElement.id+'-id');

            clipboardCopyId.on('success', function(e) {
            	
                if(e.trigger.innerText === "Copy SCTID")
                	alertEvent("SCTID copied to clipboard","info");	
                if(e.trigger.innerText === "Copy term")
                	alertEvent("Term copied to clipboard", "info");
                if(e.trigger.innerText === "Copy SCTID + term")
                	alertEvent("SCTID and Term copied to clipboard", "info");
                if(e.trigger.innerText === "Copy Link to share")
                	alertEvent("Link copied to clipboard", "info");
                e.clearSelection();
            });

            clipboardCopyId.on('error', function(e) {
                console.error('Action:', e.action);
                console.error('Trigger:', e.trigger);
            });
			
          //If  clipboard object for detail tab present for full perspective destroy method is used
			if(clipboardCopyDetails)
				clipboardCopyDetails.destroy();
			
			 clipboardCopyDetails = new ClipboardJS('.'+'clip-btn-copy-'+panel.divElement.id+'-details');

            clipboardCopyDetails.on('success', function(e) {
            	
                if(e.trigger.innerText === "Copy SCTID")
                	alertEvent("SCTID copied to clipboard","info");	
                if(e.trigger.innerText === "Copy term")
                	alertEvent("Term copied to clipboard", "info");
                if(e.trigger.innerText === "Copy SCTID + term")
                	alertEvent("SCTID and Term copied to clipboard", "info");
                if(e.trigger.innerText === "Copy Link to share")
                	alertEvent("Link copied to clipboard", "info");
                e.clearSelection();
            });

            clipboardCopyDetails.on('error', function(e) {
                console.error('Action:', e.action);
                console.error('Trigger:', e.trigger);
            });
		}
            
            if (!firstMatch.active) {
                $('#home-attributes-' + panel.divElement.id).css("background-color", "LightPink");
            } else {
                $('#home-attributes-' + panel.divElement.id).css("background-color", "#428bca");
            }

            
            if (typeof i18n_drag_this == "undefined") {
                i18n_drag_this = "Drag this";
            }
            $("[draggable='true']").tooltip({
                placement: 'left auto',
                trigger: 'hover',
                title: i18n_drag_this,
                animation: true,
                delay: 500
            });

            $("[draggable='true']").mouseover(function(e){
//                console.log(e);
                var term = $(e.target).attr("data-term");
                if (typeof term == "undefined"){
                    term = $($(e.target).parent()).attr("data-term");
                }
                icon = iconToDrag(term);
            });
            
            // load descriptions panel
            
            panel.descsPId = divElement.id + "-descriptions-panel";
            
            // START FOR
            var allLangsHtml = "";
            $.each(panel.options.langRefset, function (i){
                var allDescriptions = firstMatch.descriptions.slice(0);
               
                var homeDescriptionsHtml = "";
                //For first call in full and comparing prespective in summary tab the description of all are made fix in summaryDesc
                //So for same concept no extra call is given to get all description in summary tab of concept detail
                if(acceptability==="all"&& perspective!=="switchToBrowsing" && perspective!=="switchToResponsiveLayout")
                	{
                		summaryDesc=allDescriptions;
                	}
                $.each(summaryDesc, function (i, field) {
                            if (field.activeStatus == 1) {
                            if (homeDescriptionsHtml != "") {
                                homeDescriptionsHtml = homeDescriptionsHtml + "<br>";
                            }
                            homeDescriptionsHtml = homeDescriptionsHtml + "&nbsp;&nbsp;&nbsp;&nbsp;" + field.term;
                        }                   
                });
                
                Handlebars.registerHelper('if_eq', function (a, b, opts) {
                    if (opts != "undefined") {
                        if (a == b)
                            return opts.fn(this);
                        else
                            return opts.inverse(this);
                    }
                });
                for(var j=0;j < allDescriptions.length;j++){
                	if(navigator.userAgent.indexOf("Firefox") != -1 ) 
                    {
                		if(allDescriptions[j].typeId=="DEFINITION"){
                    		var index1=allDescriptions[j];
                    		var index2=allDescriptions[0];
                    		allDescriptions[j]=index2;
                    		allDescriptions[0]=index1;
                    		break;
                    	}    
                    }
                	
                };
                    for (var i = 0; i < allDescriptions.length; i++) {
                    	
                        if(allDescriptions[i].isPreferredTerm =="0")
                        {
                            allDescriptions[i].isPreferredTerm=false;
                        }
                        else
                             allDescriptions[i].isPreferredTerm=true;
                    };
                  

                allDescriptions.sort(function (a, b) {
                    if (a.activeStatus && !b.activeStatus)
                        return -1;
                    if (!a.activeStatus && b.activeStatus)
                        return 1;
                    if (a.activeStatus == b.activeStatus) {
                        if ((!a.isPreferredTerm || a.isPreferredTerm) && (!b.isPreferredTerm && b.isPreferredTerm))
                            return -1;
                        if ((!a.isPreferredTerm && a.isPreferredTerm) && (!b.isPreferredTerm || b.isPreferredTerm))
                            return 1;
                        
                        
                        if (a.typeId < b.typeId){
                        	if(a.typeId=="FULLY_SPECIFIED_NAME")
                        	 return -1;
                        	else
                        		return 1;
                         }
                        if (a.typeId > b.typeId){
                        	if(a.typeId=="FULLY_SPECIFIED_NAME")
                           	 return -1;
                        	else
                        		return 1;
                        }
                        
                        if (a.typeId == b.typeId) {
                            if (a.isPreferredTerm && !b.isPreferredTerm)
                                return -1;
                            if (!a.isPreferredTerm && b.isPreferredTerm)
                                return 1;
                            if (a.isPreferredTerm == b.isPreferredTerm) {
                                if (a.term < b.term)
                                    return -1;
                                if (a.term > b.term)
                                    return 1;
                            }
                        }
                    }

                    return 0;
                });   
                var m=0;
                var allDescriptionList=allDescriptions;
                //If acceptability is all after all call to csnoserv second call is given to US language dialect as in detail tab contents of
                //us description loaded
                if(acceptability==="all")
                {    	
                	allDescriptionList = [];

                	$.ajaxSetup({
					async : false
                	});
                	//call given to csnoserv to get description related to us
				$.getJSON(options.serverUrl
						+ "/csnoserv/api/lookup/concept?id="
						+ panel.conceptId
						+ "&langrefset=us&callback=?",
						function(result) {
						}).done(function(result) {
				 
							allDescriptionList=result.descriptions.slice(0);
						});
					$.ajaxSetup({
					async : true
					});
                	
                
                for(var j=0;j < allDescriptionList.length;j++){
                	if(navigator.userAgent.indexOf("Firefox") != -1 ) 
                    {
                		if(allDescriptionList[j].typeId=="DEFINITION"){
                    		var index1=allDescriptionList[j];
                    		var index2=allDescriptionList[0];
                    		allDescriptionList[j]=index2;
                    		allDescriptionList[0]=index1;
                    		break;
                    	}    
                    }
                	
                };
                    for (var i = 0; i < allDescriptionList.length; i++) {
                    	
                        if(allDescriptionList[i].isPreferredTerm =="0")
                        {
                        	allDescriptionList[i].isPreferredTerm=false;
                        }
                        else
                        	allDescriptionList[i].isPreferredTerm=true;
                    };
                  

                    allDescriptionList.sort(function (a, b) {
                    if (a.activeStatus && !b.activeStatus)
                        return -1;
                    if (!a.activeStatus && b.activeStatus)
                        return 1;
                    if (a.activeStatus == b.activeStatus) {
                        if ((!a.isPreferredTerm || a.isPreferredTerm) && (!b.isPreferredTerm && b.isPreferredTerm))
                            return -1;
                        if ((!a.isPreferredTerm && a.isPreferredTerm) && (!b.isPreferredTerm || b.isPreferredTerm))
                            return 1;
                        
                        
                        if (a.typeId < b.typeId){
                        	if(a.typeId=="FULLY_SPECIFIED_NAME")
                        	 return -1;
                        	else
                        		return 1;
                         }
                        if (a.typeId > b.typeId){
                        	if(a.typeId=="FULLY_SPECIFIED_NAME")
                           	 return -1;
                        	else
                        		return 1;
                        }
                        
                        if (a.typeId == b.typeId) {
                            if (a.isPreferredTerm && !b.isPreferredTerm)
                                return -1;
                            if (!a.isPreferredTerm && b.isPreferredTerm)
                                return 1;
                            if (a.isPreferredTerm == b.isPreferredTerm) {
                                if (a.term < b.term)
                                    return -1;
                                if (a.term > b.term)
                                    return 1;
                            }
                        }
                    }

                    return 0;
                }); 
            }
		if(inactiveDesc.length>0)
		{
			for(var i=0 ;i<inactiveDesc.length;i++)
		      {
		 	allDescriptionList.push(inactiveDesc[i]);
								//adding inactiveDescription to  allDescriptions	
		      }
		}
		
         //check if Display Synonyms along with FSN and preferred terms
	if(!$("#"+ panel.divElement.id + "-displaySynonymsOption").is(':checked'))
	{
		var synonymsOption = allDescriptionList[0];//store firstDesc in temp variable
		allDescriptionList=[]; //empty array
		allDescriptionList.push(synonymsOption);	
	}

		//check for display ids 
	if($("#" + panel.divElement.id +"-displayIdsOption").is(":checked"))
	{
		console.log("panel options");
		panel.options.showIds=true;
		console.log(panel.options);
	}else{
		panel.options.showIds=false;	
	}
                var context = {
                    options: panel.options,                   
                   // longLangName: loopSelectedLangRefset,
                    divElementId: panel.divElement.id,
                    allDescriptions: allDescriptionList
                };
                
                allLangsHtml += JST["views/conceptDetailsPlugin/tabs/details/descriptions-panel.hbs"](context);
                $('#home-descriptions-' + panel.divElement.id).html(homeDescriptionsHtml);                
            });
            // END FOR
            $("#" + panel.descsPId).html(allLangsHtml);
            $('#' + panel.descsPId).find("[rel=tooltip-right]").tooltip({ placement: 'right'});
            // load relationships panel and home parents/roles
            if (typeof acceptability !== "undefined") {
            	  
                for (i = 0; i < acceptablityArray .length; i++) {
              	  $('#home-' + panel.divElement.id + '-'+acceptablityArray [i]+'-button').unbind();
              	  $('#home-' + panel.divElement.id + '-'+acceptablityArray [i]+'-button').addClass("btn-default");
                  $('#home-' + panel.divElement.id + '-'+acceptablityArray [i]+'-button').removeClass("btn-primary");
                  $('#home-' + panel.divElement.id + '-'+acceptablityArray [i]+'-button').attr("selected", false);
                    
                }
                //If acceptability is not all that means its selected option in dropdown is same as acceptability
                //else if all its first call and detail tab language should be selected "us" as option 
				if(acceptability !== "all")
				{
                $('#home-' + panel.divElement.id + '-'+acceptability.toUpperCase()+'-button').addClass("btn-primary");
                $('#home-' + panel.divElement.id + '-'+acceptability.toUpperCase()+'-button').removeClass("btn-default");    
                $('#home-' + panel.divElement.id + '-'+acceptability.toUpperCase()+'-button').attr("selected", true);
				}
				else{
					 $('#home-' + panel.divElement.id + '-US-button').addClass("btn-primary");
					 $('#home-' + panel.divElement.id + '-US-button').removeClass("btn-default");        
		             $('#home-' + panel.divElement.id + '-US-button').attr("selected", true);
				}
                                         
                $( '#home-'+panel.divElement.id+'-select-option' )
                .change(function () {
					 
					var u=document.getElementById('home-'+panel.divElement.id+'-select-option').options[0].text;
					 
					var str = "";
					
					if(perspective==="switchToBrowsing" || switchToResponsiveLayout==="switchToResponsiveLayout")
					{
						var data=document.getElementById('home-'+panel.divElement.id+'-select-option')
						 for (i = 0; i < data.options.length; i++) {
						 
						 if( $('#home-' + panel.divElement.id + '-'+data.options[i].text+'-button')[0].selected==true)
						 	{
							 str = data.options[i].text.toLowerCase() ;
						 	}          
					 	}
					}
					 else{
					 for (i = 0; i < acceptablityArray .length; i++) {
						 
						 if( $('#home-' + panel.divElement.id + '-'+acceptablityArray [i]+'-button')[0].selected==true)
						 	{
							 str = acceptablityArray [i].toLowerCase() ;
						 	}          
					 	}
					 }
                  acceptability=str;
                  panel.updateCanvas();
                }) ;
            }
            panel.relsPId = divElement.id + "-rels-panel";         
            panel.inferredParents = [];        
            panel.inferredRoles = [];            
            if (firstMatch.relationships) {                            
                firstMatch.relationships.sort(function (a, b) {
                    if (a.relationshipGroup < b.relationshipGroup) {
                        return -1;
                    } else if (a.relationshipGroup > b.relationshipGroup) {
                        return 1;
                    } else {
                        if (a.type.id == 116680003) {
                            return -1;
                        }
                        if (b.type.id == 116680003) {
                            return 1;
                        }
                        return 0;
                    }
                });
            }   
            Handlebars.registerHelper('push', function (element, array) {
                array.push(element);            
            });
            Handlebars.registerHelper('if_eq', function (a, b, opts) {
                if (opts != "undefined") {
                    if (a == b)
                        return opts.fn(this);
                    else
                        return opts.inverse(this);
                }
            });
            
                var context = {
                options: panel.options,
                firstMatch: firstMatch,
                inferredParents: panel.inferredParents,
                inferredRoles: panel.inferredRoles            
            };
            
            $("#" + panel.relsPId).html(JST["views/conceptDetailsPlugin/tabs/details/rels-panel.hbs"](context));
                Handlebars.registerHelper('if_eq', function (a, b, opts) {
                if (opts != "undefined") {
                    if (a == b)
                        return opts.fn(this);
                    else
                        return opts.inverse(this);
                }
            });
         
            var context = {
                divElementId: panel.divElement.id,               
                inferredParents: panel.inferredParents,
                options: panel.options
            };
         
            $('#home-parents-' + panel.divElement.id).html(JST["views/conceptDetailsPlugin/tabs/home/parents.hbs"](context));
            if (!panel.options.diagrammingMarkupEnabled) {
                $('#home-parents-' + panel.divElement.id).html(panel.stripDiagrammingMarkup($('#home-parents-' + panel.divElement.id).html()));
            }
            $(".treeButton").disableTextSelect();
            $("[draggable='true']").tooltip({
                placement: 'left auto',
                trigger: 'hover',
                title: i18n_drag_this,
                animation: true,
                delay: 500
            });

            $("[draggable='true']").mouseover(function(e){
//                console.log(e);
                var term = $(e.target).attr("data-term"); 
                   
                if (typeof term == "undefined"){
                    term = $($(e.target).parent()).attr("data-term");
                }
                icon = iconToDrag(term);
            });
            $("#home-parents-" + panel.divElement.id).unbind();
            $("#home-parents-" + panel.divElement.id).click(function (event) {
                if ($(event.target).hasClass("treeButton")) {
                    var ev = event.target;
                    //firefox issue!
                    if (navigator.userAgent.indexOf("Firefox") > -1) {
                        ev = $(ev).context.children;
                    }
                    var conceptId = $(ev).closest("li").attr('data-concept-id');
                    event.preventDefault();
                    if ($(ev).hasClass("glyphicon-chevron-up")) {
                        $(ev).closest("li").find("ul").remove();
                        $(ev).removeClass("glyphicon-chevron-up");
                        $(ev).addClass("glyphicon-chevron-right");
                    } else if ($(ev).hasClass("glyphicon-chevron-right")) {
                        $(ev).removeClass("glyphicon-chevron-right");
                        $(ev).addClass("glyphicon-refresh");
                        $(ev).addClass("icon-spin");
                        panel.getParent(conceptId, ev);
                    } else if ($(ev).hasClass("glyphicon-minus")) {
                    }
                } 
            });
            $("#home-parents-" + panel.divElement.id).dblclick(function (event){
               
                var conceptId = $(event.target).closest("li").attr('data-concept-id');
                if( typeof conceptId!="undefined")
                {
					
                        panel.conceptId = conceptId;
						 
						 
						acceptability="all";
                        panel.updateCanvas();                        
                        //Comment below code so that change in Concept detail panel should not be refleted in Taxonomy panel
                        channel.publish(panel.divElement.id, {
                        term: $(event.target).attr('data-term'),
                        module: $(event.target).attr("data-module"),
                        conceptId: conceptId,
                        source: panel.divElement.id,
                        definitionStatus: $(event.target).attr('data-definitionStatus')
                    });
                }
            });

            Handlebars.registerHelper('eqLastGroup', function (a, opts) {
//                console.log(a, panel.lastGroup);
                if(panel.lastGroup == null){
                    panel.lastGroup = a;
                    return opts.fn(this);
                }
                if (a != panel.lastGroup)
                    return opts.fn(this);
                else
                    return opts.inverse(this);
            });
            Handlebars.registerHelper('if_eq', function (a, b, opts) {
                if (opts != "undefined") {
                    if (a == b)
                        return opts.fn(this);
                    else
                        return opts.inverse(this);
                }
            });

                Handlebars.registerHelper('setLastGroup', function (a) {
                panel.lastGroup = a;
            });
            Handlebars.registerHelper('lastColor', function (a) {
                if (a == "get") {
                    return "";
//                    return panel.color;
                } else {
                    if (a == "random"){
                        panel.color = getRandomColor();
                    }else{
                        panel.color = a;
                    }
                }
            });           
           
            if ($('ul#details-tabs-' + panel.divElement.id + ' li.active').attr('id') == "diagram-tab") {

                drawConceptDiagram(firstMatch, $("#diagram-canvas-" + panel.divElement.id), panel.options, panel);
            }
            $("#diagram-tab-link-" + panel.divElement.id).unbind();
            $("#diagram-tab-link-" + panel.divElement.id).click(function (e) {
                $("#diagram-canvas-" + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>");
                setTimeout(function () {
                    $("#diagram-canvas-" + panel.divElement.id).html("");
                    
                    drawConceptDiagram(firstMatch, $("#diagram-canvas-" + panel.divElement.id), panel.options, panel);
                }, 1000);
            });

            $('.more-fields-button').disableTextSelect();
            $('.more-fields-button').popover();

//          firefox popover
            if (navigator.userAgent.indexOf("Firefox") > -1) {
                $(".more-fields-button").optionsPopover({
                    contents: "",
                    disableBackButton: true
                });

                $(".more-fields-button").click(function (e) {
                    var auxHtml = $(e.target).attr('data-content');
                    $("#popoverContent").html(auxHtml);
                });
            }
                $("[draggable='true']").tooltip({
                placement: 'left auto',
                trigger: 'hover',
                title: i18n_drag_this,
                animation: true,
                delay: 500
            });

            $("[draggable='true']").mouseover(function(e){
//                console.log(e);
                var term = $(e.target).attr("data-term");
                if (typeof term == "undefined"){
                    term = $($(e.target).parent()).attr("data-term");
                }
                icon = iconToDrag(term);
            });

            if (typeof(switchLanguage) == "function") {
                switchLanguage(selectedLanguage, selectedFlag, false);
            }
            conceptRequested = 0;
       }).fail(function () {
            panel.relsPId = divElement.id + "-rels-panel";
            panel.attributesPId = divElement.id + "-attributes-panel";
            panel.descsPId = divElement.id + "-descriptions-panel";
            $("#home-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>");
            $("#diagram-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>");
           $('#' + panel.attributesPId).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>");
            $('#' + panel.descsPId).html("");
            $('#' + panel.relsPId).html("");
        });
            if (xhrChildren != null) {
            xhrChildren.abort();
            console.log("aborting children call...");
        }
        xhrChildren = $.getJSON(options.serverUrl+"/csnoserv/api/explore/alldescendants?id="+panel.conceptId+"&count=true&callback=?", function(result) {
        }).done(function (result) {
            // load relationships panel
            
            result.sort(function(a, b) {if (a.childConcept.fullySpecifiedName.toLowerCase() < b.childConcept.fullySpecifiedName.toLowerCase())
                return -1;
            if (a.childConcept.fullySpecifiedName.toLowerCase() > b.childConcept.fullySpecifiedName.toLowerCase())
                return 1;
            return 0;
            });
            Handlebars.registerHelper('if_gr', function(a,b, opts) {
                if (a){
                    if(a > b)
                        return opts.fn(this);
                    else
                        return opts.inverse(this);
                }
            });
            xhrChildren = null;
            panel.childrenPId = divElement.id + "-children-panel";
//                console.log(result);
            var context = {
                displayChildren: panel.options.displayChildren,
                divElementId: panel.divElement.id,
                childrenResult: result,
                selectedView: panel.options.selectedView
            };
            $("#home-children-cant-" + panel.divElement.id).html("(" + result.length + ")");
            $('#' + panel.childrenPId).html(JST["views/conceptDetailsPlugin/tabs/details/children-panel.hbs"](context));
            if(result.length < 30)
        	{
              	
        	document
			.getElementById("home-children-"
					+ panel.divElement.id
					+ "-body").style.display = 'block'
        $("#home-children-" + panel.divElement.id + "-body").html(JST["views/conceptDetailsPlugin/tabs/home/children.hbs"](context));
       
        	}
         else {
							console
									.log(document
											.getElementById("home-children-"
													+ panel.divElement.id
													+ "-body").parentNode);
						console
									.log(document
											.getElementById("home-children-"
													+ panel.divElement.id
													+ "-body").style.display = 'none');
							var element = document.createElement("input");
							element.type = 'button';
							element.value =result.length+' Children'; 
																
							element.setAttribute("class", 'btn btn-link');
							element.id = 'dynamicbutton'; 
							element.onclick = function() { 
								console
								.log(document
										.getElementById("home-children-"
												+ panel.divElement.id
												+ "-body").style.display = 'block');
								
								$(
										"#home-children-"
												+ panel.divElement.id
												+ "-body")
										.html(
												JST["views/conceptDetailsPlugin/tabs/home/children.hbs"]
														(context));
								
								element.remove();
							};

							
							console.log(document.getElementById('dynamicbutton'));
							var mydiv = document
									.getElementById("home-children-"
											+ panel.divElement.id + "-body").parentNode;

							mydiv.appendChild(element);
						
							console.log("home-children-"
									+ panel.divElement.id + "-body");
					

						}
            $(".treeButton").disableTextSelect();
            if (typeof i18n_drag_this == "undefined"){
                i18n_drag_this = "Drag this";
            }
            $("[draggable='true']").tooltip({
                placement: 'left auto',
                trigger: 'hover',
                title: i18n_drag_this,
                animation: true,
                delay: 500
            });

            $("[draggable='true']").mouseover(function(e){
//                console.log(e);
                var term = $(e.target).attr("data-term");
                if (typeof term == "undefined"){
                    term = $($(e.target).parent()).attr("data-term");
                }
                icon = iconToDrag(term);
            });
            $("#home-children-" + panel.divElement.id + "-body").unbind();
            $("#home-children-" + panel.divElement.id + "-body").click(function (event) {
                if ($(event.target).hasClass("treeButton")) {
                    var conceptId = $(event.target).closest("li").attr('data-concept-id');
                    var iconId = panel.divElement.id + "-treeicon-" + conceptId;
                    event.preventDefault();
                    if ($("#" + iconId).hasClass("glyphicon-chevron-down")) {
                        //console.log("close");
                        $(event.target).closest("li").find("ul").remove();
                        $("#" + iconId).removeClass("glyphicon-chevron-down");
                        $("#" + iconId).addClass("glyphicon-chevron-right");
                    } else if ($("#" + iconId).hasClass("glyphicon-chevron-right")) {
                        //console.log("open");
                        $("#" + iconId).removeClass("glyphicon-chevron-right");
                        $("#" + iconId).addClass("glyphicon-refresh");
                        $("#" + iconId).addClass("icon-spin");
                        panel.getChildren($(event.target).closest("li").attr('data-concept-id'), true);
                    } else if ($("#" + iconId).hasClass("glyphicon-minus")) {
                    }
                } 

            });

            $("#home-children-" + panel.divElement.id + "-body").dblclick(function (event){
                var conceptId = $(event.target).closest("li").attr('data-concept-id');                
               if( typeof conceptId!="undefined")
               { 
                panel.conceptId = conceptId;   
 				
				acceptability="all";
                panel.updateCanvas();
				//Comment below code so that change in Concept detail panel should not be refleted in Taxonomy panel
                channel.publish(panel.divElement.id, {
                    term: $(event.target).closest("li").attr('data-term'),
                    module: $(event.target).closest("li").attr("data-module"),
                    conceptId: conceptId,
                    source: panel.divElement.id,
                    definitionStatus: $(event.target).closest("li").attr('data-definitionStatus')
                });
               }
            });
            if (typeof i18n_display_children == "undefined"){
                i18n_display_children = "Display Children";
            }
            $("#" + panel.divElement.id + "-showChildren").tooltip({
                placement : 'right',
                trigger: 'hover',
                title: i18n_display_children,
                animation: true,
                delay: 500
            });
            $("#" + panel.divElement.id + "-showChildren").click(function(){
                panel.options.displayChildren = true;
				acceptability="all";
                panel.updateCanvas();
            });
        }).fail(function () {
            $('#' + panel.childrenPId).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>");
        });
    }

this.getChildren = function(conceptId, forceShow) {
       
        if (xhrChildren != null) {
            xhrChildren.abort();
            console.log("aborting children call...");
        }
        
              xhrChildren = $.getJSON(options.serverUrl+"/csnoserv/api/explore/alldescendants?id="+conceptId+"&count=true&callback=?", function(result) {
              }).done(function(result) {
            result.sort(function(a, b) {
                if (a.childConcept.fullySpecifiedName.toLowerCase() < b.childConcept.fullySpecifiedName.toLowerCase())
                    return -1;
                if (a.childConcept.fullySpecifiedName.toLowerCase() > b.childConcept.fullySpecifiedName.toLowerCase())
                    return 1;
                return 0;
            });
            //console.log(JSON.stringify(result));
            var listIconIds = [];
            //console.log(JSON.stringify(listIconIds));
            var context = {              
                childrenResult: result,
                divElementId: panel.divElement.id,
                selectedView: panel.options.selectedView
            };
               
            Handlebars.registerHelper('if_eq', function(a, b, opts) {
                if (opts != "undefined") {
                    if(a == b)
                        return opts.fn(this);
                    else
                        return opts.inverse(this);
                }
            });
            Handlebars.registerHelper('push', function (element){
                listIconIds.push(element);
            });
            $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh");
            $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin");
            if (result.length > 0) {
                $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-chevron-down");
            } else {
                $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-minus");
            }
            $("#" + panel.divElement.id + "-treenode-" + conceptId).closest("li").append(JST["views/conceptDetailsPlugin/tabs/home/children.hbs"](context));
            $(".treeButton").disableTextSelect();
            $("[draggable='true']").tooltip({
                placement: 'left auto',
                trigger: 'hover',
                title: i18n_drag_this,
                animation: true,
                delay: 500
            });

            $("[draggable='true']").mouseover(function(e){
//                console.log(e);
                var term = $(e.target).attr("data-term");
                if (typeof term == "undefined"){
                    term = $($(e.target).parent()).attr("data-term");
                }
                icon = iconToDrag(term);
            });

        }).fail(function() {
            $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin");
            $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh");
            $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-minus");
        });
    }

    this.getParent = function(conceptId, target){
        if (xhrParents != null) {
            xhrParents.abort();
            console.log("aborting this.getParent call...");
        }  
        xhrParents = $.getJSON(options.serverUrl+"/csnoserv/api/explore/parents?id="+conceptId+"&callback=?", function(result) {         
        }).done(function(result) {
            result.sort(function(a, b) {
                if (a.fullySpecifiedName.toLowerCase() < b.fullySpecifiedName.toLowerCase())
                    return -1;
                if (a.fullySpecifiedName.toLowerCase() > b.fullySpecifiedName.toLowerCase())
                    return 1;
                return 0;
            });
            var auxHtml = "";
            var ind = $(target).attr('data-ind');
            if (result.length > 0){
                if ($(target).attr('data-firstt')){
                    auxHtml = "<ul style='margin-left: 95px; list-style-type: none; padding-left: 15px'>";
                }else{
                    auxHtml = "<ul style='list-style-type: none; padding-left: 15px'>";
                }
                $.each(result, function(i, field){
//                    console.log(field);
                    auxHtml = auxHtml + "<li class='treeLabel' data-module='" + field.moduleId + "' data-concept-id='" + field.id + "' data-term='" + field.fullySpecifiedName + "'><button class='btn btn-link btn-xs treeButton' style='padding:2px'>";
                    if (field.id == "138875005" || field.id == "9999999999"){
                        auxHtml = auxHtml + "<i class='glyphicon glyphicon-minus treeButton' data-ind='" + ind + "'></i></button>";
                    }else{
                        auxHtml = auxHtml + "<i class='glyphicon glyphicon-chevron-right treeButton' data-ind='" + ind + "'></i></button>";
                    }
                    if (field.definitionStatusId == "PRIMITIVE"){
                        auxHtml = auxHtml + "<span class='badge alert-warning' draggable='true' ondragstart='drag(event)' data-module='" + field.moduleId + "' data-concept-id='" + field.id + "' data-term='" + field.fullySpecifiedName + "'>&nbsp;&nbsp;</span>&nbsp;&nbsp";
                    }else{
                        auxHtml = auxHtml + "<span class='badge alert-warning' draggable='true' ondragstart='drag(event)' data-module='" + field.moduleId + "' data-concept-id='" + field.id + "' data-term='" + field.fullySpecifiedName + "'>&equiv;</span>&nbsp;&nbsp";
                    }
                    auxHtml = auxHtml + "<a id='" + ind + panel.divElement.id + "-treeicon-" + field.id + "' href='javascript:void(0);' style='color: inherit;text-decoration: inherit;'>";
                    auxHtml = auxHtml + "<span class='treeLabel selectable-row' data-module='" + field.moduleId + "' data-concept-id='" + field.id + "' data-term='" + field.fullySpecifiedName + "'>" + field.fullySpecifiedName + "</span></a></li>";
                });
                auxHtml = auxHtml + "</ul>";
            }
            $(target).removeClass("glyphicon-refresh");
            $(target).removeClass("icon-spin");
            if (result.length > 0) {
                $(target).addClass("glyphicon-chevron-up");
            } else {
                $(target).addClass("glyphicon-minus");
            }
            $(target).closest("li").prepend(auxHtml);
            $(".treeButton").disableTextSelect();
            $("[draggable='true']").tooltip({
                placement: 'left auto',
                trigger: 'hover',
                title: i18n_drag_this,
                animation: true,
                delay: 500
            });

            $("[draggable='true']").mouseover(function(e){
//                console.log(e);
                var term = $(e.target).attr("data-term");
                if (typeof term == "undefined"){
                    term = $($(e.target).parent()).attr("data-term");
                }
                icon = iconToDrag(term);
            });
        }).fail(function(){
        });
    }
    this.stripDiagrammingMarkup = function(htmlString) {
        if (!htmlString)
            htmlString = "";
        htmlString = htmlString.replace(new RegExp(panel.escapeRegExp("sct-primitive-concept-compact"), 'g'), "");
        htmlString = htmlString.replace(new RegExp(panel.escapeRegExp("sct-defined-concept-compact"), 'g'), "");
        htmlString = htmlString.replace(new RegExp(panel.escapeRegExp("sct-attribute-compact"), 'g'), "");
        return htmlString;
    };
    this.escapeRegExp = function(str) {
        return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    };
    this.loadMarkers = function (){
        var auxMarker = "", right = 0, top = 0, aux = false, visible = false;
        $.each(componentsRegistry, function(i, field){
            var panelId = field.divElement.id;
            if ($("#" + panelId + "-subscribersMarker").is(':visible')){
                visible = true;
            }
        });
        if (panel.subscribers.length == 0){
            right = 14;
            $("#" + panel.divElement.id + "-ownMarker").hide();
        }else{
            if (!visible){
                $("#" + panel.divElement.id + "-ownMarker").hide();
            }
            aux = true;
        }
        if ($("#" + panel.divElement.id + "-subscribersMarker").is(':visible')){
            $("#" + panel.divElement.id + "-panelTitle").html($("#" + panel.divElement.id + "-panelTitle").html().replace(/&nbsp;/g, ''));
            if (aux){
                $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html());
            }
            $.each(panel.subscriptionsColor, function(i, field){
                auxMarker = auxMarker + "<i class='glyphicon glyphicon-bookmark' style='color: "+ field +"; top:" + top + "px; right: " + right + "px;'></i>";
                $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html());
                top = top + 5;
                right = right + 10;
            });
            $("#" + panel.divElement.id + "-subscribersMarker").html(auxMarker);
        }
    }

    // Subsription methods
    this.subscribe = function(panelToSubscribe) {
        var panelId = panelToSubscribe.divElement.id;
        var alreadySubscribed = false;
        $.each(panel.subscriptionsColor, function(i, field){
            if (field == panelToSubscribe.markerColor){
                alreadySubscribed = true;
            }
        });
        console.log('Subscribing to id: ' + panelId, !alreadySubscribed);
        if (!alreadySubscribed) {
            var subscription = channel.subscribe(panelId, function(data, envelope) {
//                console.log("listening in " + panel.divElement.id);
                panel.conceptId = data.conceptId;
                if ($("#home-children-" + panel.divElement.id + "-body").length > 0){
                }else{
                    panel.setupCanvas();
                    if (panel.loadMarkers)
                        panel.loadMarkers();
                }
				 
				acceptability="all";
                panel.updateCanvas();
            });
            panel.subscriptions.push(subscription);
            panelToSubscribe.subscribers.push(panel.divElement.id);
            panel.subscriptionsColor.push(panelToSubscribe.markerColor);
        }
        $("#" + panelId + "-ownMarker").show();
        $("#" + panel.divElement.id + "-subscribersMarker").show();
        $("#" + panelId + "-ownMarker").show();
    }

   } 
function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

(function($) {
    $.fn.addConceptDetails = function(conceptId, options) {
        this.filter("div").each(function() {
            var cd = new conceptDetails(this, conceptId, options);
            cd.setupCanvas();
        });
    };
}(jQuery));

$(document).keypress(function(event) {
    if (event.which == '13') {
        event.preventDefault();
    }
}
);

