EOQ;
return $the_script;
}
/**
 * Very cool algorithm for sorting multi-dimensional arrays.  Found at http://us2.php.net/manual/en/function.array-multisort.php
 * Syntax: $new_array = array_csort($array [, 'col1' [, SORT_FLAG [, SORT_FLAG]]]...);
 * Explanation: $array is the array you want to sort, 'col1' is the name of the column
 * you want to sort, SORT_FLAGS are : SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING
 * you can repeat the 'col',FLAG,FLAG, as often you want, the highest prioritiy is given to
 * the first - so the array is sorted by the last given column first, then the one before ...
 * Example: $array = array_csort($array,'town','age',SORT_DESC,'name');
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 * All Rights Reserved.
 * Contributor(s): ______________________________________..
 */
function array_csort() {
   $args = func_get_args();
   $marray = array_shift($args);
   $i = 0;
   $msortline = "return(array_multisort(";
   foreach ($args as $arg) {
	   $i++;
	   if (is_string($arg)) {
		   foreach ($marray as $row) {
			   $sortarr[$i][] = $row[$arg];
		   }
	   } else {
		   $sortarr[$i] = $arg;
	   }
	   $msortline .= "\$sortarr[".$i."],";
   }
   $msortline .= "\$marray));";
   eval($msortline);
   return $marray;
}
/**
 * Converts localized date format string to jscalendar format
 * Example: $array = array_csort($array,'town','age',SORT_DESC,'name');
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 * All Rights Reserved.
 * Contributor(s): ______________________________________..
 */
function parse_calendardate($local_format) {
	/* temporarily disabled until international date formats are fixed
	preg_match("/\(?([^-]{1})[^-]*-([^-]{1})[^-]*-([^-]{1})[^-]*\)/", $local_format, $matches);
	if (isset($matches[1]) && isset($matches[2]) && isset($matches[3])) {
		$calendar_format = "%" . $matches[1] . "-%" . $matches[2] . "-%" . $matches[3];
		return str_replace(array("y", "�, "a", "j"), array("Y", "Y", "Y", "d"), $calendar_format);
	}
	else {
		return "%Y-%m-%d";
	} */
	global $current_user;
	if($current_user->date_format == 'dd-mm-yyyy')
	{
		$dt_popup_fmt = "%d-%m-%Y";
	}
	elseif($current_user->date_format == 'mm-dd-yyyy')
	{
		$dt_popup_fmt = "%m-%d-%Y";
	}
	elseif($current_user->date_format == 'yyyy-mm-dd')
	{
		$dt_popup_fmt = "%Y-%m-%d";
	}
	return $dt_popup_fmt;
	//return "%Y-%m-%d";
}
function set_default_config(&$defaults)
{
	foreach ($defaults as $name=>$value)
	{
		if ( ! isset($GLOBALS[$name]) )
		{
			$GLOBALS[$name] = $value;
		}
	}
}
$toHtml = array(
        '"' => '"',
        '<' => '<',
        '>' => '>',
        '& ' => '& ',
        "'" =>  ''',
);
function to_html($string, $encode=true){
        global $toHtml;
        if($encode && is_string($string)){//$string = htmlentities($string, ENT_QUOTES);
        $string = str_replace(array_keys($toHtml), array_values($toHtml), $string);
        }
        return $string;
}
function from_html($string, $encode=true){
        global $toHtml;
        //if($encode && is_string($string))$string = html_entity_decode($string, ENT_QUOTES);
        if($encode && is_string($string)){
                $string = str_replace(array_values($toHtml), array_keys($toHtml), $string);
        }
        return $string;
}
function get_group_options()
{
	global $adb;
	$sql = "select name from groups";
	$result = $adb->query($sql);
	return $result;
}
function get_assigned_user_or_group_name($id,$module)
{
	global $adb;
	//it might so happen that an entity is assigned to a group but at that time the group has no members. even in this case, the query should return a valid value and not just blank
  if($module == 'Leads')
  {
	 //$sql = "select (case when (user_name is null) then  (users2group.groupname) else (user_name) end) as name from leads left join users on users.id= assigned_user_id left join users2group on users2group.groupname=leads.assigned_user_id where leads.id='" .$id ."'";
    //$sql = "select (case when (user_name is null) then  (groups.name) else (user_name) end) as name from leads left join users on users.id= assigned_user_id left join groups on groups.name=leads.assigned_user_id where leads.id='" .$id ."'";
   $sql="select (case when (user_name is null) then  (leadgrouprelation.groupname) else (user_name) end) as name from leads left join users on users.id= assigned_user_id left join leadgrouprelation on leadgrouprelation.leadid=leads.id where leads.deleted=0 and leads.id='". $id ."'";
   
  }
  else if($module == 'Tasks')
  {
       $sql="select (case when (user_name is null) then  (taskgrouprelation.groupname) else (user_name) end) as name from tasks left join users on users.id= assigned_user_id left join taskgrouprelation on taskgrouprelation.taskid=tasks.id where tasks.deleted=0 and tasks.id='". $id ."'";
       //$sql = "select (case when (user_name is null) then  (groups.name) else (user_name) end) as name from tasks left join users on users.id= assigned_user_id left join groups on groups.name=tasks.assigned_user_id where tasks.id='" .$id ."'";
  }
  else if($module == 'Calls')
  {
       $sql="select (case when (user_name is null) then  (callgrouprelation.groupname) else (user_name) end) as name from calls left join users on users.id= assigned_user_id left join callgrouprelation on callgrouprelation.callid=calls.id where calls.deleted=0 and calls.id='". $id ."'";
       //     $sql = "select (case when (user_name is null) then  (groups.name) else (user_name) end) as name from calls left join users on users.id= assigned_user_id left join groups on groups.name=calls.assigned_user_id where calls.id='" .$id ."'";
  }
	$result = $adb->query($sql);
	$tempval = $adb->fetch_row($result);
	return $tempval[0];
}
function getTabname($tabid)
{
	global $vtlog;
	$vtlog->logthis("tab id is ".$tabid,'info');  
        global $adb;
	$sql = "select tablabel from tab where tabid='".$tabid."'";
	$result = $adb->query($sql);
	$tabname=  $adb->query_result($result,0,"tablabel");
	return $tabname;
}
function getTabid($module)
{
	global $vtlog;
	$vtlog->logthis("module  is ".$module,'info');  
        
        global $adb;
	$sql = "select tabid from tab where name='".$module."'";
	$result = $adb->query($sql);
	$tabid=  $adb->query_result($result,0,"tabid");
	return $tabid;
}
function getOutputHtml($uitype, $fieldname, $fieldlabel, $maxlength, $col_fields,$generatedtype)
{
	global $adb;
	global $theme;
	global $mod_strings;
	global $app_strings;
	global $current_user;
	$value = $col_fields[$fieldname];
	$custfld = '';
	if($generatedtype == 2)
		$mod_strings[$fieldlabel] = $fieldlabel;
	if($uitype == 5 || $uitype == 6 || $uitype ==23)
	{	
          global $vtlog;
          $vtlog->logthis("uitype is ".$uitype,'info');  
		if($value=='')
                {
			if($fieldname != 'birthday')
                        	$disp_value=getNewDisplayDate();
                }
                else
                {
                        $disp_value = getDisplayDate($value);
                }
		$custfld .= '';
		if($uitype == 6 || $uitype == 23)
			$custfld .= '* ';
		$custfld .= $mod_strings[$fieldlabel].': ';
		$date_format = parse_calendardate($app_strings['NTC_DATE_FORMAT']);
		$custfld .= '('.$current_user->date_format.') ('.$current_user->date_format.' '.$app_strings['YEAR_MONTH_DATE'].') ';
		if($uitype == 16)
			$custfld .= '* ';
		$custfld .= $mod_strings[$fieldlabel].': ';
		//$pick_query="select * from ".$fieldname." order by sortorderid";
		$pick_query="select * from ".$fieldname;
		$pickListResult = $adb->query($pick_query);
		$noofpickrows = $adb->num_rows($pickListResult);
		$custfld .= '';
		for($j = 0; $j < $noofpickrows; $j++)
		{
			$pickListValue=$adb->query_result($pickListResult,$j,strtolower($fieldname));
			if($value == $pickListValue)
			{
				$chk_val = "selected";	
			}
			else
			{	
				$chk_val = '';
			}
			$custfld .= ''.$pickListValue.' ';
		}
		$custfld .= ' ';
		if($uitype == 20)
                {
                        $custfld .= '* ';
                }
		$custfld .= $mod_strings[$fieldlabel].': ';
        	$custfld .= '';
                if($uitype == 24)
                {
                        $custfld .= '* ';
                }
		$custfld .= $mod_strings[$fieldlabel].': ';
        	$custfld .= '*  '.$mod_strings[$fieldlabel].':'.$mod_strings[$fieldlabel].': ';
		global $current_user;
		if($value != '')
		{
			$assigned_user_id = $value;	
		}
		else
		{
			$assigned_user_id = $current_user->id;
		}
		if($uitype == 52)
		{
			$combo_lbl_name = 'assigned_user_id';
		}
		elseif($uitype == 77)
		{
			$combo_lbl_name = 'assigned_user_id1';
		}
		$users_combo = get_select_options_with_id(get_user_array(FALSE, "Active", $assigned_user_id), $assigned_user_id);
                $custfld .= ''.$users_combo.' '.$mod_strings[$fieldlabel].': ';
          
          $result = get_group_options();
          $nameArray = $adb->fetch_array($result);
	  	
          
          global $current_user;
	  if($value != '' && $value != 0)
	  {
		  $assigned_user_id = $value;
		  $user_checked = "checked";
		  $team_checked = '';
		  $user_style='display:block';
		  $team_style='display:none';			
	  }
	  else
	  {
		  if($value=='0')
		  {
			  $record = $col_fields["record_id"];
			  $module = $col_fields["record_module"];
			  $selected_groupname = getGroupName($record, $module);
			  $user_checked = '';
		          $team_checked = 'checked';
			  $user_style='display:none';
		  	  $team_style='display:block';
		  }
		  else	
		  {				
			  $assigned_user_id = $current_user->id;
			  $user_checked = "checked";
		          $team_checked = '';
			  $user_style='display:block';
		  	  $team_style='display:none';
		  }	
	  }
         
          
          $users_combo = get_select_options_with_id(get_user_array(FALSE, "Active", $assigned_user_id), $assigned_user_id);
          
          $GROUP_SELECT_OPTION = '';
          
          $GROUP_SELECT_OPTION .= $users_combo;
          
          $GROUP_SELECT_OPTION .= ' ';
          
          
          do
          {
            $groupname=$nameArray["name"];
	    $selected = '';	
	    if($groupname == $selected_groupname)
	    {
		$selected = "selected";
            }	
            $GROUP_SELECT_OPTION .= '';
            $GROUP_SELECT_OPTION .= $nameArray["name"];
            $GROUP_SELECT_OPTION .= ' ';
          }while($nameArray = $adb->fetch_array($result));
//          $GROUP_SELECT_OPTION .=''.$app_strings['LBL_NONE_NO_LINE'].' ';
          $GROUP_SELECT_OPTION .= '  ';
		if($uitype==50 || $uitype==73)
			$custfld .= '* ';
		$custfld .= $mod_strings[$fieldlabel].': ';
		if($uitype == 73)
		{
			
			$custfld .= ''.$mod_strings[$fieldlabel].': ';
		$pick_query="select * from groups";
		$pickListResult = $adb->query($pick_query);
		$noofpickrows = $adb->num_rows($pickListResult);
		$custfld .= '';
		$custfld .= ''.$app_strings['LBL_SELECT_GROUP'].' ';
		for($j = 0; $j < $noofpickrows; $j++)
		{
			$pickListValue=$adb->query_result($pickListResult,$j,"name");
			if($value == $pickListValue)
			{
				$chk_val = "selected";	
			}
			else
			{	
				$chk_val = '';	
			}
			$custfld .= ''.$pickListValue.' ';
		}
		$custfld .= ' '.$mod_strings[$fieldlabel].': ';
		$pick_query="select * from salutationtype order by sortorderid";
		$pickListResult = $adb->query($pick_query);
		$noofpickrows = $adb->num_rows($pickListResult);
		$salt_value = $col_fields["salutationtype"];
		$custfld .= '';
		for($j = 0; $j < $noofpickrows; $j++)
		{
			$pickListValue=$adb->query_result($pickListResult,$j,"salutationtype");
			
			if($salt_value == $pickListValue)
			{
				$chk_val = "selected";	
			}
			else
			{	
				$chk_val = '';	
			}
			$custfld .= ''.$pickListValue.' ';
		}
		$custfld .= ' ';
               $custfld .= $mod_strings[$fieldlabel].': ';
	       $custfld .= ''.$mod_strings[$fieldlabel].': ';
                if($value=='')
                $value=1;
                $custfld .= '';
                for($j = 0; $j < $noofpickrows; $j++)
                {
                        $pickListValue=$adb->query_result($pickListResult,$j,"duration_minutes");
                        if($salt_value == $pickListValue)
                        {
                                $chk_val = "selected";
                        }
                        else
                        {
                                $chk_val = '';
                        }
                        $custfld .= ''.$pickListValue.' ';
                }
                $custfld .= ' ';
                $custfld .= $app_strings['LBL_HOUR_AND_MINUTE'].'';
                $custfld .= $mod_strings[$fieldlabel].': ';
                $date_format = parse_calendardate($app_strings['NTC_DATE_FORMAT']);
                $custfld .= ''.$mod_strings["DATE_FORMAT"].' '.$mod_strings[$fieldlabel].': ';
		if($value == 1)
		{
			$custfld .=''.$mod_strings[$fieldlabel].' ';
        	$custfld .= ''.$mod_strings[$fieldlabel].' ';
                $custfld .='';
                $custfld .= ''.$app_strings['COMBO_LEADS'].' ';
                $custfld .= ''.$app_strings['COMBO_ACCOUNTS'].' ';
                $custfld .= ''.$app_strings['COMBO_POTENTIALS'].' ';
		$custfld .= ''.$app_strings['COMBO_PRODUCTS'].' ';
		$custfld .= ''.$app_strings['COMBO_INVOICES'].' ';
                $custfld .= ''.$app_strings['COMBO_PORDER'].' ';
                $custfld .= ''.$app_strings['COMBO_SORDER'].'  ';
                $custfld .= ''.$app_strings['COMBO_LEADS'].' ';
                $custfld .= ''.$app_strings['COMBO_ACCOUNTS'].' ';
                $custfld .= ''.$app_strings['COMBO_POTENTIALS'].' ';
		if($act_mode == "Task")
                {
			$custfld .= ''.$app_strings['COMBO_QUOTES'].' ';
                        $custfld .= ''.$app_strings['COMBO_PORDER'].' ';
                        $custfld .= ''.$app_strings['COMBO_SORDER'].' ';
                        $custfld .= ''.$app_strings['COMBO_INVOICES'].' ';
                }
                $custfld .=' ';
                $custfld .= ''.$app_strings['COMBO_LEADS'].' ';
                $custfld .= ''.$app_strings['COMBO_CONTACTS'].' ';
	        $custfld .= '';
                $custfld .= ''.$app_strings['COMBO_CONTACTS'];
                $custfld .= ' '.$app_strings['COMBO_ACCOUNTS'].' ';
	        $custfld .= '
                '.$app_strings['COMBO_LEADS'].' 
                '.$app_strings['COMBO_ACCOUNTS'].' 
                '.$app_strings['COMBO_POTENTIALS'].' 
                '.$app_strings['COMBO_PRODUCTS'].'  ';
		if($uitype == 72)
		{
			$custfld .= '* ';
		}
		$disp_currency = getDisplayCurrency();
		$custfld .= $mod_strings[$fieldlabel].': ('.$disp_currency.') ';
		$custfld .= '';
		$pop_type = 'specific';
		if($uitype == 81)
		{
			$custfld .= '* ';
			$pop_type = 'specific_vendor_address';
		}
		$custfld .= $mod_strings[$fieldlabel].' ';
		
        	$custfld .= ''.$mod_strings[$fieldlabel].' ';
        	$custfld .= ''.$mod_strings[$fieldlabel].' ';
        	$custfld .= ''.$mod_strings[$fieldlabel].' ';
        	$custfld .= ''.$mod_strings[$fieldlabel].' ';
        	$custfld .= ''.$mod_strings[$fieldlabel].': ';
                $custfld .= '  ';
		$SET_REM = '';
	}
	else
	{
		$custfld .= '';
		//Added condition to set the subject if click Reply All from web mail
		if($_REQUEST['module'] == 'Emails' && $_REQUEST['mg_subject'] != '')
		{
			$value = $_REQUEST['mg_subject'];
		}
		if($uitype == 2)
			$custfld .= '* ';
		$custfld .= $mod_strings[$fieldlabel].': ';
		$custfld .= ''.$mod_strings[$fieldlabel].': ';
		$custfld .= ''.$col_fields[$fieldname].' '.$mod_strings[$fieldlabel].': ';
		$custfld .= ''.$col_fields[$fieldname].' '.$mod_strings[$fieldlabel].': ';
                $custfld .= ''.$col_fields[$fieldname].' ';
        }
	elseif($uitype == 51 || $uitype == 50 || $uitype == 73)
	{
		$account_id = $col_fields[$fieldname];
		if($account_id != '')
		{
			$account_name = getAccountName($account_id);
		}
		//Account Name View	
		$custfld .= ''.$mod_strings[$fieldlabel].': ';
		$custfld .= ''.$account_name.' '.$mod_strings[$fieldlabel].': ';
		$user_id = $col_fields[$fieldname];
		$user_name = getUserName($user_id);
		if(is_admin($current_user))
		{
			$custfld .= ''.$user_name.' '.$user_name.' ';
		}
	}
	elseif($uitype == 53)
	{
		$user_id = $col_fields[$fieldname];
		if($user_id != 0)
		{
			$custfld .= ''.$mod_strings[$fieldlabel].$app_strings['LBL_USER'].' : ';
			$user_name = getUserName($user_id);
			if(is_admin($current_user))
			{
				$custfld .= ''.$user_name.' '.$user_name.' ';
			}
		}
		elseif($user_id == 0)
		{
			$custfld .= ''.$mod_strings[$fieldlabel].$app_strings['LBL_GROUP'].' : ';
			$id = $col_fields["record_id"];	
			$module = $col_fields["record_module"];
			$groupname = getGroupName($id, $module);
			if(is_admin($current_user))
                        {
				$custfld .= ''.$groupname.' '.$groupname.' ';
			}			
		}
		
	}
	elseif($uitype == 55)
        {
                $custfld .= ''.$mod_strings[$fieldlabel].': ';
                $value = $col_fields[$fieldname];
                $sal_value = $col_fields["salutationtype"];
                if($sal_value == '--None--')
                {
                        $sal_value='';
                }
                $custfld .= ''.$sal_value.' '.$value.' ';
        }
	elseif($uitype == 56)
	{
		$custfld .= ''.$mod_strings[$fieldlabel].': ';
		$value = $col_fields[$fieldname];
		if($value == 1)
		{
			$display_val = 'yes';
		}
		else
		{
			$display_val = '';
		}
		$custfld .= ''.$display_val.' ';
	}
	elseif($uitype == 57)
        {
                $custfld .= ''.$mod_strings[$fieldlabel].': ';
                $contact_id = $col_fields[$fieldname];
                if($contact_id != '')
                {
                        $contact_name = getContactName($contact_id);
                }
                $custfld .= ''.$contact_name.' '.$mod_strings[$fieldlabel].': ';
		$custfld .= ''.$product_name.' '.$col_fields[$fieldname].' ';
                $custfld .= ''.$mod_strings[$fieldlabel].': ';
                $custfld .= ''.$custfldval.' ';
        }
	elseif($uitype == 69)
	{
			
                $custfld .= ''.$mod_strings[$fieldlabel].': ';
		if($col_fields[$fieldname] != '')
		{
			$imgpath = "test/product/".$col_fields[$fieldname];
			
                	$custfld .= ''.$app_strings['LBL_LEAD_NAME'].': ';
				$sql = "select * from leaddetails where leadid=".$value;
				$result = $adb->query($sql);
				$first_name = $adb->query_result($result,0,"firstname");
				$last_name = $adb->query_result($result,0,"lastname");
				$custfld .= ''.$first_name.' '.$last_name.' '.$app_strings['LBL_ACCOUNT_NAME'].': ';
				$sql = "select * from  account where accountid=".$value;
				$result = $adb->query($sql);
				$account_name = $adb->query_result($result,0,"accountname");
				$custfld .= ''.$account_name.' '.$app_strings['LBL_POTENTIAL_NAME'].': ';
				$sql = "select * from  potential where potentialid=".$value;
				$result = $adb->query($sql);
				$potentialname = $adb->query_result($result,0,"potentialname");
				$custfld .= ''.$potentialname.' '.$app_strings['LBL_PRODUCT_NAME'].': ';
				$sql = "select * from  products where productid=".$value;
				$result = $adb->query($sql);
				$productname= $adb->query_result($result,0,"productname");
				$custfld .= ''.$productname.' '.$app_strings['LBL_PORDER_NAME'].': ';
				$sql = "select * from  purchaseorder where purchaseorderid=".$value;
				$result = $adb->query($sql);
				$pordername= $adb->query_result($result,0,"subject");
				$custfld .= ''.$pordername.' '.$app_strings['LBL_SORDER_NAME'].': ';
				$sql = "select * from  salesorder where salesorderid=".$value;
				$result = $adb->query($sql);
				$sordername= $adb->query_result($result,0,"subject");
				$custfld .= ''.$sordername.' '.$app_strings['LBL_INVOICE_NAME'].': ';
				$sql = "select * from  invoice where invoiceid=".$value;
				$result = $adb->query($sql);
				$invoicename= $adb->query_result($result,0,"subject");
				$custfld .= ''.$invoicename.' '.$mod_strings[$fieldlabel].': ';
			$custfld .= ''.$value.' ';
		}
	}
	elseif($uitype == 66)
	{
		$value = $col_fields[$fieldname];
		if($value != '')
		{
			$parent_module = getSalesEntityType($value);
			if($parent_module == "Leads")
			{
				$custfld .= ''.$app_strings['LBL_LEAD_NAME'].': ';
				$sql = "select * from leaddetails where leadid=".$value;
				$result = $adb->query($sql);
				$first_name = $adb->query_result($result,0,"firstname");
				$last_name = $adb->query_result($result,0,"lastname");
				$custfld .= ''.$first_name.' '.$last_name.' '.$app_strings['LBL_ACCOUNT_NAME'].': ';
				$sql = "select * from  account where accountid=".$value;
				$result = $adb->query($sql);
				$account_name = $adb->query_result($result,0,"accountname");
				$custfld .= ''.$account_name.' '.$app_strings['LBL_POTENTIAL_NAME'].': ';
				$sql = "select * from  potential where potentialid=".$value;
				$result = $adb->query($sql);
				$potentialname = $adb->query_result($result,0,"potentialname");
				$custfld .= ''.$potentialname.' '.$app_strings['LBL_QUOTE_NAME'].': ';
                                $sql = "select * from  quotes where quoteid=".$value;
                                $result = $adb->query($sql);
                                $quotename = $adb->query_result($result,0,"subject");
                                $custfld .= ''.$quotename.' '.$app_strings['LBL_PORDER_NAME'].': ';
                                $sql = "select * from  purchaseorder where purchaseorderid=".$value;
                                $result = $adb->query($sql);
                                $pordername = $adb->query_result($result,0,"subject");
                                $custfld .= ''.$pordername.' '.$app_strings['LBL_SORDER_NAME'].': ';
                                $sql = "select * from  salesorder where salesorderid=".$value;
                                $result = $adb->query($sql);
                                $sordername = $adb->query_result($result,0,"subject");
                                $custfld .= ''.$sordername.' '.$app_strings['LBL_INVOICE_NAME'].': ';
                                $sql = "select * from  invoice where invoiceid=".$value;
                                $result = $adb->query($sql);
                                $invoicename = $adb->query_result($result,0,"subject");
                                $custfld .= ''.$invoicename.' '.$mod_strings[$fieldlabel].': ';
			$custfld .= ''.$value.' ';
		}
	}
	elseif($uitype == 67)
	{
		$value = $col_fields[$fieldname];
		if($value != '')
		{
			$parent_module = getSalesEntityType($value);
			if($parent_module == "Leads")
			{
				$custfld .= ''.$app_strings['LBL_LEAD_NAME'].': ';
				$sql = "select * from leaddetails where leadid=".$value;
				$result = $adb->query($sql);
				$first_name = $adb->query_result($result,0,"firstname");
				$last_name = $adb->query_result($result,0,"lastname");
				$custfld .= ''.$first_name.' '.$last_name.' '.$app_strings['LBL_CONTACT_NAME'].': ';
				$sql = "select * from  contactdetails where contactid=".$value;
				$result = $adb->query($sql);
				$first_name = $adb->query_result($result,0,"firstname");
                                $last_name = $adb->query_result($result,0,"lastname");
                                $custfld .= ''.$first_name.' '.$last_name.' '.$mod_strings[$fieldlabel].': ';
			$custfld .= ''.$value.' ';
		}
	}
	elseif($uitype == 68)
	{
		$value = $col_fields[$fieldname];
		if($value != '')
		{
			$parent_module = getSalesEntityType($value);
			if($parent_module == "Contacts")
			{
				$custfld .= ''.$app_strings['LBL_CONTACT_NAME'].': ';
				$sql = "select * from  contactdetails where contactid=".$value;
				$result = $adb->query($sql);
				$first_name = $adb->query_result($result,0,"firstname");
                                $last_name = $adb->query_result($result,0,"lastname");
                                $custfld .= ''.$first_name.' '.$last_name.' '.$app_strings['LBL_ACCOUNT_NAME'].': ';
				$sql = "select * from account where accountid=".$value;
				$result = $adb->query($sql);
				$account_name = $adb->query_result($result,0,"accountname");
				$custfld .= ''.$account_name.' '.$mod_strings[$fieldlabel].': ';
			$custfld .= ''.$value.' ';
		}
	}
	elseif($uitype==63)
        {
	   $custfld .= ''.$mod_strings[$fieldlabel].': ';	
           $custfld .= ''.$col_fields[$fieldname].'h  '.$col_fields['duration_minutes'].'m ';
        }
	elseif($uitype == 6)
        {
		$custfld .= ''.$mod_strings[$fieldlabel].': ';
	
          	if($col_fields[$fieldname]=='0')
                $col_fields[$fieldname]='';
		if($col_fields['time_start']!='')
                {
                       $start_time = $col_fields['time_start'];
                }
		if($col_fields[$fieldname] == '0000-00-00')
		{
			$displ_date = '';	
		}
		else
		{
			$displ_date = getDisplayDate($col_fields[$fieldname]);
		}
	
          	$custfld .= ''.$displ_date.' '.$start_time.' ';
	}
	elseif($uitype == 5 || $uitype == 23 || $uitype == 70)
	{
		$custfld .= ''.$mod_strings[$fieldlabel].': ';
		$cur_date_val = $col_fields[$fieldname];
		if($cur_date_val == '0000-00-00')
		{
			$display_val = '';	
		}
		else
		{
			$display_val = getDisplayDate($cur_date_val);
		}
		$custfld .= ''.$display_val.' ';	
	}
	elseif($uitype == 71 || $uitype == 72)
	{
		$custfld .= ''.$mod_strings[$fieldlabel].': ';
		$display_val = '';
		if($col_fields[$fieldname] != '' && $col_fields[$fieldname] != 0)
		{	
			$curr_symbol = getCurrencySymbol();
			$display_val = $curr_symbol.' '.$col_fields[$fieldname];
		}
		$custfld .= ''.$display_val.' ';	
	}
	elseif($uitype == 75 || $uitype == 81)
        {
                $custfld .= ''.$mod_strings[$fieldlabel].': ';
                $vendor_id = $col_fields[$fieldname];
                if($vendor_id != '')
                {
                        $vendor_name = getVendorName($vendor_id);
                }
                $custfld .= ''.$vendor_name.' '.$mod_strings[$fieldlabel].': ';
                $potential_id = $col_fields[$fieldname];
                if($potential_id != '')
                {
                        $potential_name = getPotentialName($potential_id);
                }
                $custfld .= ''.$potential_name.' '.$mod_strings[$fieldlabel].': ';
                $quote_id = $col_fields[$fieldname];
                if($quote_id != '')
                {
                        $quote_name = getQuoteName($quote_id);
                }
                $custfld .= ''.$quote_name.' '.$mod_strings[$fieldlabel].': ';
                $purchaseorder_id = $col_fields[$fieldname];
                if($purchaseorder_id != '')
                {
                        $purchaseorder_name = getPoName($purchaseorder_id);
                }
                $custfld .= ''.$purchaseorder_name.' '.$mod_strings[$fieldlabel].': ';
                $salesorder_id = $col_fields[$fieldname];
                if($salesorder_id != '')
                {
                        $salesorder_name = getSoName($salesorder_id);
                }
                $custfld .= ''.$salesorder_name.' '.$mod_strings[$fieldlabel].': ';
		if($col_fields[$fieldname])
                {
                        $reminder_str= $rem_days.' '.$mod_strings['LBL_DAYS'].' '.$rem_hrs.' '.$mod_strings['LBL_HOURS'].' '.$rem_min.' '.$mod_strings['LBL_MINUTES'].'  '.$mod_strings['LBL_BEFORE_EVENT'];
                }
                $custfld .= ' '.$reminder_str.' ';
	}
	else
	{
	  $custfld .= ''.$mod_strings[$fieldlabel].': ';
	
          if($col_fields[$fieldname]=='0')
                $col_fields[$fieldname]='';
	
          $custfld .= ''.$col_fields[$fieldname].' ';
	}
	return $custfld;	
}
function getSalesEntityType($crmid)
{
global $vtlog;
$vtlog->logthis("in getSalesEntityType ".$crmid,'info');  
	
	global $adb;
	$sql = "select * from crmentity where crmid=".$crmid;
        $result = $adb->query($sql);
	$parent_module = $adb->query_result($result,0,"setype");
	return $parent_module;
}
function getAccountName($account_id)
{
global $vtlog;
$vtlog->logthis("in getAccountName ".$account_id,'info');  
	global $adb;
	if($account_id != '')
	{
		$sql = "select accountname from account where accountid=".$account_id;
        	$result = $adb->query($sql);
		$accountname = $adb->query_result($result,0,"accountname");
	}
	return $accountname;
}
function getProductName($product_id)
{
global $vtlog;
$vtlog->logthis("in getproductname ".$product_id,'info');  
	global $adb;
	$sql = "select productname from products where productid=".$product_id;
        $result = $adb->query($sql);
	$productname = $adb->query_result($result,0,"productname");
	return $productname;
}
function getPotentialName($potential_id)
{
global $vtlog;
$vtlog->logthis("in getPotentialName ".$potential_id,'info');  
	global $adb;
	$sql = "select potentialname from potential where potentialid=".$potential_id;
        $result = $adb->query($sql);
	$potentialname = $adb->query_result($result,0,"potentialname");
	return $potentialname;
}
function getContactName($contact_id)
{
global $vtlog;
$vtlog->logthis("in getContactName ".$contact_id,'info');  
        global $adb;
        $sql = "select * from contactdetails where contactid=".$contact_id;
        $result = $adb->query($sql);
        $firstname = $adb->query_result($result,0,"firstname");
        $lastname = $adb->query_result($result,0,"lastname");
        $contact_name = $firstname.' '.$lastname;
        return $contact_name;
}
function getVendorName($vendor_id)
{
global $vtlog;
$vtlog->logthis("in getVendorName ".$vendor_id,'info');  
        global $adb;
        $sql = "select * from vendor where vendorid=".$vendor_id;
        $result = $adb->query($sql);
        $vendor_name = $adb->query_result($result,0,"vendorname");
        return $vendor_name;
}
function getQuoteName($quote_id)
{
global $vtlog;
$vtlog->logthis("in getQuoteName ".$quote_id,'info');  
        global $adb;
        $sql = "select * from quotes where quoteid=".$quote_id;
        $result = $adb->query($sql);
        $quote_name = $adb->query_result($result,0,"subject");
        return $quote_name;
}
function getPriceBookName($pricebookid)
{
global $vtlog;
$vtlog->logthis("in getPriceBookName ".$pricebookid,'info');  
        global $adb;
        $sql = "select * from pricebook where pricebookid=".$pricebookid;
        $result = $adb->query($sql);
        $pricebook_name = $adb->query_result($result,0,"bookname");
        return $pricebook_name;
}
function getPoName($po_id)
{
global $vtlog;
$vtlog->logthis("in getPoName ".$po_id,'info');  
        global $adb;
        $sql = "select * from purchaseorder where purchaseorderid=".$po_id;
        $result = $adb->query($sql);
        $po_name = $adb->query_result($result,0,"subject");
        return $po_name;
}
function getSoName($so_id)
{
global $vtlog;
$vtlog->logthis("in getSoName ".$so_id,'info');  
        global $adb;
        $sql = "select * from salesorder where salesorderid=".$so_id;
        $result = $adb->query($sql);
        $so_name = $adb->query_result($result,0,"subject");
        return $so_name;
}
function getGroupName($id, $module)
{
global $vtlog;
$vtlog->logthis("in getGroupName ".$id.'  module is    '.$module,'info');  
	global $adb;
	if($module == 'Leads')
	{
		$sql = "select * from leadgrouprelation where leadid=".$id;
	}
        elseif($module == 'HelpDesk')
        {
                $sql = "select * from ticketgrouprelation where ticketid=".$id;
        }
	elseif($module = 'Calls')
	{
		$sql = "select * from activitygrouprelation where activityid=".$id;
	}
	elseif($module = 'Tasks')
	{
		$sql = "select * from taskgrouprelation where taskid=".$id;
	}
	$result = $adb->query($sql);
	$groupname = $adb->query_result($result,0,"groupname");
	return $groupname;
}
function getColumnFields($module)
{
global $vtlog;
$vtlog->logthis("in getColumnFields ".$module,'info');  
	global $adb;
	$column_fld = Array();
        $tabid = getTabid($module);
	$sql = "select * from field where tabid=".$tabid;
        $result = $adb->query($sql);
        $noofrows = $adb->num_rows($result);
	for($i=0; $i<$noofrows; $i++)
	{
		$fieldname = $adb->query_result($result,$i,"fieldname");
		$column_fld[$fieldname] = ''; 
	}
	return $column_fld;	
}
function getUserName($userid)
{
global $vtlog;
$vtlog->logthis("in getUserName ".$userid,'info');  
	global $adb;
	if($userid != '')
	{
		$sql = "select user_name from users where id=".$userid;
		$result = $adb->query($sql);
		$user_name = $adb->query_result($result,0,"user_name");
	}
	return $user_name;	
}
function getUserEmail($userid)
{
global $vtlog;
$vtlog->logthis("in getUserEmail ".$userid,'info');  
        global $adb;
        if($userid != '')
        {
                $sql = "select email1 from users where id=".$userid;
                $result = $adb->query($sql);
                $email = $adb->query_result($result,0,"email1");
        }
        return $email;
}		
//outlook security
function getUserId_Ol($username)
{
global $vtlog;
$vtlog->logthis("in getUserId_Ol ".$username,'info');  
	global $adb;
	$sql = "select id from users where user_name='".$username."'";
	$result = $adb->query($sql);
	$num_rows = $adb->num_rows($result);
	if($num_rows > 0)
	{
		$user_id = $adb->query_result($result,0,"id");
    }
    else
    {
	    $user_id = 0;
    }    	
	return $user_id;
}	
//outlook security
function getNavigationValues($start, $noofrows, $list_max_entries_per_page)
{
	$navigation_array = Array();	
	require_once('config.php');
	//Setting the start to end counter
	$starttoendvaluecounter = $list_max_entries_per_page - 1;
	//Setting the ending value
	if($noofrows > $list_max_entries_per_page)
	{
		$end = $start + $starttoendvaluecounter;
		if($end > $noofrows)
		{
			$end = $noofrows;
		}
		$startvalue = 1;
		$remainder = $noofrows % $list_max_entries_per_page;
		if($remainder > 0)
		{
			$endval = $noofrows - $remainder + 1;
		}
		elseif($remainder == 0)
		{
			$endval = $noofrows - $starttoendvaluecounter;
		}
	}
	else
	{
		$end = $noofrows;
	}
	//Setting the next and previous value
	if(isset($start) && $start != '')
	{
		$tempnextstartvalue = $start + $list_max_entries_per_page;
		if($tempnextstartvalue <= $noofrows)
		{
			$nextstartvalue = $tempnextstartvalue;
		}
		$tempprevvalue = $_REQUEST['start'] - $list_max_entries_per_page;
		if($tempprevvalue  > 0)
		{
			$prevstartvalue = $tempprevvalue;
		}
	}
	else
	{
		if($noofrows > $list_max_entries_per_page)
		{
			$nextstartvalue = $list_max_entries_per_page + 1;
		}
	}
	$navigation_array['start'] = $start;
	$navigation_array['end'] = $endval;
	$navigation_array['prev'] = $prevstartvalue;
	$navigation_array['next'] = $nextstartvalue;
	$navigation_array['end_val'] = $end;
	return $navigation_array;
} 		
function getURLstring($focus)
{
	$qry = "";
	foreach($focus->column_fields as $fldname=>$val)
	{
		if(isset($_REQUEST[$fldname]) && $_REQUEST[$fldname] != '')
		{
			if($qry == '')
			$qry = "&".$fldname."=".$_REQUEST[$fldname];
			else
			$qry .="&".$fldname."=".$_REQUEST[$fldname];
		}
	}
	if(isset($_REQUEST['current_user_only']) && $_REQUEST['current_user_only'] !='')
	{
		$qry .="¤t_user_only=".$_REQUEST['current_user_only'];
	}
	if(isset($_REQUEST['advanced']) && $_REQUEST['advanced'] =='true')
	{
		$qry .="&advanced=true";
	}
	if($qry !='')
	{
		$qry .="&query=true";
	}
	return $qry;
}
function getListViewHeader($focus, $module,$sort_qry='',$sorder='',$order_by='',$relatedlist='',$oCv='')
{
	global $adb;
	global $theme;
	global $app_strings;
	global $mod_strings;
	//Seggregating between module and smodule
        if(isset($_REQUEST['smodule']) && $_REQUEST['smodule'] == 'VENDOR')
        {
                $smodule = 'Vendor';
        }
        elseif(isset($_REQUEST['smodule']) && $_REQUEST['smodule'] == 'PRICEBOOK')
        {
                $smodule = 'PriceBook';
        }
        else
        {
                $smodule = $module;
        }
	$arrow='';
	$qry = getURLstring($focus);
	$theme_path="themes/".$theme."/";
	$image_path=$theme_path."images/";
	$list_header = '';
	$list_header .= ''.$name.' ';
				$list_header .=''.$app_strings['LBL_EDIT'].' | '.$app_strings['LBL_DELETE'].' ';
	$list_header .= ' ';
	return $list_header;
}
function getSearchListViewHeader($focus, $module,$sort_qry='',$sorder='',$order_by='')
{
	global $adb;
	global $theme;
	global $app_strings;
        global $mod_strings;
        $arrow='';
	//$theme = $focus->current_theme;
	$theme_path="themes/".$theme."/";
	$image_path=$theme_path."images/";		
	$list_header = '';
	$list_header .= ''.$name.' ';
			$list_header .=' ';
	return $list_header;
}
function getRelatedToEntity($module,$list_result,$rset)
{
	global $adb;
	$seid = $adb->query_result($list_result,$rset,"relatedto");
	if(isset($seid) && $seid != '')
	{
		$parent_module = $parent_module = getSalesEntityType($seid);
		if($parent_module == 'Accounts')
		{
			$parent_query = "SELECT accountname FROM account WHERE accountid=".$seid;
			$parent_result = $adb->query($parent_query);
			$parent_name = $adb->query_result($parent_result,0,"accountname");
		}
		if($parent_module == 'Leads')
		{
			$parent_query = "SELECT firstname,lastname FROM leaddetails WHERE leadid=".$seid;
			$parent_result = $adb->query($parent_query);
			$parent_name = $adb->query_result($parent_result,0,"firstname") ." " .$adb->query_result($parent_result,0,"lastname");
		}
		if($parent_module == 'Potentials')
		{
			$parent_query = "SELECT potentialname FROM potential WHERE potentialid=".$seid;
			$parent_result = $adb->query($parent_query);
			$parent_name = $adb->query_result($parent_result,0,"potentialname");
		}
		if($parent_module == 'Products')
		{
			$parent_query = "SELECT productname FROM products WHERE productid=".$seid;
			$parent_result = $adb->query($parent_query);
			$parent_name = $adb->query_result($parent_result,0,"productname");
		}
		if($parent_module == 'Orders')
		{
			$parent_query = "SELECT subject FROM purchaseorder WHERE purchaseorderid=".$seid;
			$parent_result = $adb->query($parent_query);
			$parent_name = $adb->query_result($parent_result,0,"subject");
		}
		if($parent_module == 'SalesOrder')
		{
			$parent_query = "SELECT subject FROM salesorder WHERE salesorderid=".$seid;
			$parent_result = $adb->query($parent_query);
			$parent_name = $adb->query_result($parent_result,0,"subject");
		}
		if($parent_module == 'Invoice')
		{
			$parent_query = "SELECT subject FROM invoice WHERE invoiceid=".$seid;
			$parent_result = $adb->query($parent_query);
			$parent_name = $adb->query_result($parent_result,0,"subject");
		}
		$parent_value = "".$parent_name." "; 
	}
	else
	{
		$parent_value = '';
	}
	return $parent_value;
}
function getRelatedTo($module,$list_result,$rset)
{
        global $adb;
	if($module == "Notes")
        {
                $notesid = $adb->query_result($list_result,$rset,"notesid");
                $action = "DetailView";
                $evt_query="select senotesrel.crmid,crmentity.setype from senotesrel, crmentity where senotesrel.notesid ='".$notesid."' and senotesrel.crmid = crmentity.crmid";
	}else if($module == "Products")
	{
		$productid = $adb->query_result($list_result,$rset,"productid");
                $action = "DetailView";
                $evt_query="select seproductsrel.crmid,crmentity.setype from seproductsrel, crmentity where seproductsrel.productid ='".$productid."' and seproductsrel.crmid = crmentity.crmid";
	}else
	{
		$activity_id = $adb->query_result($list_result,$rset,"activityid");
		$action = "DetailView";
		$evt_query="select seactivityrel.crmid,crmentity.setype from seactivityrel, crmentity where seactivityrel.activityid='".$activity_id."' and seactivityrel.crmid = crmentity.crmid";
		if($module == 'HelpDesk')
		{
			$activity_id = $adb->query_result($list_result,$rset,"parent_id");
			if($activity_id != '')
				$evt_query = "select * from crmentity where crmid=".$activity_id;
		}
	}
        $evt_result = $adb->query($evt_query);
        $parent_module = $adb->query_result($evt_result,0,'setype');
        $parent_id = $adb->query_result($evt_result,0,'crmid');
	if($module == 'HelpDesk' && ($parent_module == 'Accounts' || $parent_module == 'Contacts'))
        {
                global $theme;
                $module_icon = '".$parent_name." ";
        return $parent_value;
}
//parameter added for customview $oCv 27/5
function getListViewEntries($focus, $module,$list_result,$navigation_array,$relatedlist='',$returnset='',$edit_action='EditView',$del_action='Delete',$oCv='')
{
	global $adb;
	global $app_strings;
	$noofrows = $adb->num_rows($list_result);
	$list_header = '';
	global $theme;
	$evt_status;
	$theme_path="themes/".$theme."/";
	$image_path=$theme_path."images/";
	//getting the fieldtable entries from database
	$tabid = getTabid($module);
	
	//added for customview 27/5
	if($oCv)
        {
                if(isset($oCv->list_fields))
                {
                        $focus->list_fields = $oCv->list_fields;
                }
        }
	for ($i=$navigation_array['start']; $i<=$navigation_array['end_val']; $i++)
	{
		if (($i%2)==0)
			$list_header .= '';
		else
			$list_header .= ' ';
		//Getting the entityid
		$entity_id = $adb->query_result($list_result,$i-1,"crmid");
		$owner_id = $adb->query_result($list_result,$i-1,"smownerid");
		if($relatedlist == '')
		{
			$list_header .= '".$contact_name." ";
						}
						if ($name == 'Close')
						{
							if($status =='Deferred' || $status == 'Completed' || $status == 'Held' || $status == '')
							{
								$value="";
							}
							else
							{
								$activityid = $adb->query_result($list_result,$i-1,"activityid");
								$activitytype = $adb->query_result($list_result,$i-1,"activitytype");
                                                                if($activitytype=='Task')
                                                                $evt_status='&status=Completed';
                                                                else
                                                                $evt_status='&eventstatus=Held';
								if(isPermitted("Activities",1,$activityid) == 'yes')
                        					{
                                                                	$value = "X ";
								}
								else
								{
									$value = "";
								}
								
							}
						}
					}
					elseif($module == "Products" && $name == "Related to")
                                        {
                                                $value=getRelatedTo($module,$list_result,$i-1);
                                        }
					elseif($module == 'Notes' && $name=='Related to')
					{
						$value=getRelatedTo($module,$list_result,$i-1);
					}
					elseif($name=='Account Name')
					{
						//modified for customview 27/5
						if($module == 'Accounts')
                                                {
                                                	$account_id = $adb->query_result($list_result,$i-1,"crmid");
                                                	$account_name = getAccountName($account_id);
                                                	$value = ''.$account_name.' ';
                                                }else
                                                {
                                                	$account_id = $adb->query_result($list_result,$i-1,"accountid");
                                                	$account_name = getAccountName($account_id);
                                                	$value = ''.$account_name.' ';
                                                }
					}
					elseif(($module == 'PriceBook' || $module == 'Quotes' || $module == 'Orders' || $module == 'Faq') && $name == 'Product Name')
					{
						if($module == 'Faq')
							$product_id = $adb->query_result($list_result,$i-1,"product_id");
						else
							$product_id = $adb->query_result($list_result,$i-1,"productid");
						if($product_id != '')
							$product_name = getProductName($product_id);
						else
                                                        $product_name = '';
						$value = ''.$product_name.' ';
					}
					elseif($module == 'Quotes' && $name == 'Potential Name')
					{
						$potential_id = $adb->query_result($list_result,$i-1,"potentialid");
						$potential_name = getPotentialName($potential_id);
						$value = ''.$potential_name.' ';
					}
					elseif($owner_id == 0 && $name == 'Assigned To')
                                        {
                                               $value = getGroupName($entity_id, $module);
                                       }
					else
					{
						$query = "select * from field where tabid=".$tabid." and fieldname='".$fieldname."'";
						$field_result = $adb->query($query);
						$list_result_count = $i-1;
						$value = getValue($field_result,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"list","",$returnset);
					}
				}
				//Added condition to hide the close symbol in Related Lists
//				if($relatedlist != '' && $value == "X ")
				if($name == 'Close' && $relatedlist != '')
				{
					$list_header .= '';
				}
				else
				{
					$list_header .= ''.$value.' ';
					$list_header .='';
		$mod_dir=getModuleDirName($module);
		if(isPermitted($module,1,$entity_id) == 'yes')
		{
			
			
			$list_header .=''.$app_strings['LNK_EDIT'].'  | ';
		}
		if(isPermitted($module,2,$entity_id) == 'yes')
		{
			$del_param = 'index.php?action='.$del_action.'&module='.$mod_dir.'&record='.$entity_id.$returnset;
			$list_header .= ''.$app_strings['LNK_DELETE'].' ';
		}
		$list_header .= ' ';
		$list_header .= '  ';
	}
	$list_header .= '';
		else
			$list_header .= ' ';
		//Getting the entityid
		$entity_id = $adb->query_result($list_result,$i-1,"crmid");
		$list_header .= '".$contact_name." ";
						}
					}
					elseif(($module == 'Faq' || $module == 'Notes') && $name=='Related to')
					{
						$value=getRelatedToEntity($module,$list_result,$i-1);
					}
					elseif($name=='Account Name' && ($module == 'Potentials' || $module == 'SalesOrder' || $module == 'Quotes'))
                                        {
                                                $account_id = $adb->query_result($list_result,$i-1,"accountid");
                                                $account_name = getAccountName($account_id);
                                                $value = $account_name;
                                        }
					elseif($name=='Quote Name' && $module == 'SalesOrder')
                                        {
                                                $quote_id = $adb->query_result($list_result,$i-1,"quoteid");
                                                $quotename = getQuoteName($quote_id);
                                                $value = $quotename;
                                        }
					else
					{
						$query = "select * from field where tabid=".$tabid." and fieldname='".$fieldname."'";
						$field_result = $adb->query($query);
						$list_result_count = $i-1;
						$value = getValue($field_result,$list_result,$fieldname,$focus,$module,$entity_id,$list_result_count,"search",$focus->popup_type);
					}
				}
			$list_header .= ''.$value.' ';
			$list_header .=' ';
	}
	$list_header .= ''.$temp_val.' ';
	}
	elseif($uitype == 13)
        {
                $value = ''.$temp_val.' ';
        }
	elseif($uitype == 56)
	{
		if($temp_val == 1)
		{
			$value = 'yes';
		}
		else
		{
			$value = '';
		}
	}	
	elseif($uitype == 57)
	{
		global $adb;
		if($temp_val != '')
                {
			$sql="select * from contactdetails where contactid=".$temp_val;		
			$result=$adb->query($sql);
			$firstname=$adb->query_result($result,0,"firstname");
			$lastname=$adb->query_result($result,0,"lastname");
			$name=$lastname.' '.$firstname;
			$value= ''.$name.' ';
		}
		else
			$value='';
	}
        elseif($uitype == 61)
        {
                global $adb;
		$attachmentid=$adb->query_result($adb->query("select * from seattachmentsrel where crmid = ".$entity_id),0,'attachmentsid');
		$value = ''.$temp_val.' ';
        }
	elseif($uitype == 62)
	{
		global $adb;
		$parentid = $adb->query_result($list_result,$list_result_count,"parent_id");
		$parenttype = $adb->query_result($list_result,$list_result_count,"parent_type");
		if($parenttype == "Leads")	
		{
			$tablename = "leaddetails";	$fieldname = "lastname";	$idname="leadid";	
		}
		if($parenttype == "Accounts")	
		{
			$tablename = "account";		$fieldname = "accountname";     $idname="accountid";
		}
		if($parenttype == "Products")	
		{
			$tablename = "products";	$fieldname = "productname";     $idname="productid";
		}
		if($parenttype == "HelpDesk")	
		{
			$tablename = "troubletickets";	$fieldname = "title";        	$idname="crmid";
		}
		if($parenttype == "Products")	
		{
			$tablename = "products";	$fieldname = "productname";     $idname="productid";
		}
		if($parenttype == "Invoice")	
		{
			$tablename = "invoice";	$fieldname = "subject";     $idname="invoiceid";
		}
		if($parentid != '')
                {
			$sql="select * from ".$tablename." where ".$idname." = ".$parentid;
			//echo ''.$fieldvalue.' ';
		}
		else
			$value='';
	}
	elseif($uitype == 66)
	{
		global $adb;
		$parentid = $adb->query_result($list_result,$list_result_count,"parent_id");
		$parenttype = $adb->query_result($list_result,$list_result_count,"parent_type");
		if($parenttype == "Leads")	
		{
			$tablename = "leaddetails";	$fieldname = "lastname";	$idname="leadid";	
		}
		if($parenttype == "Accounts")	
		{
			$tablename = "account";		$fieldname = "accountname";     $idname="accountid";
		}
		if($parenttype == "HelpDesk")	
		{
			$tablename = "troubletickets";	$fieldname = "title";        	$idname="crmid";
		}
		if($parentid != '')
                {
			$sql="select * from ".$tablename." where ".$idname." = ".$parentid;
			//echo ''.$fieldvalue.' ';
		}
		else
			$value='';
	}
	elseif($uitype == 67)
	{
		global $adb;
		$parentid = $adb->query_result($list_result,$list_result_count,"parent_id");
		$parenttype = $adb->query_result($list_result,$list_result_count,"parent_type");
		if($parenttype == "Leads")	
		{
			$tablename = "leaddetails";	$fieldname = "lastname";	$idname="leadid";	
		}
		if($parenttype == "Contacts")	
		{
			$tablename = "contactdetails";		$fieldname = "contactname";     $idname="contactid";
		}
		if($parentid != '')
                {
			$sql="select * from ".$tablename." where ".$idname." = ".$parentid;
			//echo ''.$fieldvalue.' ';
		}
		else
			$value='';
	}
	elseif($uitype == 68)
	{
		global $adb;
		$parentid = $adb->query_result($list_result,$list_result_count,"parent_id");
		$parenttype = $adb->query_result($list_result,$list_result_count,"parent_type");
		if($parenttype == '' && $parentid != '')
                        $parenttype = getSalesEntityType($parentid);
		if($parenttype == "Contacts")	
		{
			$tablename = "contactdetails";		$fieldname = "contactname";     $idname="contactid";
		}
		if($parenttype == "Accounts")	
		{
			$tablename = "account";	$fieldname = "accountname";	$idname="accountid";	
		}
		if($parentid != '')
                {
			$sql="select * from ".$tablename." where ".$idname." = ".$parentid;
			//echo ''.$fieldvalue.' ';
		}
		else
			$value='';
	}
	elseif($uitype == 78)
        {
		global $adb;
		if($temp_val != '')
                {
			
                        $quote_name = getQuoteName($temp_val);
			$value= ''.$quote_name.' ';
		}
		else
			$value='';
        }
	elseif($uitype == 79)
        {
		global $adb;
		if($temp_val != '')
                {
			
                        $purchaseorder_name = getPoName($temp_val);
			$value= ''.$purchaseorder_name.' ';
		}
		else
			$value='';
        }
	elseif($uitype == 80)
        {
		global $adb;
		if($temp_val != '')
                {
			
                        $salesorder_name = getSoName($temp_val);
			$value= ''.$salesorder_name.' ';
		}
		else
			$value='';
        }
	elseif($uitype == 75 || $uitype == 81)
        {
		global $adb;
		if($temp_val != '')
                {
			
                        $vendor_name = getVendorName($temp_val);
			$value= ''.$vendor_name.' ';
		}
		else
			$value='';
        }
	else
	{
	
		if($fieldname == $focus->list_link_field)
		{
			if($mode == "search")
			{
				if($popuptype == "specific")
				{
					// Added for get the first name of contact in Popup window
                                        if($colname == "lastname" && $module == 'Contacts')
					{
                                               $firstname=$adb->query_result($list_result,$list_result_count,'firstname');
                                        	$temp_val =$firstname.' '.$temp_val;
					}
					$temp_val = str_replace("'",'\"',$temp_val);
			
					$value = ''.$temp_val.' ';
				}
				elseif($popuptype == "detailview")
                                {
                                        if($colname == "lastname" && $module == 'Contacts')
                                               $firstname=$adb->query_result($list_result,$list_result_count,'firstname');
                                        $temp_val =$firstname.' '.$temp_val;
					$focus->record_id = $_REQUEST['recordid'];
                                        $value = 'record_id.'"); window.close()\'>'.$temp_val.' ';
                                }
				elseif($popuptype == "formname_specific")
				{
					$value = ''.$temp_val.' ';
				}
				elseif($popuptype == "inventory_prod")
				{
					$row_id = $_REQUEST['curr_row'];
					
					$unitprice=$adb->query_result($list_result,$list_result_count,'unit_price');
					$qty_stock=$adb->query_result($list_result,$list_result_count,'qtyinstock');
					$value = ''.$temp_val.' ';
				}
				elseif($popuptype == "inventory_prod_po")
				{
					$row_id = $_REQUEST['curr_row'];
					$unitprice=$adb->query_result($list_result,$list_result_count,'unit_price');
					//$qty_stock=$adb->query_result($list_result,$list_result_count,'qtyinstock');
					$value = ''.$temp_val.' ';
				}
				elseif($popuptype == "inventory_pb")
				{
					$prod_id = $_REQUEST['productid'];
					$flname =  $_REQUEST['fldname'];
					$listprice=getListPrice($prod_id,$entity_id);	
					
					$value = ''.$temp_val.' ';
				}
				elseif($popuptype == "specific_account_address")
				{
					require_once('modules/Accounts/Account.php');
					$acct_focus = new Account();
					$acct_focus->retrieve_entity_info($entity_id,"Accounts");
					$value = 'column_fields['bill_street'].'", "'.$acct_focus->column_fields['ship_street'].'", "'.$acct_focus->column_fields['bill_city'].'", "'.$acct_focus->column_fields['ship_city'].'", "'.$acct_focus->column_fields['bill_state'].'", "'.$acct_focus->column_fields['ship_state'].'", "'.$acct_focus->column_fields['bill_code'].'", "'.$acct_focus->column_fields['ship_code'].'", "'.$acct_focus->column_fields['bill_country'].'", "'.$acct_focus->column_fields['ship_country'].'"); window.close()\'>'.$temp_val.' ';
				}
				elseif($popuptype == "specific_vendor_address")
				{
					require_once('modules/Products/Vendor.php');
					$acct_focus = new Vendor();
					$acct_focus->retrieve_entity_info($entity_id,"Vendor");
					$value = 'column_fields['treet'].'", "'.$acct_focus->column_fields['city'].'", "'.$acct_focus->column_fields['state'].'", "'.$acct_focus->column_fields['postalcode'].'", "'.$acct_focus->column_fields['country'].'"); window.close()\'>'.$temp_val.' ';
				}
				else
				{
					if($colname == "lastname")
                                                $firstname=$adb->query_result($list_result,$list_result_count,'firstname');
                                        $temp_val =$firstname.' '.$temp_val;
					$temp_val = str_replace("'",'\"',$temp_val);
	
					$value = ''.$temp_val.' ';
				}
			}
			else
			{
				if(($module == "Leads" && $colname == "lastname") || ($module == "Contacts" && $colname == "lastname"))
				{
			                if($colname == "lastname")
			                        $firstname=$adb->query_result($list_result,$list_result_count,'firstname');
			                $temp_val =$firstname.' '.$temp_val;
					$value = ''.$temp_val.' ';
				}
				elseif($module == "Activities")
                                {
                                        $actvity_type = $adb->query_result($list_result,$list_result_count,'activitytype');
                                        if($actvity_type == "Task")
                                        {
                                               $value = ''.$temp_val.' ';
                                        }
                                        else
                                        {
                                                $value = ''.$temp_val.' ';
                                        }
                                }
				elseif($module == "Vendor")
				{
						
                                        $value = ''.$temp_val.' ';
				}
				elseif($module == "PriceBook")
				{
						
                                        $value = ''.$temp_val.' ';
				}
				elseif($module == "SalesOrder")
				{
						
                                        $value = ''.$temp_val.' ';
				}
                                else
                                {
                                        $value = ''.$temp_val.' ';
                                }
			}
		}
		else
		{
			$value = $temp_val;
		}
	}
//	$value .= $returnset;
	return $value; 
}
function getListQuery($module,$where='')
{
	if($module == "HelpDesk")
	{
		$query = "select crmentity.crmid,troubletickets.title,troubletickets.status,troubletickets.priority,crmentity.smownerid, contactdetails.contactid, troubletickets.parent_id, contactdetails.firstname, contactdetails.lastname, account.accountid, account.accountname, ticketcf.* from troubletickets inner join ticketcf on ticketcf.ticketid = troubletickets.ticketid inner join crmentity on crmentity.crmid=troubletickets.ticketid left join contactdetails on troubletickets.parent_id=contactdetails.contactid left join account on account.accountid=troubletickets.parent_id left join users on crmentity.smownerid=users.id and troubletickets.ticketid = ticketcf.ticketid where crmentity.deleted=0";
		//$query = "select crmentity.crmid,troubletickets.title,troubletickets.status,troubletickets.priority,crmentity.smownerid, contactdetails.firstname, contactdetails.lastname, ticketcf.* from troubletickets inner join crmentity on crmentity.crmid=troubletickets.ticketid inner join ticketcf on ticketcf.ticketid = troubletickets.ticketid  left join contactdetails on troubletickets.contact_id=contactdetails.contactid left join users on crmentity.smownerid=users.id where crmentity.deleted=0";
	}
	if($module == "Accounts")
	{
		//$query = "select crmentity.crmid, account.accountname,accountbillads.city,account.website,account.phone,crmentity.smownerid, accountscf.*  from account, accountbillads, accountshipads, accountscf  inner join crmentity on crmentity.crmid=account.accountid and account.accountid=accountbillads.accountaddressid and account.accountid = accountscf.accountid and account.accountid=accountshipads.accountaddressid where crmentity.deleted=0";
		$query = "select crmentity.crmid, account.accountname,accountbillads.city,account.website,account.phone,crmentity.smownerid, accountscf.*  from account inner join crmentity on crmentity.crmid=account.accountid inner join accountbillads on account.accountid=accountbillads.accountaddressid inner join accountshipads on account.accountid=accountshipads.accountaddressid inner join accountscf on account.accountid = accountscf.accountid where crmentity.deleted=0";
	}
	if ($module == "Potentials")
	{
		 //$query = "select crmentity.crmid, crmentity.smownerid,account.accountname, potential.*, potentialscf.* from potential , account, potentialscf inner join crmentity on crmentity.crmid=potential.potentialid and potential.accountid = account.accountid and potentialscf.potentialid = potential.potentialid where crmentity.deleted=0 ".$where;
		 $query = "select crmentity.crmid, crmentity.smownerid,account.accountname, potential.accountid,potential.potentialname,potential.sales_stage,potential.amount,potential.currency,potential.closingdate,potential.typeofrevenue, potentialscf.* from potential inner join crmentity on crmentity.crmid=potential.potentialid inner join account on potential.accountid = account.accountid inner join potentialscf on potentialscf.potentialid = potential.potentialid where crmentity.deleted=0 ".$where;
	}
	if($module == "Leads")
	{
		//$query = "select crmentity.crmid, leaddetails.firstname, leaddetails.lastname, leaddetails.company, leadaddress.phone, leadsubdetails.website, leaddetails.email, crmentity.smownerid, leadscf.* from leaddetails, leadaddress, leadsubdetails, leadscf  inner join crmentity on crmentity.crmid=leaddetails.leadid and leaddetails.leadid=leadaddressid and leaddetails.leadid = leadscf.leadid and leadaddress.leadaddressid=leadsubdetails.leadsubscriptionid where crmentity.deleted=0 and leaddetails.converted=0";
		$query = "select crmentity.crmid, leaddetails.firstname, leaddetails.lastname, leaddetails.company, leadaddress.phone, leadsubdetails.website, leaddetails.email, crmentity.smownerid, leadscf.* from leaddetails inner join crmentity on crmentity.crmid=leaddetails.leadid inner join leadsubdetails on leadsubdetails.leadsubscriptionid=leaddetails.leadid inner join leadaddress on leadaddress.leadaddressid=leadsubdetails.leadsubscriptionid inner join leadscf on leaddetails.leadid = leadscf.leadid where crmentity.deleted=0 and leaddetails.converted=0";
	}
	if($module == "Products")
	{
		$query = "select crmentity.crmid, products.*, productcf.* from products inner join crmentity on crmentity.crmid=products.productid left join productcf on products.productid = productcf.productid left join seproductsrel on seproductsrel.productid = products.productid where crmentity.deleted=0";
	}
        if($module == "Notes")
        {
		$query="select crmentity.crmid, notes.title, notes.contact_id, notes.filename, crmentity.modifiedtime,senotesrel.crmid as relatedto, contactdetails.firstname, contactdetails.lastname, notes.* from notes inner join crmentity on crmentity.crmid=notes.notesid left join senotesrel on senotesrel.notesid=notes.notesid left join contactdetails on contactdetails.contactid = notes.contact_id where crmentity.deleted=0";
        }
        if($module == "Calls")
        {
		$query = "select crmentity.crmid, crmentity.smownerid, seactivityrel.activityid, calls.* from calls inner join crmentity on crmentity.crmid = calls.callid left join seactivityrel on seactivityrel.activityid = calls.callid where crmentity.deleted=0";
        }
	if($module == "Contacts")
        {
                $query = "select crmentity.crmid, crmentity.smownerid, contactdetails.*, contactaddress.*, contactsubdetails.*, contactscf.*, account.accountname from contactdetails, contactaddress, contactsubdetails, contactscf inner join crmentity on crmentity.crmid=contactdetails.contactid and contactdetails.contactid=contactaddress.contactaddressid and contactdetails.contactid = contactscf.contactid and contactaddress.contactaddressid=contactsubdetails.contactsubscriptionid left join account on account.accountid = contactdetails.accountid where crmentity.deleted=0";
		//$query = "select crmentity.crmid, crmentity.smownerid, contactdetails.*, contactaddress.*, contactsubdetails.*, contactscf.*, account.accountname from contactdetails, contactaddress, contactsubdetails, contactscf,crmentity,account where crmentity.crmid=contactdetails.contactid and contactdetails.contactid=contactaddress.contactaddressid and contactdetails.contactid = contactscf.contactid and contactaddress.contactaddressid=contactsubdetails.contactsubscriptionid and account.accountid = contactdetails.accountid and crmentity.deleted=0";
        }
	if($module == "Meetings")
        {
		$query = "select crmentity.crmid,crmentity.smownerid, meetings.*, activity.subject, activity.activityid, contactdetails.lastname, contactdetails.firstname, contactdetails.contactid from meetings inner join crmentity on crmentity.crmid=meetings.meetingid inner join activity on activity.activityid= crmentity.crmid left join cntactivityrel on cntactivityrel.activityid= activity.activityid left join contactdetails on contactdetails.contactid= cntactivityrel.contactid WHERE crmentity.deleted=0";
        }
	if($module == "Activities")
        {
		$query = " select crmentity.crmid,crmentity.smownerid,crmentity.setype, activity.*, contactdetails.lastname, contactdetails.firstname, contactdetails.contactid, account.accountid, account.accountname, recurringevents.recurringtype from activity inner join crmentity on crmentity.crmid=activity.activityid left join cntactivityrel on cntactivityrel.activityid= activity.activityid left join contactdetails on contactdetails.contactid= cntactivityrel.contactid left join seactivityrel on seactivityrel.activityid = activity.activityid left outer join account on account.accountid = contactdetails.accountid left outer join recurringevents on recurringevents.activityid=activity.activityid WHERE crmentity.deleted=0 and (activity.activitytype = 'Meeting' or activity.activitytype='Call' or activity.activitytype='Task') ".$where  ;
		//included by Jaguar
        }
	if($module == "Emails")
        {
                //$query = "select crmentity.crmid,crmentity.smownerid, emails.emailid, emails.filename, activity.subject, activity.activityid, contactdetails.lastname, contactdetails.firstname, contactdetails.contactid , activity.date_start from emails inner join crmentity on crmentity.crmid=emails.emailid inner join activity on activity.activityid = crmentity.crmid left join cntactivityrel on cntactivityrel.activityid= activity.activityid left join contactdetails on contactdetails.contactid= cntactivityrel.contactid WHERE crmentity.deleted=0";
		$query = "select crmentity.crmid,crmentity.smownerid, emails.emailid, emails.filename, activity.subject, activity.activityid, contactdetails.lastname, contactdetails.firstname, contactdetails.contactid , activity.date_start from emails inner join crmentity on crmentity.crmid=emails.emailid inner join activity on activity.activityid = crmentity.crmid left join seactivityrel on seactivityrel.activityid = activity.activityid left join contactdetails on contactdetails.contactid=seactivityrel.crmid left join cntactivityrel on cntactivityrel.activityid= activity.activityid and cntactivityrel.contactid=cntactivityrel.contactid WHERE crmentity.deleted=0";
        }
	if($module == "Faq")
	{
		$query = "select crmentity.crmid, faq.*, crmentity.createdtime, crmentity.modifiedtime from faq inner join crmentity on crmentity.crmid=faq.id left join products on faq.product_id=products.productid where crmentity.deleted=0";
	}
	if($module == "Vendor")
	{
		$query = "select crmentity.crmid, vendor.* from vendor inner join crmentity on crmentity.crmid=vendor.vendorid where crmentity.deleted=0";
	}
	if($module == "PriceBook")
	{
		$query = "select crmentity.crmid, pricebook.* from pricebook inner join crmentity on crmentity.crmid=pricebook.pricebookid where crmentity.deleted=0";
	}
	if($module == "Quotes")
	{
		$query = "select crmentity.*, quotes.*, quotesbillads.*, quotesshipads.*,potential.potentialname,account.accountname from quotes inner join crmentity on crmentity.crmid=quotes.quoteid inner join quotesbillads on quotes.quoteid=quotesbillads.quotebilladdressid inner join quotesshipads on quotes.quoteid=quotesshipads.quoteshipaddressid left outer join account on account.accountid=quotes.accountid left outer join potential on potential.potentialid=quotes.potentialid where crmentity.deleted=0".$where;
	}
	if($module == "Orders")
	{
		$query = "select crmentity.*, purchaseorder.*, pobillads.*, poshipads.*,vendor.vendorname from purchaseorder inner join crmentity on crmentity.crmid=purchaseorder.purchaseorderid left outer join vendor on purchaseorder.vendorid=vendor.vendorid inner join pobillads on purchaseorder.purchaseorderid=pobillads.pobilladdressid inner join poshipads on purchaseorder.purchaseorderid=poshipads.poshipaddressid where crmentity.deleted=0";
	}
	if($module == "SalesOrder")
	{
		$query = "select crmentity.*, salesorder.*, sobillads.*, soshipads.*,quotes.subject as quotename, account.accountname from salesorder inner join crmentity on crmentity.crmid=salesorder.salesorderid inner join sobillads on salesorder.salesorderid=sobillads.sobilladdressid inner join soshipads on salesorder.salesorderid=soshipads.soshipaddressid left outer join quotes on quotes.quoteid=salesorder.quoteid left outer join account on account.accountid=salesorder.accountid where crmentity.deleted=0".$where;
	}
	if($module == "Invoice")
	{
		$query = "select crmentity.*, invoice.*, invoicebillads.*, invoiceshipads.*,salesorder.subject as salessubject from invoice inner join crmentity on crmentity.crmid=invoice.invoiceid inner join invoicebillads on invoice.invoiceid=invoicebillads.invoicebilladdressid inner join invoiceshipads on invoice.invoiceid=invoiceshipads.invoiceshipaddressid left outer join salesorder on salesorder.salesorderid=invoice.salesorderid where crmentity.deleted=0".$where;
	}
	//Appending the Security parameters by DON
	global $others_permission_id;
	global $current_user;	
	if($others_permission_id == 3 && $module != 'Notes' && $module != 'Products' && $module != 'Faq' && $module!= 'Vendor' && $module != 'PriceBook')
	{
		$query .= " and crmentity.smownerid in(".$current_user->id .",0)";
	}
	return $query;
}
function getActionid($action)
{
global $vtlog;
$vtlog->logthis("get Actionid ".$action,'info');  
	$actionid = '';
	if($action == 'Save')
	{
		$actionid= 0;
	}
	else if($action == 'EditView')
	{
		$actionid= 1;
	}
	else if($action == 'Delete')
	{
		$actionid= 2;
	}
	else if($action == 'index')
	{
		$actionid= 3;
	}
	else if($action == 'DetailView')
	{
		$actionid= 4;
	}		
	else if($action == 'Import')
	{
		$actionid= 5;
	}
	else if($action == 'Export')
	{
		$actionid= 6;
	}
	else if($action == 'BusinessCard')
	{
		$actionid= 7;
	}
	else if($action == 'Merge')
	{
		$actionid= 8;
	}
	else if($action == 'VendorEditView')
        {
                $actionid= 1;
        }
        else if($action == 'VendorDetailView')
        {
                $actionid= 4;
        }
        else if($action == 'SaveVendor')
        {
                $actionid= 0;
        }
        else if($action == 'DeleteVendor')
        {
                $actionid= 1;
        }
	else if($action == 'PriceBookEditView')
        {
                $actionid= 1;
        }
        else if($action == 'PriceBookDetailView')
        {
                $actionid= 4;
        }
        else if($action == 'SavePriceBook')
        {
                $actionid= 0;
        }
        else if($action == 'DeletePriceBook')
        {
                $actionid= 1;
        }
	else if($action == 'SalesOrderEditView')
        {
                $actionid= 1;
        }
        else if($action == 'SalesOrderDetailView')
        {
                $actionid= 4;
        }
        else if($action == 'SaveSalesOrder')
        {
                $actionid= 0;
        }
        else if($action == 'DeleteSalesOrder')
        {
                $actionid= 1;
        }
	$vtlog->logthis("action id selected is ".$actionid ,'info');  
	return $actionid;
}
function getActionname($actionid)
{
	global $vtlog;
	$vtlog->logthis("getActionName   ".$actionid ,'info');  
	$actionname = '';
	if($actionid == 0)
	{
		$actionname= 'Save';
	}
	else if($actionid == 1)
	{
		$actionname= 'EditView';
	}
	else if($actionid == 2)
	{
		$actionname= 'Delete';
	}
	else if($actionid == 3)
	{
		$actionname= 'index';
	}
	else if($actionid == 4)
	{
		$actionname= 'DetailView';
	}		
	else if($actionid == 5)
	{
		$actionname= 'Import';
	}
	else if($actionid == 6)
	{
		$actionname= 'Export';
	}
	else if($actionid == 7)
	{
		$actionname= 'BusinessCard';
	}
	else if($actionid == 8)
	{
		$actionname= 'Merge';
	}
	return $actionname;
}
function getUserId($record)
{
	global $vtlog;
	$vtlog->logthis("in getUserId ".$record,'info');  
	global $adb;
        $user_id=$adb->query_result($adb->query("select * from crmentity where crmid = ".$record),0,'smownerid');
	return $user_id;	
}
function insertProfile2field($profileid)
{
	global $vtlog;
	$vtlog->logthis("in insertProfile2field ".$profileid,'info');  
	
	global $adb;
	$adb->database->SetFetchMode(ADODB_FETCH_ASSOC); 
	$fld_result = $adb->query("select * from field where generatedtype=1 and displaytype in (1,2)");
        $num_rows = $adb->num_rows($fld_result);
        for($i=0; $i<$num_rows; $i++)
        {
                 $tab_id = $adb->query_result($fld_result,$i,'tabid');
                 $field_id = $adb->query_result($fld_result,$i,'fieldid');
                 $adb->query("insert into profile2field values (".$profileid.",".$tab_id.",".$field_id.",0,1)");
	}
}
function insert_def_org_field()
{
	global $adb;
	$adb->database->SetFetchMode(ADODB_FETCH_ASSOC); 
	$fld_result = $adb->query("select * from field where generatedtype=1 and displaytype in (1,2)");
        $num_rows = $adb->num_rows($fld_result);
        for($i=0; $i<$num_rows; $i++)
        {
                 $tab_id = $adb->query_result($fld_result,$i,'tabid');
                 $field_id = $adb->query_result($fld_result,$i,'fieldid');
                 $adb->query("insert into def_org_field values (".$tab_id.",".$field_id.",0,1)");
	}
}
function getProfile2FieldList($fld_module, $profileid)
{
	global $vtlog;
	$vtlog->logthis("in getProfile2FieldList ".$fld_module. ' profile id is  '.$profileid,'info');  
	global $adb;
	$tabid = getTabid($fld_module);
	
	$query = "select profile2field.visible,field.* from profile2field inner join field on field.fieldid=profile2field.fieldid where profile2field.profileid=".$profileid." and profile2field.tabid=".$tabid;
	$result = $adb->query($query);
	return $result;
}
function getDefOrgFieldList($fld_module)
{
	global $vtlog;
	$vtlog->logthis("in getDefOrgFieldList ".$fld_module,'info');  
	global $adb;
	$tabid = getTabid($fld_module);
	
	$query = "select def_org_field.visible,field.* from def_org_field inner join field on field.fieldid=def_org_field.fieldid where def_org_field.tabid=".$tabid;
	$result = $adb->query($query);
	return $result;
}
function getQuickCreate($tabid,$actionid)
{
        $QuickCreateForm= 'true';
        $profile_id = $_SESSION['authenticated_user_profileid'];
        $tab_per_Data = getAllTabsPermission($profile_id);
        $permissionData = $_SESSION['action_permission_set'];
        if($tab_per_Data[$tabid] !=0)
        {
                $QuickCreateForm= 'false';
        }
        if($permissionData[$tabid][1] !=0)
        {
                $QuickCreateForm= 'false';
        }
	return $QuickCreateForm;
}
function ChangeStatus($status,$activityid,$activity_mode='')
 {
	global $vtlog;
	$vtlog->logthis("in ChangeStatus ".$status. ' activityid is  '.$activityid,'info');  
        global $adb;
        if ($activity_mode == 'Task')
        {
                $query = "Update activity set status='".$status."' where activityid = ".$activityid;
        }
        elseif ($activity_mode == 'Events')
        {
                $query = "Update activity set eventstatus='".$status."' where activityid = ".$activityid;
        }
        $adb->query($query);
 }
//parameter $viewid added for customview 27/5
function AlphabeticalSearch($module,$action,$fieldname,$query,$type,$popuptype='',$recordid='',$return_module='',$append_url='',$viewid='')
{
	if($type=='advanced')
		$flag='&advanced=true';
	if($popuptype != '')
		$popuptypevalue = "&popuptype=".$popuptype;
        if($recordid != '')
                $returnvalue = '&recordid='.$recordid;
        if($return_module != '')
                $returnvalue .= '&return_module='.$return_module;
	for($var='A',$i =1;$i<=26;$i++,$var++)
		$list .= ''.$var.' ";
	for($i=$start;$i<=$end;$i++)
	{
		if($i==$selvalue)
		$def_sel = "SELECTED";
		$OPTION_FLD .= "".$i." \n";
		$def_sel = "";
	}
	$OPTION_FLD .=" ";
	return $OPTION_FLD;
}
function getAssociatedProducts($module,$focus,$seid='')
{
	global $adb;
	$output = '';
	global $theme;
	$theme_path="themes/".$theme."/";
	$image_path=$theme_path."images/";
	if($module == 'Quotes')
	{
		$query="select products.productname,products.unit_price,products.qtyinstock,quotesproductrel.* from quotesproductrel inner join products on products.productid=quotesproductrel.productid where quoteid=".$focus->id;
	}
	elseif($module == 'Orders')
	{
		$query="select products.productname,products.unit_price,products.qtyinstock,poproductrel.* from poproductrel inner join products on products.productid=poproductrel.productid where purchaseorderid=".$focus->id;
	}
	elseif($module == 'SalesOrder')
	{
		$query="select products.productname,products.unit_price,products.qtyinstock,soproductrel.* from soproductrel inner join products on products.productid=soproductrel.productid where salesorderid=".$focus->id;
	}
	elseif($module == 'Invoice')
	{
		$query="select products.productname,products.unit_price,products.qtyinstock,invoiceproductrel.* from invoiceproductrel inner join products on products.productid=invoiceproductrel.productid where invoiceid=".$focus->id;
	}
	elseif($module == 'Potentials')
	{
		$query="select products.productname,products.unit_price,products.qtyinstock,seproductsrel.* from products inner join seproductsrel on seproductsrel.productid=products.productid where crmid=".$seid;
	}
	elseif($module == 'Products')
	{
		$query="select products.productid,products.productname,products.unit_price,products.qtyinstock,crmentity.* from products inner join crmentity on crmentity.crmid=products.productid where crmentity.deleted=0 and productid=".$seid;
	}
	$result = $adb->query($query);
	$num_rows=$adb->num_rows($result);
	for($i=1;$i<=$num_rows;$i++)
	{
		$productname=$adb->query_result($result,$i-1,'productname');
		$unitprice=$adb->query_result($result,$i-1,'unit_price');
		$qtyinstock=$adb->query_result($result,$i-1,'qtyinstock');
		$productid=$adb->query_result($result,$i-1,'productid');
		$qty=$adb->query_result($result,$i-1,'quantity');
		$listprice=$adb->query_result($result,$i-1,'listprice');
		if($listprice == '')
			$listprice = $unitprice;
		if($qty =='')
			$qty = 1;
		$total = $qty*$listprice;
		$product_id_var = 'hdnProductId'.$i;
		$status_var = 'hdnRowStatus'.$i;
		$qty_var = 'txtQty'.$i;
		$list_price_var = 'txtListPrice'.$i;	
		$total_var = 'total'.$i;
		if($num_rows%2 == 0)
		{
			$row_class = "evenListRow";
		}
		else
		{
			$row_class = "oddListRow";
		}
		$output .= '';
		$output .= ''.$qtyinstock.'
 '.$unitprice.'
 '.$total.'
Del ';
		}
		else
		{
			$output .= '';
		}
		$output .= '  ';	
	}
	return $output;
}
function getNoOfAssocProducts($module,$focus,$seid='')
{
	global $adb;
	$output = '';
	if($module == 'Quotes')
	{
		$query="select products.productname,products.unit_price,quotesproductrel.* from quotesproductrel inner join products on products.productid=quotesproductrel.productid where quoteid=".$focus->id;
	}
	elseif($module == 'Orders')
	{
		$query="select products.productname,products.unit_price,poproductrel.* from poproductrel inner join products on products.productid=poproductrel.productid where purchaseorderid=".$focus->id;
	}
	elseif($module == 'SalesOrder')
	{
		$query="select products.productname,products.unit_price,soproductrel.* from soproductrel inner join products on products.productid=soproductrel.productid where salesorderid=".$focus->id;
	}
	elseif($module == 'Invoice')
	{
		$query="select products.productname,products.unit_price,invoiceproductrel.* from invoiceproductrel inner join products on products.productid=invoiceproductrel.productid where invoiceid=".$focus->id;
	}
	elseif($module == 'Potentials')
	{
		$query="select products.productname,products.unit_price,seproductsrel.* from products inner join seproductsrel on seproductsrel.productid=products.productid where crmid=".$seid;
	}	
	elseif($module == 'Products')
	{
		$query="select products.productname,products.unit_price, crmentity.* from products inner join crmentity on crmentity.crmid=products.productid where crmentity.deleted=0 and productid=".$seid;
	}
	$result = $adb->query($query);
	$num_rows=$adb->num_rows($result);
	return $num_rows;
}
function getListPrice($productid,$pbid)
{
	global $vtlog;
	$vtlog->logthis("in getListPrice productid ".$productid,'info');  
	global $adb;
	$query = "select listprice from pricebookproductrel where pricebookid=".$pbid." and productid=".$productid;
	$result = $adb->query($query);
	$lp = $adb->query_result($result,0,'listprice');
	return $lp;
}
function getDetailAssociatedProducts($module,$focus)
{
	global $adb;
	global $theme;
	global $vtlog;
        $theme_path="themes/".$theme."/";
        $image_path=$theme_path."images/";
	$vtlog->logthis("in getDetailAssociatedProducts. Module is  ".$module,'debug');
	$output = '';
	$output .= 'Product Details 
 ';
    $output .= '
';
	*/
	return $output;
}
function getConvertQuoteToSoObject($focus,$quote_focus,$quoteid)
{
	global $vtlog;
	$vtlog->logthis("in getConvertQuoteToSoObject ".$quoteid,'info');  
        $focus->column_fields['quote_id'] = $quoteid;
        $focus->column_fields['subject'] = $quote_focus->column_fields['subject'];
        $focus->column_fields['contact_id'] = $quote_focus->column_fields['contact_id'];
        $focus->column_fields['potential_id'] = $quote_focus->column_fields['potential_id'];
        $focus->column_fields['account_id'] = $quote_focus->column_fields['account_id'];
        $focus->column_fields['carrier'] = $quote_focus->column_fields['carrier'];
        $focus->column_fields['bill_street'] = $quote_focus->column_fields['bill_street'];
        $focus->column_fields['ship_street'] = $quote_focus->column_fields['ship_street'];
        $focus->column_fields['bill_city'] = $quote_focus->column_fields['bill_city'];
        $focus->column_fields['ship_city'] = $quote_focus->column_fields['ship_city'];
        $focus->column_fields['bill_state'] = $quote_focus->column_fields['bill_state'];
        $focus->column_fields['ship_state'] = $quote_focus->column_fields['ship_state'];
        $focus->column_fields['bill_code'] = $quote_focus->column_fields['bill_code'];
        $focus->column_fields['ship_code'] = $quote_focus->column_fields['ship_code'];
        $focus->column_fields['bill_country'] = $quote_focus->column_fields['bill_country'];
        $focus->column_fields['ship_country'] = $quote_focus->column_fields['ship_country'];
        $focus->column_fields['description'] = $quote_focus->column_fields['description'];
        $focus->column_fields['terms_conditions'] = $quote_focus->column_fields['terms_conditions'];
        return $focus;
}
function getConvertQuoteToInvoice($focus,$quote_focus,$quoteid)
{
	global $vtlog;
	$vtlog->logthis("in getConvertQuoteToInvoice ".$quoteid,'info'); 
	$focus->column_fields['subject'] = $quote_focus->column_fields['subject'];
	$focus->column_fields['account_id'] = $quote_focus->column_fields['account_id'];
	$focus->column_fields['bill_street'] = $quote_focus->column_fields['bill_street'];
	$focus->column_fields['ship_street'] = $quote_focus->column_fields['ship_street'];
	$focus->column_fields['bill_city'] = $quote_focus->column_fields['bill_city'];
	$focus->column_fields['ship_city'] = $quote_focus->column_fields['ship_city'];
	$focus->column_fields['bill_state'] = $quote_focus->column_fields['bill_state'];
	$focus->column_fields['ship_state'] = $quote_focus->column_fields['ship_state'];
	$focus->column_fields['bill_code'] = $quote_focus->column_fields['bill_code'];
	$focus->column_fields['ship_code'] = $quote_focus->column_fields['ship_code'];
	$focus->column_fields['bill_country'] = $quote_focus->column_fields['bill_country'];
	$focus->column_fields['ship_country'] = $quote_focus->column_fields['ship_country'];
	$focus->column_fields['description'] = $quote_focus->column_fields['description'];
	$focus->column_fields['terms_conditions'] = $quote_focus->column_fields['terms_conditions'];
	return $focus;
}
function getConvertSoToInvoice($focus,$so_focus,$soid)
{
	global $vtlog;
	$vtlog->logthis("in getConvertSoToInvoice ".$soid,'info');  
	$focus->column_fields['salesorder_id'] = $soid;
	$focus->column_fields['subject'] = $so_focus->column_fields['subject'];
	$focus->column_fields['customerno'] = $so_focus->column_fields['customerno'];
	$focus->column_fields['duedate'] = $so_focus->column_fields['duedate'];
	$focus->column_fields['account_id'] = $so_focus->column_fields['account_id'];
	$focus->column_fields['exciseduty'] = $so_focus->column_fields['exciseduty'];
	$focus->column_fields['salescommission'] = $so_focus->column_fields['salescommission'];
	$focus->column_fields['purchaseorder'] = $so_focus->column_fields['purchaseorder'];
	$focus->column_fields['bill_street'] = $so_focus->column_fields['bill_street'];
	$focus->column_fields['ship_street'] = $so_focus->column_fields['ship_street'];
	$focus->column_fields['bill_city'] = $so_focus->column_fields['bill_city'];
	$focus->column_fields['ship_city'] = $so_focus->column_fields['ship_city'];
	$focus->column_fields['bill_state'] = $so_focus->column_fields['bill_state'];
	$focus->column_fields['ship_state'] = $so_focus->column_fields['ship_state'];
	$focus->column_fields['bill_code'] = $so_focus->column_fields['bill_code'];
	$focus->column_fields['ship_code'] = $so_focus->column_fields['ship_code'];
	$focus->column_fields['bill_country'] = $so_focus->column_fields['bill_country'];
	$focus->column_fields['ship_country'] = $so_focus->column_fields['ship_country'];
	$focus->column_fields['description'] = $so_focus->column_fields['description'];
	$focus->column_fields['terms_conditions'] = $so_focus->column_fields['terms_conditions'];
	return $focus;
}
function upload_product_image_file($mode,$id)
{
	global $root_directory;
	global $vtlog;
	$vtlog->logthis("Inside upload_product_image_file. The id is ".$id,'debug');
	$uploaddir = $root_directory ."/test/product/";
	$file_path_name = $_FILES['imagename']['name'];
	$file_name = basename($file_path_name);
	$file_name = $id.'_'.$file_name;
	$filetype= $_FILES['imagename']['type'];
	$filesize = $_FILES['imagename']['size'];
	$ret_array = Array();
	if($filesize > 0)
	{
		if(move_uploaded_file($_FILES["imagename"]["tmp_name"],$uploaddir.$file_name))
		{
			$upload_status = "yes";
			$ret_array["status"] = $upload_status;
			$ret_array["file_name"] = $file_name;
			
		}
		else
		{
			$errorCode =  $_FILES['imagename']['error'];
			$upload_status = "no";
			$ret_array["status"] = $upload_status;
			$ret_array["errorcode"] = $errorCode;
			
			
		}
	}
	else
	{
		$upload_status = "no";
                $ret_array["status"] = $upload_status;
	}
	return $ret_array;		
}
function getProductImageName($id)
{
	global $adb;
	global $vtlog;
	$query = "select imagename from products where productid=".$id;
	$result = $adb->query($query);
	$image_name = $adb->query_result($result,0,"imagename");
	$vtlog->logthis("Inside getProductImageName. The image_name is ".$image_name,'debug');
	return $image_name;
	
}
function updateSubTotal($module,$tablename,$colname,$colname1,$entid_fld,$entid,$prod_total)
{
        global $adb;
        //getting the subtotal
        $query = "select ".$colname.",".$colname1." from ".$tablename." where ".$entid_fld."=".$entid;
        $result1 = $adb->query($query);
        $subtot = $adb->query_result($result1,0,$colname);
        $subtot_upd = $subtot - $prod_total;
        $gdtot = $adb->query_result($result1,0,$colname1);
        $gdtot_upd = $gdtot - $prod_total;
        //updating the subtotal
        $sub_query = "update ".$tablename." set ".$colname."=".$subtot_upd.",".$colname1."=".$gdtot_upd." where ".$entid_fld."=".$entid;
        $adb->query($sub_query);
}
function getInventoryTotal($return_module,$id)
{
	global $adb;
	if($return_module == "Potentials")
	{
		$query ="select products.productname,products.unit_price,products.qtyinstock,seproductsrel.* from products inner join seproductsrel on seproductsrel.productid=products.productid where crmid=".$id;
	}
	elseif($return_module == "Products")
	{
		$query="select products.productid,products.productname,products.unit_price,products.qtyinstock,crmentity.* from products inner join crmentity on crmentity.crmid=products.productid where crmentity.deleted=0 and productid=".$id;
	}
	$result = $adb->query($query);
	$num_rows=$adb->num_rows($result);
	$total=0;
	for($i=1;$i<=$num_rows;$i++)
	{
		$unitprice=$adb->query_result($result,$i-1,'unit_price');
		$qty=$adb->query_result($result,$i-1,'quantity');
		$listprice=$adb->query_result($result,$i-1,'listprice');
		if($listprice == '')
		$listprice = $unitprice;
		if($qty =='')
		$qty = 1;
		$total = $total+($qty*$listprice);
	}
	return $total;
}
?>