$j.fn.jfinder = function(options)
{ var settings = $j.extend(
           {  'debug' : 0,
              'upload_url'    :  '/services/quiz/get_themes/',
              'upload_params'    :  {},
              'element_click_cmd' : '',
              'checkbox_name' : 'element',
              createItemContent: createItemContent
           }, options);

//console.log(this) ;

    var container =this[0] ;
    var f = finder(container, remoteSource, settings);

     // scroll to the right if necessary
     f.on('column-created', function columnCreated()
     {  container.scrollLeft = container.scrollWidth - container.clientWidth;
        console.log('column-created');
         $j('.v2').prepare_ajax({}) ;
      });


     f.on('leaf-selected', function selected(item)
     {
       console.log('Leaf selected', item);
     });

     f.on('item-selected', function selected(item)
     {  var item_id=0 ;
        var item_type='' ;
        var item_clss='' ;
        //var checkbox=$j(item.item.firstChild).find('input') ;
        // console.log(checkbox) ;
         //console.log($j($j(item.item.firstChild)).find('input')) ;
         //var checkbox=$j($j(item.item.firstChild)).find('input') ;
         //if ()
        //$j(checkbox!=undefined)
         //if ($j(checkbox).is(':checked')) $j(checkbox).removeAttr('checked') ;
         //                        else                             $j(checkbox).attr('checked',true) ;

        if (item.item.firstChild.childNodes[0].attributes.item_id!=null) item_id=item.item.firstChild.childNodes[0].attributes.item_id.nodeValue ;
        if (item.item.firstChild.childNodes[0].attributes.item_type!=null) item_type=item.item.firstChild.childNodes[0].attributes.item_type.nodeValue ;
        if (item.item.firstChild.childNodes[0].attributes.item_clss!=null) item_clss=item.item.firstChild.childNodes[0].attributes.item_clss.nodeValue ;
        if (item_id>0 && settings.element_click_cmd!="") send_ajax_request({cmd:settings.element_click_cmd,item_id:item_id,item_type:item_type,item_clss:item_clss}) ;
        return(true);
     });
     



     function remoteSource(parent, cfg, callback) {
       //console.log('remoteSource',parent,cfg) ;

       //var loadingIndicator = createLoadingColumn();
       //var xhrUid = ++xhrCnt;
       //var type = 'region';


       if (parent!=null)settings.upload_params['id']=parent.id ;
       else              settings.upload_params['id']=settings.root_id ;

       var req_uri = settings.upload_url;
       req_uri+='?'+$j.param( settings.upload_params );


       // determine which column we're on based on previous selection
       if (parent==null || parent.has_children)
         {  // xhr request
            $j.getJSON(req_uri,function(jsonObject){callback(jsonObject);})  ;
         }
        //   type = 'subregion';
        // } else if (parent.type === 'subregion') {
        //   type = 'name'; // country
        // } else { // must be a country
        //   return cfg.emitter.emit('create-column', createSimpleColumn(parent));
        // }
       //}

       // loading spinner
       //cfg.emitter.emit('create-column', loadingIndicator);



      /* xhr({
         //uri: 'https://restcountries.eu/rest/v1/all'
         uri: req_uri //'https://192.168.1.133/services/quiz/get_themes/'
       }, function done(err, resp, body) {
         var rawData = JSON.parse(body);
         //var data = uniqueCountryData(rawData, type, parent);
         var data = rawData;

         // clear loading spinner
         //_.remove(loadingIndicator);

         // stale request
         if (xhrUid !== xhrCnt) {
           return;
         }

         // execute callback
         callback(data);
       });   */
     }




     function createLoadingColumn() {
       var div = _.el('div.fjs-col.leaf-col');
       var row = _.el('div.leaf-row');
       var text = _.text('Loading...');
       var i = _.el('span');

       _.addClass(i, ['fa', 'fa-refresh', 'fa-spin']);
       _.append(row, [i, text]);

       return _.append(div, row);
     }

     // item render
     function createItemContent(cfg, item)
     { var data = item.children || cfg.data;
       //console.log(item,cfg) ;
       var frag = document.createDocumentFragment();

       var label = document.createElement('span');


       var label_text = document.createElement('span');
       var iconPrepend = document.createElement('i');


       var iconAppend = document.createElement('i');
       var prependClasses = ['fa'];
       var appendClasses = ['fa'];


       // prepended icon
       if (item.type === 'theme') { prependClasses.push('fa-list-ul'); }
       if (item.type === 'section') { prependClasses.push('fa-list-ul'); }
       else                         { prependClasses.push('fa-dot-circle');}
       addClass(iconPrepend, prependClasses);

       // text label
       if (item.show_checkbox)
       {   var checkbox = document.createElement('input');
           checkbox.setAttribute("type", 'checkbox');
           checkbox.setAttribute("value", 1);
           checkbox.setAttribute("name",settings.checkbox_name+'['+item.id+']');
           checkbox.setAttribute("item_id",item.id);
           if (item.checked) checkbox.setAttribute("checked",true);
           //if (item.checkbox_attr!=null) fore

           if (item.checkbox_cmd)
           {   var checkboxClasses = ['v2'];
               addClass(checkbox, checkboxClasses);
               checkbox.setAttribute("cmd",item.checkbox_cmd);
           }
           label.appendChild(checkbox);
       }
       else label.appendChild(iconPrepend);
       
       label_text.textContent = item.label;
       label_text.setAttribute("id", 'el_label_'+item.id);
       label.appendChild(label_text);
       label.setAttribute("item_id", item.id);
       label.setAttribute("item_type", item.type);
       label.setAttribute("item_clss", item.clss);
       frag.appendChild(label);

       // appended icon
       if (data) { appendClasses.push('fa-caret-right');}
       else if ('url' in item) { appendClasses.push('fa-external-link');}

       addClass(iconAppend, appendClasses);

       if (item.has_children) frag.appendChild(iconAppend);

       return frag;
     }

     var nativeIsArray = Array.isArray

     var shimIsArray = function (obj) {return toString.call(obj) === "[object Array]"}
     var isArray = nativeIsArray || isArray


     /**
      * Add one or more classnames to an element
      * @param {Element} element
      * @param {Array.<string>|String} array of classnames or string with
      * classnames separated by whitespace
      * @return {Element}
      */
     function addClass(element, className) {
       var classNames = className;

       function _addClass(el, cn) {
         if (!el.className) {
           el.className = cn;
         } else if (!hasClass(el, cn)) {
           if (el.classList) {
             el.classList.add(cn);
           } else {
             el.className += ' ' + cn;
           }
         }
       }

       if (!isArray(className)) {
         classNames = className.trim().split(/\s+/);
       }
       classNames.forEach(_addClass.bind(null, element));

       return element;
     }

     /**
      * Check if element has a class
      * @param  {Element}  element
      * @param  {String}  className
      * @return {boolean}
      */
     function hasClass(element, className) {
       if (!element || !('className' in element)) {
         return false;
       }

       return element.className.split(/\s+/).indexOf(className) !== -1;
     }


     return(this) ;


} ;



