var lineList = Array();
var p_z_index = 205;
var l_z_index = 100;
var footer_h = 90;
var level_h = 220;
var add_top = 10;

    var line_colors = Array(null, '#A7A7A7', '#A7A7A7', '#98CB00', '#98CB00', '#A7A7A7', '#A7A7A7', '#E3014F', '#E3014F');
    var line_widths = Array(0, 2, 2, 2, 2, 2, 2, 2, 2); // Array(0, 1, 1, 2, 2, 1, 1, 2, 2);
    var line_types  = Array(null, false, false, true, true, true, true, true, true);
    var level_pos   = Array(0, 1, 1, 0.5, 0.5, -1, -1, 0, 0);  // NORMAL
    var level_pos   = Array(0, -1, -1, 0.5, 0.5, 1, 1, 0, 0);  // UPSIDE_DOWN

var mouse_on_menu = false;

function GetCenter(id)
{
    var o = (typeof id == 'string') ? document.getElementById(id) : id;
    var w1 = parseInt(o.style.width);
    var h1 = parseInt(o.style.height);
    var l1 = parseInt(o.style.left);
    var t1 = parseInt(o.style.top);
    return {"x": l1 + Math.round(w1/2), "y": t1 + Math.round(h1/2)};
}

function PersonClick2(person_id, types, do_not_move, tree_id)
{
    var parent_person = document.getElementById('person' + person_id + '_wrapper');
    var member_list = MakeAjaxRequest("action=get_user_relatives&who=" + person_id + "&type=" + types + "&tree_id=" + tree_id)
    var members = member_list.split('\n');
    var count = members.length - 1;
    p_z_index++;
    var l = 0;
    var t = 0;
    if (do_not_move)
    {
    	l = parseInt(parent_person.style.left);
    }
    else
    {
    	var m = mousePageXY();
    	l = parseInt(m.x) - 50; // -50 -> чтобы мышь попадала на слой
    }

    switch (types)
    {
        case "1,2":    // родители
            parent_person.link1 = true;
            break;
        case "3,4":    // братья-сёстры
            parent_person.link2 = true;
            l += 130;
            break;
        case "5,6":    // дети
            parent_person.link3 = true;
            break;
        case "7,8":    // супруг
            parent_person.link4 = true;
            l -= 130;
            break;
    }

    var new_person = null;
    var cur_person = null;
    var person_exists = null;
    var this_level = 0;
    var p_type = 0;
    var move_down = false;

    if (count == 0 && do_not_move != true)
    {
        alert('Родственников по этой линии нет');
        return;
    }

    for (var i = 0; i < count; i++)
    {
        cur_person = Array();
        cur_person = members[i].split('|'); // who_id | rel_type | rel_label | html

        p_type = parseInt(cur_person[1]);
        var correct = 0;
        if (parseFloat(parent_person.level) % 1 != 0 && parseFloat(level_pos[p_type]) % 1 != 0)
        {
            correct = 0.5;
        }
        this_level = parseFloat(parent_person.level) + parseFloat(level_pos[p_type]) - correct;
        if (this_level < 0)
            move_down = true;
        t = footer_h + level_h * this_level + add_top;
        person_exists = document.getElementById('person' + cur_person[0] + '_wrapper');
        new_person = AddPerson(cur_person[0], p_z_index, l, t, cur_person[3], this_level);
        if (person_exists == null)
            moveobject = new_person;
        if (do_not_move)
            moveobject = null;
        l += parseInt(new_person.style.width) + 20;
        AddLine(parent_person, new_person, line_colors[p_type], line_widths[p_type], line_types[p_type]);
    }
    movefixlevel = true;

    if (move_down)
    {
        var person = null;
        var all = document.getElementById('personsDropped').getElementsByTagName('*');
        for (var i = 0; i < all.length; i++)
        {
            person = all[i];
            if (person.className == 'rect' && person.id.substring(0,6) == 'person')
            {
                // person.style.top = parseInt(person.style.top) + level_h;
                person.level = parseFloat(person.level) + 1;
            }
        }
        AddLevel(true);
        //MovePersonsDown(level_h)
    }

    RecombineTreeItems();
}

function MovePersons(delta)
{    var all = document.getElementById('personsDropped').getElementsByTagName('*');
    for (var i = 0; i < all.length; i++)
    {
        person = all[i];
        if (person.className == 'rect' && person.id.substring(0,6) == 'person')
        {
            person.style.top = parseInt(person.style.top) + delta;
        }
    }
}

function MovePersonsDown(length)
{
    var size = level_h / 10;
    var delay = 50;
    var person = null;
    var all = document.getElementById('personsDropped').getElementsByTagName('*');
    for (var i = 0; i < all.length; i++)
    {
        person = all[i];
        if (person.className == 'rect' && person.id.substring(0,6) == 'person')
        {
           	person.style.top = parseInt(person.style.top) + size;
        }
    }
    RecombineTreeItems();
    RecombineTreeItems2();

    length -= size;
    if (length > 0)
    {
         setTimeout("MovePersonsDown(" + length + ")", delay);
    }
}

function AddPerson(id, z_index, l, t, text, person_level)
{
    var person = document.getElementById('person' + id + '_wrapper');
    if (person != null)
    {
        return person;
    }
    person = document.createElement('div');
    person.className = "rect"; // person
    person.id = "person" + id + "_wrapper";  /// no 'wrapper'
    person.style.left = l + "px";
    person.style.top =  t + "px";
    person.style.width = 116 + "px"; // need to auto-add people while 1st load
    person.style.height = 125 + "px";
    person.style.zIndex = z_index;
    person.level = person_level;
    person.innerHTML = text;
    person.onmousedown = function()
    {
        setMove(person, null, null, true); // or this?
    }
    person.onmouseup = function()
    {
        setMove(null, 0, 0);
    }
    person.onselectstart = function()
    {
        return false;
    }
    person.ondblclick = function()
    {
    	// PersonClick(id);
    }
    person.onmousemove = function()
    {
   		// PersonClick(id);
    }
    person.onmouseover = function()
    {
        // debug   ЗАМЕНИТЬ ВЕСЬ БЛОК НА  ---->> RegisterMenu
        var hintId = 'browse_tree_menu';
        var hint = document.getElementById(hintId);
        if (hint)
        {
	        SetAllMenus(hintId);
	        ShowMenu(this.id);

	        hint.onmouseover = function() { can_hide_menu = false; } ;
		    hint.onmouseout = function() { can_hide_menu = true; setTimeout('HideMenu()', hide_timer); } ;
		    hint.onclick = function() { can_hide_menu = true; HideMenu(); } ;

		    if (hint.all) // ff fix
		    {
			    for (var i = 0; i < hint.all.length; i++)
			    {
			    	sub_hint = hint.all[i];
			    	sub_hint.onmousemove = function() { can_hide_menu = false; } ;
			    }
			}
        }
    }

    document.getElementById('personsDropped').appendChild(person);
    setTimeout("UpdateImage(" + person.id + ");", 200);

    // СТРОГО ПОСЛЕ appendChild!
    //RegisterMenu('browse_tree_menu', person.id, 0);

    return person;
}

function UpdateImage(person)
{
	var obj;
	if (ff()) person.all = person.getElementsByTagName('*');
    for (var i = 0; i < person.all.length; i++)
    {
        obj = person.all[i];
        if (obj.tagName.toLowerCase() == 'img')
        {
            var str = obj.src;
            obj.style.visibility = 'hidden';
            obj.src = '';
            obj.src = str;
            obj.style.visibility = 'visible';
        }
    }

}

function AddLine(from_d, to_d, col, w, draw_from_side)
{
    l_z_index++;
    var line;
    for (var i = 0; i < lineList.length; i++)
    {
        line = lineList[i];
        if (line['from'] == from_d && line['to'] == to_d)
            return false;
        if (line['from'] == to_d && line['to'] == from_d)
            return false;
    }

    //var html = "<div class=\"black_line\" id=\"line" + l_z_index + "\">";
    var html = "div";
    line = document.createElement(html);
    line.className = "black_line";
    line.id = "line" + l_z_index;
    line.style.left = 0;
    line.style.top = 0;
    line.style.width = 0;
    line.style.height = 0;
    line.style.zIndex = l_z_index;

    var l = lineList.length;
    lineList[l] = Array();
    lineList[l]['from'] = from_d;
    lineList[l]['to'] = to_d;
    lineList[l]['color'] = col;
    lineList[l]['w'] = w;
    lineList[l]['line'] = line;
    lineList[l]['draw_from_side'] = draw_from_side;

    document.getElementById('linksDropped').appendChild(line);
    // RedrawLine(lineList[lineList.length - 1]);
}

function RedrawLine(ind)
{
	//try
	{
		var l = lineList[ind];
		var line = l['line'];
		var d1 = l['from']; //g('person1');
		var d2 = l['to']; //g('person2');
		/*
		if (typeof d1 == 'string')
		    d1 = g(d1);
		if (typeof d2 == 'string')
		    d2 = g(d2);
		*/
		if (!d1 || !d2)
			return;
		var d1c = GetCenter(d1.id);
		var d2c = GetCenter(d2.id);
		line.style.left = Math.min(d1c.x, d2c.x);
		line.style.top = Math.min(d1c.y, d2c.y);
		line.style.width = Math.abs(d1c.x - d2c.x);
		line.style.height = Math.abs(d1c.y - d2c.y);
		var top = 0;
		var bottom = 0;
		var left = 0;
		var right = 0;
		var w = l['w'];
		if (l['draw_from_side'] == true)
		{
		    if (d1c.y < d2c.y)
		        top = w;
		    else
		        bottom = w;
		    if (d1c.x < d2c.x)
		        right = w;
		    else
		        left = w;
		}
		else
		{
		    if (d1c.y < d2c.y)
		        bottom = w;
		    else
		        top = w;
		    if (d1c.x < d2c.x)
		        left = w;
		    else
		        right = w;
		}
		var color = l['color'];
		line.style.borderLeft = left.toString() + "px solid " + color;
		line.style.borderRight = right.toString() + "px solid " + color;
		line.style.borderTop = top.toString() + "px solid " + color;
		line.style.borderBottom = bottom.toString() + "px solid " + color;
	}
	//catch (e) { /* some null vars */ }
}

function RecombineTreeItems()
{
	var line = null;
	for (var i = 0; i < lineList.length; i++)
	{
	    line = lineList[i];
	    //if (moveobject.style != null && moveobject.style.zIndex != null && (line['from'] == moveobject && line['from'].style.zIndex == moveobject.style.zIndex || line['to'] == moveobject && line['to'].style.zIndex == moveobject.style.zIndex))
	        RedrawLine(i);
	}
}
