Index: trunk/contactcenter/inc/class.ui_data.inc.php
===================================================================
--- trunk/contactcenter/inc/class.ui_data.inc.php	(revision 284)
+++ trunk/contactcenter/inc/class.ui_data.inc.php	(revision 285)
@@ -14,5 +14,5 @@
   \***************************************************************************/
 
-
+	
 	class ui_data
 	{
@@ -20,8 +20,8 @@
 			'data_manager' => true,
 		);
-
+		
 		var $bo;
 		var $typeContact;
-
+		
 		var $page_info = array(
 			'n_cards'          => 20,
@@ -34,12 +34,12 @@
 			'actual_catalog'   => false
 		);
-
+		
 		/*!
-
+		
 			@function ui_data
 			@abstract The constructor. Sets the initial parameters and loads
 				the data saved in the session
 			@author Raphael Derosso Pereira
-
+			
 		*/
 		function ui_data()
@@ -47,11 +47,7 @@
 			$temp = $GLOBALS['phpgw']->session->appsession('ui_data.page_info','contactcenter');
 			$temp2 = $GLOBALS['phpgw']->session->appsession('ui_data.all_entries','contactcenter');
-
-			//TODO: Achar um modo de descarregar este array da sessï¿œo quando o usuï¿œrio sair da tela do contactcenter.
-			//TODO: Descarregar este array da memï¿œria toda vez que uma nova consulta por letras ou mudanï¿œa de catï¿œlogo for feita.
-			$temp3 = $GLOBALS['phpgw']->session->appsession('ui_data.last_search_ids','contactcenter');
-
+			
 			$this->bo = CreateObject('contactcenter.bo_contactcenter');
-
+			
 			if ($temp)
 			{
@@ -63,10 +59,5 @@
 				$this->all_entries = $temp2;
 			}
-
-			if ($temp3)
-			{
-				$this->last_search_ids = $temp3;
-			}
-
+			
 			if (!$this->page_info['actual_catalog'])
 			{
@@ -74,7 +65,7 @@
 				$this->page_info['actual_catalog'] = $catalogs[0];
 			}
-
-			$this->page_info['actual_catalog'] =& $this->bo->set_catalog($this->page_info['actual_catalog']);
-
+			
+			$this->page_info['actual_catalog'] =& $this->bo->set_catalog($this->page_info['actual_catalog']);			
+			
 			if($this->page_info['actual_catalog']['class'] == 'bo_group_manager')
 				$this -> typeContact = 'groups';
@@ -84,13 +75,13 @@
 
 		/*!
-
+		
 			@function index
 			@abstract Builds the Main Page
 			@author Raphael Derosso Pereira
 			@author Jonas Goes
-
-		*/
+			
+		*/		
 		function index()
-		{
+		{	
 			if(!@is_object($GLOBALS['phpgw']->js))
 			{
@@ -101,11 +92,11 @@
 			$GLOBALS['phpgw']->js->validate_file('venus','jsStructUtil');
 			$GLOBALS['phpgw']->js->validate_file('venus','cssUtil');
-
+			
 //			$GLOBALS['phpgw']->js->set_onload('setTimeout(\'updateCards()\',1000)');
 			$GLOBALS['phpgw']->common->phpgw_header();
-
+			
 			$GLOBALS['phpgw']->template->set_file(array('index' => 'index.tpl'));
 			$GLOBALS['phpgw']->template->set_var('cc_root_dir', $GLOBALS['phpgw_info']['server']['webserver_url'].'/contactcenter/');
-
+			
 			/* Quick Add */
 			$GLOBALS['phpgw']->template->set_var('cc_qa_alias',lang('Alias').':');
@@ -116,6 +107,7 @@
 			$GLOBALS['phpgw']->template->set_var('cc_qa_save',lang('Save'));
 			$GLOBALS['phpgw']->template->set_var('cc_qa_clear',lang('Clear'));
+			$GLOBALS['phpgw']->template->set_var('cc_qa_close',lang('Close'));
 			/* End Quick Add */
-
+			
 			$cc_css_file = $GLOBALS['phpgw_info']['server']['webserver_url'].'/contactcenter/styles/cc.css';
 			$cc_card_image_file = $GLOBALS['phpgw_info']['server']['webserver_url'].'/contactcenter/templates/default/images/card.png';
@@ -123,10 +115,10 @@
 			$GLOBALS['phpgw']->template->set_var('cc_dtree_css', $cc_dtree_file);
 			$GLOBALS['phpgw']->template->set_var('cc_card_image',$cc_card_image_file);
-
+			
 			$GLOBALS['phpgw']->template->set_var('cc_personal',lang('Personal'));
-
+			
 			$GLOBALS['phpgw']->template->set_var('cc_full_add',lang('Full Add'));
 			$GLOBALS['phpgw']->template->set_var('cc_reset',lang('Reset'));
-
+			
 			$GLOBALS['phpgw']->template->set_var('cc_personal_data',lang('Personal Data'));
 			$GLOBALS['phpgw']->template->set_var('cc_addresses',lang('Addresses'));
@@ -137,5 +129,5 @@
 			$GLOBALS['phpgw']->template->set_var('cc_catalogs',lang('Catalogues'));
 			$GLOBALS['phpgw']->template->set_var('cc_group_add',lang('Group Add'));
-
+			
 			/* Panel */
 			$GLOBALS['phpgw']->template->set_var('cc_panel_new',lang('New').'...');
@@ -143,5 +135,7 @@
 			$GLOBALS['phpgw']->template->set_var('cc_panel_table',lang('Table View'));
 			$GLOBALS['phpgw']->template->set_var('cc_panel_cards',lang('Cards View'));
-
+			$GLOBALS['phpgw']->template->set_var('cc_btn_import_export', lang('Import/Export'));
+			$GLOBALS['phpgw']->template->set_var('cc_btn_new', lang("New..."));
+			
 			$GLOBALS['phpgw']->template->set_var('cc_panel_search_found',lang('Showing found entries'));
 			$GLOBALS['phpgw']->template->set_var('cc_panel_first_page',lang('First Page'));
@@ -151,5 +145,5 @@
 			$GLOBALS['phpgw']->template->set_var('cc_all',lang('all'));
 			/* End Panel */
-
+			
 			/* Messages */
 			$GLOBALS['phpgw']->template->set_var('cc_msg_no_cards',lang('No Cards'));
@@ -166,10 +160,11 @@
 			$GLOBALS['phpgw']->template->set_var('cc_empty',lang('Empty'));
 			/* End Messages */
-
+			
 			$GLOBALS['phpgw']->template->set_var('cc_results',lang('Results'));
 			$GLOBALS['phpgw']->template->set_var('cc_is_my',lang('Is My'));
+			$GLOBALS['phpgw']->template->set_var('cc_ie_personal',lang('Import/Export pesonal contacts'));
 			$GLOBALS['phpgw']->template->set_var('cc_btn_search',lang('Search'));
 			$GLOBALS['phpgw']->template->set_var('cc_add_relation',lang('Add Relation'));
-			$GLOBALS['phpgw']->template->set_var('cc_del_relation',lang('Remove Selected Relations'));
+			$GLOBALS['phpgw']->template->set_var('cc_del_relation',lang('Remove Selected Relations'));			
 			$GLOBALS['phpgw']->template->set_var('cc_msg_group',lang('Group'));
 			$GLOBALS['phpgw']->template->set_var('cc_msg_contact_full',lang('Contact [Full]'));
@@ -179,6 +174,56 @@
 			$GLOBALS['phpgw']->template->set_var('phpgw_img_dir', $GLOBALS['phpgw_info']['server']['webserver_url'] . '/phpgwapi/images');
 
+			$GLOBALS['phpgw']->template->set_var('cc_msg_import_contacts', lang('Import Contacts'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_export_contacts', lang('Export Contacts'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_expresso_info_csv', lang('The Expresso supports the contacts importation in the CSV file format.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_choose_file_type', lang('Select the file type'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_outlook_express', lang('Outlook Express'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_outlook2k', lang('Outlook 2000'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_expresso_default', lang('Expresso (default)'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_choose_contacts_file', lang('Select the file that contains the contacts to be imported:'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_close_win', lang('Close'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_close', lang('Close'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_ie_personal', lang('Import / Export personal Contacts'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_import_fail', lang('The importation has failed. Verify the file format.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_importing_contacts', lang('Importing Contacts...'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_import_finished', lang('The importation has finished.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_new', lang(' new'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_failure', lang(' failed'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_exists', lang(' were existent'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_show_more_info', lang('show more info'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_clean', lang('Clean'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_invalid_csv', lang('Select a valid CSV file to import your contacts'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_export_csv', lang('Select the format type that you want to export your contacts'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_automatic', lang('Automatic'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_export_error', lang('An error has occurred while the exportation.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_new_email', lang('New Email'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_main', lang('Main'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_alternative', lang('Alternative'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_select_email', lang('Select E-Mail'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_new_phone', lang('New Telephone'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_home', lang('Home'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_cellphone', lang('Cellphone'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_work', lang('Work'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_fax', lang('Fax'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_pager', lang('Pager'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_choose_phone', lang('Select the telephone'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_warn_firefox', lang('Warning: Too old version of Firefox'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_firefox_half1', lang('For this application work correctly</u>'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_firefox_half2', lang('it\'s necessary to update your Firefox Browser for a new version (version > 1.5) Install now clicking in the link bellow, or if you want to update it later'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_click_close', lang('click Close'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_install_now', lang('Install Now'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_install_new_firefox', lang('Install a new Firefox version'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_moz_thunderbird', lang('Export as Mozilla Thunderbird CSV.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_outlook_express_pt', lang('Export as Outlook Express (Portuguese) CSV.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_outlook_express_en', lang('Export as Outlook Express (English) CSV.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_outlook_2k_pt', lang('Export as Outlook 2000 (Portuguese) CSV.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_outlook_2k_en', lang('Export as Outlook 2000 (English) CSV.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_expresso_default_csv', lang('Export as Expresso (Default) CSV.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_copy_to_catalog', lang('Copy to personal catalog.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_add_contact_to_group', lang('You did not add any contact for this group.'));
+			$GLOBALS['phpgw']->template->set_var('cc_msg_fill_field_name', lang('Fill the field Full Name'));
+			
 			$GLOBALS['phpgw']->template->parse('out','index');
-
+			
 			$api = CreateObject('contactcenter.ui_api');
 			$main = $api->get_full_add();
@@ -191,12 +236,12 @@
 		}
 
-
+		
 		/*!
-
+		
 			@function data_manager
-			@abstract Calls the right method and passes to it the right
+			@abstract Calls the right method and passes to it the right 
 				parameters
 			@author Raphael Derosso Pereira
-
+		
 		*/
 		function data_manager()
@@ -207,19 +252,17 @@
 				case 'set_n_cards':
 					return $this->set_n_cards((int)$_GET['ncards']);
-
-				case 'get_cards_data':
-
+					
+				case 'get_cards_data':					
 					$ids = false;
 					// To support ldap catalogs using accentuation
 					if ($_POST['letter'] == 'search' && isset($_POST['data']))
 					{
-						//$ids = utf8_decode($this->search($_POST['data']));
-						$ids = $this->search($_POST['data']);
+						$ids = utf8_decode($this->search($_POST['data']));
 					}
-
-					//return $this->get_cards_data($_POST['letter'], $_POST['page'], unserialize(str_replace('\\"','"',$ids)));
-					return $this->get_cards_data($_POST['letter'], $_POST['page'], $ids);
-					//return $this->get_cards_data($_POST['letter'], $_POST['page'], unserialize(str_replace('\\"','"',$_POST['ids'])));
-
+					
+					if(isset($_SESSION['ids']))
+						$ids = $_SESSION['ids'];
+					
+					return $this->get_cards_data($_POST['letter'], $_POST['page'], $ids);						
 				case 'get_cards_data_get':
 					return $this->get_cards_data($_GET['letter'], $_GET['page'], unserialize(str_replace('\\"','"',$_GET['ids'])));
@@ -229,9 +272,12 @@
 					return $this->get_photo($_GET['id']);
 
-
+				case 'get_visible_all_ldap':
+					echo $this->get_visible_all_ldap();
+					return;
+					
 				/* Catalog Methods */
 				case 'set_catalog':
 					return $this->set_catalog($_GET['catalog']);
-
+					
 				case 'get_catalog_tree':
 					echo serialize($this->get_catalog_tree($_GET['level']));
@@ -250,12 +296,12 @@
 					echo serialize($this->get_catalog_add_contact(utf8_decode($_POST['id'])));
 					return;
-
+					
 				/* Full Add Methods */
 				case 'get_full_data':
 					return $this->get_full_data($_GET['id']);
-
+				
 				case 'get_group':
 					return $this->get_group_data($_GET['id']);
-
+					
 				case 'get_contact_full_add_const':
 					return $this->get_contact_full_add_const();
@@ -269,28 +315,30 @@
 				case 'get_states':
 					return $this->get_states($_GET['country']);
-
+					
 				case 'get_cities':
 					return $this->get_cities($_GET['country'], $_GET['state'] ? $_GET['state'] : null);
-
-
+					
+					
 				/* Other Methods */
-				case 'quick_add':
+				case 'quick_add':															
 					return $this->quick_add($_POST['add']);
-
-				case 'add_group':
+				
+				case 'add_group':															
 					return $this->add_group($_POST['add']);
-
+									
 				case 'remove_entry':
 					return $this->remove_entry((int)$_GET['remove']);
-
+				
 				case 'remove_all_entries':
 					return $this->remove_all_entries();
 
 				case 'remove_group':
-
-					return $this->remove_group((int)$_GET['remove']);
+					 					
+					return $this->remove_group((int)$_GET['remove']);					
 
 				case 'search':
-					return $this->search(str_replace('\\"', '"', $_GET['data']));
+					$ids = false;
+					$ids = $this->search($_GET['data']);
+					return $this->get_cards_data('search', '1', $ids);
 
 				case 'email_win':
@@ -326,11 +374,11 @@
 
 		/*!
-
+		
 			@function set_n_cards
 			@abstract Informs the class the number of cards the page can show
 			@author Raphael Derosso Pereira
-
+			
 			@param integer $n_cards The number of cards
-
+			
 		*/
 		function set_n_cards($n_cards)
@@ -341,17 +389,17 @@
 				echo 1;
 			}
-
+			
 			$this->save_session();
 		}
-
+				
 		/*!
-
+		
 			@function set_catalog
 			@abstract Sets the current catalog selected by the user
 			@author Raphael Derosso Pereira
-
+			
 			@param string $id_catalog The sequence of IDs to reach the catalog
 				separated by commas
-
+		
 		*/
 		function set_catalog($id_catalog)
@@ -359,5 +407,5 @@
 			$id_catalog = str_replace('\\"', '"', $id_catalog);
 			$temp =& $this->bo->set_catalog($id_catalog);
-
+			
 			if ($temp)
 			{
@@ -366,7 +414,7 @@
 				$this->page_info['actual_catalog'] =& $temp;
 				$this->save_session();
-
+				
 				$catalog_info = $this->bo->get_branch_by_level($this->bo->catalog_level[0]);
-
+				
 				if ($catalog_info['class'] === 'bo_global_ldap_catalog' ||
 				    $catalog_info['class'] === 'bo_catalog_group_catalog')
@@ -378,5 +426,5 @@
 					$perms = 15;
 				}
-
+				
 				echo serialize(array(
 					'status' => 'ok',
@@ -386,5 +434,5 @@
 				return;
 			}
-
+			
 			echo serialize(array(
 				'status' => 'ok',
@@ -392,16 +440,16 @@
 			));
 		}
-
-
+		
+		
 		/*!
-
+		
 			@function get_catalog_tree
 			@abstract Returns the JS serialized array to used as the tree
 				level
 			@author Raphael Derosso Pereira
-			@author Mï¿œrio Cï¿œsar Kolling (error messages and timeout)
-
-			@param (string) $level The level to be taken
-
+            @author Mário César Kolling (error messages and timeout)
+			
+			@param (string) $level The level to be taken 
+		
 		*/
 		function get_catalog_tree($level)
@@ -412,5 +460,5 @@
 
 				$parent = '0';
-
+				
 				if (!($tree = $this->bo->get_catalog_tree($level)))
 				{
@@ -426,5 +474,5 @@
 				$parent = substr($level, 0, $last_dot);
 				$child = substr($level, $last_dot+1, strlen($level));
-
+			
 				if (!($tree[$child] = $this->bo->get_catalog_tree($level)))
 				{
@@ -445,8 +493,8 @@
 				}
 			}
-
+			
 			$folderImageDir = $GLOBALS['phpgw']->common->image('contactcenter','globalcatalog-mini.png');
 			$folderImageDir = substr($folderImageDir, 0, strpos($folderImageDir, 'globalcatalog-mini.png'));
-
+			
 			// Deals with error messages from the server and returns them to the browser
 			if ($tree['msg'])
@@ -474,48 +522,9 @@
 					'status' => 'error'
 				);
-
 			}
 		}
-
-/*		function get_catalog_tree($level, $name = 'tree')
-		{
-			if ($level === '0')
-			{
-				$folderImageDir = $GLOBALS['phpgw_info']['server']['webserver_url'] . '/phpgwapi/dftree/images/';
-				$tree_js =  $name." = new dFTree({'name': '".$name."'});\n";
-
-				$parent = '0';
-				$child  = '0';
-
-				if (!($tree = $this->bo->get_catalog_tree($level)))
-				{
-					return '0';
-				}
-			}
-			else
-			{
-				$last_dot = strrpos($level,'.');
-				$parent = substr($level, 0, $last_dot);
-				$child = substr($level, $last_dot+1, strlen($level));
-
-				$tree_js = '';
-
-				if (!($tree[$child] = $this->bo->get_catalog_tree($level)))
-				{
-					return '0';
-				}
-			}
-
-			$folderImageDir = $GLOBALS['phpgw']->common->image('contactcenter','globalcatalog-mini.png');
-			$folderImageDir = substr($folderImageDir, 0, strpos($folderImageDir, 'globalcatalog-mini.png'));
-
-			$tree_js .= $this->convert_tree($tree, $name, $folderImageDir, $parent);
-
-			return $tree_js;
-		}
-*/
-
+		
 		/*!
-
+		
 			@function get_actual_catalog
 			@abstract Returns the actual selected Catalog
@@ -524,7 +533,7 @@
 		*/
 		function get_actual_catalog()
-		{
+		{			
 			$level = $this->bo->get_level_by_branch($this->bo->get_actual_catalog(), $this->bo->tree['branches'], '0');
-
+			
 			if ($level)
 			{
@@ -540,13 +549,13 @@
 			);
 		}
-
+		
 		/*!
-
+		
 			@function get_cards_data
 			@abstract Returns the information that is placed on the cards
 			@author Raphael Derosso Pereira
-
+			
 			@param string $letter The first letter to be searched
-			@param (int)  $page The page to be taken
+			@param (int)  $page The page to be taken 
 			@param (str)  $ids The ids to be taken in case of search
 
@@ -556,16 +565,17 @@
 		function get_cards_data($letter, $page, $ids)
 		{
+			if( $ids )
+				$_SESSION['ids'] = $ids;		   
 
 			// It's an external catalog?
 			$external = $this->bo->is_external($this->page_info['actual_catalog']);
-
 			//echo $page."\n";
 			if ($letter !== 'search' and ($letter != $this->page_info['actual_letter'] or
-			    ($letter == $this->page_info['actual_letter'] and $page == $this->page_info['actual_page']) or
+			    ($letter == $this->page_info['actual_letter'] and $page == $this->page_info['actual_page']) or 
 			    $this->page_info['changed']))
 			{
 				unset($ids);
 				$this->page_info['changed'] = false;
-
+				 
 				switch ($this->page_info['actual_catalog']['class'])
 				{
@@ -654,7 +664,7 @@
 							);
 						}
-
+						
 						$find_field[0] = array('contact.id_contact','contact.names_ordered');
-
+						
 						$find_other[0] = array(
 							//'offset' => (($page-1)*$this->page_info['n_cards']),
@@ -662,12 +672,9 @@
 							'order'  => 'contact.names_ordered'
 						);
-
+						
 						break;
-
-					//case 'bo_external_ldap_catalog':
-
-					//	break;
-
+					
 					case 'bo_global_ldap_catalog':
+					
 						$field_name = 'id_contact';
 
@@ -718,10 +725,5 @@
 											'value' => 'u'
 											),
-											/*1 => array(
-											'field' => 'contact.account_type',
-											'type'  => '=',
-											'value' => 'g'
-											),*/
-											2 => array(
+											1 => array(
 											'field' => 'contact.account_type',
 											'type'  => '=',
@@ -834,5 +836,5 @@
 										'value' => 'g'
 										),*/
-										2 => array(
+										1 => array(
 										'field' => 'contact.account_type',
 										'type'  => '=',
@@ -842,5 +844,4 @@
 								);
 							}
-
 						}
 
@@ -858,5 +859,5 @@
 							$find_field[0] = array('contact.id_contact','contact.names_ordered');
 						}
-
+						
 						$find_other[0] = array(
 							//'offset' => (($page-1)*$this->page_info['n_cards']),
@@ -864,12 +865,12 @@
 							'order'  => 'contact.names_ordered'
 						);
-
+						
 						break;
-
+					
 					case 'bo_company_manager':
 						$field_name = 'id_company';
-
+	
 						$find_field[0] = array('company.id_company','company.company_name');
-
+						
 						$find_other[0] = array(
 							//'offset' => (($page-1)*$this->page_info['n_cards']),
@@ -877,5 +878,5 @@
 							'order'  => 'company.company_name'
 						);
-
+	
 						$find_restric[0] = array(
 							0 => array(
@@ -885,13 +886,13 @@
 							)
 						);
-
+							
 						break;
 
 					case 'bo_group_manager':
-
+					
 						$field_name = 'id_group';
-
+						
 						if ($letter !== 'number')	{
-
+							
 							$find_restric[0] = array(
 								0 => array(
@@ -903,45 +904,45 @@
 						}
 						 else {
-
+							
 							$find_restric[0] = array(
 								0 => array(
 											'field' => 'group.title',
 											'type'  => 'LIKE',
-											'value' => '0%'
+											'value' => '0%'										
 								)
-							);
+							);						
 						}
-
+						
 						array_push($find_restric[0],  array(
 											'field' => 'group.owner',
 											'type'  => '=',
-											'value' => $GLOBALS['phpgw_info']['user']['account_id']
+											'value' => $GLOBALS['phpgw_info']['user']['account_id']										
 								)
 						);
-
-						$find_field[0] = array('group.id_group','group.title','group.short_name');
+						
+						$find_field[0] = array('group.id_group','group.title','group.short_name');						
 						$find_other[0] = array(
 							'order'  => 'group.title'
 						);
-
+						
 						break;
-
+						
 					case 'bo_catalog_group_catalog':
 						$this->page_info['actual_entries'] = false;
-
+						
 						$this->page_info['actual_letter'] = $letter;
 						$this->page_info['actual_page'] = 0;
-
+						
 						$this->save_session();
 						$final[0] = 0;
-						$final[1] = $this -> typeContact;
-						echo serialize($final);
+						$final[1] = $this->typeContact;
+						echo serialize($final);						
 						return;
 
 				}
-
+				
 				$result = $this->bo->find($find_field[0],$find_restric[0],$find_other[0]);
 				$n_entries = count($result);
-
+				
 				if ($n_entries)
 				{
@@ -957,12 +958,12 @@
 				{
 					$this->page_info['actual_entries'] = false;
-
+					
 					$this->page_info['actual_letter'] = $letter;
 					$this->page_info['actual_page'] = 0;
-
-					$this->save_session();
+					
+					$this->save_session();				
 					$final[0] = 0;
-					$final[1] = $this -> typeContact;
-					echo serialize($final);
+					$final[1] = $this->typeContact;
+					echo serialize($final);											
 					return;
 				}
@@ -973,23 +974,23 @@
 					{
 						$this->page_info['actual_entries'][] = $value[$field_name];
-					}
-				}
-			}
-//*************************************************************************
+					} 
+					//print_r($this->page_info['actual_entries']);
+				}
+			}
 			else if ($letter === 'search')
 			{
 				//if (!$ids and $this->page_info['actual_letter'] !== 'search')
-				if (!$ids && !$this->last_search_ids)
+				if (!$ids)
 				{
 					error_log('!$ids e $this->page_info[\'actual_letter\'] != search');
 					$this->page_info['actual_entries'] = false;
-
+					
 					$this->page_info['actual_letter'] = $letter;
 					$this->page_info['actual_page'] = 0;
-
+					
 					$this->save_session();
 					$final[0] = 0;
 					$final[1] = $this -> typeContact;
-					echo serialize($final);
+					echo serialize($final);					
 					return;
 				}
@@ -1007,19 +1008,6 @@
 					return;
 				}
-				else if ($ids || $this->last_search_ids)
-				{
-
-					if ($ids)
-					{
-
-						$this->last_search_ids = $ids;
-
-					}
-					else {
-
-						$ids = $this->last_search_ids;
-
-					}
-
+				else if ($ids)
+				{				
 					$this->page_info['actual_letter']  = $letter;
 					$this->page_info['actual_entries'] = $ids;
@@ -1038,5 +1026,5 @@
 					$page = $this->page_info['n_pages'];
 				}
-
+				
 				$final = array(
 					0 => (int)$this->page_info['n_pages'],
@@ -1050,30 +1038,28 @@
 						5 => 'cc_alias',
 						6 => 'cc_id',
-						7 => 'cc_forwarding_address',
-						8 => 'cc_empNumber',
-						9 => 'cc_department'
+						7 => 'cc_forwarding_address'
 					)
 				);
-
+				
 				//echo 'Page: '.$page.'<br>';
 				$id_i = (($page-1)*$this->page_info['n_cards']);
 				$id_f = $id_i + $this->page_info['n_cards'];
 				$n_entries = count($this->page_info['actual_entries']);
-
+				
 				//echo 'ID_I: '.$id_i.'<br>';
 				//echo 'ID_F: '.$id_f.'<br>';
-				///---------------- Correï¿œï¿œo Temporï¿œria PHP5 -----------------------///
+				///---------------- Correção Temporária PHP5 -----------------------///
 				$ids = array();
-				$array_temp = array();
-
+				$array_temp = array();			
+								
 				foreach($this->page_info['actual_entries'] as $key=>$tmp){
-					$array_temp[] = $tmp;
-				}
-
+					$array_temp[] = $tmp;				
+				}	
+				
 				for($i = $id_i; $i < $id_f and $i < $n_entries; $i++)
 				{
 					$ids[] = $array_temp[$i];
 				}
-
+				
 				/// Original
 				//for($i = $id_i; $i < $id_f and $i < $n_entries; $i++)
@@ -1082,8 +1068,8 @@
 				//}
 				///
-
+				
 				$fields = $this->bo->catalog->get_fields(false);
 
-				if( $this -> typeContact == 'groups') {
+				if( $this->typeContact == 'groups') {
 					$final = array(
 						0 => (int)$this->page_info['n_pages'],
@@ -1094,36 +1080,36 @@
 							2 => 'cc_id',
 							3 => 'cc_contacts'
-						)
-					);
-
+						)						
+					);					
+					
 					$groups =& $this->bo->catalog->get_multiple_entries($ids,$fields);
-
+					
 					$i = 0;
 					// contatos do grupo
-					$boGroups = CreateObject('contactcenter.bo_group');
+					$boGroups = CreateObject('contactcenter.bo_group');					
 					$contacts = array();
 					foreach($groups as $group)		{
-
+										
 						$final[3][$i][0] = $group['title'] ? $group['title'] : 'none';
-						$final[3][$i][1] = $group['short_name'] ? $group['short_name'] : 'none';
+						$final[3][$i][1] = $group['short_name'] ? $group['short_name'] : 'none';						
 						$final[3][$i][2] = $group['id_group'] ? $group['id_group'] : 'none';
 						$contacts = $boGroups -> get_contacts_by_group($group['id_group']);
 						$final[3][$i][3] = $contacts;
-						$i++;
+						$i++;							
 					}
-
+					
 					$this->page_info['actual_letter'] = $letter;
-					$this->page_info['actual_page'] = $page;
-
-
+					$this->page_info['actual_page'] = $page;					
+					
+					
 					$lnk_compose = "location.href=('../expressoMail1_2/index.php?to=";
-
+					
 					$final[5] = '<span class="link"  onclick="'.$lnk_compose;
-					$final[10] = 'groups';
-					$this->save_session();
+					$final[10] = 'groups';																												
+					$this->save_session();					
 					echo serialize($final);
-					return;
-				}
-
+					return;					
+				}
+				
 				$fields['photo'] = true;
 				$fields['names_ordered'] = true;
@@ -1132,8 +1118,8 @@
 				$fields['companies'] = 'default';
 				$fields['connections'] = 'default';
-
-				// ?aqui alterar a chamada desse mï¿œtodo para receber o base dn?
-				$contacts =& $this->bo->catalog->get_multiple_entries($ids,$fields);
-
+				// ?aqui alterar a chamada desse método para receber o base dn?
+				$contacts = &$this->bo->catalog->get_multiple_entries($ids,$fields);
+				
+				
 				if (!is_array($contacts) or !count($contacts))
 				{
@@ -1143,11 +1129,11 @@
 					return;
 				}
-
+				
 				$i = 0;
 				foreach($contacts as $index => $contact)
 				{
 					/*
-					 * TODO: Os timeouts de conexï¿œo foram retirados, ver se serï¿œ necessï¿œrio retornar essa funcionalidade, e,
-					 * neste caso, terminar a implementaï¿œï¿œo das mensagens de retorno.
+					 * TODO: Os timeouts de conexão foram retirados, ver se será necessário retornar essa funcionalidade, e,
+					 * neste caso, terminar a implementação das mensagens de retorno.
 					 */
 					if ($index !== 'error'){
@@ -1156,11 +1142,7 @@
 						$final[3][$i][2] = $contact['companies']['company1']['title']?$contact['companies']['company1']['title']:'none';
 
-						//Para exibir a matricula do empregado
-						$final[3][$i][8] = $contact['companies']['company1']['empNumber']?$contact['companies']['company1']['empNumber']:'none';
-						//Para exibir o setor/lotaï¿œï¿œo do empregado
-						$final[3][$i][9] = $contact['companies']['company1']['department']?$contact['companies']['company1']['department']:'none';
-
 						/* Select the correct Email and Telephone to be shown */
 						$preferences = ExecMethod('contactcenter.ui_preferences.get_preferences');
+						
 						if (!is_array($preferences))
 						{
@@ -1188,14 +1170,12 @@
 										$default_phone_found = true;
 									}
-									
-									if (!($_SESSION['phpgw_info']['user']['preferences']['contactcenter']['telephone_number'] == $conn_info['connection_value']) && $_SESSION['phpgw_info']['user']['preferences']['contactcenter']['voip_enabled'] && $conn_info['connection_value'] && preg_match('/^\([0-9]{2}\)[0-9]{4}\-[0-9]{4}$/',$conn_info['connection_value'])==1 && !$external) {
+									if (!($_SESSION['phpgw_info']['user']['preferences']['contactcenter']['telephone_number'] == $conn_info['connection_value']) && $_SESSION['phpgw_info']['user']['preferences']['contactcenter']['voip_enabled'] && $conn_info['connection_value'] && preg_match('/^\([0-9]{2}\)[0-9]{4}\-[0-9]{4}$/',$conn_info['connection_value'])==1 && !$external){
 										$conn_info['connection_value'] = "<a title=\"".lang("Call Extension")."\" href=\"#\" onclick=\"connectVoip('".$conn_info['connection_value']."', 'com')\">".$conn_info['connection_value']."</a>";
-								}
-									
+									}
 									$final[3][$i][3] = $conn_info['connection_value'] ? $conn_info['connection_value'] : 'none';
 								}
 							}
 						}
-
+						
 						if (!$final[3][$i][3])
 						{
@@ -1217,5 +1197,4 @@
 						$final[4][$i] = $contact['photo'] ? 1  : 0;
 						$i++;
-
 					}
 					else
@@ -1230,30 +1209,37 @@
 				$this->page_info['actual_letter'] = $letter;
 				$this->page_info['actual_page'] = $page;
-
-				$this->save_session();
-
+				
+				$this->save_session();				
 				echo serialize($final);
 				return;
 			}
-
+			
 			$this->page_info['actual_letter'] = $letter;
 			$this->page_info['actual_page'] = $page;
-
+			
 			$this->save_session();
-
+			
 			$final[0] = 0;
 			$final[1] = $this -> typeContact;
 			echo serialize($final);
 		}
-
+		
+		function get_visible_all_ldap()
+		{
+			$bo = CreateObject('contactcenter.bo_ldap_manager');
+			$ldap_query = $bo->srcs;
+			return $ldap_query[1]['visible'];	
+		}
+
+ 
 		/*!
-
+		
 			@function get_group_data
 			@abstract Returns all the information of a given Group
 			@author Nilton Emilio Buhrer Neto
-
+			
 			@param (integer) $id The id to get information
-
-		*/
+		
+		*/		
 		function get_group_data($id)
 		{
@@ -1261,31 +1247,38 @@
 			$fields = $this->bo->catalog->get_fields(true);
 			$data = $this->bo->catalog->get_single_entry($id,$fields);
-
-			if($id) {
+			
+			if($id) {			
 				// get All Contacts by group.
-				$data['contact_in_list'] = $this->bo->catalog->get_contacts_by_group($id);
-			}
-
+				$data['contact_in_list'] = $this->bo->catalog->get_contacts_by_group($id);								
+			}
+			
 			$boGroup = CreateObject('contactcenter.bo_group');
-
-			$data['contact_list'] = $boGroup->get_all_contacts();
-
-			$data['result'] = 'ok';
-			echo serialize($data);
-		}
-
+						
+			$all_contacts = $boGroup->get_all_contacts();
+			
+			$contact_options = "";
+			if(count($all_contacts)) {					
+				foreach($all_contacts as $idx => $contact) {				
+					$contact_options .= "<OPTION value='".$contact['id_connection']."'>".$contact['names_ordered']." (".$contact['connection_value'].")</OPTION>";
+				}
+			}
+			$data['contact_list'] = $contact_options;
+			$data['result'] = 'ok';								
+			echo serialize($data);			
+		}		
+		
 		/*!
-
+		
 			@function get_full_data
 			@abstract Returns all the information of a given Entry
 			@author Raphael Derosso Pereira
-
+			
 			@param (integer) $id The id to get information
-
+		
 		*/
 		function get_full_data($id)
 		{
 			$dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
-			$this->bo->catalog = CreateObject('contactcenter.bo_people_catalog');
+			$this->bo->catalog = CreateObject('contactcenter.bo_people_catalog');		
 			$fields = $this->bo->catalog->get_fields(true);
 			$fields['photo'] = false;
@@ -1320,5 +1313,5 @@
 			}
 			$datecount = 0;
-
+			
 			$data['result'] = 'ok';
 			$data['cc_full_add_contact_id'] = $id;
@@ -1362,5 +1355,5 @@
 
 			/* Relations */
-
+			
 			echo serialize($data);
 		}
@@ -1399,26 +1392,26 @@
 				return;
 			}
-
+			
 			echo 0;
 		}
-
+		
 		/*!
-
+		
 			@function quick_add
 			@abstract Adds a new Contact using the Quick Add interface
 			@author Raphael Derosso Pereira
-
+			
 			@param string $sdata Serialized data
 		*/
 		function quick_add($sdata)
 		{
-
+			
 			$sdata = str_replace('\\"', '"', $sdata);
 			$new_array = unserialize($sdata);
 			$tdata = array();
-
+			
 			foreach($new_array as $tmp)
 				$tdata[] = $tmp;
-
+			
 			if (!$tdata)
 			{
@@ -1427,22 +1420,22 @@
 					'status' => 'abort'
 				));
-
+				
 				return;
 			}
-
-			// verifica se email jï¿œ existe!
+			
+			// verifica se email já existe!
 			$boGroup = CreateObject('contactcenter.bo_group');
 			$contact = $boGroup->verify_contact($tdata[4]);
-
+												
 			if($contact)
-			{
+			{							
 				$str_contact = "\r\n - ".implode("\r\n - ",$contact);
-
+				
 				echo serialize(array(
 					'msg'    => lang('Problems on adding your Contact. The email "%1" already exists in: %2',$tdata[4], $str_contact),
 					'status' => 'alreadyExists'
 				));
-
-				return;
+				
+				return;			
 			}
 
@@ -1460,7 +1453,7 @@
 
 			if ($boPeople ->quick_add($data))
-			{
+			{				
 				$this->page_info['changed'] = true;
-
+				
 				echo serialize(array(
 					'msg'    => lang('Entry added with success!'),
@@ -1476,14 +1469,14 @@
 			}
 
-			$this->save_session();
-
+			$this->save_session();	
+			
 		}
 
 		/*!
-
+		
 			@function add_group
 			@abstract Adds a new Group using the Add Group interface
 			@author Nilton Emilio Buhrer Neto
-
+			
 			@param string $sdata Serialized data
 		*/
@@ -1493,5 +1486,5 @@
 			$tdata = unserialize($sdata);
 			$new_tdata = array();
-
+			
 			if (!$tdata)
 			{
@@ -1500,22 +1493,22 @@
 					'status' => 'abort'
 				));
-
+				
 				return;
 			}
-
+			
 			foreach($tdata as $tmp)
 				$new_tdata[] = $tmp;
-
-			$data['title'] = $new_tdata[0];
+			
+			$data['title'] = $new_tdata[0];			
 			$data['contact_in_list'] = $new_tdata[1];
 			$data['id_group'] = $new_tdata[2];
-
+						
 			$boGroup = CreateObject('contactcenter.bo_group_manager');
 			$id = $boGroup -> add_group($data);
-
+			
 			if ($id)
 			{
 				$this->page_info['changed'] = true;
-
+				
 				echo serialize(array(
 					'msg'    => lang('Entry added with success!'),
@@ -1535,14 +1528,14 @@
 
 		/*!
-
+		
 			@function remove_group
 			@abstract Removes a group if the user has the right to do it
-			@author Nilton Emilio Buhrer Neto
+			@author Nilton Emilio Buhrer Neto			
 			@param (integer) $id The id to be removed
-
+				
 		*/
 		function remove_group($id)
-		{
-				$soGroup = CreateObject('contactcenter.so_group');
+		{				
+				$soGroup = CreateObject('contactcenter.so_group');				
 				$data = array ('id_group' => $id);
 				if($soGroup -> delete($data)) {
@@ -1550,5 +1543,5 @@
 						'msg'    => lang('Removed Entry ID '.$id.'!'),
 						'status' => 'ok'
-					));
+					));							
 				}
 				else {
@@ -1559,10 +1552,10 @@
 				}
 
-			$this->save_session();
+			$this->save_session();				
 		}
 
 
 		function remove_all_entries (){
-
+		
 			$error = false;
 			$this->all_entries = $this->bo->catalog->get_all_entries_ids();
@@ -1572,5 +1565,5 @@
 				if(!$result) {
 					$error = true;
-					break;
+					break;		
 				}
 			}
@@ -1581,5 +1574,5 @@
 					'status' => 'ok'
 				));
-			}
+			} 
 			else {
 				echo serialize(array(
@@ -1593,11 +1586,11 @@
 
 		/*!
-
+		
 			@function remove_entry
 			@abstract Removes an entry if the user has the right to do it
 			@author Raphael Derosso Pereira
-
+			
 			@param (integer) $id The id to be removed
-
+				
 		*/
 		function remove_entry ($id)
@@ -1608,8 +1601,8 @@
 				return;
 			}
-
+			
 			$this->page_info['changed'] = true;
 			$result = $this->bo->catalog->remove_single_entry($id);
-
+			
 			if ($result)
 			{
@@ -1618,5 +1611,5 @@
 					unset($this->page_info['actual_entries'][$pos]);
 				}
-
+				
 				$temp = false;
 				reset($this->page_info['actual_entries']);
@@ -1625,5 +1618,5 @@
 					$temp[] = $t;
 				}
-
+				
 				$this->page_info['actual_entries'] = $temp;
 
@@ -1640,11 +1633,11 @@
 				));
 			}
-
+			
 			$this->save_session();
 		}
 
-
+		
 		/*!
-
+		
 			@function post_full_add
 			@abstract Saves all the information altered/entered in the Full Add
@@ -1655,8 +1648,9 @@
 		function post_full_add()
 		{
-			$data = unserialize(str_replace('\\"', '"', $_POST['data']));
+			$data =  $_POST['data'];
+			// Exceptions!!! utf8 special chars. 
+			$data = preg_replace("/\%u2(\d+)(\d+)(\d+)/","-",$data);
+			$data = unserialize(str_replace('\\"', '"', $data));
 			$this -> bo -> catalog = CreateObject('contactcenter.bo_people_catalog');
-
-//			echo str_replace('\\"', '"', $_POST['data']);
 
 			if (!is_array($data))
@@ -1682,5 +1676,5 @@
 					'status' => 'fatal'
 				));
-
+				
 				return;
 			}
@@ -1696,7 +1690,7 @@
 				$id_photo = '_new_';
 			}
-
-			/*
-			 * Process Photo, if available
+			
+			/* 
+			 * Process Photo, if available 
 			 */
 			$sleep_count = 0;
@@ -1715,5 +1709,5 @@
 			}
 			$GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'n'));
-
+			
 			if (isset($this->page_info['photos'][$id_photo]))
 			{
@@ -1732,11 +1726,11 @@
 				$this->save_session();
 			}
-
+			
 			/*
 			 * Arrange Date so it gets inserted correctly
 			 */
-
+			 
 			$dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
-
+		
 			$j = 0;
 			for ($i = 0; $i < 5; $i+=2)
@@ -1771,5 +1765,5 @@
 					continue;
 				}
-
+				
 				switch($field)
 				{
@@ -1783,5 +1777,5 @@
 						/* Do Nothing. This is just to make sure no invalid field is passed */
 						break;
-
+					
 					case 'id_status':
 					case 'id_prefix':
@@ -1792,9 +1786,9 @@
 						}
 						break;
-
+					
 					case 'birthdate_0':
 					case 'birthdate_1':
 					case 'birthdate_2':
-
+					
 						switch($date[$datecount]['digit'])
 						{
@@ -1818,5 +1812,5 @@
 							break;
 						}
-
+						
 						if (!checkdate($date['value'][0], $date['value'][1], $date['value'][2]))
 						{
@@ -1827,5 +1821,5 @@
 							return;
 						}
-
+						
 						$data['birthdate'] = $date['value'][2].'-'.$date['value'][0].'-'.$date['value'][1];
 						break;
@@ -1850,5 +1844,5 @@
 							{
 								$index = 'address'.$type;
-
+								
 								$id_state = $this->bo->catalog->add_state($state_info);
 								$data['addresses'][$index]['id_state'] = $id_state;
@@ -1868,5 +1862,5 @@
 							{
 								$index = 'address'.$type;
-
+								
 								$id_city = $this->bo->catalog->add_city($city_info);
 								$data['addresses'][$index]['id_city'] = $id_city;
@@ -1909,5 +1903,5 @@
 				);
 			}
-
+			
 			eval($code);
 
@@ -1925,5 +1919,5 @@
 
 		/*!
-
+		
 			@function post_photo
 			@abstract Wrapper to post a photo without reload a page.
@@ -1935,10 +1929,10 @@
 			//print_r($_FILES);
 			$GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'y'));
-
+			
 			if (!is_array($_FILES) and is_array(!$_FILES['cc_pd_photo']))
 			{
 				$this->page_info['photos'][$id]['status'] = 'no_upload';
 				$this->page_info['photos'][$id]['msg'] = lang('No Photos uploaded to Server.');
-
+				
 				$this->save_session();
 				$GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
@@ -1950,5 +1944,5 @@
 				$this->page_info['photos'][$id]['status'] = 'no_GD_lib';
 				$this->page_info['photos'][$id]['msg'] = lang('Cannot manipulate Image. No Image added. Please, if you want to use images, ask the Administrator to install GD library.');
-
+				
 				$this->save_session();
 				$GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
@@ -1976,5 +1970,5 @@
 				return;
 			}
-
+			
 			switch($_FILES['cc_pd_photo']['type'])
 			{
@@ -2006,5 +2000,5 @@
 
 				default:
-
+					
 					$this->page_info['photos'][$id]['status'] = 'invalid_image';
 					$this->page_info['photos'][$id]['msg'] = lang('The file must be an JPEG, PNG or GIF Image.');
@@ -2019,23 +2013,23 @@
 					$this->page_info['photos'][$id]['status'] = 'invalid_file';
 					$this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
-
+					
 					$this->save_session();
 					$GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
 					return;
 			}
-
+			
 			$img_size = getimagesize($_FILES['cc_pd_photo']['tmp_name']);
 			$dst_img = imagecreatetruecolor(60, 80);
-
+			
 			if (!imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, 60, 80, $img_size[0], $img_size[1]))
 			{
 				$this->page_info['photos'][$id]['status'] = 'invalid_file';
 				$this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
-
+				
 				$this->save_session();
 				$GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
 				return;
 			}
-
+			
 			ob_start();
 			imagepng($dst_img);
@@ -2047,5 +2041,5 @@
 
 			$this->save_session();
-
+		
 			$GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
 
@@ -2068,5 +2062,5 @@
 			$fields = $this->bo->catalog->get_fields(false);
 			$fields['photo'] = true;
-
+			
 			$contact = $this->bo->catalog->get_single_entry($id, $fields);
 
@@ -2077,5 +2071,5 @@
 				return;
 			}
-
+			
 			header('Content-type: image/jpeg');
 			$photo = imagecreatefromstring ($contact['photo']);
@@ -2089,7 +2083,7 @@
 			return;
 		}
-
+		
 		/*!
-
+		
 			@function get_states
 			@abstract Echos a serialized array containing all the states for the given country
@@ -2113,10 +2107,10 @@
 				return;
 			}
-
+			
 			$result = array(
 				'msg'    => lang('States Successfully retrieved!'),
 				'status' => 'ok'
 			);
-
+			
 			foreach ($states as $state_info)
 			{
@@ -2157,15 +2151,15 @@
 				return;
 			}
-
+			
 			$result = array(
 				'msg'    => lang('Cities Successfully retrieved!'),
 				'status' => 'ok'
 			);
-
+			
 			foreach ($cities as $city_info)
 			{
 				$result['data'][$city_info['id_city']] = $city_info['name'];
 			}
-
+			
 			echo serialize($result);
 		}
@@ -2173,10 +2167,10 @@
 
 		/*!
-
+		
 			@function search
 			@abstract Echos a serialized array containing the IDs
 				of the entries that matches the search argument
 			@author Raphael Derosso Pereira
-			@author Mï¿œrio Cï¿œsar Kolling (external catalogs)
+			@author Mário César Kolling (external catalogs)
 
 			@param string $str_data A serialized array with two informations:
@@ -2187,4 +2181,5 @@
 
 		*/
+		// SERPRO
 		function search($str_data)
 		{
@@ -2192,15 +2187,16 @@
 			// It's an external catalog?
 			$external = $this->bo->is_external($this->page_info['actual_catalog']);
-
-			if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
-			{
-				//echo serialize(array(
-				//	'msg'    => lang('Invalid parameters'),
-				//	'status' => 'abort'
-				//));
-
-				return array('error' => lang('Invalid parameters'));
-			}
-
+			
+            if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
+            {
+                echo serialize(array(                                                                                                   
+                   'msg'    => lang('Invalid parameters'),                                                                             
+                    'status' => 'abort'
+                ));
+            
+                return array('error' => lang('Invalid parameters'));                                                                                                                 
+            }   
+
+            
 			/*
 			 * TODO: look into the database to discover the database's encoding and convert the search_for field accordingly
@@ -2213,30 +2209,30 @@
 				$data['search_for'] = utf8_encode($data['search_for']);
 			}
-
-			$rules  = array();
-
-			if ($data['search_for'] === '*')
-			{
-				$rules = array(
-					0 => array(
-						'field' => $data['fields']['search'],
-						'type'  => 'LIKE',
-						'value' => '%'
-					)
-				);
-			}
-			else
-			{
-				$names = explode(' ', $data['search_for']);
-
-				if (!is_array($names))
-				{
-					//echo serialize(array(
-					//	'msg'    => lang('Invalid Search Parameter'),
-					//	'status' => 'abort'
-					//));
-
-					return array('error' => lang('Invalid Search Parameter'));
-				}
+            
+            $rules  = array();                                                                                                          
+            
+            
+            if ($data['search_for'] === '*')                                                                                            
+            {
+                $rules = array(                                                                                                         
+                    0 => array(                                                                                                         
+                        'field' => $data['fields']['search'],                                                                           
+                        'type'  => 'LIKE',
+                        'value' => '%'
+                    )   
+                );  
+            }   
+            else                                                                                                                        
+            {
+                $names = explode(' ', $data['search_for']);                                                                             
+                
+                if (!is_array($names))                                                                                                  
+                {
+                    echo serialize(array(                                                                                               
+                        'msg'    => lang('Invalid Search Parameter'),                                                                   
+                        'status' => 'abort'
+                    ));
+ 
+                }
 
 				if (!$external && $this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
@@ -2271,17 +2267,17 @@
 					);
 				}
-
-				foreach ($names as $name)
-				{
-					if ($name != '')
-					{
-						array_push($rules, array(
-							'field' => $data['fields']['search'],
-							'type'  => 'iLIKE',
-							'value' => '%'.$name.'%'
-						));
-					}
-				}
-			}
+                
+                foreach ($names as $name)
+                {
+                    if ($name != '')
+                    {
+                        array_push($rules, array(
+                            'field' => $data['fields']['search'],
+                            'type'  => 'iLIKE',
+                            'value' => '%'.$name.'%'
+                        ));
+                    }
+                }
+            }
 
 			if ($external || $this->page_info['actual_catalog']['class'] == 'bo_people_catalog' ||
@@ -2305,37 +2301,119 @@
 			}
 
-			if (!is_array($ids) || !count($ids))
-			{
-				//echo serialize(array(
-				//	'msg'    => lang('No Entries Found!'),
-				//	'status' => 'empty'
-				//));
-
+            if (!is_array($ids) || !count($ids))
+            {
 				$this->last_search_ids = null;
 				$this->save_session();
 				return null;
-			}
-
-			$id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
-
-			$ids_f = array();
-			foreach ($ids as $e_info)
-			{
-				//$ids_f[] = "base64::" . base64_encode($e_info[$id_field]);
-				$ids_f[] = $e_info[$id_field];
-			}
-
-			//error_log("ids_f serializados: " . serialize($ids_f) . "\n", 3, '/var/www/teste.log');
-
-			//return serialize($ids_f);
+            }
+
+            $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
+			
+            $ids_f = array();
+
+            foreach ($ids as $e_info)
+            {
+                $ids_f[] = $e_info[$id_field];
+            }
+
 			return $ids_f;
-
-			//echo serialize(array(
-			//	'data'   => $ids_f,
-			//	'msg'    => lang('Found %1 Entries', count($ids)),
-			//	'status' => 'ok'
-			//));
 		}
-
+		
+		// CELEPAR
+		/*
+        function search($str_data)
+        {
+            $data = unserialize($str_data);
+
+            if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
+            {
+                echo serialize(array(
+                    'msg'    => lang('Invalid parameters'),
+                    'status' => 'abort'
+                ));
+
+                return;
+            }
+
+            $rules  = array();
+
+            if ($data['search_for'] === '*')
+            {
+                $rules = array(
+                    0 => array(
+                        'field' => $data['fields']['search'],
+                        'type'  => 'LIKE',
+                        'value' => '%'
+                    )
+                );
+            }
+            else
+            {
+                $names = explode(' ', $data['search_for']);
+
+                if (!is_array($names))
+                {
+                    echo serialize(array(
+                        'msg'    => lang('Invalid Search Parameter'),
+                        'status' => 'abort'
+                    ));
+                    
+                    return;
+                }
+                
+                foreach ($names as $name)
+                {
+                    if ($name != '')
+                    {
+                        array_push($rules, array(
+                            'field' => $data['fields']['search'],
+                            'type'  => 'iLIKE',
+                            'value' => '%'.$name.'%'
+                        ));
+                    }
+                }
+            }
+
+            
+            
+            //$catalog = $this->bo->get_branch_by_level($this->bo->catalog_level[0]);
+            
+            //if ($catalog['class'] === 'bo_people_catalog')
+            //{
+            //    array_push($rules, array(
+            //        'field' => 'contact.id_owner',
+            //        'type'  => '=',
+            //        'value' => $GLOBALS['phpgw_info']['user']['account_id']
+            //    ));
+            //}
+            
+            
+            $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
+
+            if (!is_array($ids) || !count($ids))
+            {
+                echo serialize(array(
+                    'msg'    => lang('No Entries Found!'),
+                    'status' => 'empty'
+                ));
+
+                return;
+            }
+            $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
+
+            $ids_f = array();
+            foreach ($ids as $e_info)
+            {
+                $ids_f[] = $e_info[$id_field];
+            }
+
+            echo serialize(array(
+                'data'   => $ids_f,
+                'msg'    => lang('Found %1 Entries', count($ids)),
+                'status' => 'ok'
+            ));
+			
+			return;
+        }*/
 		/*!
 
@@ -2345,5 +2423,5 @@
 			@author Raphael Derosso Pereira
 
-			@param array str_data A serialized array containing the ID's of the entries
+			@param array str_data A serialized array containing the ID's of the entries 
 				to be taken, the fields to be taken and the rules to be used on the
 				retrieval:
@@ -2358,5 +2436,5 @@
 		{
 			$data = unserialize($str_data);
-
+			
 			if (!is_array($data) or !count($data) or !count($data['fields']) or !count($data['ids']))
 			{
@@ -2368,5 +2446,5 @@
 
 			$entries = $this->bo->catalog->get_multiple_entries($data['ids'], $data['fields']);
-
+			
 			if (!is_array($entries) or !count($entries))
 			{
@@ -2387,9 +2465,9 @@
 
 			@function get_all_entries
-			@abstract Returns the specified fields for all catalog's entries
+			@abstract Returns the specified fields for all catalog's entries 
 				in the default CC UI format
 			@author Raphael Derosso Pereira
 
-			@params array str_data A serialized array containing the fields to
+			@params array str_data A serialized array containing the fields to 
 				be grabbed, the maximum number of entries to be returned and a
 				boolean specifying if the calls refers to a new grab or to an
@@ -2400,8 +2478,8 @@
 		{
 			$data = unserialize($str_data);
-
-			if (!is_array($data) or
-			    !count($data) or
-				!count($data['fields']) or
+			
+			if (!is_array($data) or 
+			    !count($data) or 
+				!count($data['fields']) or 
 				!$data['maxlength'] or
 				(!$data['new'] and !$data['offset']))
@@ -2429,5 +2507,5 @@
 				$data['offset'] = 0;
 			}
-
+			
 			if ($data['maxlength'] != -1)
 			{
@@ -2440,5 +2518,5 @@
 
 			$prefs = ExecMethod('contactcenter.ui_preferences.get_preferences');
-
+			
 			$jsCode = array();
 			$count = 0;
@@ -2450,21 +2528,21 @@
 				}
 
-				if($this-> typeContact == 'groups') {
-
+				if($this-> typeContact == 'groups') {				
+					
 					foreach ($each as $field => $value)	{
-
+										
 						if ($field === 'title')	{
 							$optionName = '\\"'.$value.'\\"';
-
+							 
 						}
 						else if ($field === 'short_name')	{
-
+							
 							$jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$optionName.' ('.$value.')", "'.$count.'");';
-							$count++;
-						}
+							$count++;																					
+						}					
 					}
 				}
-
-				else  {
+				
+				else  {	
 					foreach ($each as $field => $value)	{
 						if ($field === 'names_ordered')	{
@@ -2474,5 +2552,5 @@
 						}
 						else if ($field === 'connections')	{
-
+							
 							foreach ($value as $connection)		{
 								if ($connection['id_type'] == $prefs['personCardEmail'])	{
@@ -2487,7 +2565,7 @@
 
 			$jsCodeFinal = implode("\n", $jsCode);
-
+			
 			$nEntries = count($result);
-
+			
 			if (!$nEntries)
 			{
@@ -2507,5 +2585,5 @@
 			);
 		}
-
+		
 		/*********************************************************************\
 		 *                      Auxiliar Methods                             *
@@ -2513,9 +2591,9 @@
 
 		/*!
-
+		
 			@function save_session
 			@abstract Saves the data on the session
 			@author Raphael Derosso Pereira
-
+		
 		*/
 		function save_session()
@@ -2523,14 +2601,13 @@
 			$GLOBALS['phpgw']->session->appsession('ui_data.page_info','contactcenter',$this->page_info);
 			$GLOBALS['phpgw']->session->appsession('ui_data.all_entries','contactcenter',$this->all_entries);
-			$GLOBALS['phpgw']->session->appsession('ui_data.last_search_ids','contactcenter',$this->last_search_ids);
 		}
 
 		/*!
-
+		
 			@function convert_tree
 			@abstract Converts the tree array in the BO format to a JS tree array compatible
 				with the one available in eGW
 			@author Raphael Derosso Pereira
-
+		
 			@param (array)  $tree    The tree in the BO format
 			@param (string) $name    The tree name
@@ -2566,5 +2643,5 @@
 					'caption' => $value['name']
 				);
-
+				
 				switch($value['type'])
 				{
@@ -2589,12 +2666,12 @@
 				$this->bo->catalog->src_info = $ldap->srcs[1];
 			}
-
-			$ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
+			
+			$ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);				
 			$dn=$this->bo->catalog->src_info['dn'];
 			$justThese = array("givenname","givenname","sn","telephonenumber","mail");
-			$sr = ldap_read($ds,$id, "objectClass=*",$justThese);
-			$info = ldap_get_entries($ds, $sr);
+			$sr = ldap_read($ds,$id, "objectClass=*",$justThese);							
+			$info = ldap_get_entries($ds, $sr);							
 			for($z = 0; $z < 5; $z++) {
-				$participant = $info[0][$justThese[$z]];
+				$participant = $info[0][$justThese[$z]];													
 				array_push($array_participants, $participant);
 			}
@@ -2602,59 +2679,59 @@
 			ldap_close($ds);
 			echo serialize($array_participants);
-		}
-
-		function get_catalog_participants_list($id)
+		}	
+		
+		function get_catalog_participants_list($id) 
 		{
-
-			$fields = $this->bo->catalog->get_fields(false);
+			
+			$fields = $this->bo->catalog->get_fields(false);			
 			$fields['names_ordered'] = true;
-			$fields['mail_forwarding_address'] = true;
-			$contact = $this->bo->catalog->get_single_entry($id,$fields);
-
+			$fields['mail_forwarding_address'] = true;			
+			$contact = $this->bo->catalog->get_single_entry($id,$fields);			
+			
 			$array_participants = array();
 			$array_emails = array();
-
+			
 			$filter = null;
-			for($z = 0; $z < $contact['mail_forwarding_address']['count']; $z++) {
+			for($z = 0; $z < $contact['mail_forwarding_address']['count']; $z++) {			
 					if(strstr($contact['mail_forwarding_address'][$z],'@')) {
 						$filter.="(mail=".$contact['mail_forwarding_address'][$z].")";
 						$array_emails[$contact['mail_forwarding_address'][$z]] = "<font color=black>".$contact['mail_forwarding_address'][$z]."</font>";
-					}
-					else
+					}																
+					else 
 						$array_participants[$z] = "<font color=red>".$contact['mail_forwarding_address'][$z]."</font>";
-			}
-
+			}					
+			
 			if($filter) {
-				$filter = "(|".$filter.")";
+				$filter = "(|".$filter.")";							
 				if(!$this->bo->catalog->src_info) {
 					$ldap = CreateObject('contactcenter.bo_ldap_manager');
 					$this->bo->catalog->src_info = $ldap->srcs[1];
 				}
-				$ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
+				$ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);				
 				$dn=$this->bo->catalog->src_info['dn'];
 				$justThese = array("cn","mail");
-				$sr = ldap_search($ds,$dn, $filter,$justThese);
-				$info = ldap_get_entries($ds, $sr);
+				$sr = ldap_search($ds,$dn, $filter,$justThese);								
+				$info = ldap_get_entries($ds, $sr);							
 				for($z = 0; $z < $info['count']; $z++) {
 					$participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
-					$array_emails[$info[$z]['mail'][0]] = null;
-					array_push($array_participants, $participant);
-				}
-
+					$array_emails[$info[$z]['mail'][0]] = null; 								
+					array_push($array_participants, $participant);					
+				}
+				
 				foreach($array_emails as $index => $email)
-					if($email)
-						array_push($array_participants, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$email."<br>");
-
+					if($email) 
+						array_push($array_participants, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$email."<br>");				
+												
 				ldap_close($ds);
 			}
 			sort($array_participants);
-			$innerHTML = '';
+			$innerHTML = '';			
 			foreach($array_participants as $index => $participant){
 				$innerHTML .= $participant;
 			}
-			$return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);
+			$return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);			 
 			echo serialize($return);
-		}
-
+		}	
+		
 		function export_contacts($typeExport){
 
@@ -2667,5 +2744,5 @@
 
 
-			// Essa iteraï¿œï¿œo transforma uma esturuta com contatos redundantes e separados por email ou tel.
+			// Essa iteração transforma uma esturuta com contatos redundantes e separados por email ou tel.
 			// em outra com apenas 1 elemento pra cada contato
 			$i=0;
@@ -2678,45 +2755,45 @@
 					$all_contacts[$i]['phone']=$object['connection_value'];
 			}
-
+			
 			switch($typeExport) {
 
 				case 'outlook_en':
 					$streamBuffer = "Name;E-mail Address;Notes;Mobile Phone;Pager;Company;".
-							"Job Title;Home Phone;Home Fax;Business Phone;Business Fax\r\n";
+							"Job Title;Home Phone;Home Fax;Business Phone;Business Fax\r\n";							
 					foreach($all_contacts as $index => $object){
 						$streamBuffer.= $object['name'].";".$object['email'].";;;;;;".$object['phone'].";;;\r\n";
 					}
 				break;
-
+				
 				case 'outlook_pt-BR':
-					$streamBuffer = "Nome;End. de email;Endereï¿œo residencial;".
-					"Cidade do endereï¿œo residencial;CEP do endereï¿œo residencial;".
-					"Estado;Paï¿œs/regiï¿œo do endereï¿œo residencial;Telefone residencial;".
-					"Rua do endereï¿œo comercial;Cidade do endereï¿œo comercial;".
-					"CEP do endereï¿œo comercial;Estado do endereï¿œo comercial;".
-					"Paï¿œs/regiï¿œo do endereï¿œo comercial;Telefone comercial;Empresa;Cargo\r\n";
+					$streamBuffer = "Nome;End. de email;Endereço residencial;".
+					"Cidade do endereço residencial;CEP do endereço residencial;".
+					"Estado;País/região do endereço residencial;Telefone residencial;".
+					"Rua do endereço comercial;Cidade do endereço comercial;".
+					"CEP do endereço comercial;Estado do endereço comercial;".
+					"País/região do endereço comercial;Telefone comercial;Empresa;Cargo\r\n";							
 					foreach($all_contacts as $index => $object){
 						$streamBuffer.= $object['name'].";".$object['email'].";;;;;;".$object['phone'].";;;;;;;;\r\n";
 					}
 				break;
-
+				
 				case 'outlook2000_pt-BR':
 					$streamBuffer = "\"Tratamento\",\"Nome\",\"Segundo Nome\",\"Sobrenome\",\"Sufixo\",".
-					"\"Empresa\",\"Departamento\",\"Cargo\",\"Rua do endereï¿œo comercial\",\"Rua do endereï¿œo comercial 2\",".
-					"\"Rua do endereï¿œo comercial 3\",\"Cidade do endereï¿œo comercial\",\"Estado do endereï¿œo comercial\",".
-					"\"CEP do endereï¿œo comercial\",\"Paï¿œs do endereï¿œo comercial\",\"Endereï¿œo residencial\",\"Rua residencial 2\",".
-					"\"Rua residencial 3\",\"Cidade do endereï¿œo residencial\",\"Estado\",\"CEP do endereï¿œo residencial\",\"Paï¿œs do endereï¿œo residencial\",".
-					"\"Outro endereï¿œo\",\"Outro endereï¿œo 2\",\"Outro endereï¿œo 3\",\"Cidade\",\"Estado\",\"CEP\",\"Paï¿œs\",".
+					"\"Empresa\",\"Departamento\",\"Cargo\",\"Rua do endereço comercial\",\"Rua do endereço comercial 2\",".
+					"\"Rua do endereço comercial 3\",\"Cidade do endereço comercial\",\"Estado do endereço comercial\",".
+					"\"CEP do endereço comercial\",\"País do endereço comercial\",\"Endereço residencial\",\"Rua residencial 2\",".
+					"\"Rua residencial 3\",\"Cidade do endereço residencial\",\"Estado\",\"CEP do endereço residencial\",\"País do endereço residencial\",".
+					"\"Outro endereço\",\"Outro endereço 2\",\"Outro endereço 3\",\"Cidade\",\"Estado\",\"CEP\",\"País\",".
 					"\"Telefone do assistente\",\"Fax comercial\",\"Telefone comercial\",\"Telefone comercial 2\",\"Retorno de chamada\",".
 					"\"Telefone do carro\",\"Telefone principal da empresa\",\"Fax residencial\",\"Telefone residencial\",".
 					"\"Telefone residencial 2\",\"ISDN\",\"Telefone celular\",\"Outro fax\",\"Outro telefone\",\"Pager\",\"Telefone principal\",".
-					"\"Radiofone\",\"Telefone TTY/TDD\",\"Telex\",\"Aniversï¿œrio\",\"Anotaï¿œï¿œes\",\"Caixa postal\",\"Categorias\",".
-					"\"Cï¿œdigo da empresa\",\"Cï¿œdigo do governo\",\"Cï¿œnjuge\",\"Conta\",\"Endereï¿œo de correio eletrï¿œnico\",".
-					"\"Nome de exibiï¿œï¿œo do correio eletr.\",\"Endereï¿œo de correio eletrï¿œnico 2\",".
-					"\"Nome de exibiï¿œï¿œo do correio eletr.2\",\"Endereï¿œo de correio eletrï¿œnico 3\",".
-					"\"Nome de exibiï¿œï¿œo do correio eletr.3\",\"Datas especiais\",\"Disponibilidade da Internet\",".
-					"\"Filhos\",\"Hobby\",\"Idioma\",\"Indicaï¿œï¿œo\",\"Informaï¿œï¿œes para cobranï¿œa\",\"Iniciais\",\"Local\",".
-					"\"Nome do assistente\",\"Nome do gerenciador\",\"Pï¿œgina da Web\",\"Palavras-chave\",\"Particular\",\"Personalizado 1\",\"Personalizado 2\",".
-					"\"Personalizado 3\",\"Personalizado 4\",\"Prioridade\",\"Profissï¿œo\",\"Quilometragem\",\"Sala\",\"Sensibilidade\",\"Servidor de diretï¿œrio\",".
+					"\"Radiofone\",\"Telefone TTY/TDD\",\"Telex\",\"Aniversário\",\"Anotações\",\"Caixa postal\",\"Categorias\",".
+					"\"Código da empresa\",\"Código do governo\",\"Cônjuge\",\"Conta\",\"Endereço de correio eletrônico\",".
+					"\"Nome de exibição do correio eletr.\",\"Endereço de correio eletrônico 2\",".
+					"\"Nome de exibição do correio eletr.2\",\"Endereço de correio eletrônico 3\",".
+					"\"Nome de exibição do correio eletr.3\",\"Datas especiais\",\"Disponibilidade da Internet\",".
+					"\"Filhos\",\"Hobby\",\"Idioma\",\"Indicação\",\"Informações para cobrança\",\"Iniciais\",\"Local\",".
+					"\"Nome do assistente\",\"Nome do gerenciador\",\"Página da Web\",\"Palavras-chave\",\"Particular\",\"Personalizado 1\",\"Personalizado 2\",".
+					"\"Personalizado 3\",\"Personalizado 4\",\"Prioridade\",\"Profissão\",\"Quilometragem\",\"Sala\",\"Sensibilidade\",\"Servidor de diretório\",".
 					"\"Sexo\"\r\n";
 					foreach($all_contacts as $index => $object){
@@ -2724,5 +2801,5 @@
 					}
 				break;
-
+				
 				case 'outlook2000_en':
 					$streamBuffer = "Title,First Name,Middle Name,Last Name,Suffix,Company,Department,Job Title,".
@@ -2740,13 +2817,13 @@
 					}
 				break;
-
+					
 				case 'thunderbird':
-					$streamBuffer = "\n";
+					$streamBuffer = "\n";							
 					foreach($all_contacts as $index => $object){
 						$streamBuffer.= ",,".$object['name'].",,".$object['email'].",,".$object['phone'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
 					}
 				break;
-
-				default:
+				
+				case 'expresso':
 					$streamBuffer = "Nome,Email,Telefone\r\n";
 					foreach($all_contacts as $index => $object){
@@ -2754,5 +2831,5 @@
 					}
 				break;
-
+				
 			}
 
@@ -2762,5 +2839,5 @@
 			if(!$f)
 				echo null;
-
+		
 			fputs($f,$streamBuffer);
 			fclose($f);
@@ -2769,15 +2846,56 @@
 		}
 
+		// Get the csv field and put into array, from php.net
+		function parse_line($input_text, $delimiter = ',', $text_qualifier = '"') {
+  			$text = trim($input_text);
+  			  if(is_string($delimiter) && is_string($text_qualifier)) {
+       			 $re_d = '\x' . dechex(ord($delimiter));            //format for regexp
+        		$re_tq = '\x' . dechex(ord($text_qualifier));    //format for regexp
+        		
+        		$fields = array();
+        		$field_num = 0;
+        		while(strlen($text) > 0) {
+            		if($text{0} == $text_qualifier) {
+                		preg_match('/^' . $re_tq . '((?:[^' . $re_tq . ']|(?<=\x5c)' . $re_tq . ')*)' . $re_tq . $re_d . '?(.*)$/', $text, $matches);
+		               
+        		        $value = str_replace('\\' . $text_qualifier, $text_qualifier, $matches[1]);
+             			$text = trim($matches[2]);
+               
+                		$fields[$field_num++] = $value;
+            		} else {
+                		preg_match('/^([^' . $re_d . ']*)' . $re_d . '?(.*)$/', $text, $matches);
+		               
+        		        $value = $matches[1];
+               			$text = trim($matches[2]);
+               
+              		  	$fields[$field_num++] = $value;
+            	}
+        	}
+        		return $fields;
+		    } else
+       			return false;
+		}
 
 		function import_contacts($typeImport){
 
-			$delim 		= ($typeImport == 'outlook' ? ';' : ',');
-
-			if($file = $_SESSION['contactcenter']['importCSV']) {
-				unset($_SESSION['contactcenter']['importCSV']);
+			if($file = $_SESSION['contactcenter']['importCSV']) {				
+				unset($_SESSION['contactcenter']['importCSV']);				
 				$len = filesize($file);
 				$count = 0;
 				$return = array('error' => false, '_new' => 0, '_existing' => 0, '_failure' => 0);
    				$handle = @fopen($file, "r") or die(serialize($return['error'] = true));
+   				
+				$input_header = fgets($handle);
+				if ($typeImport == 'outlook')
+					$delim = ';';
+				else if ($typeImport == 'auto')
+				$delim = strstr($input_header,',') ? ',' : ';';
+				else  
+					$delim = ',';
+				$csv_header = $this->parse_line($input_header,$delim);
+				$firstContact = fgets($handle);
+				preg_match("/\"(.+)\"[,;]/sU",$firstContact,$matches); // yahoo csv
+   				rewind($handle);	   			
+
    				$header = @fgetcsv($handle, $len, $delim) or die(serialize($return['error'] = true));
    				if(count($header)  < 2 || count($header) > 100) {
@@ -2787,8 +2905,10 @@
    					return;
    				}
-
-				$boGroup = CreateObject('contactcenter.bo_group');
-				$boPeople = CreateObject('contactcenter.bo_people_catalog');
-
+   				
+   				if ($matches[0][strlen($matches[0])-1] == ';')
+					$delim = ';';
+   				
+			$boGroup = CreateObject('contactcenter.bo_group');
+			$boPeople = CreateObject('contactcenter.bo_people_catalog');
 				switch($typeImport){
 					case 'outlook2000':
@@ -2807,15 +2927,42 @@
 						$phone_pos=7;
 						break;
-					default:
+					case 'expresso':
 						$name_pos=0;
 						$email_pos=1;
 						$phone_pos=2;
-				}
+						break;
+					default:
+						foreach($csv_header as $index => $fieldName)
+						{
+							switch($fieldName){
+							case 'Name':
+							case 'Nome':
+							case 'First Name':
+								$name_pos = $index;
+								break;
+							case 'E-mail':
+							case 'Email':
+							case 'E-mail Address':
+							case 'Endereço de correio eletrônico':
+							case 'End. de email':
+								$email_pos = $index;
+								break;
+							case 'Home Phone':
+							case 'Phone':
+							case 'Telefone':
+							case 'Telefone principal':
+							case 'Telefone comercial':
+								$phone_pos = $index;
+								break;
+							}
+						}	
+						break;
+				}
+				
 
 				while (($data = fgetcsv($handle, $len, $delim))) {
-
        				foreach ($header as $key=>$heading)
                			$row[$heading]=(isset($data[$key])) ? $data[$key] : '';
-
+       				
 					$sdata = array();
 					$full_name  = trim($row[$header[$name_pos]]);
@@ -2831,20 +2978,28 @@
 					$sdata['connections']['default_phone']['connection_name'] = lang('Main');
 					$sdata['connections']['default_phone']['connection_value'] = $phone;
-
-					// 	verifica se email jï¿œ existe!
+					
+					// 	verifica se email já existe!
 					$contact = $boGroup->verify_contact($email);
-
+										
+					if(!$sdata['given_names'] && $email){
+							$a_email = explode("@",$email);
+							$sdata['given_names'] = $a_email[0];
+					}
+
+					$line_iteration = $return['_failure'] + $return['_existing'] + $return['_new']; 
 					if($contact){
 						$return['_existing']++;
-					}
+					}														
 					else if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
 						$return['_failure']++;
+						$return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid E-Mail address: " . $email ."<br>";
 					}
 					else if (!$sdata['given_names'] || !$email || !$boPeople ->quick_add($sdata)){
-						$return['_failure']++;
+						$return['_failure']++;							
+						$return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid Name: " . $sdata['given_names'] ."<br>";
 					}
 					else
 						$return['_new']++;
-       			}
+       			}       			
    				fclose($handle);
 				unlink($file);
@@ -2860,5 +3015,5 @@
 			$new = null;
 			$code = null;
-
+			
 			if ($parent === '0')
 			{
@@ -2866,5 +3021,5 @@
 				$code .= $name.".add(new dNode({id:'0', caption: '".lang('Catalogues')."'}),'none');\n";
 			}
-
+			
 			foreach ($tree as $id => $value)
 			{
@@ -2872,11 +3027,11 @@
 
 				switch ($value['type'])
-				{
+				{					
 					case 'unknown':
-						$code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption:'{$value['name']}', onFirstOpen: 'getCatalogTree(\\'{$parent}.{$id}\\');', onClick: 'getCatalogTree(\\'{$parent}.{$id}\\'); waitForTree(\\'{$parent}.{$id}\\', 0)'}),'$parent');\n";
+						$code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption:'{$value['name']}', onFirstOpen: 'getCatalogTree(\\'{$parent}.{$id}\\');', onClick: 'getCatalogTree(\\'{$parent}.{$id}\\'); waitForTree(\\'{$parent}.{$id}\\', 0)'}),'$parent');\n"; 
 						break;
-
+					
 					case 'catalog_group':
-						$code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption: '{$value['name']}'}),'$parent');\n";
+						$code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption: '{$value['name']}'}),'$parent');\n"; 
 						$code .= $this->convert_tree($value['sub_branch'],$name,$iconDir,$parent.'.'.$id);
 						break;
@@ -2887,11 +3042,11 @@
 						$code .= $this->convert_tree($value['sub_branch'],$name,$iconDir,$parent.'.'.$id);
 						break;
-
+					
 					case 'catalog':
 						$code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption: '{$value['name']}', onClick: 'setCatalog(\\'{$parent}.{$id}\\')'}),'$parent');\n";
-
-				}
-			}
-
+						
+				}
+			}
+			
 			return $code;
 		}
