/*
 * 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 searchPanel(divElement, options) {
    var thread = null;
    var panel = this;
    var lastT = "";
    var xhr = null;
    var lastSemanticTag=""; 
    var lastStatus="active";
    var groupByConceptStateChange=false;
    var statusStateChange=false;
    if (typeof componentsRegistry == "undefined") {
        componentsRegistry = [];
    }

    this.markerColor = 'black';
    if (typeof globalMarkerColor == "undefined") {
        globalMarkerColor = 'black';
    }
    this.type = "search";
    this.divElement = divElement;
    this.options = jQuery.extend(true, {}, options);

    var componentLoaded = false;
    panel.shown0 = false;
    $.each(componentsRegistry, function (i, field) {
        if (field.divElement.id == panel.divElement.id) {
            componentLoaded = true;
        }
    });
    if (componentLoaded == false) {
        componentsRegistry.push(panel);
    }
    panel.subscribers = [];
    panel.subscriptions = [];
    panel.subscriptionsColor = [];
    this.history = [];

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

        $('#' + panel.divElement.id + '-searchBox').keyup(function () {
            clearTimeout(thread);
            var $this = $(this);
            thread = setTimeout(function () {
                panel.search($this.val(),false);
            }, 500);
        });
  $("#" + panel.divElement.id).find('.semtag-button').click(function (event) {
            console.log("Semtag click: " + $(this).html());
        });

        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.updateStatusFilterLabel();

        $("#" + panel.divElement.id + "-activeOnlyButton").click(function (event) {
            panel.options.statusSearchFilter = 'active';  
            statusStateChange=true;           
            panel.updateStatusFilterLabel();
        });

        $("#" + panel.divElement.id + "-activeInactiveButton").click(function (event) {
            panel.options.statusSearchFilter = 'both';
            statusStateChange=true;           
            panel.updateStatusFilterLabel();
        });

        $("#" + panel.divElement.id + "-inactiveOnlyButton").click(function (event) {
            panel.options.statusSearchFilter = 'inactive';
            statusStateChange=true;
            panel.updateStatusFilterLabel();
        });
    
        $("#" + panel.divElement.id + "-ownMarker").css('color', panel.markerColor);
    };

    this.updateStatusFilterLabel = function() {
        if (typeof i18n_active_and_inactive == "undefined") {
            i18n_active_and_inactive = 'Active and inactive components';
        }
        if (typeof i18n_inactive_only == "undefined") {
            i18n_inactive_only = 'Inactive components only';
        }
        if (typeof i18n_active_only == "undefined") {
            i18n_active_only = 'Active components only';
        }
        if (panel.options.statusSearchFilter == 'both') {
            $("#" + panel.divElement.id + '-searchStatus').html(i18n_active_and_inactive);
            $("#" + panel.divElement.id + '-navStatusFilterLabel').html(i18n_active_and_inactive);
        } else if (panel.options.statusSearchFilter == 'inactive') {
            $("#" + panel.divElement.id + '-searchStatus').html(i18n_inactive_only);
            $("#" + panel.divElement.id + '-navStatusFilterLabel').html(i18n_inactive_only);
        } else {
            panel.options.statusSearchFilter = 'active';
            $("#" + panel.divElement.id + '-searchStatus').html(i18n_active_only);
            $("#" + panel.divElement.id + '-navStatusFilterLabel').html(i18n_active_only);
        }
        var searchTerm = $('#' + panel.divElement.id + '-searchBox').val();
        if (searchTerm.length > 0 && (lastStatus!=panel.options.statusSearchFilter)) {
            panel.search(searchTerm,true);

        }
    }

    var semanticTagCount={};
    

    this.search = function (t, forceSearch) {
        if (typeof panel.options.semTagFilter == "undefined") {
            panel.options.semTagFilter = "none";
        }
    
                    $("#" + panel.divElement.id + "-clearButton").click(function () {
                            panel.options.semTagFilter = "none";                        
                    
                        $('#' + panel.divElement.id + '-searchBox').val('');
                        $('#' + panel.divElement.id + '-searchFilters').html("");
                        $('#' + panel.divElement.id + '-resultsTable').html("");
                        $('#' + panel.divElement.id + '-searchBar').html("");
                        $('#' + panel.divElement.id + '-searchBar2').html("");
                        $('#' + panel.divElement.id + '-typeIcon').removeClass('glyphicon-ok');
                        $('#' + panel.divElement.id + '-typeIcon').removeClass('text-success');
                        $('#' + panel.divElement.id + '-typeIcon').addClass('glyphicon-remove');
                        $('#' + panel.divElement.id + '-typeIcon').addClass('text-danger');                        
                        t = "";
                        lastT="";
        });


        if (t != "" && (t != lastT || forceSearch)) {
            if (t.length < 3) {
                $('#' + panel.divElement.id + '-typeIcon').removeClass('glyphicon-ok');
                $('#' + panel.divElement.id + '-typeIcon').removeClass('text-success');
                $('#' + panel.divElement.id + '-typeIcon').addClass('glyphicon-remove');
                $('#' + panel.divElement.id + '-typeIcon').addClass('text-danger');
            } else {
                $('#' + panel.divElement.id + '-typeIcon').removeClass('glyphicon-remove');
                $('#' + panel.divElement.id + '-typeIcon').removeClass('text-danger');
                $('#' + panel.divElement.id + '-typeIcon').addClass('glyphicon-ok');
                $('#' + panel.divElement.id + '-typeIcon').addClass('text-success');                
                
                var search_box_text = $('#' + panel.divElement.id + '-searchBox').val();
                if (search_box_text != lastT && search_box_text!="") {
                    panel.options.semTagFilter = "none";
                };
                lastT = t;
                                                //console.log(t);
                var d = new Date();
                var time = d.getTime();
                var groupByConcept=false;

                panel.history.push({searchTerm: t, time: time});
                //t = t.charAt(0).toUpperCase() + t.slice(1);
                //console.log("Capitalized t: " + t);
                $('#' + panel.divElement.id + '-searchFilters').html("");
                $('#' + panel.divElement.id + '-resultsTable').html("<i class='glyphicon glyphicon-refresh icon-spin'></i>");             
                var resultsHtml = "";
               if (xhr != null) {
                    xhr.abort();
                    console.log("aborting call...");
                }
                $('#' + panel.divElement.id + '-searchBar').html("<span class='text-muted'>Searching..</span>");
                
                t = t.trim();
            
                      //  t = t.toLowerCase();
                      //  t = t.replace("(","");
                      //  t = t.replace(")","");
                   // }



                          if ($("#" + panel.divElement.id + "-groupConcept").is(":checked"))
                            {  
                                   groupByConcept=true;                                                           
                            }  
                            else
                            {
                                groupByConcept=false;                                                                
                            }
                            lastSemanticTag="none";     
                      
                    var startTime = Date.now();
              
                        if("none" ==panel.options.semTagFilter )
                        {
                            
                            searchUrl=options.serverUrl+"/csnoserv/api/search/search?term="+encodeURIComponent(t)+"&state="+panel.options.statusSearchFilter+"&semantictag=all&acceptability=all&groupbyconcept="+groupByConcept+"&returnlimit=-1"+"&callback=?";
                        }
                        else
                        {
                               
                               lastSemanticTag=panel.options.semTagFilter;
                               searchUrl=options.serverUrl+"/csnoserv/api/search/search?term="+encodeURIComponent(t)+"&state="+panel.options.statusSearchFilter+"&semantictag="+panel.options.semTagFilter+"&acceptability=all&groupbyconcept="+groupByConcept+"&returnlimit=-1"+"&callback=?";
                        }   
                        console.log(searchUrl);
                    lastStatus =panel.options.statusSearchFilter;
                    xhr = $.getJSON(searchUrl,function (result) {

                    }).done(function (result) {   
                             
                        if("none" !=panel.options.semTagFilter && (groupByConceptStateChange || statusStateChange))
                        {
                                groupByConceptStateChange=false;
                                statusStateChange=false;
                            searchUrl=options.serverUrl+"/csnoserv/api/search/search?term="+encodeURIComponent(t)+"&state="+panel.options.statusSearchFilter+"&semantictag=all&acceptability=all&groupbyconcept="+groupByConcept+"&returnlimit=-1"+"&callback=?";
                                       $.ajaxSetup({
                                            async: false
                                        });                     

                                     xhr = $.getJSON(searchUrl,function (resultTotal) {
                                        }).done(function (resultTotal) {  
                                            semanticTagCount={};                                            
                                             for (var i = 0; i <resultTotal.length; i++) {                               
                                                if(resultTotal[i].hierarchy in semanticTagCount)
                                                    {
                                                        var count= semanticTagCount[resultTotal[i].hierarchy];
                                                        ++count;
                                                        semanticTagCount[resultTotal[i].hierarchy]=count; 
                                                    }
                                                else
                                                    {
                                                        semanticTagCount[resultTotal[i].hierarchy] = 1;
                                                    }
                                            } 
                                        });                                        
                                 $.ajaxSetup({
                                            async: true
                                        });                     
                                 //   alert("-");
                            }
                            if("none" ==panel.options.semTagFilter)
                            {
                                       semanticTagCount={};

                                             for (var i = 0; i <result.length; i++) {                               
                                                if(result[i].hierarchy in semanticTagCount)
                                                    {
                                                        var count= semanticTagCount[result[i].hierarchy];
                                                        ++count;
                                                        semanticTagCount[result[i].hierarchy]=count; 
                                                    }
                                                else
                                                    {
                                                        semanticTagCount[result[i].hierarchy] = 1;
                                                    }
                                            }  

                            }
                                                                                         

                         

                                    function sortObject(object){                                    
                                    var sortable = [], sortedObj = {};
                                    for (var attr in object)
                                        sortable.push([attr, object[attr]]);                                  
                                    sortable.sort(function(a, b) {return b[1] - a[1]});
                                    $.each(sortable, function (i, field){
                                        sortedObj[field[0]] = field[1];
                                    });
                                    return sortedObj;
                                }

                                semanticTagCount =sortObject(semanticTagCount);    
                                

                                

                        $('#' + panel.divElement.id + '-resultsTable').find('.more-row').remove();
                        var endTime = Date.now();
                        var elapsed = (endTime - startTime)/1000;
                        Handlebars.registerHelper('if_eq', function(a, b, opts) {
                            if (opts != "undefined") {
                                if(a == b)
                                    return opts.fn(this);
                                else
                                    return opts.inverse(this);
                            }
                        });
                   
                    //    var auxArray = [];
                  
                        var context = {                            
                            semanticTagCount: semanticTagCount,
                            result: result,
                            elapsed: elapsed,
                            divElementId: panel.divElement.id,
                            options: panel.options
                        };
                        $('#' + panel.divElement.id + '-searchBar').html(JST["views/searchPlugin/body/bar.hbs"](context));                           
                        $('#' + panel.divElement.id + '-searchBar2').html(JST["views/searchPlugin/body/bar2.hbs"](context));                        
                      
                        $("#" + panel.divElement.id + '-searchBar2').find('.semtag-link').click(function (event) {
                            panel.options.semTagFilter = $(event.target).attr('data-semtag');
                            if(!(lastT==t &&  (panel.options.semTagFilter ==lastSemanticTag && panel.options.semTagFilter!="none") ))
                            panel.search(t,true);
                        });
                     
                        $("#" + panel.divElement.id + '-searchBar2').find('.remove-semtag').click(function (event) {
                            panel.options.semTagFilter = "none";
                            lastSemanticTag="none"
                            panel.search(t, true);
                        });
                                              xhr = null;
                        var matchedDescriptions = result;
                        var remaining=0;
                      
                        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){
                                if(a > parseInt(b))
                                    return opts.fn(this);
                                else
                                    return opts.inverse(this);
                            }
                        });
                        Handlebars.registerHelper('if_gre', function(a,b, opts) {
                            if (a){
                                if(parseInt(a) >= b)
                                    return opts.fn(this);
                                else
                                    return opts.inverse(this);
                            }
                        });
                      
                        Handlebars.registerHelper('hasFilters', function(options, opts){
                            if (options.semTagFilter != "none")
                                {
                                return  opts.fn(this);;
                            } else {
                                return opts.inverse(this);
                            }
                        });
                        var context = {
                            options: panel.options,
                            result: result,
                            divElementId: panel.divElement.id,
                      
                        };

                 				
                            $('#' + panel.divElement.id + '-resultsTable').html(JST["views/searchPlugin/body/default.hbs"](context));
                  
                        $("#" + panel.divElement.id + "-groupConcept").click(function(){
                            groupByConceptStateChange=true;
                            panel.search(t, true);

                        });
                        $("#" + panel.divElement.id + "-remove-all-filters").unbind();
                        $("#" + panel.divElement.id + "-remove-all-filters").click(function (event) {
                            panel.options.semTagFilter = "none";
                            panel.options.langFilter = "none";
                            panel.options.moduleFilter = "none";
                            panel.options.refsetFilter = "none";
                            panel.search(t, true);
                        });
                     
                        $('#' + panel.divElement.id + '-resultsTable').find(".result-item").click(function (event) {
                               channel.publish(panel.divElement.id, {
                                term: $(event.target).attr("data-term"),
                                module: $(event.target).attr("data-module"),
                                conceptId: $(event.target).attr('data-concept-id'),
                                definitionStatus: $(event.target).attr('data-definitionStatus'),
                                source: panel.divElement.id
                            });
                        });                      

                    }).fail(function () {
                        resultsHtml = resultsHtml + "<tr><td class='text-muted'>No results</td></tr>";
                        $('#' + panel.divElement.id + '-resultsTable').html(resultsHtml);
                        $('#' + panel.divElement.id + '-searchBar2').html("");
                    });
                }
            }
        }
    //}


    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.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.setupCanvas();
 }

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

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

(function($) {
    $.fn.addSearch = function(options) {
        this.filter("div").each(function() {
            var tx = new conceptDetails(this, options);            
        });
    };
}(jQuery));
