<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/**
 * Popup Picker
 *
 * The contents of this file are subject to the SugarCRM Public License Version
 * 1.1.3 ("License"); You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * All copies of the Covered Code must include on each user interface screen:
 *    (i) the "Powered by SugarCRM" logo and
 *    (ii) the SugarCRM copyright notice
 * in the same form as they appear in the distribution.  See full license for
 * requirements.
 *
 * The Original Code is: SugarCRM Open Source
 * The Initial Developer of the Original Code is SugarCRM, Inc.
 * Portions created by SugarCRM are Copyright (C) 2004-2006 SugarCRM, Inc.;
 * All Rights Reserved.
 * Contributor(s): ______________________________________.
 */



global $theme;

require_once('modules/ContactLeads/ContactLead.php');
require_once('modules/ContactLeads/ContactLeadFormBase.php');
require_once('themes/'.$theme.'/layout_utils.php');

require_once('XTemplate/xtpl.php');
require_once('include/ListView/ListView.php');

$image_path = 'themes/'.$theme.'/images/';

class Popup_Picker
{
	
	
	/*
	 * 
	 */
	function Popup_Picker()
	{
		;
	}
	
	/*
	 * 
	 */
   function _get_where_clause(){
    $where = '';
    if(isset($_REQUEST['query'])){
     $where_clauses = array();
     append_where_clause($where_clauses, "first_name", "contactleads.first_name");
     append_where_clause($where_clauses, "last_name", "contactleads.last_name");
     append_where_clause($where_clauses, "first_name_advanced", "contactleads.first_name");
     append_where_clause($where_clauses, "last_name_advanced", "contactleads.last_name");
     append_where_clause($where_clauses, "address_postalcode", "contactleads.primary_address_postalcode");
     append_where_clause($where_clauses, "address_postalcode_advanced", "contactleads.primary_address_postalcode");
     append_where_clause($where_clauses, "address_street", "contactleads.primary_address_street");
     append_where_clause($where_clauses, "address_street_advanced", "contactleads.primary_address_street");
     append_where_clause($where_clauses, "address_city", "contactleads.primary_address_city");
     append_where_clause($where_clauses, "address_city_advanced", "contactleads.primary_address_city");
     append_where_clause($where_clauses, "address_country", "contactleads.primary_address_country");
     append_where_clause($where_clauses, "address_country_advanced", "contactleads.primary_address_country");
     append_where_clause($where_clauses, "address_state", "contactleads.primary_address_state");
     append_where_clause($where_clauses, "address_state_advanced", "contactleads.primary_address_state");
     append_where_clause($where_clauses, "phone", "contactleads.phone_work");
     append_where_clause($where_clauses, "phone_advanced", "contactleads.phone_work");
     append_where_clause($where_clauses, "account_id", "accounts.id");
     append_where_clause($where_clauses, "account_id_advanced", "accounts.id");
     append_where_clause($where_clauses, "account_name", "accounts.name");
     append_where_clause($where_clauses, "account_name_advanced", "accounts.name");
     append_where_clause($where_clauses, "assistant", "contactleads.assistant");
     append_where_clause($where_clauses, "assistant_advanced", "contactleads.assistant");
     append_where_clause($where_clauses, "do_not_call_advanced", "contactleads.do_not_call");
     //append_where_clause($where_clauses, "assigned_user_id", "contactleads.assigned_user_id");
     if(($_REQUEST['foreign_contactlead_advanced']==1 || $_REQUEST['foreign_contactlead_advanced']==0) && !isset($_REQUEST['foreign_contactlead_advanced']))append_where_clause($where_clauses, "foreign_contactlead_advanced", "contactleads.foreign_contactlead");
     if(($_REQUEST['mailing_tag_advanced']==1 || $_REQUEST['mailing_tag_advanced']==0) && !isset($_REQUEST['mailing_tag_advanced']))append_where_clause($where_clauses, "mailing_tag_advanced", "contactleads.mailing_tag");
	 if(count($_REQUEST['assigned_user_id'])>0){
	 	foreach($_REQUEST['assigned_user_id'] as $au){
			$where_clauses[]="contactleads.assigned_user_id='".$au."'";
		}
	 }
	 if(count($_REQUEST['assigned_user_id_advanced'])>0){
	 	foreach($_REQUEST['assigned_user_id_advanced'] as $au){
			$where_clauses[]="contactleads.assigned_user_id='".$au."'";
		}
	 }
	 if($_REQUEST['only_my_items'])$where_clauses[]="contactleads.assigned_user_id='".$_SESSION['authenticated_user_id']."'";
     /*append_where_clause($where_clauses, "address_postalcode", "contactleads.alt_address_postalcode");
     append_where_clause($where_clauses, "address_street", "contactleads.alt_address_street");
     append_where_clause($where_clauses, "address_city", "contactleads.alt_address_city");
     append_where_clause($where_clauses, "address_country", "contactleads.alt_address_country");
     append_where_clause($where_clauses, "address_state", "contactleads.alt_address_state");*/
	 
     //append_where_clause($where_clauses, "assigned_user_advanced", "contactleads.assigned_user_id");
     $where = generate_where_statement($where_clauses);
	 echo $where;
    }
    return $where;
   }
		
	/**
	 *
	 */
	function process_page_dial()
	{
		global $system_config;
		/*
		 * CHECK IF USER WOULD LIKE TO USE PRO VERSION
		 */
		if( isset($system_config->settings['system_asterisk_pro']) && $system_config->settings['system_asterisk_pro'] == 1)
		{
			$asterisk_popup='include/asterisk/Asterisk_popup.tpl';
			$pro='include/asterisk/pro.php';
			/*
			 * CHECK THAT ALL NECESSARY FILES FOR PRO VERSION ARE AVAILABLE
			 */
			if( file_exists($asterisk_popup) && file_exists($pro) ){
				require_once('include/asterisk/pro.php');
				proLogic();
			}
			/*
			 * IF ALL FILES ARE NOT THERE THEN DISPLAY WHERE THEY ARE AVAILABLE AT
			 */
			else
			{
				/*
				 * TRYING TO USE PRO WITHOUT NECESSARY FILES
				 */
				echo "<html><body onLoad=\"javascript:self.resizeTo(400,130)\"><center><font color='red'><br>Either the PRO version is not enabled or you are not using the PRO version.  For more information you may visit <a href='http://www.voicerd.com/products.php'>http://www.voicerd.com/products.php</a><br> or email VoiceRD ( <a href='mailto:voicerd@novacoast.com?subject=Acquiring SugarCRM Pro'>voicerd@novacoast.com</a> )</font></center></body></html>";
			}
		}
		/*
		 * USE THE OPEN SOURCE VERSION
		 */
		else{
			$this->openSourceLogic();
		}
	}


	function openSourceLogic()
	{
		global $system_config;
		global $current_user;
		
		$display_number = $_REQUEST['number'];
		//remove anything that is not a number or an asterisk(*) 
		$number =  preg_replace ( "/[^\d\*]/", "", $_REQUEST['number'] );

		/*
		 * If there is a prefix to be dialed then pre-pend that to the number that will be dialed
		 */
		if(!isset($system_config->settings['system_asterisk_prefix']) || $system_config->settings['system_asterisk_prefix'] != "" )
		{
			/*
			 * Grab the prefix number and remove anything that is not a number or an asterisk(*)
			 */
			$prefix = $system_config->settings['system_asterisk_prefix'];
			$prefix = preg_replace ( "/[^\d\*]/", "", $prefix );
			/*
			 * Pre-prend the prefix to the dial number and to the display number
			 */
			$display_number = $prefix."+".$display_number;
			$number = $prefix.$number;
		}

		/*
		 * If asterisk port was left empty in admin setting then default to 5038
		 */
		if(!isset($system_config->settings['system_asterisk_port']) || $system_config->settings['system_asterisk_port'] == "" )
			$system_config->settings['system_asterisk_port'] = "5038";

		/*
		 * If asterisk internal context was left empty in admin settings then default to "from-internal"
		 */ 
		if(!isset($system_config->settings['system_asterisk_internal_context']) || $system_config->settings['system_asterisk_internal_context'] == "" )
        		$system_config->settings['system_asterisk_internal_context'] = "from-internal";

		/*
		 * If asterisk external context was left empty in admin settings then default to "from-internal"
		 */ 
		if(!isset($system_config->settings['system_asterisk_external_context']) || $system_config->settings['system_asterisk_external_context'] == "" )
        		$system_config->settings['system_asterisk_external_context'] = "from-internal";

		/*
                 * If asterisk auto pickup is blank default to *3
                 */
                if(!isset($system_config->settings['system_asterisk_auto_pickup']) || $system_config->settings['system_asterisk_auto_pickup'] == "" )
                        $system_config->settings['system_asterisk_auto_pickup'] = "*3";

		/*
		 * if any of the required fields were left empty in admin settings then signal error.
		 */
		if( !isset($system_config->settings['system_asterisk_server']) || $system_config->settings['system_asterisk_server'] == "" || !isset($system_config->settings['system_asterisk_username']) || $system_config->settings['system_asterisk_username'] == "" || !isset($system_config->settings['system_asterisk_secret']) || $system_config->settings['system_asterisk_secret'] == "" )
		{
			return "Asterisk Configuration Error.";
		}
		/*
		 * If all required fields are filled in then dial
		 */
		else
		{
			//HTML code
			$output_html="<html>";
			if( isset($system_config->settings['system_asterisk_popup_timer']) && $system_config->settings['system_asterisk_popup_timer'] !="" )
			{
				$output_html.= "<body onLoad=\"javascript:self.resizeTo(350,130);setTimeout(window.close,".($system_config->settings['system_asterisk_popup_timer']*1000).")\">";
			}
			else
			{
				$output_html="<body onLoad=\"javascript:self.resizeTo(350,130)\">";
			}
			$output_html.=<<<EOQ
			<table width='100%' colspacing='0' colpadding'0'>
			<tr>
			<th align='center'><font size='5'>Dialing...$display_number</font></th>
			</tr><!--<tr>
			<th valign='bottom' align='center'><font color='red'><br>Go to <a href='http://www.voicerd.com/products.php'>http://www.voicerd.com/products.php</a><br>for more information or email <a href='mailto:ehoward@novacoast.com?subject=Acquiring SugarCRM Pro'>ehoward@novacoast.com</a></font></th>
			</tr>-->
			</table>
			</body>
			</html>
EOQ;

			 ///If user has auto pickup selected then pre-pend
                        if(isset($current_user->asterisk_auto_pickup) && $current_user->asterisk_auto_pickup == '1'){
                                $number = $system_config->settings['system_asterisk_auto_pickup'].$number;
                        }

			//Asterisk DialCode
			$timeout = 30;
			$socket = fsockopen(  $system_config->settings['system_asterisk_server'],$system_config->settings['system_asterisk_port'], $errno, $errstr, $timeout);
			if(!$socket){ die("Error Connecting to Asterisk Server"); }
			fputs($socket, "Action: Login\r\n");
			fputs($socket, "UserName: ".$system_config->settings['system_asterisk_username']."\r\n");
			fputs($socket, "Secret: ".$system_config->settings['system_asterisk_secret']."\r\n\r\n");
			fputs($socket, "Action: Originate\r\n");
			//Partially contributed by SugarForge User mikeyb
			$callerid = $current_user->asterisk_extension;
			if (strpos($current_user->asterisk_extension, '/') === false) {
				fputs($socket, "Channel: Local/".$current_user->asterisk_extension."@".$system_config->settings['system_asterisk_internal_context']."\r\n");
			} else {
				fputs($socket, "Channel: ".$current_user->asterisk_extension."\r\n");
			}
			fputs($socket, "Context: ".$system_config->settings['system_asterisk_external_context']."\r\n");
			fputs($socket, "Exten: ".$number."\r\n");
			fputs($socket, "Priority: 1\r\n");
			fputs($socket, "Callerid: ".$current_user->asterisk_extension."\r\n\r\n");
			$wrets=fgets($socket,128);
			echo $output_html;
		}
	}
	////////END ASTERISK PATCH////////
	function process_page()
	{
		global $theme;
		global $mod_strings;
		global $app_strings;
		global $currentModule;
		global $sugar_version, $sugar_config;
		
		$output_html = '';
		$where = '';
		
		$where = $this->_get_where_clause();
		
		$image_path = 'themes/'.$theme.'/images/';
		
		$formBase = new ContactLeadFormBase();
		if(isset($_REQUEST['doAction']) && $_REQUEST['doAction'] == 'save')
		{
			$formBase->handleSave('', false, true);
		}

		$first_name = empty($_REQUEST['first_name']) ? '' : $_REQUEST['first_name'];
		$last_name = empty($_REQUEST['last_name']) ? '' : $_REQUEST['last_name'];
		$account_name = empty($_REQUEST['account_name']) ? '' : $_REQUEST['account_name'];
		$request_data = empty($_REQUEST['request_data']) ? '' : $_REQUEST['request_data'];
		$hide_clear_button = empty($_REQUEST['hide_clear_button']) ? false : true;
		$lbl_save_button_title = $app_strings['LBL_SAVE_BUTTON_TITLE'];
		$lbl_save_button_key = $app_strings['LBL_SAVE_BUTTON_KEY'];
		$lbl_save_button_label = $app_strings['LBL_SAVE_BUTTON_LABEL'];
		
		// TODO: cleanup the construction of $addform
		$formbody = $formBase->getFormBody('','','EmailEditView');
		$addform = '<table><tr><td nowrap="nowrap" valign="top">'
			.str_replace('<br>', '</td><td nowrap="nowrap" valign="top">&nbsp;', $formbody)
			. '</td></tr></table>'
			. '<input type="hidden" name="action" value="Popup" />';
		$formSave = <<<EOQ
		<input type="submit" name="button" class="button" title="$lbl_save_button_title" accesskey="$lbl_save_button_key" value="  $lbl_save_button_label  " />
		<input type="button" name="button" class="button" title="{$app_strings['LBL_CANCEL_BUTTON_TITLE']}" accesskey="{$app_strings['LBL_CANCEL_BUTTON_KEY']}" value="{$app_strings['LBL_CANCEL_BUTTON_LABEL']}" onclick="toggleDisplay('addform');" />
EOQ;
		$createContactLead = <<<EOQ
		<input type="button" name="showAdd" class="button" value="{$mod_strings['LNK_NEW_CONTACTLEAD']}" onclick="toggleDisplay('addform');" />
EOQ;
		$addformheader = get_form_header($mod_strings['LNK_NEW_CONTACTLEAD'], $formSave, false);
		$button  = "<form action='index.php' method='post' name='form' id='form'>\n";
		//if (!empty($_REQUEST['mode']) && strtoupper($_REQUEST['mode']) == 'MULTISELECT') {
			$multi_select=true;
			$button .= "<input type='button' name='button' class='button' onclick=\"send_back_selected('ContactLeads',document.MassUpdate,'mass[]','" .$app_strings['ERR_NOTHING_SELECTED']."');\" title='"
				.$app_strings['LBL_SELECT_BUTTON_TITLE']."' accesskey='"
				.$app_strings['LBL_SELECT_BUTTON_KEY']."' value='  "
				.$app_strings['LBL_SELECT_BUTTON_LABEL']."  ' />\n";
		//}
		//END:FOR MULTI-SELECT
		if(!$hide_clear_button)
		{
			$button .= "<input type='button' name='button' class='button' onclick=\"send_back('','');\" title='"
				.$app_strings['LBL_CLEAR_BUTTON_TITLE']."' accesskey='"
				.$app_strings['LBL_CLEAR_BUTTON_KEY']."' value='  "
				.$app_strings['LBL_CLEAR_BUTTON_LABEL']."  ' />\n";
		}
		$button .= "<input type='submit' name='button' class='button' onclick=\"window.close();\" title='"
			.$app_strings['LBL_CANCEL_BUTTON_TITLE']."' accesskey='"
			.$app_strings['LBL_CANCEL_BUTTON_KEY']."' value='  "
			.$app_strings['LBL_CANCEL_BUTTON_LABEL']."  ' />\n";
		//$button.="<input type='hidden' name='saved_associated_data' value=''><input type='hidden' name='ContactLeads_CONTACTLEAD_offset' id='ContactLeads_CONTACTLEAD_offset' value='".$_REQUEST['ContactLeads_CONTACTLEAD_offset']."'>";
		$button .= "</form>\n";

		$first_name              = empty($_REQUEST['first_name'])              ? ''    : $_REQUEST['first_name'];
    $last_name              = empty($_REQUEST['last_name'])              ? ''    : $_REQUEST['last_name'];
$form = new XTemplate('modules/ContactLeads/Popup_picker.html');
    $form->assign('FIRST_NAME',         $first_name);
    $form->assign('LAST_NAME',         $last_name);
	
	$fields=array("first_name","last_name","address_postalcode","address_street","address_state","address_city","address_country","phone","account_id","account_name","assistant","assigned_user_id");
	
	foreach($fields as $f){
		if($_REQUEST[$f])$form->assign(strtoupper($f),$_REQUEST[$f]);
		else $form->assign(strtoupper($f),$_REQUEST[$f."_advanced"]);
	}
	
	$w=mysql_query("select id,first_name,last_name from users where status='Active' and deleted='0' order by first_name asc, last_name asc");
	while($r=mysql_fetch_array($w)){
		$atr.='<option value="'.$r['id'].'"';
		if(@in_array($r['id'],$_REQUEST['assigned_user_id_advanced']))$atr.=' selected';
		$atr.='>'.$r['first_name'].' '.$r['last_name'].'</option>';
	}
	if($_REQUEST['tab'])$form->assign("TABB",$_REQUEST['tab']);
	else $form->assign("TABB","basic");
	
	
	$form->assign('ASSIGNED_TO_LIST',$atr);
	$atr="";
	$arr=array(""=>"","1"=>"Yes","0"=>"No");
	foreach($arr as $k=>$v){
		$atr.='<option value="'.$k.'"';
		if($k==$_REQUEST['foreign_contactlead_advanced'])$atr.=' selected';
		$atr.='>'.$v.'</option>';
	}
	$form->assign('FOREIGN_CONTACTLEAD',$atr);
	$atr="";
	$arr=array(""=>"","1"=>"Yes","0"=>"No");
	foreach($arr as $k=>$v){
		$atr.='<option value="'.$k.'"';
		if($k==$_REQUEST['mailing_tag_advanced'])$atr.=' selected';
		$atr.='>'.$v.'</option>';
	}
	$form->assign('MAILING_TAG',$atr);


		$form->assign('MOD', $mod_strings);
		$form->assign('APP', $app_strings);
		$form->assign('CREATECONTACTLEAD', $createContactLead);
		$form->assign('ADDFORMHEADER', $addformheader);
		$form->assign('ADDFORM', $addform);
		$form->assign('THEME', $theme);
		$form->assign('MODULE_NAME', $currentModule);
		$form->assign('FIRST_NAME', $first_name);
		$form->assign('LAST_NAME', $last_name);
		$form->assign('ACCOUNT_NAME', $account_name);
		$form->assign('request_data', $request_data);
		//if(!$_REQUEST['ContactLeads_CONTACTLEAD_offset'])$offset=0;
		//else $offset=$_REQUEST['ContactLeads_CONTACTLEAD_offset']+20;
		//print_r($_REQUEST);
		if(!isset($_REQUEST['ContactLeads_CONTACTLEAD_offset'])){
			$form->assign("PAG","<input type='hidden' name='saved_associated_data' value=''>
<input type='hidden' name='ContactLeads_CONTACTLEAD_offset' id='ContactLeads_CONTACTLEAD_offset' value='0'>".$button);

		}
		else{
			$form->assign("PAG",$button);
		}
	
		$form->assign('offset',$offset);
	$form->assign('DIV',$_REQUEST['div']);
	$form->assign('PRE',$_REQUEST['pre']);
	if($_REQUEST['only_my_items'])$form->assign("OMI_CHECKED","checked");
	
	$dnc.='<option value="" ';
	if($_REQUEST['do_not_call_advanced']=="")$dnc.='selected="selected"';
	$dnc.='></option>';
 	$dnc.='<option value="0" ';
	if($_REQUEST['do_not_call_advanced']=="0")$dnc.='selected="selected"';
	$dnc.='> No</option>';
	$dnc.='<option value="1" ';
	if($_REQUEST['do_not_call_advanced']=="1")$dnc.='selected="selected"';
	$dnc.='> Yes</option';
	$form->assign('DO_NOT_CALL_LIST',$dnc);

		ob_start();
		insert_popup_header($theme);
		$output_html .= ob_get_contents();
		ob_end_clean();
		
		$output_html .= get_form_header($mod_strings['LBL_SEARCH_FORM_TITLE'], '', false);
		
		$form->parse('main.SearchHeader');
		$output_html .= $form->text('main.SearchHeader');
		
		$output_html .= get_form_footer();
		
		// Reset the sections that are already in the page so that they do not print again later.
		$form->reset('main.SearchHeader');

		// create the listview
		$seed_bean = new ContactLead();
		$ListView = new ListView();
		$ListView->display_header_and_footer=false;
		$ListView->show_export_button = false;
		$ListView->process_for_popups = true;
		$ListView->setXTemplate($form);
		$ListView->setHeaderTitle($mod_strings['LBL_LIST_FORM_TITLE']);
		$ListView->setHeaderText($button);
		$ListView->setQuery($where, '', '', 'CONTACTLEAD');
		$ListView->setModStrings($mod_strings);
		$ListView->multi_select_popup=true;

		ob_start();
		$ListView->processListView($seed_bean, 'main', 'CONTACTLEAD');
		$output_html .= ob_get_contents();
		ob_end_clean();
				
		$output_html .= get_form_footer();
		$output_html .= insert_popup_footer();
		return $output_html;
	}
	
	function process_page_for_merge()
	{
		global $theme;
		global $mod_strings;
		global $app_strings;
		global $currentModule;
		global $sugar_version, $sugar_config;
		
		$output_html = '';
		$where = '';
		
		$where = $this->_get_where_clause();
		
		$image_path = 'themes/'.$theme.'/images/';
		
		$first_name = empty($_REQUEST['first_name']) ? '' : $_REQUEST['first_name'];
		$last_name = empty($_REQUEST['last_name']) ? '' : $_REQUEST['last_name'];
		$account_name = empty($_REQUEST['account_name']) ? '' : $_REQUEST['account_name'];
		$hide_clear_button = empty($_REQUEST['hide_clear_button']) ? false : true;
		$button  = "<form action='index.php' method='post' name='form' id='form'>\n";
		//START:FOR MULTI-SELECT
		$multi_select=false;
		if (!empty($_REQUEST['mode']) && strtoupper($_REQUEST['mode']) == 'MULTISELECT') {
			$multi_select=true;
			$button .= "<input type='button' name='button' class='button' onclick=\"send_back_selected('ContactLeads',document.MassUpdate,'mass[]','" .$app_strings['ERR_NOTHING_SELECTED']."');\" title='"
				.$app_strings['LBL_SELECT_BUTTON_TITLE']."' accesskey='"
				.$app_strings['LBL_SELECT_BUTTON_KEY']."' value='  "
				.$app_strings['LBL_SELECT_BUTTON_LABEL']."  ' />\n";
		}
		//END:FOR MULTI-SELECT
		if(!$hide_clear_button)
		{
			$button .= "<input type='button' name='button' class='button' onclick=\"send_back('','');\" title='"
				.$app_strings['LBL_CLEAR_BUTTON_TITLE']."' accesskey='"
				.$app_strings['LBL_CLEAR_BUTTON_KEY']."' value='  "
				.$app_strings['LBL_CLEAR_BUTTON_LABEL']."  ' />\n";
		}
		$button .= "<input type='submit' name='button' class='button' onclick=\"window.close();\" title='"
			.$app_strings['LBL_CANCEL_BUTTON_TITLE']."' accesskey='"
			.$app_strings['LBL_CANCEL_BUTTON_KEY']."' value='  "
			.$app_strings['LBL_CANCEL_BUTTON_LABEL']."  ' />\n";
		$button .= "</form>\n";

		$form = new XTemplate('modules/ContactLeads/Popup_picker.html');
		$form->assign('MOD', $mod_strings);
		$form->assign('APP', $app_strings);
		$form->assign('THEME', $theme);
		$form->assign('MODULE_NAME', $currentModule);
		$form->assign('FIRST_NAME', $first_name);
		$form->assign('LAST_NAME', $last_name);
		$form->assign('ACCOUNT_NAME', $account_name);
		$request_data = empty($_REQUEST['request_data']) ? '' : $_REQUEST['request_data'];
		$form->assign('request_data', $request_data);

		ob_start();
		insert_popup_header($theme);
		$output_html .= ob_get_contents();
		ob_end_clean();
		
		$output_html .= get_form_header($mod_strings['LBL_SEARCH_FORM_TITLE'], '', false);
		
		$form->parse('main.SearchHeader');
		$output_html .= $form->text('main.SearchHeader');
		
		$output_html .= get_form_footer();
		
		// Reset the sections that are already in the page so that they do not print again later.
		$form->reset('main.SearchHeader');
		
		// create the listview
		$seed_bean = new ContactLead();
		$ListView = new ListView();
		$ListView->display_header_and_footer=false;
		$ListView->show_export_button = false;
		$ListView->process_for_popups = true;
		$ListView->setXTemplate($form);
		$ListView->multi_select_popup=$multi_select;
		if ($multi_select) $ListView->xTemplate->assign("TAG_TYPE","SPAN"); else  $ListView->xTemplate->assign("TAG_TYPE","A");
		$ListView->setHeaderTitle($mod_strings['LBL_LIST_FORM_TITLE']);
		$ListView->setQuery($where, '', 'contactleads.last_name, contactleads.first_name', 'CONTACTLEAD');
		$ListView->setModStrings($mod_strings);

		ob_start();
		$output_html .= get_form_header($mod_strings['LBL_LIST_FORM_TITLE'], $button, false);
				//BEGIN ATHENA CUSTOMIZATION - rsmith
			$query = $_REQUEST['select'].' WHERE '.$_REQUEST['where']."'".$_REQUEST['id']."'";
			
			//$response = $seed_bean->process_list_query($_REQUEST['select'], 0, -1, -1, $_REQUEST['where']."'".$_REQUEST['id']."'");
			
			$result = $seed_bean->db->query($query,true,"Error retrieving $seed_bean->object_name list: ");

			$list = Array();
			if(empty($rows_found))
			{
  				$rows_found =  $seed_bean->db->getRowCount($result);
			}
			
			$row_offset = 0;
global $sugar_config;
			$max_per_page = $sugar_config['list_max_entries_per_page'];

				while(($row = $seed_bean->db->fetchByAssoc($result)) != null)
			    	{
						$seed_bean = new ContactLead();
						foreach($seed_bean->field_defs as $field=>$value)
						{
							if (isset($row[$field])) 
							{
								$seed_bean->$field = $row[$field];
							}
							else if (isset($row[$seed_bean->table_name .'.'.$field])) 
							{
								$seed_bean->$field = $row[$seed_bean->table_name .'.'.$field];
							}
							else
							{
								$seed_bean->$field = "";
							}	
						}
						$seed_bean->fill_in_additional_list_fields();

						$list[] = $seed_bean;
			    	}
					
			$ListView->processListViewTwo($list, 'main', 'CONTACTLEAD');

		//END ATHENA CUSTOMIZATION - rsmith
		$output_html .= ob_get_contents();
		ob_end_clean();
				
		$output_html .= get_form_footer();
		$output_html .= insert_popup_footer();
		return $output_html;
		
	}

	/**
	 *
	 */
	function process_page_for_email()
	{
		global $theme;
		global $mod_strings;
		global $app_strings;
		global $currentModule;
		global $sugar_version, $sugar_config;
		
		$output_html = '';
		$where = '';
		
		$where = $this->_get_where_clause();
		
		$image_path = 'themes/'.$theme.'/images/';
		
		$first_name = empty($_REQUEST['first_name']) ? '' : $_REQUEST['first_name'];
		$last_name = empty($_REQUEST['last_name']) ? '' : $_REQUEST['last_name'];
		$account_name = empty($_REQUEST['account_name']) ? '' : $_REQUEST['account_name'];
		$hide_clear_button = empty($_REQUEST['hide_clear_button']) ? false : true;
		$button  = "<form action='index.php' method='post' name='form' id='form'>\n";
		//START:FOR MULTI-SELECT
		$multi_select=false;
		if (!empty($_REQUEST['mode']) && strtoupper($_REQUEST['mode']) == 'MULTISELECT') {
			$multi_select=true;
			$button .= "<input type='button' name='button' class='button' onclick=\"send_back_selected('ContactLeads',document.MassUpdate,'mass[]','" .$app_strings['ERR_NOTHING_SELECTED']."');\" title='"
				.$app_strings['LBL_SELECT_BUTTON_TITLE']."' accesskey='"
				.$app_strings['LBL_SELECT_BUTTON_KEY']."' value='  "
				.$app_strings['LBL_SELECT_BUTTON_LABEL']."  ' />\n";
		}
		//END:FOR MULTI-SELECT
		if(!$hide_clear_button)
		{
			$button .= "<input type='button' name='button' class='button' onclick=\"send_back('','');\" title='"
				.$app_strings['LBL_CLEAR_BUTTON_TITLE']."' accesskey='"
				.$app_strings['LBL_CLEAR_BUTTON_KEY']."' value='  "
				.$app_strings['LBL_CLEAR_BUTTON_LABEL']."  ' />\n";
		}
		$button .= "<input type='submit' name='button' class='button' onclick=\"window.close();\" title='"
			.$app_strings['LBL_CANCEL_BUTTON_TITLE']."' accesskey='"
			.$app_strings['LBL_CANCEL_BUTTON_KEY']."' value='  "
			.$app_strings['LBL_CANCEL_BUTTON_LABEL']."  ' />\n";
		$button .= "</form>\n";

		$form = new XTemplate('modules/ContactLeads/Popup_picker.html');
		$form->assign('MOD', $mod_strings);
		$form->assign('APP', $app_strings);
		$form->assign('THEME', $theme);
		$form->assign('MODULE_NAME', $currentModule);
		$form->assign('FIRST_NAME', $first_name);
		$form->assign('LAST_NAME', $last_name);
		$form->assign('ACCOUNT_NAME', $account_name);
		
		ob_start();
		insert_popup_header($theme);
		$output_html .= ob_get_contents();
		ob_end_clean();
		
		$output_html .= get_form_header($mod_strings['LBL_SEARCH_FORM_TITLE'], '', false);
		
		$form->parse('main.SearchHeader');
		$output_html .= $form->text('main.SearchHeader');
		
		$output_html .= get_form_footer();
		
		// Reset the sections that are already in the page so that they do not print again later.
		$form->reset('main.SearchHeader');
		
		// create the listview
		$seed_bean = new ContactLead();
		$ListView = new ListView();
		$ListView->display_header_and_footer=false;
		$ListView->show_export_button = false;
		$ListView->process_for_popups = true;
		$ListView->setXTemplate($form);
		$ListView->multi_select_popup=$multi_select;
		if ($multi_select) $ListView->xTemplate->assign("TAG_TYPE","SPAN"); else  $ListView->xTemplate->assign("TAG_TYPE","A");
		$ListView->setHeaderTitle($mod_strings['LBL_LIST_FORM_TITLE']);
		$ListView->setQuery($where, '', 'contactleads.last_name, contactleads.first_name', 'CONTACTLEAD');
		$ListView->setModStrings($mod_strings);

		ob_start();
		$output_html .= get_form_header($mod_strings['LBL_LIST_FORM_TITLE'], $button, false);
		$ListView->processListView($seed_bean, 'main', 'CONTACTLEAD');
		$output_html .= ob_get_contents();
		ob_end_clean();
				
		$output_html .= get_form_footer();
		$output_html .= insert_popup_footer();
		return $output_html;
	}

	/**
	 *
	 */
	function process_page_for_address()
	{
		global $theme;
		global $mod_strings;
		global $app_strings;
		global $currentModule;
		global $sugar_version, $sugar_config;
		
		$output_html = '';
		$where = '';
		
		$where = $this->_get_where_clause();
		
		$image_path = 'themes/'.$theme.'/images/';
		
		$formBase = new ContactLeadFormBase();
		if(isset($_REQUEST['doAction']) && $_REQUEST['doAction'] == 'save')
		{
			
			$formBase->handleSave('', false, true);
		}

		$first_name = empty($_REQUEST['first_name']) ? '' : $_REQUEST['first_name'];
		$last_name = empty($_REQUEST['last_name']) ? '' : $_REQUEST['last_name'];
		$account_name = empty($_REQUEST['account_name']) ? '' : $_REQUEST['account_name'];
		$request_data = empty($_REQUEST['request_data']) ? '' : $_REQUEST['request_data'];
		$hide_clear_button = empty($_REQUEST['hide_clear_button']) ? false : true;
		$lbl_save_button_title = $app_strings['LBL_SAVE_BUTTON_TITLE'];
		$lbl_save_button_key = $app_strings['LBL_SAVE_BUTTON_KEY'];
		$lbl_save_button_label = $app_strings['LBL_SAVE_BUTTON_LABEL'];
		
		// TODO: cleanup the construction of $addform
		$formbody = $formBase->getFormBody('','','EmailEditView');
		$addform = '<table><tr><td nowrap="nowrap" valign="top">'
			.str_replace('<br>', '</td><td nowrap="nowrap" valign="top">&nbsp;', $formbody)
			. '</td></tr></table>'
			. '<input type="hidden" name="action" value="Popup" />';
		$formSave = <<<EOQ
		<input type="submit" name="button" class="button" title="$lbl_save_button_title" accesskey="$lbl_save_button_key" value="  $lbl_save_button_label  " />
		<input type="button" name="button" class="button" title="{$app_strings['LBL_CANCEL_BUTTON_TITLE']}" accesskey="{$app_strings['LBL_CANCEL_BUTTON_KEY']}" value="{$app_strings['LBL_CANCEL_BUTTON_LABEL']}" onclick="toggleDisplay('addform');" />
EOQ;
		$createContactLead = <<<EOQ
		<input type="button" name="showAdd" class="button" value="{$mod_strings['LNK_NEW_CONTACTLEAD']}" onclick="toggleDisplay('addform');" />
EOQ;
		$addformheader = get_form_header($mod_strings['LNK_NEW_CONTACTLEAD'], $formSave, false);
		$button  = "<form action='index.php' method='post' name='form' id='form'>\n";
		if(!$hide_clear_button)
		{
			$button .= "<input type='button' name='button' class='button' onclick=\"send_back('','');\" title='"
				.$app_strings['LBL_CLEAR_BUTTON_TITLE']."' accesskey='"
				.$app_strings['LBL_CLEAR_BUTTON_KEY']."' value='  "
				.$app_strings['LBL_CLEAR_BUTTON_LABEL']."  ' />\n";
		}
		$button .= "<input type='submit' name='button' class='button' onclick=\"window.close();\" title='"
			.$app_strings['LBL_CANCEL_BUTTON_TITLE']."' accesskey='"
			.$app_strings['LBL_CANCEL_BUTTON_KEY']."' value='  "
			.$app_strings['LBL_CANCEL_BUTTON_LABEL']."  ' />\n";
		$button .= "</form>\n";

		$form = new XTemplate('modules/ContactLeads/Address_picker.html');
		$form->assign('MOD', $mod_strings);
		$form->assign('APP', $app_strings);
		//$form->assign('CREATECONTACTLEAD', $createContactLead);
		$form->assign('ADDFORMHEADER', $addformheader);
		$form->assign('ADDFORM', $addform);
		$form->assign('THEME', $theme);
		$form->assign('MODULE_NAME', $currentModule);
		$form->assign('FIRST_NAME', $first_name);
		$form->assign('LAST_NAME', $last_name);
		$form->assign('ACCOUNT_NAME', $account_name);
		$form->assign('request_data', $request_data);
		
		// fill in for mass update
		$button = "<input type='hidden' name='module' value='ContactLeads'><input type='hidden' id='form_action' name='action' value='index'><input type='hidden' name='massupdate' value='true'><input type='hidden' name='delete' value='false'><input type='hidden' name='mass' value='Array'><input type='hidden' name='Update' value='Update'>";
		if(isset($_REQUEST['mass']) && is_array($_REQUEST['mass'])) {
			foreach(array_unique($_REQUEST['mass']) as $record) {
				$button .= "<input style='display: none' checked type='checkbox' name='mass[]' value='$record'>\n";  
			}		
		}
		$button .= "<input type='hidden' name='saved_associated_data' value=''>";
		$button .= "<input type='hidden' name='query' value='true'>";
		$button .= "<input type='hidden' name='close_window' value='true'>";
		$button .= "<input type='hidden' name='html' value='change_address'>";
		$button .= "<input type='hidden' name='account_name' value='$account_name'>";
		$button .= "<span style='display: none'><textarea name='primary_address_street'>" . str_replace("&lt;br&gt;", "\n", $_REQUEST["primary_address_street"]) . "</textarea></span>";
		$button .= "<input type='hidden' name='primary_address_city' value='". $_REQUEST["primary_address_city"] ."'>";
		$button .= "<input type='hidden' name='primary_address_state' value='". $_REQUEST["primary_address_state"] ."'>";
		$button .= "<input type='hidden' name='primary_address_postalcode' value='". $_REQUEST["primary_address_postalcode"] ."'>";
		$button .= "<input type='hidden' name='primary_address_country' value='". $_REQUEST["primary_address_country"] ."'>";
		//$button .= "<input type='hidden' name='ContactLeads_CONTACTLEAD_offset' value=''>";
		$button .= "<input title='".$mod_strings['LBL_COPY_ADDRESS_CHECKED']."'  class='button' LANGUAGE=javascript type='submit' name='button' value='  ".$mod_strings['LBL_COPY_ADDRESS_CHECKED']."  '>\n";
		$button .= "<input title='".$app_strings['LBL_CANCEL_BUTTON_TITLE']."' accessKey='".$app_strings['LBL_CANCEL_BUTTON_KEY']."' class='button' LANGUAGE=javascript onclick=\"window.close()\" type='submit' name='button' value='  ".$app_strings['LBL_CANCEL_BUTTON_LABEL']."  '>\n";

		

		ob_start();
		insert_popup_header($theme);
		$output_html .= ob_get_contents();
		ob_end_clean();
		
		//$output_html .= get_form_header($mod_strings['LBL_SEARCH_FORM_TITLE'], '', false);
		
		//$form->parse('main.SearchHeader');
		//$output_html .= $form->text('main.SearchHeader');
		
		$output_html .= get_form_footer();
		
		// Reset the sections that are already in the page so that they do not print again later.
		$form->reset('main.SearchHeader');

		// create the listview
		$seed_bean = new ContactLead();
		$ListView = new ListView();
		$ListView->show_export_button = false;
		$ListView->multi_select_popup=true;
		$ListView->process_for_popups = true;
		$ListView->setXTemplate($form);
		$ListView->setHeaderTitle($mod_strings['LBL_LIST_FORM_TITLE']);
		$ListView->setHeaderText($button);
		$ListView->setQuery($where, '', '', 'CONTACTLEAD');
		$ListView->setModStrings($mod_strings);
		
		
		ob_start();
		$ListView->processListViewMulti($seed_bean, 'main', 'CONTACTLEAD');
		$output_html .= ob_get_contents();
		ob_end_clean();
	    
	    // Regular Expression to override sListView 
        $exp = '/sListView.save_checks/si'; 
        $change = 'save_checks';
        $output_html = preg_replace(array($exp), array($change), $output_html);
		$output_html .= '<script>		
		
        checked_items = Array();
		inputs_array = document.MassUpdate.elements;

		for(wp = 0 ; wp < inputs_array.length; wp++) {
			if(inputs_array[wp].name == "mass[]" && inputs_array[wp].style.display == "none") {
				checked_items.push(inputs_array[wp].value);
			} 
		}
		for(i in checked_items) {
			for(wp = 0 ; wp < inputs_array.length; wp++) {
				if(inputs_array[wp].name == "mass[]" && inputs_array[wp].value == checked_items[i]) {
					inputs_array[wp].checked = true;
				}
			}
		}



        </script>';
	    
		$output_html .= get_form_footer();
		$output_html .= insert_popup_footer();
		return $output_html;
	}
}
?>
