﻿/*--------------------------------------------------------------------------
 *  
 *  ASP.NET TreeView Control helper
 *  (c) 2008,2009 Nikita A. Popov <mrpopoff@mail.ru>
 *
 *
/*--------------------------------------------------------------------------*/

var TreeViewControl = Class.create();
TreeViewControl.prototype = {
    TREEVIEW_ID : 0,
    LINK : 0,
    CHECKBOX : 1,
        
	initialize: function(control, options)
	{
        Object.extend(this.options, options);
        
        this.TREEVIEW_ID = control;
        
		this.control = $(control);
		if(!this.control) return;
		this.controlId = "#" + this.control.id;
		
		// получаем список веток и навешиваем для них обработку событий
		var items = $$(this.controlId+" tr");
		var class_name = control + "_0";
		
		$A( cssQuery("td > a[class=" + class_name +"]", items) ).each( ( function(treeLink)
		{
			treeLink.href = "#";
		    Event.observe(treeLink, "click", (function(e) { this.toggleCheckBox( treeLink.id ); }).bind(this), false);
		} ).bind(this) );

		$A( cssQuery("td > input[type='checkbox']", items) ).each( (function(checkBox)
		{
		    Event.observe(checkBox, "click", (function(e) { this.checkBox_onclick( checkBox, e ); }).bind(this), false);
        }).bind(this));			
	},
    
    // чтение контента, совместимое с IE и FireFox
    getNodeInnerText: function( obj )
    {
        try
        {
            if ( Prototype.Browser.IE )
                return obj.innerText;        
            return obj.textContent;
        }
        catch( e )
        {
            return "";
        }
    },    
    // обрабатываем щелчок мыши на тексте ветки дерева
    toggleCheckBox: function(senderId)
    {
        var nodeIndex = this.getNodeIndex(senderId, this.LINK);
        var checkBoxId = this.TREEVIEW_ID + "n" + nodeIndex + "CheckBox";
        var checkBox = document.getElementById(checkBoxId);
        if ( checkBox == null ) return;
        
        checkBox.checked = !checkBox.checked;
        
        this.toggleChildCheckBoxes(checkBox);
        this.toggleParentCheckBox(checkBox);
    },
    // checkbox - обработчик щелчка мыши
    checkBox_onclick: function( checkBox, eventElement)
    {
        this.toggleChildCheckBoxes(checkBox);
        this.toggleParentCheckBox(checkBox);
    },
    // индекс нажатой ссылки или checkbox
    getNodeIndex: function(elementId, elementType)
    {
         var nodeIndex;
         if(elementType == this.LINK)
         {
            nodeIndex = elementId.substring((this.TREEVIEW_ID + "t").length);
         }
         else if (elementType == this.CHECKBOX)
         {
            nodeIndex = elementId.substring((this.TREEVIEW_ID + "n").length, elementId.indexOf("CheckBox"));
         }
         return nodeIndex;
    },
    // включает-выключает вложенные checkboxes
    toggleChildCheckBoxes: function(checkBox)
    {
        var postfix = "n";
        var childContainerId = this.TREEVIEW_ID + postfix + this.getNodeIndex(checkBox.id, this.CHECKBOX) + "Nodes";
        var childContainer = document.getElementById(childContainerId);
        if (childContainer)
        {
            var childCheckBoxes = childContainer.getElementsByTagName("input");
            for (var i = 0; i < childCheckBoxes.length; i++)
            {
                childCheckBoxes[i].checked = checkBox.checked;
            }
        }
    },
    // переключает чекбокс в ветке верхнего уровня
    toggleParentCheckBox: function(checkBox)
    {
        if(checkBox.checked == false)
        {
            var parentContainer = this.getParentNodeById(checkBox, this.TREEVIEW_ID);
            if(parentContainer) 
            {
                var parentCheckBoxId = parentContainer.id.substring( 0, parentContainer.id.search("Nodes")) + "CheckBox";
                var parentCheckbox = $(parentCheckBoxId);
                if( parentCheckbox != null && parentCheckbox.type == "checkbox") 
                {
                    parentCheckbox.checked = false;
                    this.toggleParentCheckBox(parentCheckbox);
                }
            }
        }
    },
    // ID родительского контейнера
    getParentNodeById: function(element, id)
    {
        var parent = element.parentNode;
        if (parent == null)
        {
            return false;
        }
        if (parent.id.search(id) == -1)
        {
            return this.getParentNodeById(parent, id);
        }
        else
        {
            return parent;
        }
    },
    // строка состояния веток дерева
    getNodesState: function()
    {
        var str = "";
        
		var items = $$(this.controlId+" tr");
		var class_name = this.controlId + "_0";
		   
		var tree  = this;     
		$A( cssQuery("td > input[type='checkbox']", items) ).each( function(checkBox)
		{
		    if ( str.length != 0 ) str += ",";
		    //var nodeId = checkBox.id.replace( this.TREEVIEW_ID + "n", this.TREEVIEW_ID + "t" ).replace( "CheckBox", "" );
  		    //str += checkBox.parentNode.childNodes[1].innerText + '=' + checkBox.checked;
  		    if ( checkBox.title != null && checkBox.title != '' )
  		        str += checkBox.title + '=' + checkBox.checked;
  		    else
  	            str += tree.getNodeInnerText( checkBox.parentNode.childNodes[1] ) + '=' + checkBox.checked;
  		    
        });
        
        return str;    
    },
    //сбрасывание отметок во всех ветках
    resetNodes : function()
    {
		var items = $$(this.controlId+" tr");
		var class_name = this.controlId + "_0";
		        
		$A( cssQuery("td > input[type='checkbox']", items) ).each( function(checkBox)
		{
  		    checkBox.checked = false;  		    
        });
    },
        	
	show: function() 
	{
	    this.control.style.display = "block";
	},
	
	hide: function() 
	{
	    this.control.style.display = "none";
	},	
	//поставить отметки в ветки, присутствующиеся в строке str
	setNodesSate: function (strLayers, descr)
	{	    	    
	    var items = $$(this.controlId+" tr");
	    var tree  = this;	
	    $A( cssQuery("td > input[type='checkbox']", items) ).each( function(checkBox)
		{		
		    var layer = '';
		    
		    if ( checkBox.title != null && checkBox.title != '' )
		        layer = checkBox.title;
		    else
		        layer = tree.getNodeInnerText ( checkBox.parentNode.childNodes[1] );
		    		        
		    if(strLayers.indexOf( layer ) >= 0)
	        {
	            checkBox.checked = true;
	        }
	        	      
	        if ( descr != null && descr.length > 0 )
	        {  
                var start = descr.indexOf( layer );
                if ( start >= 0 )
                {
                    //start = start + layer.length + 1;
                    checkBox.parentNode.childNodes[1].title = descr.substring( start + layer.length + 1, descr.indexOf( '|', start ) ) ;  
                }
            }	        
        });			       		
	}
}
