/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function taxonomyPanel(divElement, conceptId, options) {
    
    var nodeCount = 0;
    var panel = this;
    var xhr = null;    
    var displayCount="On";
    //displaySyncTaxonomyStatus variable used for,should sync taxonomy button display on taxnomy panel
    var displaySyncTaxonomyStatus=true;
    if(panel.constructor.caller.name==="switchToComparingTaxonomies")
    	displaySyncTaxonomyStatus=false;
    if (typeof componentsRegistry == "undefined") {
        componentsRegistry = [];
    }

    this.markerColor = 'black';
    if (typeof globalMarkerColor == "undefined") {
        globalMarkerColor = 'black';
    }

    this.type = "taxonomy";
    this.divElement = divElement;
    this.options = jQuery.extend(true, {}, options);
       
    var componentLoaded = false;
    $.each(componentsRegistry, function(i, field) {
        if (field.divElement.id == panel.divElement.id) {
            componentLoaded = true;
        }
    });
    if (componentLoaded == false) {
        componentsRegistry.push(panel);
    }
    panel.default = {};
    panel.default.conceptId = conceptId;
    panel.subscribers = [];
    panel.subscriptions = [];
    panel.subscriptionsColor = [];
    this.history = [];


    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);
                
                  if (typeof data.conceptId != "undefined" && data.conceptId!="138875005" ) {
					  var taxonomySync=document.getElementById("displayTaxonomyStatus").textContent;
                        //Depending on Taxonomy sync button  below code change in Concept detail panel and search panel will be refleted in Taxonomy panel
                if(taxonomySync==="On")
                   {
                    $.getJSON(options.serverUrl+"/csnoserv/api/explore/parents?id="+data.conceptId+"&callback=?", function(result) {        
                    // done
                    }).done(function(result) {

                        var selectedDefStatus=data.definitionStatus;
                     if(selectedDefStatus="PRIMITIVE")
                    {
                        selectedDefStatus="900000000000074008";   
                    }
                    else
                    {
                        selectedDefStatus="900000000000073002";    
                    }
                        panel.setupParents(result, {conceptId: data.conceptId, defaultTerm: data.term, definitionStatus: selectedDefStatus});                        
                    }).fail(function() {
                    });
				  }}
                if(typeof data.conceptId == "undefined" || data.conceptId=="138875005")
                {
                   panel.setupParents([], {conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "900000000000074008"});
                }
                
               conceptId=data.conceptId;
            });
            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();
    }


    this.setupCanvas = function() {
        var context = {
            divElementId: panel.divElement.id,
            displaySyncTaxonomyStatus: displaySyncTaxonomyStatus 
            
        };
        $(divElement).html(JST["views/taxonomyPlugin/main.hbs"](context));


        $("#" + panel.divElement.id + "-resetButton").disableTextSelect();


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


          if (typeof i18n_reset == "undefined") {
            i18n_reset = 'Reset';
        }

        $("#" + panel.divElement.id + "-resetButton").tooltip({
            placement : 'left',
            trigger: 'hover',
            title: i18n_reset,
            animation: true,
            delay: 1000
        });

        $("#" + panel.divElement.id + "-resetButton").click(function() {
        	document.getElementById( panel.divElement.id + "-resetButton").disabled=true;
           panel.setupParents([], {conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "900000000000074008"});
         //   panel.setToConcept(panel.default.conceptId);
        });
        
       
        	 $("#" + panel.divElement.id + "-descendantsCountTrue")
             .click(function () {
            	 document.getElementById(panel.divElement.id + "-displayStatus").textContent="On";
            	 var hidearray=document.querySelectorAll('[data-'+panel.divElement.id+'-descendants]');
            	 var index;
            	 //displayCount="On";
            	 for (index = 0; index < hidearray.length; index++) { 
            		    hidearray[index].style.visibility = "visible";   
            		} 
             });
        	 $("#" + panel.divElement.id + "-descendantsCountFalse")
             .click(function () {
            	 document.getElementById(panel.divElement.id + "-displayStatus").textContent="Off";
            	 var hidearray=document.querySelectorAll('[data-'+panel.divElement.id+'-descendants]');
            	 var index;
            	 //displayCount="Off";
            	 for (index = 0; index < hidearray.length; index++) { 
            		    hidearray[index].style.visibility = "hidden";   
            		} 
             });
        	 $("#" + panel.divElement.id + "-TaxonomySyncTrue")
             .click(function () {
            	 document.getElementById("displayTaxonomyStatus").textContent="On";
            	
             });
        	 $("#" + panel.divElement.id + "-TaxonomySyncFalse")
             .click(function () {
            	 document.getElementById("displayTaxonomyStatus").textContent="Off";
            	
             });
        	
     
    }

    this.setupParents = function(parents, focusConcept) {
        var lastParent;
        $.each(parents, function(i, parent){
            lastParent = parent;
        });
        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('if_gr', function(a,b, opts) {
            if(a > b)
                return opts.fn(this);
            else
                return opts.inverse(this);
        });
        Handlebars.registerHelper('if_def', function(conceptId, opts){
            if (conceptId == panel.default.conceptId)
                return opts.fn(this);
            else
                return opts.inverse(this);
        });
        var context = {
            parents: parents,
            focusConcept: focusConcept,
            divElementId: panel.divElement.id
        };
        Handlebars.registerHelper('slice', function (a, b) {
            $("#" + panel.divElement.id + "-panelBody").html($("#" + panel.divElement.id + "-panelBody").html().slice(a, b));
        });
        $("#" + panel.divElement.id + "-panelBody").html(JST["views/taxonomyPlugin/body/parents.hbs"](context));
        //console.log(JST["views/taxonomyPlugin/body/parents.hbs"](context));
        $(".treeButton").disableTextSelect();
        $("#" + panel.divElement.id + "-panelBody").unbind("dblclick");
        $("#" + panel.divElement.id + "-panelBody").dblclick(function(event) {
                
                if ($(event.target).hasClass("treeLabel")) {
                var d = new Date();
                var time = d.getTime();
                var selectedModule = $(event.target).attr('data-module');
                var selectedId = $(event.target).attr('data-concept-id');
                var selectedLabel = $(event.target).attr('data-term');
                var selectedDefStatus= $(event.target).attr('data-definitionStatus');
                    if(selectedDefStatus="PRIMITIVE")
                    {
                        selectedDefStatus="900000000000074008";   
                    }
                    else
                    {
                        selectedDefStatus="900000000000073002";    
                    }
                panel.history.push({term: selectedLabel, conceptId: selectedId, time: time});
                if (typeof selectedId != "undefined") {
                    $.getJSON(options.serverUrl+"/csnoserv/api/explore/parents?id="+selectedId+"&callback=?", function(result) {        
                    // done
                    }).done(function(result) {
                        panel.setupParents(result, {conceptId: selectedId, defaultTerm: selectedLabel, definitionStatus: selectedDefStatus, module: selectedModule});
                    }).fail(function() {
                    });
                }
            }

        });  
        $("#" + panel.divElement.id + "-panelBody").unbind("click");
        $("#" + panel.divElement.id + "-panelBody").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'));
                } else if ($("#" + iconId).hasClass("glyphicon-chevron-up")){
                    $("#" + iconId).removeClass("glyphicon-chevron-up");
                    $("#" + iconId).addClass("glyphicon-refresh");
                    $("#" + iconId).addClass("icon-spin");
                    panel.wrapInParents($(event.target).closest("li").attr('data-concept-id'), $(event.target).closest("li"));
                } else if ($("#" + iconId).hasClass("glyphicon-minus")){
                  //  $("#" + iconId).removeClass("glyphicon-minus");
                  //  $("#" + iconId).addClass("glyphicon-chevron-right");
                }
            } else if ($(event.target).hasClass("treeLabel")) {                
                var selectedId = $(event.target).attr('data-concept-id');                
                if (typeof selectedId != "undefined") {
                    channel.publish(panel.divElement.id, {
                        term: $(event.target).attr('data-term'),
                        module: $(event.target).attr("data-module"),
                        conceptId: selectedId, 
                        source: panel.divElement.id                    
                    });                 
                }
            }

        });

        var iconId = panel.divElement.id + "-treeicon-" + focusConcept.conceptId;
        $("#" + iconId).removeClass("glyphicon-chevron-right");
        $("#" + iconId).addClass("glyphicon-refresh");
        $("#" + iconId).addClass("icon-spin");
        //console.log("getChildren..." + focusConcept.conceptId);
        panel.getChildren(focusConcept.conceptId);
    };

    this.getChildren = function(conceptId) {
        if (typeof panel.options.selectedView == "undefined") {
            panel.options.selectedView = "inferred";
        }  
		
			displayCount=document.getElementById(panel.divElement.id + "-displayStatus").textContent;
            $.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 = {
                result: result,
                divElementId: panel.divElement.id,
                selectedView: panel.options.selectedView,
                displayCount:displayCount
            };

            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/taxonomyPlugin/body/children.hbs"](context));

            $(".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);
            });
            result={};
            if(document.getElementById( panel.divElement.id + "-resetButton").disabled==true)
            	document.getElementById( panel.divElement.id + "-resetButton").disabled=false;
        }).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.wrapInParents = function(conceptId, liItem) {
        var topUl = $("#" + panel.divElement.id + "-panelBody").find('ul:first');
        $.getJSON(options.serverUrl+"/csnoserv/api/explore/parents?id="+conceptId+"&callback=?", function(parents) {
            // done
        }).done(function(parents) {
            if (parents.length > 0) {
                var firstParent = "empty";
                var parentsStrs = [];
                $.each(parents, function(i, parent) {
                    var parentLiHtml = "<li data-concept-id='" + parent.id + "' data-term='" + parent.fullySpecifiedName + "' class='treeLabel'>";
                    parentLiHtml = parentLiHtml + "<button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-chevron-";
                    if (parent.id == "138875005" || parent.id == "9999999999"){
                        parentLiHtml = parentLiHtml + "down";
                    }else{
                        parentLiHtml = parentLiHtml + "up";
                    }
                    parentLiHtml = parentLiHtml + " treeButton'  id='" + panel.divElement.id + "-treeicon-" + parent.id + "'></i></button>";
                    if (parent.definitionStatusId == "PRIMITIVE") {
                        parentLiHtml = parentLiHtml + '<span class="badge alert-warning" data-concept-id="' + parent.id + '" data-term="' + parent.fullySpecifiedName + '" draggable="true" ondragstart="drag(event)" class="treeLabel selectable-row" id="' + panel.divElement.id + '-treenode-' + parent.id + '">&nbsp;&nbsp;</span>&nbsp;&nbsp;';
                    } else {
                        parentLiHtml = parentLiHtml + '<span class="badge alert-warning" data-concept-id="' + parent.id + '" data-term="' + parent.fullySpecifiedName + '" draggable="true" ondragstart="drag(event)" class="treeLabel selectable-row" id="' + panel.divElement.id + '-treenode-' + parent.id + '">&equiv;</span>&nbsp;&nbsp;';
                    }                   
                    parentLiHtml = parentLiHtml + '<a href="javascript:void(0);" style="color: inherit;text-decoration: inherit;"><span class="treeLabel selectable-row" data-concept-id="' + parent.id + '" data-term="' + parent.fullySpecifiedName + '"> ' + parent.fullySpecifiedName + '</span></a>';
                    parentLiHtml = parentLiHtml + "</li>";
                    parentsStrs.push(parentLiHtml);
                    if (firstParent == "empty") {
                        firstParent = parent.id;
                    }
                });

                var staticChildren = topUl.children().slice(0);
                topUl.append(parentsStrs[0]);
                $('#' + panel.divElement.id + '-treenode-' + firstParent).closest('li').append("<ul id='parent-ul-id-" + firstParent + "' style='list-style-type: none; padding-left: 15px;'></ul>");
                var newMainChild;
                $.each(staticChildren, function(i, child) {
                    if ($(child).attr('data-concept-id') == conceptId) {
                        newMainChild = $(child);
                        var newUl = $('#' + panel.divElement.id + '-treenode-' + firstParent).closest('li').find('ul:first');
                        newUl.append($(child));
                        $(child).find('i:first').removeClass("glyphicon-chevron-up");
                        $(child).find('i:first').addClass("glyphicon-chevron-down");
                    }
                });
                $.each(staticChildren, function(i, child) {
                    if ($(child).attr('data-concept-id') != conceptId) {
                        $.each($(child).children(), function(i, subchild) {
                            if ($(subchild).is('ul')) {
                                newMainChild.append(subchild);
                            }
                        });
                        $('#' + panel.divElement.id + '-treenode-' +$(child).attr('data-concept-id')).closest('li').remove();
                    }
                });
                $.each(parentsStrs, function(i, parentsStr) {
                    if (parentsStr != parentsStrs[0]) {
                        topUl.prepend(parentsStr);
                    }
                });
                $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh");
                $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin");
                $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-chevron-down");
            } else {
                $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh");
                $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin");
                $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-chevron-up");
            }
            $("[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.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);
        }
    }

    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();      
     if ((!conceptId || conceptId == 138875005) && (options.currentPerspective!="full") ){
        this.setupParents([], {conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "900000000000074008"});
        }
    if (xhr != null) {
            xhr.abort();
            console.log("aborting call...");
        }       
   
}
(function($) {
    $.fn.addTaxonomy = function(options) {
        this.filter("div").each(function() {
            var tx = new conceptDetails(this, options);
        });
    };
}(jQuery));
