<?php
define("CSS_DIR", "css/");
// require("includes/smtp_class.php");


class Survey_Functions
{
	function __construct($survey_dsn)
	{
		// echo 'Constructor Function';
		$this->sql =& new Survey_SQL($survey_dsn);
		$this->include_path = $this->directory;
	}

	//--------------------------------------------------------------------------
	// Class destructor
	//--------------------------------------------------------------------------    
	function __destruct()
	{
		// echo 'this object has been destroyed';
	}
}

class General_Functions
{
	function __construct()
	{
		// echo 'Constructor Function';
		$this->sql =& new Project_SQL;
		$this->isCssClassWritten = false;
		$this->directory = CSS_DIR;
		$this->include_path = $this->directory;
		$this->sub_table = false;
		
		$query = "SELECT * FROM version ORDER BY date DESC";
		$this->sql->query($query, SQL_ALL, SQL_ASSOC);
		$versn_rec = $this->sql->record[0];
		$versn = $versn_rec['vno'].".".$versn_rec['bno'];
		define("VERSION", $versn);
		
		$query = "SELECT * FROM custom_settings LEFT JOIN custom_survey_master ON (custom_survey_master.sur_code = custom_settings.stngs_survey_code)";
		$this->sql->query($query, SQL_ALL, SQL_ASSOC);
		$stngs_rec = $this->sql->record[0];
                
		define("APP_NAME", $stngs_rec['stngs_app_name']);
		define("FIN_YR", $stngs_rec['stngs_financial_year']);
		define("DT_FMT", $stngs_rec['stngs_dateformat']);
		define("SURVY", $stngs_rec['stngs_survey_code']);
		define("SURVYTITLE", $stngs_rec['sur_title']);
		define("SURVYFXD", $stngs_rec['stngs_survey_fixed']);
		
		if($stngs_rec['stngs_dateformat'] == 'd-m-yyyy')
			$dt_frmt = '%Y-%m-%d';
		elseif($stngs_rec['stngs_dateformat'] == 'dd-mm-yyyy')
			$dt_frmt = '%d-%m-%Y';
		elseif($stngs_rec['stngs_dateformat'] == 'mm-dd-yyyy')
			$dt_frmt = '%m-%d-%Y';
		elseif($stngs_rec['stngs_dateformat'] == 'yyyy-mm-dd')
			$dt_frmt = '%Y-%m-%d';
		
		$query = "SELECT * FROM custom_app_settings WHERE app_survey_id = '".$stngs_rec['stngs_survey_code']."'";
		$this->sql->query($query, SQL_ALL, SQL_ASSOC);
		$app_stngs_rec = $this->sql->record[0];
		
		define("COUPONFXD", $app_stngs_rec['app_cupn_cde_fixed']);
		define("BIOREF", $app_stngs_rec['app_fing_req']);
		define("SURCMP", $app_stngs_rec['app_surcmp_req']);
		define("LABREQ", $app_stngs_rec['app_labreq_req']);
		define("LCTN", $app_stngs_rec['app_location']);
		define("DT_FRMT", $dt_frmt);
		// Added by Vidhya - 30/11/2017
		define("CUPN_SHOWVAR",$app_stngs_rec['app_cupn_showvar']);
		// Added by Vidhya - 08/12/2017
		define("CUPN_STDARM",$app_stngs_rec['app_std_arm']);
	}

	//--------------------------------------------------------------------------
	// Class destructor
	//--------------------------------------------------------------------------    
	function __destruct()
	{
		// echo 'this object has been destroyed';
	}
	
	function SetModes($parameters)
	{
		unset($this->modes);
		$this->modes = array();
        if(is_array($parameters)){
            foreach($parameters as $modeName => $modeValue){
                $this->modes[$modeName] = $modeValue;
            }            
        }
	}
	
	protected function IsFileExists($file){
        $file = trim($file);
        if(strtolower($this->platform) == "windows" && $file != ""){
            if(@file_exists($file)) return true;
        }else if(file_exists($file)){
            return true;
        }
        return false;
    }
	
	function date_format($date, $fmt, $display = false)
	{
		$date_array = split('-', $date);
		/*echo $fmt;
		print_r($date_array);*/
		
		if($display)
		{
			if($fmt == 'dd-mm-yyyy')
			{
				$day = $date_array[0]; 
				$month = $date_array[1]; 
				$year = $date_array[2]; 
			}
			elseif($fmt == 'mm-dd-yyyy')
			{
				$day = $date_array[0]; 
				$year = $date_array[1]; 
				$month = $date_array[2]; 
			}
			elseif($fmt == 'yyyy-mm-dd')
			{
				$year = $date_array[0]; 
				$month = $date_array[1]; 
				$day = $date_array[2]; 
			}
			return $year."-".$month."-".$day;
		}
		else
		{
			if($fmt == 'dd-mm-yyyy')
			{
				$day = $date_array[0]; 
				$month = $date_array[1]; 
				$year = $date_array[2]; 
			}
			elseif($fmt == 'mm-dd-yyyy')
			{
				$month = $date_array[0]; 
				$day = $date_array[1]; 
				$year = $date_array[2]; 
			}
			elseif($fmt == 'yyyy-mm-dd')
			{
				$year = $date_array[0]; 
				$month = $date_array[1]; 
				$day = $date_array[2]; 
			}
			return $year."-".$month."-".$day;
		}
	}
	
	function DefineCssClass(){
        echo "\n<style type='text/css'>.resizable-textarea .grippie { BACKGROUND: url(".$this->directory."images/grippie.png) #eee no-repeat center 2px; }</style>";
        // read style color definitions
        $file_name = $this->directory."styles/".$this->cssClass."/colors.inc.php";
        if($this->IsFileExists($file_name)){ 
            include($file_name);
            if(isset($rowColor)){
                $this->rowColor[0] = $rowColor[0]; // odd row color 
                $this->rowColor[1] = $rowColor[1]; // even row color
                $this->rowColor[2] = $rowColor[2]; // odd row color in main colomn
                $this->rowColor[3] = $rowColor[3]; // even row color in main colomn
                $this->rowColor[4] = $rowColor[4]; // row mouse over lighting 
                $this->rowColor[5] = $rowColor[5]; // on mouse click 
                $this->rowColor[6] = $rowColor[6]; // header (th main) column
                $this->rowColor[7] = $rowColor[7]; // selected row mouse over lighting
                $this->rowColor[8] = $rowColor[8];
                $this->rowColor[9] = $rowColor[9];
                return true;                
            }
        }
        
        $this->rowColor[0] = "#fcfaf6"; // odd row color 
        $this->rowColor[1] = "#ffffff"; // even row color
        $this->rowColor[2] = "#ebeadb"; // odd row color in main colomn
        $this->rowColor[3] = "#ebeadb"; // even row color in main colomn
        $this->rowColor[4] = "#e2f3fc"; // row mouse over lighting 
        $this->rowColor[5] = "#fdfde7"; // on mouse click 
        $this->rowColor[6] = "#e2e0cb"; // header (th main) column 
        $this->rowColor[7] = "#f9f9e3"; // selected row mouse over lighting
        $this->rowColor[8] = "#fcfaf6";
        $this->rowColor[9] = "#fcfaf6";
    }
	
	function SetCssClass($class = "default"){        
        $this->cssClass = strtolower($class);
		$this->WriteCssClass();
    }
	
	function WriteCssClass(){
        if(!$this->isCssClassWritten){
            echo "\n<!-- DataGrid CSS definitions - START -->";
            echo "\n<link href='".$this->include_path."styles/print.css' type='text/css' rel='stylesheet' media='print' />";
            $this->DefineCssClass();
            // if we in Print Mode
            if($this->isPrinting){
                $this->rowColor[0] = "";
                $this->rowColor[1] = "";            
                $this->rowColor[2] = ""; // dark
                $this->rowColor[3] = ""; // light
                $this->rowColor[4] = ""; // row mouse over lighting
                $this->rowColor[5] = ""; // on mouse click
                $this->rowColor[6] = ""; // header (th main) column
                $this->rowColor[7] = ""; // selected row mouse over lighting
                $this->rowColor[8] = "";
                $this->rowColor[9] = "";
                echo "\n<!--[if IE]><link rel='stylesheet' type='text/css' href='".$this->include_path."styles/print/style_IE.css' /><![endif]-->";            
                echo "\n<link rel='stylesheet' type='text/css' href='".$this->include_path."styles/print/style.css' />";
                $this->cssClass = "print";
            }else{
                if(!$this->IsFileExists($this->directory."styles/".$this->cssClass."/style.css")){
                    $this->cssClass = "default";
                    if($this->debug) $this->warnings[] = "Cannot find file: <b>".$this->include_path."styles/".$this->cssClass."/style.css</b>. Check if this file exists and you use a correct path!";;
                }
                echo "\n<!--[if IE]><link rel='stylesheet' type='text/css' href='".$this->include_path."styles/".$this->cssClass."/style_IE.css' /><![endif]-->";            
                echo "\n<link rel='stylesheet' type='text/css' href='".$this->include_path."styles/".$this->cssClass."/style.css' />";            
            }
            echo "\n<!-- DataGrid CSS definitions - END -->\n\n";            
            $this->isCssClassWritten = true;            
        }
    }
	
	function UserLog($form_name, $table_name, $id, $mode)
	{
		$_query = sprintf("INSERT INTO custom_user_activity_log values(0, '%s', '%s', '%s', '%s', '%s', '%s', now())",
			mysql_escape_string(USR),
			mysql_escape_string($_SERVER['REMOTE_ADDR']),
			mysql_escape_string($form_name),
			mysql_escape_string($table_name),
			mysql_escape_string($id),
			mysql_escape_string($mode)
		);
		$rec = $this->sql->query($_query);
	}
	
	function ViewModeColumns($rec, $columns = "", $table_width, $primary_key, $prefix = "", $type = "")
	{
		unset($this->columnsViewMode);
		$this->columnsViewMode = array();
		unset($this->ColumnsName);
		$this->ColumnsName = array();
		
		if(is_array($columns))
		{
			foreach($columns as $fldName => $fldValue)
			{
				$this->ColumnsName[] = $fldName;
				$this->columnsViewMode[$fldName] = $fldValue;
			}
			
			if($type == "")
				$disp = '<div style="margin-left: auto; margin-right: auto; width: '.$table_width.';"><table class="'.$this->cssClass.'_dg_table" style="width: 100%;" id="example">';
			else
				$disp = '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example'.$type.'">';
			
			$disp .= '<thead><tr>';
			
			$action_view = true;
			foreach($columns as $fldName => $fldValue)
			{
				foreach($fldValue as $fldAttrib => $fldAttrValue)
				{
					if($fldAttrib == 'type')
					{
						if($fldAttrValue == 'label')
						{
							$disp .= '<th class="'.$this->cssClass.'_dg_th_normal dg_left dg_nowrap" align="'.$this->columnsViewMode[$fldName]['align'].'" style="width: '.$this->columnsViewMode[$fldName]['width'].'">'.$this->columnsViewMode[$fldName]['header'].'</th>';
						}
						if($fldAttrValue == 'status')
						{
							$disp .= '<th class="'.$this->cssClass.'_dg_th_normal dg_center dg_nowrap" align="'.$this->columnsViewMode[$fldName]['align'].'" style="width: '.$this->columnsViewMode[$fldName]['width'].'">'.$this->columnsViewMode[$fldName]['header'].'</th>';
						}
						if($fldAttrValue == 'checkbox')
						{
							$disp .= '<th class="'.$this->cssClass.'_dg_th_normal dg_left dg_nowrap" align="'.$this->columnsViewMode[$fldName]['align'].'" style="width: '.$this->columnsViewMode[$fldName]['width'].'"><input type="checkbox" onclick="SetChecked(this.checked, \''.$fldName.'[]\', this.form);" /></th>';
						}
						if($fldAttrValue == 'radio')
						{
							$disp .= '<th class="'.$this->cssClass.'_dg_th_normal dg_left dg_nowrap" align="'.$this->columnsViewMode[$fldName]['align'].'" style="width: '.$this->columnsViewMode[$fldName]['width'].'"><!--<input type="radio" onclick="SetChecked(this.checked, \''.$fldName.'[]\', this.form);" />-->&nbsp;</th>';
						}
						if($fldAttrValue == 'custom')
						{
							// $action_view = false;
							$disp .= '<th class="'.$this->cssClass.'_dg_th_normal dg_left dg_nowrap" align="'.$this->columnsViewMode[$fldName]['align'].'" style="width: '.$this->columnsViewMode[$fldName]['width'].'">'.$this->columnsViewMode[$fldName]['header'].'</th>';
						}
					}
				}
			}
			
			// echo($_SERVER['SCRIPT_NAME']." != ".DOC_ROOT.'/index.php')."<br />";
			
			if($_SERVER['SCRIPT_NAME'] != DOC_ROOT.'/index.php')
				$action_link = 'index.php?page='.$_REQUEST['page'];
			elseif(!$this->sub_table)
				$action_link = $_SERVER['SCRIPT_NAME'].'?page='.$_REQUEST['page'];
			else
			{
				$m = $_REQUEST[$prefix.'mode'];
				$_SERVER['QUERY_STRING'] = str_replace('&'.$prefix.'mode='.$m,'',$_SERVER['QUERY_STRING']);
				$m = $_REQUEST[$prefix.'id'];
				$_SERVER['QUERY_STRING'] = str_replace('&'.$prefix.'id='.$m,'',$_SERVER['QUERY_STRING']);
				
				$action_link = $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
			}
			
			$act_type = isset($_REQUEST['act_type']) ? $_REQUEST['act_type'] : "";
			
			if($act_type != "")
				$action_link .= "&act_type=".$act_type;
			
			// echo $action_link;
			
			if($this->modes['add'] || $this->modes['edit'] || $this->modes['details'] || $this->modes['delete'] || $this->modes['details_view'] || $this->modes['print'])
			{
				if($action_view)
				{
					$disp .= '<th class="'.$this->cssClass.'_dg_th_normal dg_center dg_nowrap">
								<!--Actions&nbsp;&nbsp;&nbsp;-->';
								if($this->modes['add'])
									$disp .= '<a class="'.$this->cssClass.'_dg_a_header" style="cursor: pointer;" onclick="redirect_function(\''.$action_link.'\', \'add\', \'\', \''.$prefix.'\');" ><img src="images/add.png" title="Add New" style="width: 16px;" > Add New</a>';
								elseif($this->modes['print'])
									$disp .= 'Print&nbsp;&nbsp;&nbsp;';
								else
									$disp .= 'Actions&nbsp;&nbsp;&nbsp;';
					$disp .= '</th>';
				}
			}
			$disp .= '</thead></tr>';
			
			if($type == "")
				$disp .= '<thead id="rw_filter" style="display: none;"><tr>';
			else
				$disp .= '<thead id="rw_filter'.$type.'"><tr>';
			
			foreach($columns as $fldName => $fldValue)
			{
				foreach($fldValue as $fldAttrib => $fldAttrValue)
				{
					if($fldAttrib == 'type')
					{
						if($fldAttrValue != 'status' && $fldAttrValue != 'checkbox')
							$disp .= '<th class="'.$this->cssClass.'_dg_td dg_left dg_nowrap"><input type="text" name="search_engine" class="search_init" value="'.$this->columnsViewMode[$fldName]['header'].'" /></th>';
						else
							$disp .= '<th class="'.$this->cssClass.'_dg_td dg_left dg_nowrap">&nbsp;&nbsp;</th>';
					}
				}
			}
			if($this->modes['edit'] || $this->modes['details'] || $this->modes['delete'])
				$disp .= '<th class="'.$this->cssClass.'_dg_td dg_left dg_nowrap">&nbsp;&nbsp;</th>';
			
			$disp .= '</tr></thead>';
			
			$j = 0;
			
			foreach($rec as $rowField => $rowfldValue)
			{
				$disp .= '<tr>';
				foreach($this->ColumnsName as $col => $value)
				{
					if($this->columnsViewMode[$value]['type'] == 'checkbox')
						$disp .= '<td class="'.$this->cssClass.'_dg_td dg_left"><input type="checkbox" value="'.$rowfldValue[$value].'" name="'.$value.'[]" id="'.$value.'_'.$j.'" /></td>';
					elseif($this->columnsViewMode[$value]['type'] == 'radio')
						$disp .= '<td class="'.$this->cssClass.'_dg_td dg_left"><input type="radio" value="'.$rowfldValue[$value].'" name="'.$value.'[]" id="'.$value.'_'.$j.'" /></td>';
					elseif($this->columnsViewMode[$value]['type'] == 'status')
					{
						$disp .= '<td class="'.$this->cssClass.'_dg_td dg_center">';
						if($rowfldValue[$value] == 'Active')
							$disp .= '<a class="'.$this->cssClass.'_dg_a_header" style="cursor: pointer;" onclick="redirect_function(\''.$action_link.'\', \'status\', '.$rowfldValue[$primary_key].', \'\');" ><img src="images/Active-Small.png" title="Active" ></a>';
						else
							$disp .= '<a class="'.$this->cssClass.'_dg_a_header" style="cursor: pointer;" onclick="redirect_function(\''.$action_link.'\', \'status\', '.$rowfldValue[$primary_key].', \'\');" ><img src="images/Inactive-Small.png" title="Inactive" ></a>';
						$disp .= '</td>';
					}
					elseif($this->columnsViewMode[$value]['type'] == 'custom')
					{
						$disp .= '<td class="'.$this->cssClass.'_dg_td dg_left">';
						
						foreach($this->columnsViewMode[$value]['attrib'] as $attribkey => $attribval)
						{
							$disp .= $attribval;
						}
						$disp .= '</td>';
					}
					else
						$disp .= '<td class="'.$this->cssClass.'_dg_td dg_left">'.$rowfldValue[$value].'</td>';
				}
				$j++;
				
				if($this->modes['edit'] || $this->modes['details'] || $this->modes['delete'] || $this->modes['details_view'] || $this->modes['print'])
				{
					if($action_view)
					{
						$disp .= '<th class="'.$this->cssClass.'_dg_td dg_center dg_nowrap">';
						if($this->modes['edit'])
							$disp .= '<a class="'.$this->cssClass.'_dg_a" style="cursor: pointer;" onclick="redirect_function(\''.$action_link.'\', \'edit\', '.$rowfldValue[$primary_key].', \''.$prefix.'\');" ><img src="images/Edit.png" title="Edit" ></a>&nbsp;&nbsp;&nbsp;';
						if($this->modes['details'])
							$disp .= '<a class="'.$this->cssClass.'_dg_a" style="cursor: pointer;" onclick="redirect_function(\''.$action_link.'\', \'details\', '.$rowfldValue[$primary_key].', \''.$prefix.'\');" ><img src="images/Details.png" title="Details" ></a>&nbsp;&nbsp;&nbsp;';
						if($this->modes['delete'])
							$disp .= '<a class="'.$this->cssClass.'_dg_a" style="cursor: pointer;" onclick="redirect_function(\''.$action_link.'\', \'delete\', '.$rowfldValue[$primary_key].', \''.$prefix.'\');" ><img src="images/delete.png" title="Delete" ></a>';
						if($this->modes['details_view'])
							$disp .= '<a class="'.$this->cssClass.'_dg_a" style="cursor: pointer;" onclick="redirect_function(\''.$action_link.'\', \'details_view\', '.$rowfldValue[$primary_key].', \''.$prefix.'\');" ><img src="images/Details.png" title="Details" ></a>';
						if($this->modes['print'])
							$disp .= '<a class="'.$this->cssClass.'_dg_a" style="cursor: pointer;" onclick="redirect_function(\''.$action_link.'\', \'pdf\', '.$rowfldValue[$primary_key].', \''.$prefix.'\');" ><img src="images/pdf_icon.gif" title="Pdf" ></a>';
						$disp .= '</th>';
					}
				}
				
				$disp .= '</tr>';
			}
			if($type == "")
				echo $disp .= '</table></div>';
			else
				return $disp .= '</table>';
		}
    }
	
	function dropdown($intIdField, $strNameField, $strTableName, $condition, $strOrderField, $strNameOrdinal, $default, $attributes="", $strMethod="asc", $display=true)
	{
		global $ctrl_id_arr;
		
		if(is_array($strNameField))
			$strNameField1 = implode(", ",$strNameField);
		else
			$strNameField1 = $strNameField;
		
		$pos = (strpos($strNameOrdinal,"[]")) ? strpos($strNameOrdinal,"[]") : "''";
		
		if($pos == "''")
			$strNameOrdinal_id = $strNameOrdinal;
		else
			$strNameOrdinal_id = substr($strNameOrdinal,0,$pos);
		
		$disp = "<select name=\"$strNameOrdinal\" id=\"$strNameOrdinal_id\" $attributes>\n";
		$disp .= "<option value=\"\">Select</option>\n";
		
		if($condition != '')
			$strQuery = "SELECT DISTINCT $intIdField, $strNameField1 FROM $strTableName WHERE status = 'Y' AND $condition ORDER BY $strOrderField $strMethod";
		else
			$strQuery = "SELECT DISTINCT $intIdField, $strNameField1 FROM $strTableName WHERE status = 'Y' ORDER BY $strOrderField $strMethod";
		
		if($condition != '')
			$strQuery = "SELECT DISTINCT $intIdField, $strNameField1 FROM $strTableName WHERE $condition ORDER BY $strOrderField $strMethod";
		else
			$strQuery = "SELECT DISTINCT $intIdField, $strNameField1 FROM $strTableName ORDER BY $strOrderField $strMethod";
		
		// echo $strQuery;
		
		$this->sql->query($strQuery, SQL_ALL, SQL_ASSOC);
		$rsrcResult = $this->sql->record;
		
		foreach($rsrcResult as $arrayRowRec => $arrayRow)
		{
			$strA = $arrayRow["$intIdField"];
			
			if(is_array($strNameField))
				$strB = $arrayRow[$strNameField[0]]." - ".$arrayRow[$strNameField[1]];
			else
				$strB = $arrayRow["$strNameField"];
			
			if($strA == $default)
				$slected = "selected='selected'";
			else
				$slected = "";
			
			$disp .= "<option value=\"$strA\" $slected>$strB</option>\n";
		}
		
		if($display)
			echo $disp .= "</select>";
		else
			return $disp .= "</select>";
	}
	
	function generateSelect($name = '', $options = array(), $default, $attributes = "")
	{
		$pos = (strpos($name,"[]")) ? strpos($name,"[]") : "''";
		
		if($pos == "''")
			$str_id = $name;
		else
			$str_id = substr($name,0,$pos);
		
		$html = '<select name="'.$name.'" id="'.$str_id.'" '.$attributes.'>';
		$html .= "<option value=\"\">Select</option>";
		foreach ($options as $value => $option)
		{
			if($value == $default && $default != "")
				$slected = "selected='selected'";
			else
				$slected = "";
			
			$html .= '<option value='.$value.' '.$slected.'>'.$option.'</option>';
		}
		$html .= '</select>';
		return $html;
	}
	
	function SendEmailMessage($mail, $body, $subject, $to, $from, $sitename, $ishtml=false, $bouncemail=null, $attachment=null, $customheaders="")
	{
		global $emailmethod, $emailsmtphost, $emailsmtpport, $emailsmtpuser, $emailsmtppassword, $defaultlang, $emailsmtpdebug, $emailsmtpssl, $emailsmtpauth, $emailcharset;
		
		$root = getcwd();
		$root = getcwd().'\includes';
		$rootdir = str_replace("\\", "/", $root);
		
		/*echo $emailsmtpauth." ".$emailsmtpssl." ".$emailsmtphost." ".$emailsmtpport." ".$emailsmtpuser." ".$emailsmtppassword;
		exit;*/
		
		$mail->IsSMTP();
		$mail->SMTPDebug  = 0;
		
		if($emailsmtpauth)
			$mail->SMTPAuth   = true;
		else
			$mail->SMTPAuth   = false;
		
		if($emailsmtpssl)
			$mail->SMTPSecure = "ssl";
		else
			$mail->SMTPSecure = "";
		
		$mail->Host       = $emailsmtphost;
		$mail->Port       = $emailsmtpport;
		$mail->Username   = $emailsmtpuser;
		$mail->Password   = $emailsmtppassword;
		
		$mail->SetFrom($from, '');
		$mail->AddReplyTo($from,"");
		$mail->Subject    = $subject;
		$mail->MsgHTML($body);
		$address = $to;
		$mail->AddAddress($address, "");
		
		if(!$mail->Send()) {
		  return false;
		} else {
		  return true;
		}
		exit;
		
		if (!is_array($customheaders) && $customheaders == '')
		{
			$customheaders=array();
		}
	
		if (is_null($bouncemail) )
		{
			$sender=$from;
		}
		else
		{
			$sender=$bouncemail;
		}
		$bUnsetEmail=false;
		if (is_null($mail))
		{
			$bUnsetEmail=true;
			$mail = new PHPMailer;
		}
		else
		{
			$mail->SMTPKeepAlive=true;
		}
		
		if (!$mail->SetLanguage($defaultlang, $rootdir.'/phpmailer/language/'))
		{
			$mail->SetLanguage('en', $rootdir.'/phpmailer/language/');
		}
		
		$mail->CharSet = $emailcharset;
		if (isset($emailsmtpssl) && trim($emailsmtpssl)!=='' && $emailsmtpssl!==0) {
			if ($emailsmtpssl===1) {$mail->SMTPSecure = "ssl";}
			 else {$mail->SMTPSecure = $emailsmtpssl;}
		 }
	
		$fromname='';
		$fromemail=$from;
		if (strpos($from,'<'))
		{
			$fromemail=substr($from,strpos($from,'<')+1,strpos($from,'>')-1-strpos($from,'<'));
			$fromname=trim(substr($from,0, strpos($from,'<')-1));
		}
	
		$sendername='';
		$senderemail=$sender;
		if (strpos($sender,'<'))
		{
			$senderemail=substr($sender,strpos($sender,'<')+1,strpos($sender,'>')-1-strpos($sender,'<'));
			$sendername=trim(substr($sender,0, strpos($sender,'<')-1));
		}
	
		switch ($emailmethod) {
			case "qmail":
				$mail->IsQmail();
				break;
			case "smtp":
				$mail->IsSMTP();
				if ($emailsmtpdebug>0)
					{
						$mail->SMTPDebug = true;
					}
				if (strpos($emailsmtphost,':')>0)
				{
					$mail->Host = substr($emailsmtphost,0,strpos($emailsmtphost,':'));
					$mail->Port = substr($emailsmtphost,strpos($emailsmtphost,':')+1);
				}
				else {
					$mail->Host = $emailsmtphost;
				}
				$mail->Username =$emailsmtpuser;
				$mail->Password =$emailsmtppassword;
				if (trim($emailsmtpuser)!="")
				{
					$mail->SMTPAuth = true;
				}
				break;
			case "sendmail":
				$mail->IsSendmail();
				break;
			default:
				//Set to the default value to rule out incorrect settings.
				$emailmethod="mail";
				$mail->IsMail();
		}
	
		$mail->SetFrom($fromemail, $fromname);
		$mail->Sender = $senderemail; // Sets Return-Path for error notifications
		$toemails = explode(";", $to);
		foreach ($toemails as $singletoemail)
		{
			if (strpos($singletoemail, '<') )
			{
			   $toemail=substr($singletoemail,strpos($singletoemail,'<')+1,strpos($singletoemail,'>')-1-strpos($singletoemail,'<'));
			   $toname=trim(substr($singletoemail,0, strpos($singletoemail,'<')-1));
			   $mail->AddAddress($toemail,$toname);
			}
			else
			{
				$mail->AddAddress($singletoemail);
			}
		}
		if (is_array($customheaders))
		{
			foreach ($customheaders as $key=>$val) {
				$mail->AddCustomHeader($val);
			}
		}
		
		// $mail->AddCustomHeader("X-Surveymailer: $sitename Emailer (LimeSurvey.sourceforge.net)");
		if (get_magic_quotes_gpc() != "0")	{$body = stripcslashes($body);}
		if ($ishtml) {
			$mail->IsHTML(true);
			$mail->Body = $body;
			$mail->AltBody = trim(strip_tags(html_entity_decode($body,ENT_QUOTES,'UTF-8')));
		} else
		   {
			$mail->IsHTML(false);
			$mail->Body = $body;
		   }
	
		// add the attachment if there is one
		if(!is_null($attachment))
			$mail->AddAttachment($attachment);
	
		if (trim($subject)!='') {$mail->Subject = "=?$emailcharset?B?" . base64_encode($subject) . "?=";}
		if ($emailsmtpdebug>0) {
			// ob_start();
		}
		$sent=$mail->Send();
		$maildebug=$mail->ErrorInfo;
		
		if ($emailsmtpdebug>0) {
			$maildebug .= '<li>SMTP debug output:</li><pre>'.strip_tags(ob_get_contents()).'</pre>';
			// ob_end_clean();
		}
		$maildebugbody=$mail->Body;
		$mail->ClearAddresses();
		$mail->ClearCustomHeaders();
		if ($bUnsetEmail)
		{
			unset($mail);
		}
		return $sent;
	}

	function getQuestionCode($qn)
	{
		$qry = "SELECT * FROM hrmsmsurvey.lime_questions WHERE title = '".$qn."'";
		$this->sql->query($qry, SQL_ALL, SQL_ASSOC);
		$rec =  $this->sql->record;
		$code = $rec[0]['sid']."X".$rec[0]['gid']."X".$rec[0]['qid'];
		return $code;
	}
	
}
?>