//Finder selector system
 (function($) {

    //message tool
    $.finder =
    {   
        sbwidth : -1
        ,toggle : function(parentid, element, scope_id, prefix)
        {
            var scope_id = scope_id ? "#"+scope_id+" " : "";
            var prefix = prefix ? prefix : "";
            var list = $("#"+prefix+"finderlist_"+parentid);
            var item = $(element).parent();
            var value = $(element).find('span.val').text();
            var topitem = $("#"+prefix+"findertopitem_"+parentid);
            var current = topitem.find("span.val").text();
            var currentid = item.attr('id').substr(item.attr('id').lastIndexOf("_")+1);
            $(scope_id+"ul.openfinderlist").each(function()
            {
               var el = $(this);
               var cid = el.attr('id').substr(el.attr('id').lastIndexOf("_")+1);
               if(cid != parentid)
               {
                   $.finder.closeList(el);
               }
            });
            
            if(list.height() > 26)
            {
                $.finder.closeList(list);
            }
            else
            {
                $.finder.openList(list);
            }
            
            if(!item.hasClass('topitem'))
            {
                topitem.find("span.val").text(value);
                topitem.attr('title', value);
                topitem.addClass("tooltip");
            }
            
            if(value != current && currentid != 0)
            {   
                //toon nieuwe dropdown (want currentid != 0)
                //haal open menus weg
                $("#"+prefix+"finderlist_"+parentid).parent().nextAll("div.listbox:has(ul.finderlist:visible)").remove();
                
                //laad nieuwe dropdown via ajax
                var action = "action=ajax&function=getsubtree&id="+currentid
                if(prefix.length > 0)
                {
                    action += "&prefix="+prefix;
                }
                $.getJSON(base_url + "/search/?" + action, function(json, status) 
                {
                    //JSON:
                    if(json.debug)
                        $.log(json.debug);
                        
                    var data = json.data;
                    if(data.status && data.status == 'success' && data.html == "")
                    {
                        $("#"+prefix+"finder_result_id").val(currentid);
                        $("#"+prefix+"searchbarform").submit();
                    }
                    else if(data.status && data.status == 'success')
                    {
                        list.parent().after(data.html);
                        
                        $('#'+prefix+'finderbar .tooltip').tooltip({track: true
                                                   ,delay: 0
                                                   ,showURL: false
                                                   ,showBody: ' - '
                                                   ,fade: 250});
                        
                        $("#"+prefix+"finderlist_"+currentid).show('slide',{queue: "finders"},300);
                        $(scope_id+".selected").removeClass("selected");
                        list.addClass("selected");
                        $("#"+prefix+"finder_result_id").val(currentid);
                    }

                    
                });
                
            }
        }
        ,reset : function(prefix)
        {
            prefix = prefix ? prefix : '';
            $("#"+prefix+"finderbar ul.finderlist:visible").each(function()
            {
                if(this.id != "finderlist_0")
                {
                    $(this).hide('slide',{direction: 'up'},800,function(){
                        $("#"+prefix+"finderbar .topitem").find("span.val").text("Kies...");
                        $("#"+prefix+"finderbar .selected").removeClass("selected");
                        $("#"+prefix+"finder_result_id").val("");
                    });
                }
            });
            
        }
        ,toggleList : function(listid, element, scope_id, event)
        {
            if(event)
            {
                if(event.stopPropagation) 
                { 
                    event.stopPropagation(); 
                }
                event.cancelBubble = true;
            }
            
            var list = $("#"+listid);
            var currentid = listid.substr(listid.lastIndexOf("_")+1);
            $("#"+scope_id+" ul.openfinderlist").each(function()
            {
               var el = $(this);
               var cid = el.attr('id').substr(el.attr('id').lastIndexOf("_")+1);
               if(cid != currentid)
               {
                   $.finder.closeList(el);
                   $('body').unbind('click');
               }
            });
            if(list.height() > 26)
            {
                $.finder.closeList(list);
            }
            else
            {
                if(event)
                {
                    $('body').click(function(e)
                    {
    					$.finder.closeList(list);
    					$('body').unbind('click');
    				});
				}
                $.finder.openList(list);
            }
            
        }
        ,getStyle : function(element, style)
        {
        	if (element.currentStyle)
        		var y = element.currentStyle[style];
        	else if (window.getComputedStyle)
        		var y = document.defaultView.getComputedStyle(element,null).getPropertyValue(style);
        	return y;
        }
        ,openList : function(list)
        {
            var clone = list.clone().hide().appendTo('body').height("auto");
            var height = clone.innerHeight();
            list.parent("div.listbox").css("zIndex",900);
            list.css("zIndex",900).animate({height: height > 250 ? 250 : height},300,function(){list.addClass('openfinderlist')});
            if(height > 250)
            {
                list.animate({width: clone.innerWidth() + $.finder.scrollbarWidth()},300);
            }
            clone.remove();
        }
        ,closeList : function(list)
        {
            list = $(list);
            var scrollWidth = list.attr('scrollWidth');
            list.scrollTop(0).scrollLeft(0).removeClass('openfinderlist');
            if(list.innerWidth() > scrollWidth)
            {
                list.animate({width: list.width() - $.finder.scrollbarWidth()},200);
            }
            list.animate({height: 26},200,function(){list.css("zIndex",500); list.parent("div.listbox").css("zIndex",500);});
        },
        scrollbarWidth : function() 
        {
            if($.finder.sbwidth == -1)
            {
        	    document.body.style.overflow = 'hidden';
            	var width = document.body.clientWidth;
            	document.body.style.overflow = 'scroll';
            	width -= document.body.clientWidth;
            	if(!width) width = document.body.offsetWidth-document.body.clientWidth;
            	document.body.style.overflow = '';
            	$.finder.sbwidth = width;
        	}
        	return $.finder.sbwidth;
        },
        openMetalink : function(id, scopeId, event, url)
        {
            if(event)
            {
                if(event.stopPropagation) 
                { 
                    event.stopPropagation(); 
                }
                event.cancelBubble = true;
            }
            var form = $("#searchbarform");
            var loc  = form.serialize();
            scopeId  = "#"+scopeId+" ";
            //add meta ids
            var metastring = "&metaids[]="+id;
            $(scopeId+" div.metalink-active").each(function()
            {
                var mid = this.id.substr(this.id.lastIndexOf("_")+1);
                metastring += "&metaids[]="+mid;
            });
            
            location.href = base_url + url + "?" + loc + metastring;
        },
        removeMeta : function(id, scopeId, event, url)
        {
            if(event)
            {
                if(event.stopPropagation) 
                { 
                    event.stopPropagation(); 
                }
                event.cancelBubble = true;
            }
            
            $("#metalink_"+id).removeClass("metalink-active");
            var form = $("#searchbarform");
            var loc  = form.serialize();
            scopeId  = "#"+scopeId+" ";
            
            //add meta ids
            var metastring = "";
            $(scopeId+" div.metalink-active").each(function()
            {
                var mid = this.id.substr(this.id.lastIndexOf("_")+1);
                metastring += "&metaids[]="+mid;
            });
            
            location.href = base_url + url + "?" + loc + metastring;
        }
        
      
    }
})(jQuery);


function findsubs(id, parents, lvl)
{
  var myparents = parents+','+id;
  parents = parents.split(',');
  
  for(var i=lvl;i<=5;i++)
  {
    $('#lvl'+parents[0]+'_'+i).addClass("invisible")
  }
  
  var lvlid   = '#lvl'+parents[0]+'_'+lvl;
  var subtree = usertree;
  for(var i=0;i<parents.length;i++)
  {
    subtree = subtree[parents[i]]['children'];
  }
  
  if(!subtree[id]['children'])
  {
    return;
  }
  
  var treename = subtree[id]['name']
  subtree  = subtree[id]['children'];
  
  $(lvlid).empty();
  $('<span></span>').append(treename).appendTo(lvlid);

  var lst = $('<ul></ul>');
  for(node in subtree)
  {
    var lnk = ($("<a></a>").attr('href','#').bind('click',{'id': subtree[node]['id'], 'myparents':myparents, 'lvl':lvl+1},function(e){
      findsubs(e.data.id, e.data.myparents, e.data.lvl);
      return false;
    })).append(subtree[node]['name']);
    
    $('<li></li>').append(lnk).appendTo(lst);
  }
  $('<div class="options"></div>').append(lst).appendTo(lvlid);
  $(lvlid).removeClass("invisible")
}
