// ***************************************
// Plugin ORGANIGRAM
// ***************************************
// Created by PORTANEO
// ***************************************

/**
    hook register
**/
$p.plugin.hook.register('app.menu.openSubMenu.addsubmenulink','$p.plugin.organigram.addOrganigramLink()',3,1);
$p.plugin.hook.register('app.notebook.buildMenu.addlink','$p.plugin.organigram.addfeatureMenuOrganigramLink()',3,1);
$p.plugin.hook.register('app.network.dashboard.displayUsers.addlink','$p.plugin.organigram.addNetworkOrganigramLink()',3,1);
$p.plugin.hook.register('$p.notebook.myprofile.end','$p.plugin.organigram.init()',3,1);

/*
    Class: $p.plugin.organigram.
    
            Organigram plugin
            
*/
$p.plugin.organigram={
	mgrhighlevel:0,
	manager:[],
	managed:[],
	tab:[],
	myposition:[],
	users:[],
	manager_cnx:0,
	v_manager_height:0,
	idsByLevel:[],
	/*
		Function:   $p.plugin.organigram.init
			Get the user managers
     */
    init:function() {
        $p.ajax.call("../includes/plugins/plugin_organigram/portal/xml_getusersmanagers.php",
            {
                'type':'load',
                'callback':
                {
                    'function':$p.plugin.organigram.displayManagerSearch
                }
            }
        );
        return false;
    },
	/*
		Function:   $p.plugin.organigram.displayManagerSearch                        
			  Display the HTML to search for a manager. (cf my profile)
               
        Parameters:
			response : XML response
            vars: hash variable
     */
    displayManagerSearch:function(response,vars) {
        var l_s = '';
        var l_result=response.getElementsByTagName("user");
        l_s+='<div style="padding-top: 15px;">';
        if (l_result.length != 0) {
            for (var i=0;i<l_result.length;i++) {
                var l_id=$p.ajax.getVal(l_result[i],"id","int",false,0);
                var l_username=$p.ajax.getVal(l_result[i],"username","str",false,"");
                var l_longname=$p.ajax.getVal(l_result[i],"longname","str",false,"");
                var lbl = (i==0)    ?     '<div class="plabel" style="width: 150px;float: left;">'+lg("myManagers")+' :'+'</div>' :   '&nbsp;';
				l_s += lbl;
				//l_s +='<div class="plabel" style="width: 150px;float: left;">'+lbl+'</div>';
                l_s += '&nbsp;<div style="float: left;">'+l_longname+'&nbsp;&nbsp;<a href="#" onclick="$p.plugin.organigram.removeAsManager('+l_id+');return false;">'+lg('suppress')+'</a>';
				l_s += '</div>';
                l_s += '<div class="float_correction"></div>';
            }
        }

       l_s += '<div class="plabel" style="width: 150px;float: left;padding-top:4px;">'+ lg("addAManager")+':</div>'
           + '<div  class="searchbox" style="float: left;">'
           + '<input type="text" autocomplete="off" size="30" name="txt_search_manager" id="txt_search_manager"  class="searchmanager" onFocus=\'$p.app.tools.inputFocus(this,"'+lg("inputEmailOrNameOrTag")+'")\' onBlur=\'$p.app.tools.inputLostFocus(this,"'+lg("inputEmailOrNameOrTag")+'");\' value="'+lg("inputEmailOrNameOrTag")+'" />'
		   + '<input type="image" id="btn_search_manager" name="btn_search_manager" onclick="$p.plugin.organigram.openPopupSearchManager();return false;" class="searchboxbtn" src="../styles/themes/classic_blue/header_menu_searchbtn.png" />'
           + '</div>'
           + '<div class="float_correction"></div>'
           + '</div>';

        $('miscellaneous').innerHTML = l_s;
        return false;
	},
	/*
                Function:   $p.plugin.organigram.displayPopupSearchManager
                                    
			  Display the popup that displays the results of the manager search
         */
    openPopupSearchManager:function() {
        var v_search = $('txt_search_manager').value;
        var v_page = 0;
        if (v_search == "" || v_search == lg("inputEmailOrNameOrTag")) {
            $p.app.alert.show(lg('errManagerEmpty'));
            return false;
        }
        else if (v_search.length<4) {
			$p.app.alert.show(lg('4caractMin'));
			return false;
        }
        else {
			$p.plugin.organigram.searchManager(v_search,v_page);
        }
        return false;
    },
    searchManager:function(v_search,v_page) {
            $p.ajax.call("../includes/plugins/plugin_organigram/portal/xml_managersearch.php"+"?p="+v_page+"&search="+$p.string.esc(v_search),
                {
                    'type':'load',
                    'callback':
                    {
                        'function':$p.plugin.organigram.treatManagerResults,
                        'variables':
                        {
                            'search':v_search,
                            'page':v_page
                        }
                    }
                }
            );
	},
	/*
                Function:   $p.plugin.organigram.treatManagerResults
                                    
			  Display the popup that displays the results of the manager search
               
               Parameters:
                
                                    response : XML response
                                    vars: hash variable
         */
    treatManagerResults:function(response,vars) {
        var manager = vars['search'];
		var l_s='<table style="border-collapse: collapse;width:100%;">';
		var l_result=response.getElementsByTagName("user");
		var limit = 10;
		var nextsearch = 'block';

        if (l_result.length == 0) {
            $p.app.alert.show(lg('noResultForThisSearch'));
        }
        else {
			if($('nextsearch'))
				$('nextsearch').style.display = 'block';
			if(l_result.length<=10) {
				limit = l_result.length;
				nextsearch = 'none';
			}

            for (var i=0;i<limit;i++) {
                var l_picture=$p.ajax.getVal(l_result[i],"picture","str",false,"");
                var l_username=$p.ajax.getVal(l_result[i],"longname","str",false,"");
                var l_id=$p.ajax.getVal(l_result[i],"id","int",false,"0");
                l_s+='<tr>'
                    +'<td valign="top" width="40" height="40">'
                    +'<div class="picture_image_medium">'
                    +'<img src="'+(l_picture=="" ? "../images/nopicture.gif":l_picture)+'" />'
                    +'</div>'
                    +'<div class="picture_frame_white_medium"> </div>'
                    +'</td>'
                    +'<td valign="top">'
                    +'<div><b>'+l_username+'</b></div>'
                    +'<a href="#" onclick="$p.plugin.organigram.addAsManager('+l_id+',\''+l_username+'\');" >'+lg("add")+'</a>'
                    +'</td>'
                    +'</tr>';
            }
			if(l_result.length>1)
				l_s+='<tr><td>'+((vars['page']>0)?'<a href="#"   id="previoussearch" onclick="$p.plugin.organigram.searchManager(\''+manager+'\','+(vars['page']-1)+');return false;">'+lg("previous")+'</a>':'')+'</td><td align="right"><a href="#"  id="nextsearch" style="display:'+nextsearch+';" onclick="$p.plugin.organigram.searchManager(\''+manager+'\','+(vars['page']+1)+');return false;">'+lg("next")+'</a></td></tr>';
            l_s+='</table>';
            $p.app.popup.show(l_s,500,500,lg("lblResultsFor")+' "'+manager+'"',true,'$p.network.myprofile()');
		}
        return false;
    },
	/*
                Function:   $p.plugin.organigram.addAsManager
                                    
			  Add a manager to the current user
                
                Parameters:
                
                                    l_id : manager id
         */
    addAsManager:function(l_id,l_name) {
        $p.ajax.call("../includes/plugins/plugin_organigram/portal/scr_add_modify_manager.php?"+"act=add&manager="+l_id,
            {
                'type':'load',
				'alarm':true,
				'forceExecution':true,
                'callback':
				{
                    'function':$p.plugin.organigram.checkManager,
					'variables':
					{
						'l_name':l_name
					}
				},
                'source':'json'
            }
        );  
    },
	/*
        Function:   $p.plugin.organigram.checkManager
                                    
			Check adding the manager
                
        Parameters:
                
			l_id : manager id
    */
	checkManager:function(response,vars) {
		if(response.status == 0) {
			$p.app.alert.show(vars['l_name']+' '+response.err,3)
		}
		$p.network.myprofile();
	},
	/*
                Function:   $p.plugin.organigram.closeAndReload
                                    
			  Close the popup and reload datas
         */
    closeAndReload:function() {
        $p.app.popup.hide();
        $p.plugin.organigram.init();
    },
	/*
                Function:   $p.plugin.organigram.removeAsManager
                                    
			  Remove a manager to the current user
                
                Parameters:
                
                                    l_id : manager id
         */
    removeAsManager:function(l_id) {
        if (confirm(lg('msgAreYouSureSupElement'))) {
            $p.ajax.call("../includes/plugins/plugin_organigram/portal/scr_add_modify_manager.php?act=del&manager="+l_id,
                {
					'type':'load',
					'alarm':true,
					'forceExecution':true,
					'callback':
					{
						'function':$p.plugin.organigram.init
					},
					'source':'json'
				}
            );
        }
		return false;
    },
	/*
        Function:   $p.plugin.organigram.addOrganigramLink
                                    
			 Add organigram link into the portal
    */
	addOrganigramLink:function()
	{
		if($("networklink"))
			$("networklink").innerHTML += '. <a href="#" onclick="$p.plugin.organigram.displayOrganigram('+$p.app.user.id+');$p.notebook.selectMenuOption('+$p.app.user.id+',8);return false;">' + lg('lblMyOrganigram') + '</a><br />';
	},
	/*
        Function:   $p.plugin.organigram.addfeatureMenuOrganigramLink
                                    
			 Add organigram link into the menu of the portal
    */
	addfeatureMenuOrganigramLink:function()
	{
		l_h_buildMenu.push({'id':8,'fct':'$p.plugin.organigram.displayOrganigram('+selectedUserId+');return false;','icon':'../includes/plugins/plugin_organigram/images/organigram.gif','label':lg('lblOrganigram')});
	},
	/*
        Function:   $p.plugin.organigram.addNetworkOrganigramLink
                                    
			 Add organigram link in the user network
    */
	addNetworkOrganigramLink:function()
	{
		l_options.push($p.img('../includes/plugins/plugin_organigram/images/organigram.gif',16,16,'','imgmid')+" <a onclick='$p.plugin.organigram.displayOrganigram("+l_id+");$p.notebook.selectMenuOption("+$p.app.user.id+",8);return false;' href='#'>"+lg("lblOrganigram")+"</a>");
	},
	/*
        Function:   $p.plugin.organigram.addSelectUserInOrganigram
                                    
			 Add user data into the organigram
        Parameters:
                user_id : user selected id
    */
	addSelectUserInOrganigram:function(user_id)
	{
		var l_s = "";		
		l_s = '<table width="80" cellspacing="0" cellpadding="0" border="0">\
		<tbody>\
		<tr>\
		<td width="100%" valign="bottom" align="center" id="manager_container'+user_id+'" colspan="1">\
		</td>\
		</tr><tr>\
		<td valign="top" align="center">\
		<table width="80" cellspacing="0" cellpadding="0" border="0"  cellspacing="0" cellpadding="0" style="margin-left:4px;">\
		<tbody><tr>\
		<td width="70px" class="'+(($p.plugin.organigram.manager.length>0)?'lineRight':'')+'" id="link_top_left'+user_id+'" >&nbsp;</td>\
		<td width="70px" class="'+(($p.plugin.organigram.manager.length>0)?'lineLeft':'')+'" id="link_top_right'+user_id+'" >&nbsp;</td>\
		</tr>\
		</tbody></table>\
		<table width="80px" cellspacing="0" cellpadding="0" border="0"  cellspacing="0" cellpadding="0">\
		<tbody><tr>\
		<td width="10px">&nbsp;</td>\
		<td width="80px"  align="center" >\
		<div class="selectuser" id="linkname'+user_id+'">&nbsp;&nbsp;&nbsp;&nbsp;'+$p.plugin.organigram.tab[0][user_id].picture.replace('../../','')+'&nbsp;&nbsp;&nbsp;&nbsp;<br />&nbsp;&nbsp;'+$p.plugin.organigram.tab[0][user_id].long_name+'&nbsp;&nbsp;</div>\
		</td>\
		<td width="10px">&nbsp;</td>\
		</tr>\
		</tbody></table>\
		<table width="80" cellspacing="0" cellpadding="0" border="0"  cellspacing="0" cellpadding="0">\
		<tbody><tr>\
		<td width="70px" class="'+(($p.plugin.organigram.managed.length>0)?'lineRight':'')+'" id="link_bottom_left'+user_id+'" >&nbsp;</td>\
		<td width="70px" class="'+(($p.plugin.organigram.managed.length>0)?'lineLeft':'')+'" id="link_bottom_right'+user_id+'" >&nbsp;</td>\
		</tr>\
		</tbody></table>\
		<table width="80" cellspacing="0" cellpadding="0" border="0"  cellspacing="0" cellpadding="0">\
		<tbody><tr>\
		<td width="80px" id="managed_contained'+user_id+'">&nbsp;</td>\
		</tr>\
		</tbody></table>\
		</td>\
		</tr>\
		</tbody></table>';
		$p.print('selectedusercontainer'+user_id,l_s);

	},
	/*
        Function:   $p.plugin.organigram.addManagedUserInOrganigram
                                    
			 Add managed user data into the organigram
        Parameters:
                user_id : user selected id
    */
	addManagedUserInOrganigram:function(user_id)
	{
		var i,j = 0;
		var html = '';
		
		var l_s = "";
		
		sub = [];
		linkTop1 = 'lineRightHigh';
		linkTop2 = 'lineLeftHigh';
		linkBottom1 = '';
		linkBottom2 = '';
		data = $p.plugin.organigram.managed;
		container = "managed_contained"+user_id;
		current_user = user_id;
		l_s += '<table width="80"  height="80" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr>';
		for(i=0;i<data.length;i++) {
			if(data[i].length==1)
			{
				current_user = data[i][0];
				l_s += '<td valign="top" width="80" height="80" align="center">\
				<table width="100%"  height="80" cellspacing="0" cellpadding="0" id="user'+current_user+'"><tbody>\
				<tr align="" width="100%">\
				<td width="100%"   height="80" valign="top" align="center">\
				<div id="cnx_top_'+current_user+'">\
				<table width="100%" cellspacing="0" cellpadding="0" border="0">\
				<tbody><tr valign="top">\
				<td width="50%" class="'+linkTop1+'">&nbsp;</td>\
				<td width="50%" class="'+linkTop2+'">&nbsp;</td></tr>\
				</tbody></table></div>\
				<table width="100%" height="80" cellspacing="0" cellpadding="0" border="0" style="background-color:#E9E9E9;border:1px solid white;">\
				<tbody><tr>\
				<td valign="top" align=center width="80" height="80" >\
				<div class="linkname" id="linkname'+current_user+'" onclick="$p.plugin.organigram.contextual(event,'+current_user+',\''+$p.plugin.organigram.tab[0][current_user].long_name+'\',\''+$p.plugin.organigram.tab[0][current_user].email+'\');">'+$p.plugin.organigram.tab[0][current_user].picture.replace('../../','')+'<br />  '+$p.plugin.organigram.tab[0][current_user].long_name+'</div>\
				</td></tr></tbody></table>\
				<div id="cnx_bottom_'+current_user+'">\
				<table width="100%" cellspacing="0" cellpadding="0" border="0" >\
				<tbody><tr valign="top" id="link'+current_user+'">\
				<td width="50%" class="'+linkBottom1+'" id="link_left'+current_user+'" >&nbsp;</td>\
				<td width="50%" class="'+linkBottom2+'" id="link_right'+current_user+'" >&nbsp;</td></tr>\
				</tbody></table></div></td></tr></tbody></table>\
				<table width="80"  height="80" cellspacing="0" cellpadding="0" border="0" align="center" ><tbody><tr><td id="user'+current_user+'_cnx"></td></tr></tbody></table>\
				</td>';
				sub.push(current_user);
			}
		}
		l_s += '</tr></tbody></table>';
		
		$(container).innerHTML = l_s;

		l_s ='<table width="80" cellspacing="0" cellpadding="0" border="0" ><tbody>\
		<tr valign="top" id="link'+sub[0]+'">\
		<td width="50%" id="link_bottom_left'+sub[0]+'" class="lineRightHigh">&nbsp;</td>\
		<td width="50%" id="link_bottom_right'+sub[0]+'" class="lineLeftHigh">&nbsp;</td>\
		</tr></tbody></table>';
		if($('cnx_top_'+sub[0]))
			$('cnx_top_'+sub[0]).innerHTML = l_s;
				if(sub.length==1) {
					l_s ='<table width="100%" cellspacing="0" cellpadding="0" border="0" ><tbody>\
					<tr valign="top" id="link'+sub[0]+'">\
					<td width="50%" id="link_top_left'+sub[0]+'" class="lineRight">&nbsp;</td>\
					<td width="50%" id="link_top_right'+sub[0]+'" class="lineLeft">&nbsp;</td>\
					</tr>\
					</tbody></table>';
					if($('cnx_top_'+sub[0]))
						$('cnx_top_'+sub[0]).innerHTML = l_s;
				} else {
					l_s ='<table width="100%" cellspacing="0" cellpadding="0" border="0" ><tbody>\
					<tr valign="top" id="link'+sub[0]+'">\
					<td width="50%" id="link_top_left'+sub[0]+'" class="lineRight">&nbsp;</td>\
					<td width="50%" id="link_top_right'+sub[0]+'" class="lineLeftHigh">&nbsp;</td>\
					</tr></tbody></table>';
					if($('cnx_top_'+sub[0]))
						$('cnx_top_'+sub[0]).innerHTML = l_s;
						
					l_s ='<table width="100%" cellspacing="0" cellpadding="0" border="0" ><tbody>\
					<tr valign="top" id="link'+sub[sub.length-1]+'">\
					<td width="50%" id="link_top_left'+sub[sub.length-1]+'" class="lineRightHigh">&nbsp;</td>\
					<td width="50%" id="link_top_right'+sub[sub.length-1]+'" class="lineLeft">&nbsp;</td>\
					</tr></tbody></table>';
					if($('cnx_top_'+sub[sub.length-1]))
						$('cnx_top_'+sub[sub.length-1]).innerHTML = l_s;
				}
	},
	/*
        Function:   $p.plugin.organigram.addManagerUserInOrganigram
                                    
			 Add manager user data into the organigram
        Parameters:
                user_id : user selected id
    */
	addManagerUserInOrganigram:function(user_id)
	{
		var i,j = 0;
		var l_s = "";
		var linkTop1 = '';
		var linkTop2 = '';
		var linkBottom1 = '';
		var linkBottom2 = '';		
		var node = '';
		var branch = [];
		var data = $p.plugin.organigram.manager;
		var prevEl = '';
		linkTop1 = 'lineRightHigh';
		linkTop2 = 'lineLeftHigh';
		linkBottom1 = 'lineRightLow';
		linkBottom2 = 'lineLeftLow';
		branch[user_id] = [];
		$("manager_container"+user_id).innerHTML = '';
		for(i=0;i<data.length;i++)
		{
			if((','+branch[user_id].join()+',').match(','+data[i][0]+',')==indef) {
				branch[user_id].push(data[i][0]);
			}
			for(j=($p.plugin.organigram.mgrhighlevel-1);j>=0;j--)
			{
				current_user = data[i][j];
				if(current_user != indef)
				{
					if(data[i][j+1]!=indef) {
						if(!branch[current_user])
							branch[current_user] = [];
						if((','+branch[current_user].join()+',').match(','+data[i][j+1]+',')==indef) {
							branch[current_user].push(data[i][j+1]);
						}
					}
					if($('user'+current_user)) {
						if(node.match(data[i])==indef) {
							$('user'+current_user).colSpan = $('user'+current_user).colSpan + 1;
							$('user'+current_user).width = parseInt($('user'+current_user).width) + 80;
							$('link_bottom'+current_user).width = parseInt($('link_bottom'+current_user).width) + 80;
						}
					} else {						
						// Cnx bottom
						l_s = '<div id="cnx_top_'+current_user+'" style="height:18px;"></div>\
						<table width="80"  height="80" cellspacing="0" cellpadding="0" id="user'+current_user+'" style="border:1px solid white;"><tbody><tr id="ctntr_'+j+'_'+i+'">\
						<td valign="top" align="center" colspan="1" height="80" id="ctn_'+j+'_'+i+'">\
						<div class="linkname"  id="linkname'+current_user+'" onclick="$p.plugin.organigram.contextual(event,'+current_user+',\''+$p.plugin.organigram.tab[0][current_user].long_name+'\',\''+$p.plugin.organigram.tab[0][current_user].email+'\');">\
						'+$p.plugin.organigram.tab[0][current_user].picture.replace("../../","")+'\
						<br>'+$p.plugin.organigram.tab[0][current_user].long_name+'\
						</div></td></tr></tbody></table>';
						// Cnx bottom
						l_s += '<div id="cnx_bottom_'+current_user+'" style="'+((i==0 && j==0)?'padding-left:4px;':'')+'"><table width="82"  height="20" cellspacing="0" cellpadding="0" id="link_bottom'+current_user+'" ><tbody><tr>\
						<td width="40" height="20" id="link_bottom_left'+current_user+'" class="lineRightLow">&nbsp;</td>\
						<td width="40" height="20" id="link_bottom_right'+current_user+'" class="lineLeftLow">&nbsp;</td>\
						</tr></tbody></table></div>';
						
						// Insert new table
						if(!$('table'+j)) {
							var newTable = '<table id="table'+j+'" colspan="1" width="80" height="80" cellspacing="0" cellpadding="0" valign="bottom">\
							<tbody><tr id="table_tr'+j+'" height="80">\
							<td id="user_td'+current_user+'" height="80" colspan="1" valign="bottom" align="center">'+l_s+'</td></tr></tbody></table>';
							$("manager_container"+user_id).innerHTML += newTable;
						}
						// Insert column
						else {
							$p.print('table_tr'+j,$('table_tr'+j).innerHTML+'<td id="user_td'+current_user+'" height="80" colspan="1" valign="bottom" align="center">'+l_s+'</td>');							
						}
						if(!$('ctn_'+(j+1)+'_'+i) && prevEl!='') {
							for(k=(j+1);k<$p.plugin.organigram.mgrhighlevel;k++) {
								var newTd = new Element ( 'td' , { 'id' : 'ctn_'+k+'_'+i , 'width' :  '82', 'height' :  '80', 'valign':'bottom','align':'center'  });							
								$("table_tr"+k).insertBefore(newTd,null);
								$('ctn_'+k+'_'+i).innerHTML = '<div style="width:82px;">&nbsp;</div>';
							}
						}
						prevEl = 'ctn_'+(j+1)+'_'+i;
					}
				}
			}
			node += ','+data[i]+',';
		}

		for(k in branch)
		{
			if(!isNaN(parseInt(k)))
			{
				if(branch[k].length==1) {
					l_s ='<table width="100%" cellspacing="0" cellpadding="0" border="0" ><tbody><tr valign="top" id="link_bottom'+branch[k][0]+'">\
					<td width="80" id="link_bottom_left'+branch[k][0]+'" class="lineRight"><div id="add_link_bottom_left'+branch[k][0]+'" style="width:200px;text-align:left;">&nbsp;</div></td>\
					<td width="80" id="link_bottom_right'+branch[k][0]+'" class="lineLeft"><div id="add_link_bottom_right'+branch[k][0]+'"style="width:200px;">&nbsp;</div></td>\
					</tr></tbody></table>';
					$("cnx_bottom_"+branch[k][0]).innerHTML = l_s;
					l_s ='<table width="100%" cellspacing="0" cellpadding="0" border="0" ><tbody><tr valign="top" id="link_top'+k+'">\
					<td width="80" id="link_top_left'+k+'" class="lineRight">&nbsp;</td>\
					<td width="80" id="link_top_right'+k+'" class="lineLeft">&nbsp;</td>\
					</tr></tbody></table>';
					if($("cnx_top_"+k)) {
						$("cnx_top_"+k).innerHTML = l_s;
					}
					
				} else {
					l_s ='<table width="100%" cellspacing="0" cellpadding="0" border="0" ><tbody><tr valign="top" id="link_top'+k+'">\
					<td width="80" id="link_top_left'+k+'" class="lineRight">&nbsp;</td>\
					<td width="80" id="link_top_right'+k+'" class="lineLeft">&nbsp;</td>\
					</tr></tbody></table>';
					if($("cnx_top_"+k)) {
						$("cnx_top_"+k).innerHTML = l_s;
					}
					l_s ='<table width="100%" cellspacing="0" cellpadding="0" border="0" ><tbody><tr valign="top" id="link_bottom'+branch[k][0]+'">\
					<td width="80" id="link_bottom_left'+branch[k][0]+'" class="lineRight">&nbsp;</td>\
					<td width="80" id="link_bottom_right'+branch[k][0]+'" class="lineLeftLow">&nbsp;</td>\
					</tr></tbody></table>';
					if($("cnx_bottom_"+branch[k][0]))
						$("cnx_bottom_"+branch[k][0]).innerHTML = l_s;
					l_s ='<table width="100%" cellspacing="0" cellpadding="0" border="0" ><tbody><tr valign="top" id="link_bottom'+branch[k][branch[k].length-1]+'">\
					<td width="80" id="link_bottom_left'+branch[k][branch[k].length-1]+'" class="lineRightLow">&nbsp;</td>\
					<td width="80" id="link_bottom_right'+branch[k][branch[k].length-1]+'" class="lineLeft">&nbsp;</td>\
					</tr></tbody></table>';
					if($("cnx_bottom_"+branch[k][branch[k].length-1]))
						$("cnx_bottom_"+branch[k][branch[k].length-1]).innerHTML = l_s;
				}
			}
		}
	},
	/*
        Function:   $p.plugin.organigram.initvar
                                    
			 initialize global variables
        Parameters:
			response - XML object 
            vars (array) - variables (optionnal)
    */
	initvar:function(response,vars) {

		if(response['response']==0) {
			if(vars['user_id']==$p.app.user.id) {
				$('organigram'+vars['user_id']).innerHTML = "<div><img src='../images/ico_alert.gif' alt='"+lg('alert')+"'/>&nbsp;"+lg('msgErrNoOrganigram')+"&nbsp;<a href='#' onclick='$p.notebook.selectMenuOption("+vars['user_id']+",1);return false;'>"+lg('lblDefineManager')+"</a></div>";
			} else {
				$('organigram'+vars['user_id']).innerHTML = "<div><img src='../images/ico_alert.gif' alt='"+lg('alert')+"'/>&nbsp;"+lg('msgErrUserNoOrganigram')+"</div>";
			}
		} else {
			$p.plugin.organigram.mgrhighlevel = parseInt(response['mgrhighlevel']);
			$p.plugin.organigram.manager = eval(response['manager']);
			$p.plugin.organigram.managed =eval(response['managed']);
			$p.plugin.organigram.tab =  eval("["+response['tab']+"]");
			$p.plugin.organigram.v_manager_height = response['v_manager_height'];

			$p.plugin.organigram.addSelectUserInOrganigram(vars['user_id']);
			$p.plugin.organigram.addManagedUserInOrganigram(vars['user_id']);
			$p.plugin.organigram.addManagerUserInOrganigram(vars['user_id']);
			if(vars['user_id']!=$p.app.user.id) {
				$('mypos'+vars['user_id']).style.display = 'block';
			}
		}
        $p.print('notebook'+vars['user_id']+'_breadcrumb',$p.app.breadCrumbs(
                [
                    {'label':lg('home'),'link':'','fct':'$p.app.openHome();return false;'},
                    {'label':(vars['user_id'] == $p.app.user.id ? lg('myNotebook') : lg('Notebook')),'link':'','fct':'$p.notebook.open('+vars['user_id']+',\'note\');return false;'},
                    {'label':lg('lblOrganigram'),'link':'','fct':''}
                ]
            )
        );	
	},
	/*
        Function:   $p.plugin.organigram.insertManagedInBranch
                                    
			 insert the managed user in the branch
    */
	insertManagedInBranch:function(selUser) {
		var l_s = '';
		if($p.plugin.organigram.tab[0][$p.app.user.id] != indef) {
			for(i=1;i<($p.plugin.organigram.myposition.length-1);i++) {
				if(!$('linkname'+$p.plugin.organigram.myposition[i])) {
				
				if($('link_left'+$p.plugin.organigram.myposition[i-1]))
					$('link_left'+$p.plugin.organigram.myposition[i-1]).className = "lineRight";
				if($('link_right'+$p.plugin.organigram.myposition[i-1]))
					$('link_right'+$p.plugin.organigram.myposition[i-1]).className = "lineLeft";

					l_s+='<table width="80"  height="80" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr><td>\
					<div id="cnx_top_'+$p.plugin.organigram.myposition[i]+'">\
					<table width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr valign="top" id="link'+$p.plugin.organigram.myposition[i]+'">\
					<td width="50%" class="lineRight" id="link_top_left'+$p.plugin.organigram.myposition[i]+'">&nbsp;</td>\
					<td width="50%" class="lineLeft" id="link_top_right'+$p.plugin.organigram.myposition[i]+'">&nbsp;</td>\
					</tr></tbody></table>\
					</div>\
					<table width="100%" height="80" cellspacing="0" cellpadding="0" border="0" style="background-color:E9E9E9;border:1px solid white;">\
					<tbody><tr><td width="80" valign="top" height="80" align="center">\
					<div  class="linkname" onclick="$p.plugin.organigram.contextual(event,'+$p.plugin.organigram.myposition[i]+',\''+$p.plugin.organigram.tab[0][$p.plugin.organigram.myposition[i]].long_name+'\',\''+$p.plugin.organigram.tab[0][$p.plugin.organigram.myposition[i]].email+'\');" id="linkname'+$p.plugin.organigram.myposition[i]+'">\
					'+$p.plugin.organigram.tab[0][$p.plugin.organigram.myposition[i]].picture.replace("../../","")+"<br />  "+$p.plugin.organigram.tab[0][$p.plugin.organigram.myposition[i]].long_name+'\
					</div>\
					</td></tr></tbody></table>\
					<div id="cnx_bottom_'+$p.plugin.organigram.myposition[i]+'">\
					<table width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr valign="top" id="link'+$p.plugin.organigram.myposition[i]+'">\
					<td width="50%" id="link_left'+$p.plugin.organigram.myposition[i]+'" class="">&nbsp;</td>\
					<td width="50%" id="link_right'+$p.plugin.organigram.myposition[i]+'" class="">&nbsp;</td></tr></tbody></table>\
					</div></td></tr></table>';
					l_s += '<table width="80"  height="80" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr><td id="user'+$p.plugin.organigram.myposition[i]+'_cnx"></td></tr></tbody></table>';
					if($('user'+$p.plugin.organigram.myposition[i-1]+'_cnx'))
						$('user'+$p.plugin.organigram.myposition[i-1]+'_cnx').innerHTML = l_s;
				}
				l_s = '';
			}
		} else {
			$p.plugin.organigram.manager_cnx = $p.plugin.organigram.myposition[1];
			$("popupcontent").style.height = (($p.plugin.organigram.myposition.length-1)*80+250)+"px";
			l_s = "<div style='position: absolute;margin-top:16px;width:200px;height:"+(($p.plugin.organigram.myposition.length-1)*80)+"px; '>\
			<div class='cachegrey' style='z-index:2;opacity: 0.5;filter: alpha(opacity=50);'></div>\
			<img width='12' height='11' src='../images/s.gif' alt='"+lg("close")+"' onclick='$p.plugin.organigram.getMyPosition("+selUser+",1);' class='org_close' style='position:absolute;margin:0 5px 5px 5px;z-index:5;'>\
			<div style='position:absolute;width:100%;z-index:3;'>\
			<table width='100%' cellspacing='0' cellpadding='0'><tr><td class='lineRight' width='50%'>&nbsp;</td><td class='lineLeftHigh' width='50%'>&nbsp;</td></tr></table>";
			
			for(i=1;i<($p.plugin.organigram.myposition.length-1);i++) {
				if(!$('linkname'+$p.plugin.organigram.myposition[i])) {

					if($('link_left'+$p.plugin.organigram.myposition[i-1]))
						$('link_left'+$p.plugin.organigram.myposition[i-1]).className = "lineRight";
					if($('link_right'+$p.plugin.organigram.myposition[i-1]))
						$('link_right'+$p.plugin.organigram.myposition[i-1]).className = "lineLeft";

					l_s+='<table width="80"  height="80" cellspacing="0" cellpadding="0" border="0" align="center"><tbody><tr><td>\
					<div id="cnx_top_'+$p.plugin.organigram.myposition[i]+'">\
					<table width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr valign="top" id="link'+$p.plugin.organigram.myposition[i]+'">\
					<td width="50%" class="lineRight" id="link_top_left'+$p.plugin.organigram.myposition[i]+'">&nbsp;</td>\
					<td width="50%" class="lineLeft" id="link_top_right'+$p.plugin.organigram.myposition[i]+'">&nbsp;</td>\
					</tr></tbody></table>\
					</div>\
					<table width="100%" height="80" cellspacing="0" cellpadding="0" border="0" style="background-color:#E9E9E9;border:1px solid white;">\
					<tbody><tr><td width="80" valign="top" height="80" align="center">\
					<div  class="linkname" onclick="$p.plugin.organigram.contextual(event,'+$p.plugin.organigram.myposition[i]+',\''+$p.plugin.organigram.users[0][$p.plugin.organigram.myposition[i]].long_name+'\',\''+$p.plugin.organigram.users[0][$p.plugin.organigram.myposition[i]].email+'\');" id="linkname'+$p.plugin.organigram.myposition[i]+'">\
					'+$p.plugin.organigram.users[0][$p.plugin.organigram.myposition[i]].picture.replace("../../","")+"<br />  "+$p.plugin.organigram.users[0][$p.plugin.organigram.myposition[i]].long_name+'\
					</div>\
					</td></tr></tbody></table>\
					<div id="cnx_bottom_'+$p.plugin.organigram.myposition[i]+'">\
					<table width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr valign="top" id="link'+$p.plugin.organigram.myposition[i]+'">\
					<td width="50%" id="link_left'+$p.plugin.organigram.myposition[i]+'" class="'+(i<($p.plugin.organigram.myposition.length-2)?'lineRight':'')+'">&nbsp;</td>\
					<td width="50%" id="link_right'+$p.plugin.organigram.myposition[i]+'" class="'+(i<($p.plugin.organigram.myposition.length-2)?'lineLeft':'')+'">&nbsp;</td></tr></tbody></table>\
					</div></td></tr></table>';
				} else {
					manager_cnx = $p.plugin.organigram.myposition[i];
				}
				
			}
			l_s += "</div></div>";
			$p.print('add_link_bottom_left'+$p.plugin.organigram.manager_cnx,l_s);

		}
		if($('linkname'+$p.app.user.id))
			$('linkname'+$p.app.user.id).style.border = '2px solid red';
		l_s = '';
	},
	/*
        Function:   $p.plugin.organigram.getMyPosition
                                    
			 Get my position in the hierarchy
        Parameters:
			selUid - selected user id
    */
	getMyPosition:function(selUid,close) {
		if($('chkmypos'+selUid).checked && (close==indef || close==0)) {
			$p.ajax.call("../includes/plugins/plugin_organigram/portal/xml_myposition.php?u="+selUid,
				{
					'type':'load',
					'callback':
					{
						'function':$p.plugin.organigram.displayMyPosition,
						'variables':
									{
										'selUid':selUid
									}
					}
				}
			);
		} else {
			$('chkmypos'+selUid).checked = 0;
			$p.plugin.organigram.hideMyPosition(selUid);
		}
        return false;
	},
	/*
        Function:   $p.plugin.organigram.hideMyPosition
                                    
			 Hide my position in the organigram
        Parameters:
			selUid - selected user id
    */
	hideMyPosition:function(selUid) {
		if($('linkname'+$p.app.user.id))
			$('linkname'+$p.app.user.id).style.border = '';
		if($('add_link_bottom_left'+$p.plugin.organigram.manager_cnx))
			$p.print('add_link_bottom_left'+$p.plugin.organigram.manager_cnx,"&nbsp;");
		$p.plugin.organigram.myposition = [];
	},
	/*
        Function:   $p.plugin.organigram.displayMyPosition
                                    
			 Display my position in the organigram
        Parameters:
			response - XML object 
            vars (array) - variables (optionnal)
    */
	displayMyPosition:function(response,vars) {
        var l_result = response.getElementsByTagName("myposition");
		var mypos = $p.ajax.getVal(l_result[0],"data","str",false,0);
		$p.plugin.organigram.users = eval("["+$p.ajax.getVal(l_result[0],"userinfo","str",false,0)+"]");
		if(mypos!=0) {
			$p.plugin.organigram.myposition = mypos.split(',');
			if($('linkname'+$p.app.user.id))
				$('linkname'+$p.app.user.id).style.border = '2px solid red';
			$p.plugin.organigram.insertManagedInBranch(vars['selUid']);
		} else {
			$p.app.error.display(lg("msgErrPositionNoFound"),3);
		}
	},
	/*
        Function:   $p.plugin.organigram.displayOrganigram
                                    
			 Display the organigram
        Parameters:
			user_id - selected user id
    */
	displayOrganigram:function(user_id)
	{
		$p.plugin.organigram.myposition = [];
		$p.notebook.open(user_id,"note",indef,8);
		
		var l_s = '<div id="organigram'+user_id+'" style="overflow:auto;" >'
		+"<table style='width:100%;border-collapse: collapse;'><tbody>"
		+"<tr><td id='selectedusercontainer"+user_id+"' align='center' valign='bottom' >"
		+'<div style="margin-top:100px;"><img src="../images/ajax-loader.gif" alt="Loading..."/></div>'
		+"</td></tr>"
		+"</tbody></table>";
		
		l_s += '<div id="mypos'+user_id+'" style="display:none;">\
		<input type="checkbox" onclick="$p.plugin.organigram.getMyPosition('+user_id+')" id="chkmypos'+user_id+'" />\
		<label for="chkmypos'+user_id+'">'+lg('lblDisplayMyPosition')+'</label>\
		</div>';
		
		l_s += '</div>';
		if($('notebook'+user_id+'_content')) {
			$p.print('notebook'+user_id+'_content',l_s);
		} else {
			$p.print('popupcontent',l_s);
		}
		
		$p.ajax.call("../includes/plugins/plugin_organigram/portal/json_getorganigram.php?uid="+user_id,
					{
						'type':'load',
                        'alarm':false,
                        'forceExecution':false,
                        'callback':
                        {
							'function':$p.plugin.organigram.initvar,
							'variables':
							{
								'user_id':user_id
                            }
                        },
                        'source':'json'
                    }
        ); 
	},
	/*
        Function:   $p.plugin.organigram.contextual
                                    
			 Create the contextual menu
        Parameters:
			e - event
			id - element id
    */
    contextual: function(e,id,name,email)
    {
        $p.html.buildContextualMenu(e,[
                {'title':lg("selectUser"),'fct':"$p.plugin.organigram.displayOrganigram("+id+");return false;"},
                {'title':lg("seehisprofil"),'fct':'$p.notebook.selectMenuOption('+id+',1,\'\',\'\',\''+name+'\');'},
                {'title':(__NETWORK_TYPE == 'R' ? lg("addInMyNetwork") : lg('followThisPerson')) ,'fct':"$p.network.card.load("+id+")"},
				{'title':lg("contactByEmail"),'href':"mailto:"+email}
            ]
        );
    }
}