<?php
/**
 * List all questions
 *
 * PHP version 5.0
 *
 * @category	Anova
 * @package		AnswerFormHandler
 * @author 		shankar_76ag08
 * @copyright	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id:
 * @since 		2008-12-22
 */
/**
 * File having common configuration variables required for the entire project
 */
require_once('../../common/configs/config.inc.php');

$CFG['lang']['include_files'][] = 'languages/%s/'.$CFG['admin']['index']['anova_module'].'/admin/viewAnswers.php';
$CFG['lang']['include_files'][] = 'languages/%s/common/email_notify.inc.php';

$CFG['html']['header'] = 'admin/html_header.php';
$CFG['html']['footer'] = 'admin/html_footer.php';

$CFG['mods']['include_files'][] = 'common/classes/class_ListRecordsHandler.lib.php';
$CFG['mods']['include_files'][] = 'common/classes/class_AnovaHandler.lib.php';

if ($_POST)
	$CFG['mods']['include_files'][] = 'common/classes/swiftmailer/lib/EasySwift.php';

if ($CFG['admin']['question']['external_audio'] OR $CFG['admin']['answer']['external_audio'] OR $CFG['admin']['question']['external_video'] OR $CFG['admin']['answer']['external_video'])
	{
		$CFG['mods']['include_files'][] = 'common/classes/class_GrapUrl.lib.php';
		$CFG['mods']['include_files'][] = 'common/classes/class_Videopian.lib.php';
	}

//compulsory
$CFG['site']['is_module_page'] = $CFG['admin']['index']['anova_module'];
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
/**
 * File to include the header file, database access file, session management file, help file and necessary functions
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');

//-------------- Class AnswerFormHandler begins --------------->>>>>//
class AnswerFormHandler extends AnovaHandler
	{
		public $question_repliesArray = array();
		public $_dir_path = '../../';

		/**
		 * AnswerFormHandler::deleteQuestion()
		 *
		 * @return
		 */
		public function deleteQuestion()
			{
				$quest_userID ='';
				//Change the video and audio status
				$this->updateQuestionVideoStatus($this->question_details['video_id']);
				$this->updateQuestionAudioStatus($this->question_details['audio_id']);
				$this->updateQuestionVideoStatus($this->question_details['external_video_id']);
				$this->updateQuestionAudioStatus($this->question_details['external_audio_id']);
				$this->deleteQuestionsComment();

				//select user_id to decrease question count and point
				$sql = 'SELECT user_id FROM '.$this->CFG['db']['tbl']['questions'].
						' WHERE ques_id='.$this->dbObj->Param('qid');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				if ($rs->PO_RecordCount()){
						$row = $rs->FetchRow();
						$quest_userID = $row['user_id'];
					}

				//Delete question
				$sql = 'DELETE FROM '.$this->CFG['db']['tbl']['questions'].
						' WHERE ques_id='.$this->dbObj->Param('qid');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				$sql = 'SELECT ans_id, video_id, audio_id, external_video_id, external_audio_id FROM '.$this->CFG['db']['tbl']['answers'].
						' WHERE ques_id='.$this->dbObj->Param('qid');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						while($row = $rs->FetchRow()){
							$this->updateAnswerVideoStatus($row['video_id']);
							$this->updateAnswerAudioStatus($row['audio_id']);
							$this->updateAnswerVideoStatus($row['external_video_id'], 'external_video_id');
							$this->updateAnswerAudioStatus($row['external_audio_id'], 'external_audio_id');
							//to delete attachments
							if ($this->CFG['admin']['attachments_answers']['allowed'])
								$this->commonDeleteAttachments('Answer', $row['ans_id']);
						} // while
					}

				//Decrement the total_ans count and points for users who posted answer against this question.
				$this->decreasePostersAnsCount($this->fields_arr['qid']);

				//Delete answers
				$sql = 'DELETE FROM '.$this->CFG['db']['tbl']['answers'].
						' WHERE ques_id='.$this->dbObj->Param('qid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				if($this->question_details['status']== 'ToActivate')
					return ;

				//Decrement total_questions from questions_category table
				$pcat_id = $this->question_details['pcat_id'];
				$cat_id = $this->question_details['cat_id'];
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions_category'].
						' SET total_questions=total_questions-1'.
						' WHERE cat_id='.$this->dbObj->Param($pcat_id).
						' OR cat_id='.$this->dbObj->Param($cat_id);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($pcat_id, $cat_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				if($this->question_details['status']== 'Blocked')
					return ;
				//Decrement total_ques,points from users_ans_log
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
						' SET total_ques=total_ques-1';
					if($this->CFG['admin']['ask_answers']['allowed'])
						$sql .= ', total_points=total_points-'.$this->CFG['admin']['ask_answers']['points'];
				$sql .= ' WHERE user_id='.$this->dbObj->Param('uid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($quest_userID));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				//to delete attachments
				if ($this->CFG['admin']['attachments_questions']['allowed'])
					$this->commonDeleteAttachments('Question', $this->fields_arr['qid']);

				//Decrement tag_count
				if($this->question_details['tags'])
					$this->updateDeletedQuestionsTagCount($this->question_details['tags']);
			}

		public function deleteQuestionsComment()
			{
				$sql = 'DELETE FROM '.$this->CFG['db']['tbl']['question_comment'].
						' WHERE ques_id='.$this->dbObj->Param($this->fields_arr['qid']);

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 * AnswerFormHandler::decreasePostersAnsCount()
		 *
		 * @param mixed $question_id
		 * @return
		 */
		public function decreasePostersAnsCount($question_id)
			{

				$sql = 'SELECT ans_id, user_id FROM '.$this->CFG['db']['tbl']['answers'].
						' WHERE status=\'Active\' AND ques_id='.$this->dbObj->Param('qid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($question_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						while($row = $rs->FetchRow())
							{

								$update_cond = '';
								if($row['ans_id']==$this->question_details['best_ans_id'])
									$update_cond = ', total_best_ans=total_best_ans-1';

								$ans_sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
										' SET total_ans=total_ans-1'.$update_cond.
										' WHERE user_id='.$this->dbObj->Param('uid');
								$ans_stmt = $this->dbObj->Prepare($ans_sql);
								$ans_rs = $this->dbObj->Execute($ans_stmt, array($row['user_id']));
								if (!$ans_rs)
									    trigger_db_error($this->dbObj);
							} // while
					}
			}

		/**
		 * AnswerFormHandler::deleteQuestionVideo()
		 *
		 * @return
		 */
		public function deleteQuestionVideo($video_field)
			{
				//Change the video and audio status
				$this->updateQuestionVideoStatus($this->question_details['video_id']);

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].
						' SET '.$video_field.'=0'.
						' WHERE ques_id='.$this->dbObj->Param('qid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 * AnswerFormHandler::deleteQuestionAudio()
		 *
		 * @return
		 */
		public function deleteQuestionAudio($audio_field)
			{
				//Change the video and audio status
				$this->updateQuestionAudioStatus($this->question_details['audio_id']);

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].
						' SET '.$audio_field.'=0'.
						' WHERE ques_id='.$this->dbObj->Param('qid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 * AnswerFormHandler::chkIsValidQuestion()
		 *
		 * @return
		 */
		public function chkIsValidQuestion()
		    {
				$this->chkIsNotEmpty('qid', $this->LANG['err_tip_compulsory']);
				if (!$this->isValidFormInputs())
					{
						$this->setCommonErrorMsg($this->LANG['err_tip_invalid_question']);
						return false;
					}
				//Query to display recent and popular questions
				$sql = 'SELECT q.ques_id, q.video_id, q.audio_id, q.external_video_id, q.external_audio_id, q.total_answer, q.pcat_id, q.votes, q.cat_id, q.best_ans_id, q.description, q.total_stars, q.tags, q.question, UNIX_TIMESTAMP(date_asked) as date_asked'.
						', '.$this->getUserTableField('display_name').' as asked_by, u.'.$this->getUserTableField('user_id').' as img_user_id, '.$this->getUserTableFields(array('image_path', 'gender', 'name', 'email', 't_height', 't_width','photo_server_url', 'photo_ext'), false).'q.status, q.user_id'.
						', q.video_id, q.audio_id, q.publish_status, q.seo_title, IF(status=\'Open\' AND date_closed>=NOW(), 1, 0) is_open FROM '.$this->CFG['db']['tbl']['questions'].' AS q'.
						', '.$this->CFG['db']['tbl']['users'].' AS u'.
						' WHERE q.user_id=u.'.$this->getUserTableField('user_id').
						' AND u.'.$this->getUserTableField('usr_status').'=\'Ok\' AND q.ques_id='.$this->dbObj->Param('qid');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));

				if (!$rs)
				        trigger_db_error($this->dbObj);
				if (!$rs->PO_RecordCount())
					{
						$this->setCommonErrorMsg($this->LANG['err_tip_invalid_question']);
						return false;
					}
				$this->question_details = $rs->FetchRow();
				return true;
		    }

		/**
		 * AnswerFormHandler::buildConditionQuery()
		 *
		 * @return
		 */
		public function buildConditionQuery()
			{
				$this->sql_condition = 'a.user_id=u.'.$this->getUserTableField('user_id').
						' AND u.'.$this->getUserTableField('usr_status').'=\'Ok\''.
						' AND a.ques_id='.$this->fields_arr['qid'].
						' AND a.ans_id!='.$this->question_details['best_ans_id'];

			}

		/**
		 * AnswerFormHandler::buildSortQuery()
		 *
		 * @return
		 */
		public function buildSortQuery()
			{
				$this->sql_sort = $this->fields_arr['orderby_field'].' '.$this->fields_arr['orderby'];
			}

		/**
		 * AnswerFormHandler::printQuery()
		 *
		 * @return
		 */
		public function printQuery()
			{
				print 'Query:<br>'.$this->sql;
			}

		/**
		 * AnswerFormHandler::chkIsValidAnswer()
		 *
		 * @param mixed $ans_id
		 * @return
		 */
		public function chkIsValidAnswer($ans_id)
		    {
				#$this->chkIsNotEmpty('aid', $this->LANG['err_tip_compulsory']);
				if (!$this->isValidFormInputs())
					{
						$this->setCommonErrorMsg($this->LANG['err_tip_invalid_answer']);
						return false;
					}
				//Query to display recent and popular questions
				$sql = 'SELECT a.ques_id, a.video_id, a.audio_id, a.user_id, a.status, a.answer, a.source, a.video_id, a.audio_id, a.external_video_id, a.external_audio_id'.
						' FROM '.$this->CFG['db']['tbl']['answers'].' AS a'.
						', '.$this->CFG['db']['tbl']['questions'].' AS q, '.$this->CFG['db']['tbl']['users'].' AS u'.
						' WHERE a.ques_id=q.ques_id AND a.user_id=u.'.$this->getUserTableField('user_id').' AND q.status IN (\'Open\', \'Resolved\')'.
						' AND u.'.$this->getUserTableField('usr_status').'=\'Ok\' AND a.ans_id='.$this->dbObj->Param('aid');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($ans_id));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				if (!$rs->PO_RecordCount())
					{
						$this->setCommonErrorMsg($this->LANG['err_tip_invalid_question']);
						return false;
					}
				$this->answer_details = $rs->FetchRow();
				$this->fields_arr['qid'] = $this->answer_details['ques_id'];
				return true;
		    }

		/**
		 * AnswerFormHandler::displayBestAnswer()
		 *
		 * @return
		 */
		public function displayBestAnswer()
		    {
				if ($this->question_details['best_ans_id'])
					{
						$displayBestAnswer_arr = array();
						$sql = 'SELECT a.ans_id, a.user_id, a.video_id, a.audio_id, a.external_video_id, a.external_audio_id, a.votes, a.answer, a.source, UNIX_TIMESTAMP(date_answered) as date_answered, a.video_id, a.audio_id'.
								', u.'.$this->getUserTableField('user_id').' as img_user_id, '.$this->getUserTableFields(array('image_path', 'gender', 't_height', 't_width','photo_server_url', 'photo_ext'), false).$this->getUserTableField('display_name').' as answered_by'.
								' FROM '.$this->CFG['db']['tbl']['answers'].' AS a'.
								', '.$this->CFG['db']['tbl']['users'].' AS u'.
								' WHERE a.user_id=u.'.$this->getUserTableField('user_id').
								' AND u.'.$this->getUserTableField('usr_status').'=\'Ok\''.
								' AND a.ques_id='.$this->dbObj->Param('qid').
								' AND a.ans_id='.$this->dbObj->Param('aid').
								' ORDER BY a.ans_id DESC';

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid'], $this->question_details['best_ans_id']));
						if (!$rs)
						        trigger_db_error($this->dbObj);

						if (!$rs->PO_RecordCount())
							return ;
						$row = $rs->FetchRow();
						$best_ans_id = $this->question_details['best_ans_id'];
						$displayBestAnswer_arr['populateCommentList'] = $this->populateCommentList($this->question_details['best_ans_id']);
						$displayBestAnswer_arr['record'] = $row;
						$displayBestAnswer_arr['best_ans_id'] = $best_ans_id;

						if (chkIsVideoAllowed('answer') AND $row['video_id'])
							{
								$displayBestAnswer_arr['ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Answer_'.$row['video_id'], '?pg=Answer_'.$row['video_id'], 'members');
								$displayBestAnswer_arr['ans_view_video']['on_click'] = 'best_video_'.$best_ans_id;
							}
						if (chkIsAudioAllowed('answer') AND $row['audio_id'])
							{
								$displayBestAnswer_arr['ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Answer_'.$row['audio_id'], '?pg=Answer_'.$row['audio_id'], 'members');
								$displayBestAnswer_arr['ans_view_audio']['on_click'] = 'best_audio_'.$best_ans_id;
							}
						if (chkExternalVideoAllowed('answer') AND $row['external_video_id'])
							{
								$displayBestAnswer_arr['ans_view_ext_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Answer_'.$row['external_video_id'], '?pg=Answer_'.$row['video_id'], 'members');
								$displayBestAnswer_arr['ans_view_ext_video']['on_click'] = 'video_add'.$best_ans_id;
							}
						if (chkExternalAudioAllowed('answer') AND $row['external_audio_id'])
							{
								$displayBestAnswer_arr['ans_view_ext_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Answer_'.$row['external_audio_id'], '?pg=Answer_'.$row['audio_id'], 'members');
								$displayBestAnswer_arr['ans_view_ext_audio']['on_click'] = 'audio_add'.$best_ans_id;
							}
						$displayBestAnswer_arr['row_answer_manual'] = nl2br(wordWrapManual($row['answer'], 50));

						if ($row['source'])
							{
								$displayBestAnswer_arr['row_source_manual'] = nl2br(wordWrapManual($row['source'], 50));
							}

						$displayBestAnswer_arr['facebook_user_details'] = '';
						if ($this->CFG['admin']['module']['facebook'])
							{
								$displayBestAnswer_arr['facebook_user_details'] = $this->fetchFacebookUserDetails($best_ans_id);
							}

						$displayBestAnswer_arr['fetchMoreAttachments'] = '';
						if ($this->CFG['admin']['attachments_answers']['allowed'] AND $this->hasMoreAttachments($this->question_details['best_ans_id'], 'Answer'))
							{
								$displayBestAnswer_arr['fetchMoreAttachments'] = $this->fetchMoreAttachments($this->question_details['best_ans_id']);
							}
						return $displayBestAnswer_arr;
					}

				return false;
		    }

		/**
		 * AnswerFormHandler::isFavoriteQuestion()
		 *
		 * @return
		 */
		public function isFavoriteQuestion()
		    {
				$sql = 'SELECT fav_id FROM '.$this->CFG['db']['tbl']['users_favorite_questions'].
						' WHERE ques_id = '.$this->dbObj->Param('qid').
						' AND user_id = '.$this->dbObj->Param('uid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid'], $this->CFG['user']['user_id']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				$ok = false;
				if ($rs->PO_RecordCount())
					$ok = true;
				return $ok;
		    }

		/**
		 * AnswerFormHandler::showAnotherQuestion()
		 *
		 * @return
		 */
		public function showAnotherQuestion()
		    {
				$sql = 'SELECT ques_id FROM '.$this->CFG['db']['tbl']['questions'].
						' WHERE ques_id<'.$this->dbObj->Param('qid').' AND status IN (\'Open\', \'Resolved\')'.
						' ORDER BY ques_id DESC LIMIT 1';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						$showAnotherQuestion_val = '';
						$row = $rs->FetchRow();
						$showAnotherQuestion_val = '<p class="clsAnotherQuestion clsClearfix"><a class="clsFloatright" href="'.$this->CFG['site']['relative_url'].'viewAnswers.php?qid='.$row['ques_id'].'">'.$this->LANG['answers_show_another_question'].'</a></p>';
						return $showAnotherQuestion_val;
					}
				return false;
		    }

		/**
		 * AnswerFormHandler::showCategoryNameInAdmin()
		 *
		 * @param mixed $cat_id
		 * @return
		 */
		public function showCategoryNameInAdmin($cat_id)
		    {
				$sql = 'SELECT cat_name, seo_title, cat_id FROM '.$this->CFG['db']['tbl']['questions_category'].' WHERE cat_id='.$this->dbObj->Param('cat_id');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($cat_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();

						$showCategoryNameInAdmin_val = '<span>'.$this->LANG['common_in'].' <a href="'.$this->CFG['site']['relative_url'].'manageAnswers.php?go=1&amp;search_cat=8&amp;search_name='.$row['seo_title'].'">'.$row['cat_name'].'</a></span>
						&nbsp;-&nbsp;';

						return $showCategoryNameInAdmin_val;
					}
				return false;
		    }

		/**
		 * AnswerFormHandler::displayQuestionDetails()
		 *
		 * @return
		 */
		public function displayQuestionDetails()
		    {
				if (!$this->question_details) return false;
				$displayQuestionDetails_arr = array();

				$qid = $this->fields_arr['qid'];
				$anchor1 = 'selConPos_'.$qid;
				$qanchor = 'selConPos1_'.$qid;

				$displayQuestionDetails_arr['qid'] = $qid;

				$displayQuestionDetails_arr['question_manual'] = wordWrapManual($this->question_details['question'], 50);
				if (chkIsVideoAllowed('question') AND $this->question_details['video_id'])
					{
						$displayQuestionDetails_arr['ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Question_'.$this->question_details['video_id'], '?pg=Question_'.$this->question_details['video_id'], 'members');
						$displayQuestionDetails_arr['ans_view_video']['on_click'] = 'ques_video_'.$qid;
					}
				if (chkIsAudioAllowed('question') AND $this->question_details['audio_id'])
					{
						$displayQuestionDetails_arr['ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Question_'.$this->question_details['audio_id'], '?pg=Question_'.$this->question_details['audio_id'], 'members');
						$displayQuestionDetails_arr['ans_view_audio']['on_click'] = 'ques_audio_'.$qid;
					}
				if (chkExternalVideoAllowed('question') AND $this->question_details['external_video_id'])
					{
						$displayQuestionDetails_arr['ans_view_ext_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Question_'.$this->question_details['external_video_id'], '?pg=Question_'.$this->question_details['external_video_id'], 'members');
						$displayQuestionDetails_arr['ans_view_ext_video']['on_click'] = 'ext_video_add'.$qid;
					}
				if (chkExternalAudioAllowed('question') AND $this->question_details['external_audio_id'])
					{
						$displayQuestionDetails_arr['ans_view_ext_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Question_'.$this->question_details['external_audio_id'], '?pg=Question_'.$this->question_details['external_audio_id'], 'members');
						$displayQuestionDetails_arr['ans_view_ext_audio']['on_click'] = 'ext_audio_add'.$qid;
					}
				$displayQuestionDetails_arr['description_manual'] = nl2br(wordWrapManual($this->question_details['description'], 50));

				$cat_id = $this->question_details['cat_id'];
				if(!$cat_id)
					$cat_id = $this->question_details['pcat_id'];

				$displayQuestionDetails_arr['showCategoryNameInAdmin'] = $this->showCategoryNameInAdmin($cat_id);

				$displayQuestionDetails_arr['fetchMoreAttachments'] = '';
				if ($this->CFG['admin']['attachments_questions']['allowed'] AND $this->hasMoreAttachments($this->question_details['ques_id']))
					{
						$displayQuestionDetails_arr['fetchMoreAttachments'] = $this->fetchMoreAttachments();
					}

				$displayQuestionDetails_arr['displayBestAnswer_arr'] = $this->displayBestAnswer();

				if ($this->question_details['is_open'] && $this->question_details['user_id'] != $this->CFG['user']['user_id'])
					{
						$displayQuestionDetails_arr['reply_answer']['url'] = getAnovaUrl('replyanswer', '?action=reply&title='.$this->question_details['seo_title'], $this->question_details['seo_title'].'/', 'members');
					}

				return $displayQuestionDetails_arr;
		    }

		/**
		 * AnswerFormHandler::displayAllAnswers()
		 *
		 * @return
		 */
		public function displayAllAnswers()
			{
				//Query to display recent and popular questions

				if (!$this->isResultsFound())
					{
						return ;
					}
				$displayAllAnswers_arr = array();

							$id_cnt = 0;
				//$anchor1 = '';
				$this->da_anchor = '';
				$inc = 1;
				while($row = $this->fetchResultRecord())
					{
						$ans_id = $row['ans_id'];
						$displayAllAnswers_arr[$inc]['ans_id'] = $ans_id;
						$displayAllAnswers_arr[$inc]['populateCommentList'] = $this->populateCommentList($row['ans_id']);
						$this->da_anchor = 'dAltMlti';
						$displayAllAnswers_arr[$inc]['anchor1'] = 'selConPos_'.$row['video_id'];
						$displayAllAnswers_arr[$inc]['anchor2'] = 'selConPoss_'.$row['audio_id'];
						$displayAllAnswers_arr[$inc]['anchor3'] = 'selConPos_'.$row['external_video_id'];
						$displayAllAnswers_arr[$inc]['anchor4'] = 'selConPoss_'.$row['external_audio_id'];

						$displayAllAnswers_arr[$inc]['record'] = $row;
						$displayAllAnswers_arr[$inc]['row_answer_manual'] = nl2br(wordWrapManual($row['answer'], 50));

						if (chkIsVideoAllowed('answer') AND $row['video_id'])
							{
								$displayAllAnswers_arr[$inc]['ans_view_video']['url'] =  getAnovaUrl('ansviewvideo', '?pg=Answer_'.$row['video_id'], '?pg=Answer_'.$row['video_id'], 'members');
								$displayAllAnswers_arr[$inc]['ans_view_video']['on_click'] = 'ans_video_'.$ans_id;
							}
						if (chkIsAudioAllowed('answer') AND $row['audio_id'])
							{
								$displayAllAnswers_arr[$inc]['ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Answer_'.$row['audio_id'], '?pg=Answer_'.$row['audio_id'], 'members');
								$displayAllAnswers_arr[$inc]['ans_view_audio']['on_click'] = 'ans_audio_'.$ans_id;
							}
						if (chkExternalVideoAllowed('answer') AND $row['external_video_id'])
							{
								$displayAllAnswers_arr[$inc]['ans_view_ext_video']['url'] =  getAnovaUrl('ansviewvideo', '?pg=Answer_'.$row['external_video_id'], '?pg=Answer_'.$row['external_video_id'], 'members');
								$displayAllAnswers_arr[$inc]['ans_view_ext_video']['on_click'] = 'ext_video_add'.$ans_id;
							}
						if (chkExternalAudioAllowed('answer') AND $row['external_audio_id'])
							{
								$displayAllAnswers_arr[$inc]['ans_view_ext_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Answer_'.$row['external_audio_id'], '?pg=Answer_'.$row['external_audio_id'], 'members');
								$displayAllAnswers_arr[$inc]['ans_view_ext_audio']['on_click'] = 'ext_audio_add'.$ans_id;
							}
						if ($row['source'])
							{
								$displayAllAnswers_arr[$inc]['row_source_manual'] = nl2br($row['source']);
							}
						$displayAllAnswers_arr[$inc]['facebook_user_details'] = '';
						if ($this->CFG['admin']['module']['facebook'])
							{
								$displayAllAnswers_arr[$inc]['facebook_user_details'] = $this->fetchFacebookUserDetails($ans_id);
							}
						$displayAllAnswers_arr[$inc]['row_answered_by_manual'] = stripString($row['answered_by'], $this->CFG['username']['short_length']);

						$displayAllAnswers_arr[$inc]['fetchMoreAttachments'] = '';
						if ($this->CFG['admin']['attachments_answers']['allowed'] AND $this->hasMoreAttachments($row['ans_id'], 'Answer'))
							{
								$displayAllAnswers_arr[$inc]['fetchMoreAttachments'] = $this->fetchMoreAttachments();
							}
						$displayAllAnswers_arr[$inc]['commentSpanIDId'] = 'commentSpanID_'.$row['ans_id'];
						$inc++;

					} // while

				return $displayAllAnswers_arr;
			}
		public function populateCommentList($c_ansid)
			{
				$sql = 'SELECT comment_id, ans_id, user_id, comment ,status,  DATE_FORMAT(date_added, \''.$this->CFG['mysql_format']['date_time'].'\') AS date_added'.
						' FROM '.$this->CFG['db']['tbl']['question_comment'].' WHERE'.
						' ans_id = '.$this->dbObj->Param('c_ans_id').'ORDER BY  comment_id DESC';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($c_ansid));
				    if (!$rs)
					    trigger_db_error($this->dbObj);
				$populateCommentList_arr = array();
				if($rs->PO_RecordCount())
					{
						$inc = 0;
						while($row = $rs->FetchRow())
							{
								$row['comment'] = nl2br(wordWrapManual(strip_slashes($row['comment']), 60));
								//$row['comment'] = html_entity_decode($row['comment'], ENT_QUOTES);
								$populateCommentList_arr[$inc]['record'] = $row;
								$populateCommentList_arr[$inc]['commentSpanIDId'] = 'commentSpanID_'.$row['comment_id'];
								$populateCommentList_arr[$inc]['user_details'] = $this->getUserDetails($row['user_id']);
								$populateCommentList_arr[$inc]['myanswers']['url'] = $this->CFG['site']['url'].'admin/viewMembers.php?uid='.$row['user_id'];
								$populateCommentList_arr[$inc]['msg'] = 'msg_'.$row['ans_id'];
								$populateCommentList_arr[$inc]['anchor'] = 'deleteComment'.$row['comment_id'];
								$inc++;
							}
					}
				return $populateCommentList_arr;
			}

		/**
		 * AnswerFormHandler::updateAbuseQuestion()
		 *
		 * @return
		 */
		public function updateAbuseQuestion()
		    {
				$sql = 'SELECT abuse_id FROM '.$this->CFG['db']['tbl']['abuse_questions'].
						' WHERE ques_id='.$this->dbObj->Param('qid').
						' AND reported_by='.$this->dbObj->Param('rid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid'],
														 $this->CFG['user']['user_id']));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				if (!$rs->PO_RecordCount())
					{
						$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['abuse_questions'].
								' SET ques_id='.$this->dbObj->Param('qid').
								', reported_by='.$this->dbObj->Param('rid').
								', reason='.$this->dbObj->Param('reason').
								', date_abused=NOW()';
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid'],
																 $this->CFG['user']['user_id'],
																 $this->fields_arr['reason']));
						if (!$rs)
						        trigger_db_error($this->dbObj);

						if ($this->dbObj->Affected_Rows())
							{
								$this->updateQuestionAbuseCount();
								$this->updateAbuseUserPoints($this->CFG['admin']['abuse_questions_points']['allowed'], $this->question_details['user_id'], $this->CFG['admin']['abuse_questions']['points']);
								$this->sendAbuseMailToAsker();
							}
					}
		    }

		/**
		 * AnswerFormHandler::updateQuestionAbuseCount()
		 *
		 * @return
		 */
		public function updateQuestionAbuseCount()
		    {
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].' SET abuse_count=abuse_count+1'.
						' WHERE ques_id='.$this->dbObj->Param('qid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
		    }

		/**
		 * AnswerFormHandler::updateAbuseAnswer()
		 *
		 * @return
		 */
		public function updateAbuseAnswer()
		    {
				$sql = 'SELECT abuse_id FROM '.$this->CFG['db']['tbl']['abuse_answers'].
						' WHERE ans_id='.$this->dbObj->Param('aid').
						' AND reported_by='.$this->dbObj->Param('rid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['aid'],
														 $this->CFG['user']['user_id']));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				if (!$rs->PO_RecordCount())
					{
						$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['abuse_answers'].
								' SET ques_id='.$this->dbObj->Param('qid').
								', ans_id='.$this->dbObj->Param('aid').
								', reported_by='.$this->dbObj->Param('rid').
								', reason='.$this->dbObj->Param('reason').
								', date_abused=NOW()';
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid'],
																 $this->fields_arr['aid'],
																 $this->CFG['user']['user_id'],
																 $this->fields_arr['reason']));
						if (!$rs)
						        trigger_db_error($this->dbObj);

						if ($this->dbObj->Affected_Rows())
							{
								$this->updateAnswerAbuseCount();
								$this->updateAbuseUserPoints($this->CFG['admin']['abuse_answers_points']['allowed'], $this->answer_details['user_id'], $this->CFG['admin']['abuse_answers']['points']);
								$this->sendAbuseMailToAnswerer();
							}
					}
		    }

		/**
		 * AnswerFormHandler::updateAnswerAbuseCount()
		 *
		 * @return
		 */
		public function updateAnswerAbuseCount()
		    {
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['answers'].' SET abuse_count=abuse_count+1'.
						' WHERE ans_id='.$this->dbObj->Param('aid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['aid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
		    }

		/**
		 * AnswerFormHandler::updateAbuseUserPoints()
		 *
		 * @param mixed $config_abuse
		 * @param mixed $uid
		 * @param mixed $points
		 * @return
		 */
		public function updateAbuseUserPoints($config_abuse, $uid, $points)
		    {
				if (!$config_abuse or $points == 0 or !isset($this->CFG['user']['user_id']) or empty($this->CFG['user']['user_id']))
					return ;
				//update users_ans_log table
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
						' SET total_points=total_points+'.$points.
						', date_updated=NOW()'.
						' WHERE user_id='.$this->dbObj->Param('uid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($uid));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				return ;
		    }

		/**
		 * AnswerFormHandler::updateBestAnswer()
		 *
		 * @return
		 */
		public function updateBestAnswer()
		    {
				#die('here');
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].' SET best_ans_id='.$this->dbObj->Param('aid').
						' WHERE ques_id='.$this->dbObj->Param('qid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['aid'], $this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($this->dbObj->Affected_Rows())
					{
						$this->sendMailToAnswerer();
						if ($this->chkIsValidAnswer($this->fields_arr['aid']))
							$this->increaseBestAnswerPoints($this->answer_details['user_id']);
					}
		    }

		/**
		 * AnswerFormHandler::publishAnswer()
		 *
		 * @return
		 */
		public function publishAnswer()
		    {
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['answers'].' SET status=\'Active\' WHERE ans_id='.$this->dbObj->Param('aid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['aid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				if ($this->dbObj->Affected_Rows())
					{
						// To increase the total answers count for the question..
						$this->updateQuestion();

						// To increase the total answer count for that answerer
						$usr_sql = 'SELECT a.ans_id, a.user_id, a.answer, a.ques_id, '.$this->getUserTableFields(array('email', 'display_name'), false).
								' a.status FROM '.$this->CFG['db']['tbl']['answers'].' AS a, '.$this->CFG['db']['tbl']['users'].' AS u'.
								' WHERE a.user_id=u.'.$this->getUserTableField('user_id').
								' AND u.'.$this->getUserTableField('usr_status').'=\'Ok\''.
								' AND a.ques_id='.$this->dbObj->Param('qid').
								' AND a.ans_id='.$this->dbObj->Param('aid').
								' ORDER BY a.ans_id DESC';

						$usr_stmt = $this->dbObj->Prepare($usr_sql);
						$usr_rs = $this->dbObj->Execute($usr_stmt, array($this->fields_arr['qid'], $this->fields_arr['aid']));
						if (!$usr_rs)
						        trigger_db_error($this->dbObj);

						$row = $usr_rs->FetchRow();

						$update_sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
								' SET total_ans=total_ans+1';
						if($this->CFG['admin']['reply_answers']['allowed'])
							$update_sql .= ', total_points=total_points+'.$this->CFG['admin']['reply_answers']['points'];
						$update_sql .= ', date_updated=NOW()'.
								' WHERE user_id='.$this->dbObj->Param('uid');
						$update_stmt = $this->dbObj->Prepare($update_sql);
						$update_rs = $this->dbObj->Execute($update_stmt, array($row['user_id']));
							if (!$update_rs)
				        			trigger_db_error($this->dbObj);

				        	// To send email alert for published users..
						$this->sendPublishedMailAlert($row['email'], $row['display_name'], $row['answer']);

					}
		    }

		/**
		 * AnswerFormHandler::sendPublishedMailAlert()
		 *
		 * @param mixed $toEmail
		 * @param mixed $reciever_name
		 * @param mixed $content_description
		 * @return
		 */
		public function sendPublishedMailAlert($toEmail, $reciever_name, $content_description)
			{
				$site_link = "<a target=\"_blank\" href=\"".URL($this->CFG['site']['url'])."\">".URL($this->CFG['site']['url'])."</a>";
				$url_link = getAnovaUrl('answer', '?title='.$this->question_details['seo_title'], $this->question_details['seo_title'].'/', 'root');
				$quesiton_link = "<a target=\"_blank\" href=\"".$url_link."\"><strong>".$this->question_details['question']."</strong></a>";

				$subject = $this->getMailContent($this->LANG['answer_publish_subject'], array('VAR_USERNAME'=>$reciever_name, 'VAR_SITENAME'=>$this->CFG['site']['name'], 'VAR_DESCRIPTION_OF_QUESTION'=>$content_description, 'VAR_QUESTION'=>$quesiton_link, 'VAR_LINK'=>$site_link));
				$content = $this->getMailContent($this->LANG['answer_publish_message'], array('VAR_USERNAME'=>$reciever_name, 'VAR_SITENAME'=>$this->CFG['site']['name'], 'VAR_DESCRIPTION_OF_QUESTION'=>$content_description, 'VAR_QUESTION'=>$quesiton_link, 'VAR_LINK'=>$site_link));

				$qowner_email = $this->question_details['email'];
				$qowner_name = $this->question_details['asked_by'];
				$owner_subject = $this->getMailContent($this->LANG['answer_publish_owner_subject'], array('VAR_USERNAME'=>$qowner_name, 'VAR_SITENAME'=>$this->CFG['site']['name'], 'VAR_DESCRIPTION_OF_QUESTION'=>$content_description, 'VAR_QUESTION'=>$quesiton_link, 'VAR_LINK'=>$site_link));
				$owner_content = $this->getMailContent($this->LANG['answer_publish_owner_message'], array('VAR_USERNAME'=>$qowner_name, 'VAR_SITENAME'=>$this->CFG['site']['name'], 'VAR_DESCRIPTION_OF_QUESTION'=>$content_description, 'VAR_QUESTION'=>$quesiton_link, 'VAR_LINK'=>$site_link));

				$this->_sendMail($toEmail, $subject, $content, $this->CFG['site']['noreply_name'], $this->CFG['site']['noreply_email']);
				$this->_sendMail($qowner_email, $owner_subject, $owner_content, $this->CFG['site']['noreply_name'], $this->CFG['site']['noreply_email']);
			}

		/**
		 * AnswerFormHandler::deleteAnswers()
		 *
		 * @param mixed $question_name
		 * @param mixed $answers_table
		 * @param mixed $users_ans_log_table
		 * @param mixed $ans_id
		 * @return
		 */
		public function deleteAnswers($question_name, $answers_table, $users_ans_log_table, $ans_id)
		    {
				$this->updateAnswerVideoStatus($this->answer_details['video_id']);
				$this->updateAnswerAudioStatus($this->answer_details['audio_id']);
				$this->updateAnswerVideoStatus($this->answer_details['external_video_id'], 'external_video_id');
				$this->updateAnswerAudioStatus($this->answer_details['external_audio_id'], 'external_audio_id');
				$this->deleteAnswersComment();

				$sql = 'SELECT user_id FROM '.$answers_table.' WHERE ans_id IN ('.$this->dbObj->Param('aid').') AND status !=\'ToActivate\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($ans_id));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						$sql = 'UPDATE '.$users_ans_log_table.' SET total_ans=total_ans-1';
						if($this->CFG['admin']['reply_answers']['allowed'])
							$sql .= ', total_points=total_points-'.$this->CFG['admin']['reply_answers']['points'];
						$sql .= ' WHERE user_id='.$this->dbObj->Param('uid');
						$stmt = $this->dbObj->Prepare($sql);
						$rs_user_log = $this->dbObj->Execute($stmt, array($row['user_id']));
						if (!$rs_user_log)
						        trigger_db_error($this->dbObj);
					}

				$sql = 'DELETE FROM '.$answers_table.' WHERE ans_id IN ('.$this->dbObj->Param('aid').')';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($ans_id));
				if (!$rs)
				        trigger_db_error($this->dbObj);

				if($this->answer_details['status'] == 'ToActivate')
					return ;

				$sql = 'UPDATE '.$question_name.' SET total_answer=total_answer-1 WHERE ques_id IN ('.$this->dbObj->Param('qid').')';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
				        trigger_db_error($this->dbObj);

				//to delete attachments
				if ($this->CFG['admin']['attachments_answers']['allowed'])
					$this->commonDeleteAttachments('Answer', $ans_id);
		    }
		public function deleteAnswersComment()
			{
				$sql = 'DELETE FROM '.$this->CFG['db']['tbl']['question_comment'].
						' WHERE ans_id  IN ('.$this->dbObj->Param('aid').')';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['aid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 * AnswerFormHandler::removeBestAnswer()
		 *
		 * @return
		 */
		public function removeBestAnswer()
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].' SET best_ans_id=0'.
						' WHERE ques_id='.$this->dbObj->Param('qid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($this->dbObj->Affected_Rows())
					{
						$this->decreaseBestAnswerPoints($this->answer_details['user_id']);
					}
			}

		/**
		 * AnswerFormHandler::resolveQuestion()
		 *
		 * @return
		 */
		public function resolveQuestion()
		    {
				#die('here');
				if ($this->question_details['status'] == 'Open')
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].
								' SET status=\'Resolved\', date_closed = NOW()'.
								' WHERE ques_id='.$this->dbObj->Param('qid');
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
						if (!$rs)
						        trigger_db_error($this->dbObj);
					}
				return ;
		    }

		/**
		 * AnswerFormHandler::addAnswer()
		 *
		 * @return
		 */
		public function addAnswer()
		    {
				if ($this->question_details['status'] == 'Open')
					{
						$this->insertAnswer();
						$this->updateQuestion();
						$this->updateUserAnswerLog();
						$this->sendMailToAsker();
					}
		    }

		/**
		 * AnswerFormHandler::insertAnswer()
		 *
		 * @return
		 */
		public function insertAnswer()
		    {
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['answers'].
						' SET user_id='.$this->dbObj->Param('uid').
						', ques_id='.$this->dbObj->Param('qid').
						', answer='.$this->dbObj->Param('answer').
						', source='.$this->dbObj->Param('source').
						', date_answered=NOW()';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id'],
														 $this->fields_arr['qid'],
														 $this->fields_arr['answer'],
														 $this->fields_arr['source']));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				return ;
		    }

		/**
		 * AnswerFormHandler::updateQuestion()
		 *
		 * @return
		 */
		public function updateQuestion()
		    {
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].
						' SET total_answer=total_answer+1'.
						', email_sent=\'No\', date_answered=NOW()'.
						' WHERE ques_id='.$this->dbObj->Param('qid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
				        trigger_db_error($this->dbObj);
		    }

		/**
		 * AnswerFormHandler::updateUserAnswerLog()
		 *
		 * @return
		 */
		public function updateUserAnswerLog()
		    {
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
						' SET total_ans=total_ans+1';
				if($this->CFG['admin']['reply_answers']['allowed'])
					$sql .= ', total_points=total_points+'.$this->CFG['admin']['reply_answers']['points'];
				$sql .=	', date_updated=NOW()'.
						' WHERE user_id='.$this->dbObj->Param('uid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id']));
				if (!$rs)
				        trigger_db_error($this->dbObj);
		    }

		/**
		 * AnswerFormHandler::sendMailToAsker()
		 *
		 * @return
		 */
		public function sendMailToAsker()
		    {
				if ($this->question_details['user_id'] == $this->CFG['user']['user_id'])
						return ;
				$email_options = $this->getEmailOptionsOfUser($this->question_details['user_id']);
				if ($email_options['reply_mail'] == 'Yes'  && !$this->isAnonymsUser($this->question_details['user_id']))
					{
						$asker_details = $this->getUserDetailsFromUsersTable($this->CFG['db']['tbl']['users'], $this->question_details['user_id']);
						$answers_reply_subject = str_ireplace('VAR_USERNAME', $asker_details['display_name'], $this->LANG['answers_reply_email_subject']);
						$answers_reply_subject = str_ireplace('VAR_SENDER_NAME', $this->CFG['user']['display_name'], $answers_reply_subject);
						$receiver_url = getMemberUrl($asker_details['user_id'], $asker_details['name']);
						$answers_reply_content = str_ireplace('VAR_USERNAME', '<a href="'.$receiver_url.'/">'.$asker_details['display_name'].'</a>', $this->LANG['answers_reply_email_content']);
						$sender_url = getMemberUrl($this->CFG['user']['user_id'], $this->CFG['user']['name']);
						$sender_name = '<a href="'.$sender_url.'">'.$this->CFG['user']['display_name'].'</a>';
						$answers_reply_content = str_ireplace('VAR_SENDER_NAME', $sender_name, $answers_reply_content);
						$answers_reply_content = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $answers_reply_content);
						$answers_reply_content = str_ireplace('VAR_QUESTION_ASKED', '<strong>'.$this->question_details['question'].'</strong>', $answers_reply_content);
						$answers_reply_content = str_ireplace('VAR_QUESTION_REPLY', nl2br($this->fields_arr['answer']), $answers_reply_content);
						$question_link = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'], $this->question_details['seo_title'].'/', 'root');
						$answers_reply_content = str_ireplace('VAR_LINK', '<a href="'.$question_link.'">'.$question_link.'</a>', $answers_reply_content);

						$this->_sendMail($asker_details['email'],
										 $answers_reply_subject,
										 $answers_reply_content,
										 $this->CFG['site']['noreply_name'],
										 $this->CFG['site']['noreply_email']);
					}
		    }

		/**
		 * AnswerFormHandler::sendMailToAnswerer()
		 *
		 * @return
		 */
		public function sendMailToAnswerer()
		    {
				#die('here');
				if ($this->question_details['user_id'] != $this->CFG['user']['user_id'])
						return ;

				$answer_details = $this->getAnswerDetails($this->fields_arr['aid']);
				$email_options = $this->getEmailOptionsOfUser($answer_details['user_id']);
				if ($email_options['best_ans_mail'] == 'Yes' && !$this->isAnonymsUser($answer_details['user_id']))
					{
						$answerer_details = $this->getUserDetailsFromUsersTable($this->CFG['db']['tbl']['users'], $answer_details['user_id']);
						$best_answers_subject = str_ireplace('VAR_USERNAME', $answerer_details['display_name'], $this->LANG['best_answer_email_subject']);

						$receiver_url = getMemberUrl($answerer_details['user_id'], $answerer_details['name']);
						$best_answers_content = str_ireplace('VAR_USERNAME', '<a href="'.$receiver_url.'/">'.$answerer_details['display_name'].'</a>', $this->LANG['best_answer_email_content']);
						$sender_url = getMemberUrl($this->CFG['user']['user_id'], $this->CFG['user']['name']);
						$sender_name = '<a href="'.$sender_url.'">'.$this->CFG['user']['display_name'].'</a>';
						$best_answers_content = str_ireplace('VAR_SENDER_NAME', $sender_name, $best_answers_content);
						$best_answers_content = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $best_answers_content);
						$best_answers_content = str_ireplace('VAR_QUESTION_ASKED', '<strong>'.$this->question_details['question'].'</strong>', $best_answers_content);
						$best_answers_content = str_ireplace('VAR_QUESTION_REPLY', nl2br($answer_details['answer']), $best_answers_content);
						$question_link = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'], $this->question_details['seo_title'].'/', 'root');
						$best_answers_content = str_ireplace('VAR_LINK', '<a href="'.$question_link.'">'.$question_link.'</a>', $best_answers_content);

						$this->_sendMail($answerer_details['email'],
										 $best_answers_subject,
										 $best_answers_content,
										 $this->CFG['site']['noreply_name'],
										 $this->CFG['site']['noreply_email']);
					}
		    }

		/**
		 * AnswerFormHandler::getAnswerDetails()
		 *
		 * @param mixed $aid
		 * @return
		 */
		public function getAnswerDetails($aid)
		    {
				$sql = 'SELECT user_id, answer FROM '.$this->CFG['db']['tbl']['answers'].' WHERE ans_id='.$this->dbObj->Param('aid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['aid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				$row = $rs->FetchRow();
				return $row;
		    }

		/**
		 * AnswerFormHandler::sendAbuseMailToAsker()
		 *
		 * @return
		 */
		public function sendAbuseMailToAsker()
		    {
				$email_options = $this->getEmailOptionsOfUser($this->question_details['user_id']);
				if ($email_options['abuse_mail'] == 'Yes' && !$this->isAnonymsUser($this->question_details['user_id']))
					{
						$asker_details = $this->getUserDetailsFromUsersTable($this->CFG['db']['tbl']['users'], $this->question_details['user_id']);
						$abuse_question_subject = str_ireplace('VAR_USERNAME', $asker_details['display_name'], $this->LANG['abuse_question_email_subject']);

						$receiver_url = getMemberUrl($asker_details['user_id'], $asker_details['name']);
						$abuse_question_content = str_ireplace('VAR_USERNAME', '<a href="'.$receiver_url.'/">'.$asker_details['display_name'].'</a>', $this->LANG['abuse_question_email_content']);
						$sender_url = getMemberUrl($this->CFG['user']['user_id'], $this->CFG['user']['name']);
						$sender_name = '<a href="'.$sender_url.'">'.$this->CFG['user']['display_name'].'</a>';
						$abuse_question_content = str_ireplace('VAR_SENDER_NAME', $sender_name, $abuse_question_content);
						$abuse_question_content = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $abuse_question_content);
						$abuse_question_content = str_ireplace('VAR_QUESTION_ASKED', '<strong>'.$this->question_details['question'].'</strong>', $abuse_question_content);
						$question_link = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'], $this->question_details['seo_title'].'/', 'root');
						$abuse_question_content = str_ireplace('VAR_LINK', '<a href="'.$question_link.'">'.$question_link.'</a>', $abuse_question_content);

						$this->_sendMail($asker_details['email'],
										 $abuse_question_subject,
										 $abuse_question_content,
										 $this->CFG['site']['noreply_name'],
										 $this->CFG['site']['noreply_email']);
					}
		    }

		/**
		 * AnswerFormHandler::sendAbuseMailToAnswerer()
		 *
		 * @return
		 */
		public function sendAbuseMailToAnswerer()
		    {
				$email_options = $this->getEmailOptionsOfUser($this->answer_details['user_id']);
				if ($email_options['abuse_mail'] == 'Yes' && !$this->isAnonymsUser($this->answer_details['user_id']))
					{
						$answerer_details = $this->getUserDetailsFromUsersTable($this->CFG['db']['tbl']['users'], $this->answer_details['user_id']);
						$abuse_answers_subject = str_ireplace('VAR_USERNAME', $answerer_details['display_name'], $this->LANG['abuse_answer_email_subject']);

						$receiver_url = getMemberUrl($answerer_details['user_id'], $answerer_details['name']);
						$abuse_answers_content = str_ireplace('VAR_USERNAME', '<a href="'.$receiver_url.'/">'.$answerer_details['display_name'].'</a>', $this->LANG['abuse_answer_email_content']);
						$sender_url = getMemberUrl($this->CFG['user']['user_id'], $this->CFG['user']['name']);
						$sender_name = '<a href="'.$sender_url.'">'.$this->CFG['user']['display_name'].'</a>';
						$abuse_answers_content = str_ireplace('VAR_SENDER_NAME', $sender_name, $abuse_answers_content);
						$abuse_answers_content = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $abuse_answers_content);
						$abuse_answers_content = str_ireplace('VAR_QUESTION_ASKED', '<strong>'.$this->question_details['question'].'</strong>', $abuse_answers_content);
						$abuse_answers_content = str_ireplace('VAR_QUESTION_REPLY', nl2br($this->answer_details['answer']), $abuse_answers_content);
						$question_link = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'], $this->question_details['seo_title'].'/', 'root');
						$abuse_answers_content = str_ireplace('VAR_LINK', '<a href="'.$question_link.'">'.$question_link.'</a>', $abuse_answers_content);

						$this->_sendMail($answerer_details['email'],
										 $abuse_answers_subject,
										 $abuse_answers_content,
										 $this->CFG['site']['noreply_name'],
										 $this->CFG['site']['noreply_email']);
					}
		    }

		/**
		 * AnswerFormHandler::_sendMail()
		 * To send email
		 *
		 * @param 		string $to_email to email id
		 * @param 		string $subject subject
		 * @param		string $body mail body
		 * @param 		string $sender_name sender name
		 * @param 		string $sender_email sender email
		 * @return 		void
		 * @access 		private
		 */
		private function _sendMail($to_email, $subject, $body, $sender_name, $sender_email)
			{
				$this->buildEmailTemplate($subject, $body, false, true);

				$EasySwift = new EasySwift($this->getSwiftConnection());
				$EasySwift->flush();
				$EasySwift->addPart($this->getEmailContent(), "text/html");
				$from_address = $sender_name.'<'.$sender_email.'>';
				return $EasySwift->send($to_email, $from_address, $this->getEmailSubject());
			}

		/**
		 * AnswerFormHandler::updateQuestionVideoStatus()
		 *
		 * @param mixed $video_id
		 * @return
		 */
		public function updateQuestionVideoStatus($video_id)
			{
				if (!$video_id) return ;

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_video'].
						' SET video_status=\'Deleted\''.
						' WHERE video_id='.$this->dbObj->Param($video_id);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($video_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 * AnswerFormHandler::updateQuestionAudioStatus()
		 *
		 * @param mixed $audio_id
		 * @return
		 */
		public function updateQuestionAudioStatus($audio_id)
			{
				if (!$audio_id) return ;

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_audio'].
						' SET audio_status=\'Deleted\''.
						' WHERE audio_id='.$this->dbObj->Param($audio_id);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($audio_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 * AnswerFormHandler::updateAnswerVideoStatus()
		 *
		 * @param mixed $video_id
		 * @return
		 */
		public function updateAnswerVideoStatus($video_id, $video_field='video_id')
			{
				if (!$video_id) return ;

				#die('here12');
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_video'].
						' SET video_status=\'Deleted\''.
						' WHERE video_id='.$this->dbObj->Param($video_id);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($video_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				if($this->dbObj->Affected_Rows())
					{
						$sql = 'SELECT content_id FROM '.$this->CFG['db']['tbl']['ans_video'].
								' WHERE video_id='.$this->dbObj->Param($video_id);

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($video_id));
						    if (!$rs)
							    trigger_db_error($this->dbObj);

						$row = $rs->FetchRow();

						$sql = 'UPDATE '.$this->CFG['db']['tbl']['answers'].' SET '.$video_field.'=0'.
								' WHERE ans_id='.$this->dbObj->Param('ans_id');

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($row['content_id']));
						    if (!$rs)
							    trigger_db_error($this->dbObj);

						$sql = 'SELECT ques_id FROM '.$this->CFG['db']['tbl']['answers'].' WHERE'.
								' ans_id='.$this->dbObj->Param('ans_id');

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($row['content_id']));
						    if (!$rs)
							    trigger_db_error($this->dbObj);

						$row = $rs->FetchRow();

						$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].' SET'.
								' total_videos=total_videos-1 WHERE'.
								' ques_id='.$this->dbObj->Param('ques_id').
								' AND total_videos>0';

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($row['ques_id']));
						    if (!$rs)
							    trigger_db_error($this->dbObj);
					}
			}

		/**
		 * AnswerFormHandler::updateAnswerAudioStatus()
		 *
		 * @param mixed $audio_id
		 * @return
		 */
		public function updateAnswerAudioStatus($audio_id, $audio_field='audio_id')
			{
				if (!$audio_id) return ;

				#die('here');
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_audio'].
						' SET audio_status=\'Deleted\''.
						' WHERE audio_id='.$this->dbObj->Param($audio_id);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($audio_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				if($this->dbObj->Affected_Rows())
					{
						$sql = 'SELECT content_id FROM '.$this->CFG['db']['tbl']['ans_audio'].
								' WHERE audio_id='.$this->dbObj->Param($audio_id);

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($audio_id));
						    if (!$rs)
							    trigger_db_error($this->dbObj);

						$row = $rs->FetchRow();

						$sql = 'UPDATE '.$this->CFG['db']['tbl']['answers'].' SET '.$audio_field.'=0'.
								' WHERE ans_id='.$this->dbObj->Param('ans_id');

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($row['content_id']));

						$sql = 'SELECT ques_id FROM '.$this->CFG['db']['tbl']['answers'].' WHERE'.
								' ans_id='.$this->dbObj->Param('ans_id');

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($row['content_id']));
						    if (!$rs)
							    trigger_db_error($this->dbObj);

						$row = $rs->FetchRow();

						$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].' SET'.
								' total_audios=total_audios-1 WHERE'.
								' ques_id='.$this->dbObj->Param('ques_id').
								' AND total_audios>0';

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($row['ques_id']));
						    if (!$rs)
							    trigger_db_error($this->dbObj);
					}
			}

		 /**
		  * AnswerFormHandler::fetchMoreAttachments()
		  *
		  * @return
		  */
		 public function fetchMoreAttachments()
			{
				if (!$this->repliesArray) return ;

				$fetchMoreAttachments_arr = array();
				$inc = 1;
				$fetchMoreAttachments_arr['row'] = array();
				foreach($this->repliesArray as $row)
					{
						$fetchMoreAttachments_arr['row'][$inc]['anchor'] = 'replyQues'.$row['attachment_id'];

						$row['date_added'] = ($row['date_added'] != '') ? $this->getTimeDiffernceFormat($row['date_added']) : '';
						$extern = strtolower(substr($row['attachment_name'], strrpos($row['attachment_name'], '.')+1));
						$attachment_file_name = getImageName($row['attachment_id']).$this->CFG['admin']['ans_pictures']['thumb_name'].'.'.$extern;
						$attachment_original_file_name = getImageName($row['attachment_id']).$this->CFG['admin']['ans_pictures']['large_name'].'.'.$extern;

						$fetchMoreAttachments_arr['row'][$inc]['img_id'] = $row['content_type'].'_'.$row['content_id'].'_'.$row['attachment_id'];
						$fetchMoreAttachments_arr['row'][$inc]['attachment_path'] = $this->CFG['site']['relative_url'].'viewAnswers.php?qid='.$this->getFormField('qid').'&imgdetail='.$fetchMoreAttachments_arr['row'][$inc]['img_id'];
						$fetchMoreAttachments_arr['row'][$inc]['gallery'] = $row['gallary'];
						$fetchMoreAttachments_arr['row'][$inc]['attachment_name'] = $row['attachment_name'];
						$fetchMoreAttachments_arr['row'][$inc]['image_path'] = $row['photo_server_url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$attachment_file_name;
						$fetchMoreAttachments_arr['row'][$inc]['image_large_path'] = $row['photo_server_url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$attachment_original_file_name;
						$fetchMoreAttachments_arr['row'][$inc]['attachment_file_name'] = getImageName($row['attachment_id']).$this->CFG['admin']['ans_pictures']['large_name'].'.'.$extern;
		                $fetchMoreAttachments_arr['row'][$inc]['record'] = $row;
		                $inc++;
					}
				return $fetchMoreAttachments_arr;
			}

		/**
		 * AnswerFormHandler::hasMoreAttachments()
		 *
		 * @param mixed $mainAnswer_id
		 * @param string $type
		 * @return
		 */
		public function hasMoreAttachments($mainAnswer_id, $type='Question')
			{
				$sql = 'SELECT attachment_id, attachment_name, photo_server_url, content_id, content_type, CONCAT(\''.$type.'_\',content_id) as gallary, UNIX_TIMESTAMP(date_added) AS date_added'.
						' FROM '.$this->CFG['db']['tbl']['attachments'].' AS bc'.
						' WHERE content_id='.$this->dbObj->Param('qid').
						' AND content_type='.$this->dbObj->Param($type).
						' ORDER BY attachment_id';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($mainAnswer_id, $type));
				if (!$rs)
				    trigger_db_error($this->dbObj);

				$this->repliesArray = array();
				while($row = $rs->FetchRow()){
					$this->repliesArray[] = $row;
				}
				return $this->repliesArray;
			}

		/**
		 * AnswerFormHandler::deleteMoreAttachments()
		 *
		 * @param mixed $aid
		 * @param mixed $attach_name
		 * @return
		 */
		public function deleteMoreAttachments($aid, $attach_name)
			{
				$sql = 'DELETE FROM '.$this->CFG['db']['tbl']['attachments'].
						' WHERE attachment_id='.$this->dbObj->Param('info_id');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($aid));
				    if (!$rs)
					    trigger_db_error($this->dbObj);

				$attachment_file1 = '../../'.$this->CFG['admin']['ans_attachments_path'].$attach_name;
				$explode_attach = explode('.',$attach_name);
				$r_attach = substr($explode_attach[0], 0, -1);
				$req_attach = $r_attach.$this->CFG['admin']['ans_pictures']['small_name'].'.'.$explode_attach[1];
				$attachment_file2 = '../../'.$this->CFG['admin']['ans_attachments_path'].$req_attach;
				unlink($attachment_file1);
				unlink($attachment_file2);
			}

		/**
		 * AnswerFormHandler::updateDeletedQuestionsTagCount()
		 *
		 * @param mixed $tags
		 * @return
		 */
		public function updateDeletedQuestionsTagCount($tags)
			{
				$tags_arr = explode(' ', $tags);
				foreach($tags_arr as $tagname)
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['tags'].
							' SET total_count=total_count-1'.
							' WHERE tag_name='.$this->dbObj->Param($tagname);
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($tagname));
						if (!$rs)
					    		trigger_db_error($this->dbObj);
					}
			}

		public function getCommentDetails($comment_id)
			{
				$sql = 'SELECT comment from '.$this->CFG['db']['tbl']['question_comment'].''.
				       ' WHERE comment_id = '.$comment_id;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
		    		trigger_db_error($this->dbObj);
				while($row = $rs->FetchRow())
					{
						return $row['comment'];
					}

			}

		public function updateComment($comment_id)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['question_comment'].
							' SET comment = \''.$this->getFormField('user_comment').'\''.
							' WHERE comment_id='.$comment_id;
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt);
						if (!$rs)
					    		trigger_db_error($this->dbObj);
			}

	   public function 	populateAjaxCommentList($comment_id)
			{
				global $smartyObj, $LANG,$CFG ;
				$sql = 'SELECT user_id, ans_id, comment_id, comment, DATE_FORMAT(date_added, \''.$this->CFG['mysql_format']['date_time'].'\') AS date_added'.
				        ' FROM  '.$this->CFG['db']['tbl']['question_comment'].
				        ' WHERE comment_id = '.$comment_id;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
		    		trigger_db_error($this->dbObj);
				$populateAjaxCommentList_arr = array();
				$inc = 0;
				while($row = $rs->FetchRow())
					{
						$row['comment'] = nl2br(wordWrapManual($row['comment'], 60));
						//$row['comment'] = html_entity_decode($row['comment'], ENT_QUOTES);
						$populateAjaxCommentList_arr[$inc]['record'] = $row;
						$populateAjaxCommentList_arr[$inc]['user_details'] = $this->getUserDetails($row['user_id']);
						$populateAjaxCommentList_arr[$inc]['myanswers']['url'] = $this->CFG['site']['url'].'admin/viewMembers.php?uid='.$populateAjaxCommentList_arr[$inc]['user_details']['user_id'];

						$populateAjaxCommentList_arr[$inc]['msg'] = 'msg_'.$row['ans_id'];
						$populateAjaxCommentList_arr[$inc]['commentSpanIDId'] = 'commentSpanID_'.$row['comment_id'];
						$inc++;
					}
			  if($this->getFormField('success') == 'success')
				  $smartyObj->assign('success','success');
			  else
				  $smartyObj->assign('success','');
  			  $smartyObj->assign('LANG',$LANG);
			  $smartyObj->assign('myobj',$this);
			  $smartyObj->assign('CFG',$CFG);
			  $smartyObj->assign('populateAjaxCommentList_arr',$populateAjaxCommentList_arr);
			  setTemplateFolder('admin/');
			  $smartyObj->display('commentAnswersAjaxList.tpl');
			}

		public function deleteComment($comment_id)
			{
				$sql = 'DELETE from '.$this->CFG['db']['tbl']['question_comment'].''.
				       ' WHERE comment_id = '.$comment_id;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
				    trigger_db_error($this->dbObj);
			}
	}
//<<<<<-------------- Class AnswerFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$answers = new AnswerFormHandler();
$questions->left_navigation_div = 'anovaAnswers';
$answers->setPageBlockNames(array('form_search', 'form_add', 'form_abuse_question', 'form_abuse_answer', 'form_confirm', 'form_question', 'form_answers', 'form_best_answer', 'show_option_to_comment', 'cancel_option_to_comment', 'post_your_comment'));

//default form fields and values...
$answers->setFormField('qid', '');
$answers->setFormField('aid', '');
$answers->setFormField('viid', '');
$answers->setFormField('auid', '');
$answers->setFormField('search_name', '');
$answers->setFormField('search_cat', '');
$answers->setFormField('answer', '');
$answers->setFormField('source', '');
$answers->setFormField('action', '');
$answers->setFormField('act', '');
$answers->setFormField('reason', '');
$answers->setFormField('str', '');
$answers->setFormField('msg', '');
$answers->setFormField('attachments', '');
$answers->setFormField('attachment_id', '');
$answers->setFormField('attach_content_id', '');
$answers->setFormField('attachment_name', '');
$answers->setFormField('comment_id', '');
$answers->setFormField('c_qid', '');
$answers->setFormField('user_comment', '');
$answers->setFormField('success', '');
$answers->setFormField('imgdetail', '');
$answers->setFormField('w', '');
$answers->setFormField('h', '');
/*************Start navigation******/
$answers->numpg = $CFG['data_tbl']['numpg'];
$answers->setFormField('start', 0);
$answers->setFormField('numpg', $CFG['data_tbl']['numpg']);//

$answers->setMinRecordSelectLimit($CFG['data_tbl']['min_record_select_limit']);
$answers->setMaxRecordSelectLimit($CFG['data_tbl']['max_record_select_limit']);
$answers->setNumPerPageListArr($CFG['data_tbl']['numperpage_list_arr']);
//Set tables and fields to return
$answers->setTableNames(array());
$answers->setReturnColumns(array());
//orderby field and orderby
$answers->setFormField('orderby_field', '');
$answers->setFormField('orderby', '');
/*************End navigation******/

$answers->sanitizeFormInputs($_REQUEST);
if ($answers->isFormGETed($_REQUEST, 'imgdetail'))
	{
		$answers->includeAjaxHeader();
		if ($answers->chkIsValidQuestion())
			{
				$answers->displayImageGallery($answers->getFormField('imgdetail'), true);
			}
		$answers->includeAjaxFooter();
		die();
	}
if ($answers->isFormPOSTed($_REQUEST, 'showOptionToComment'))
	{
		ob_start();
		$answers->sanitizeFormInputs($_REQUEST);
		$showOptionToComment_arr = array();
		$comment_id = $answers->getFormField('comment_id');
		$commentSpanIDId = 'commentSpanID_'.$answers->getFormField('comment_id');
		$showOptionToComment_arr['comment']['details'] = $answers->getCommentDetails($answers->getFormField('comment_id'));
		$showOptionToComment_arr['submit']['onclick'] = $CFG['site']['url'].'admin/viewAnswers.php?success=success&qid='.$answers->getFormField('qid').'&action=view&ajax_page=true&postYourComment=1&comment_id='.$answers->getFormField('comment_id');
		$showOptionToComment_arr['cancel']['onclick'] = $CFG['site']['url'].'admin/viewAnswers.php?qid='.$answers->getFormField('qid').'&action=view&ajax_page=true&cancelOptionToComment=1&comment_id='.$answers->getFormField('comment_id');
		$answers->setPageBlockShow('show_option_to_comment');
		$answers->includeAjaxHeader();
		$smartyObj->assign('showOptionToComment_arr', $showOptionToComment_arr);
		$smartyObj->assign('comment_id', $comment_id);
		$smartyObj->assign('commentSpanIDId', $commentSpanIDId);
		setTemplateFolder('admin/');
		$smartyObj->display('commentAnswersAjax.tpl');
		//$smartyObj->display('replyBugsAjax.tpl');
		$answers->includeAjaxFooter();
		die();
	}
if ($answers->isFormPOSTed($_REQUEST, 'cancelOptionToComment'))
	{
		ob_start();
		$answers->sanitizeFormInputs($_REQUEST);
		$answers->setPageBlockShow('cancel_option_to_comment');
		$answers->populateAjaxCommentList($answers->getFormField('comment_id'));
		$answers->includeAjaxHeader();
		setTemplateFolder('admin/');
		$smartyObj->display('commentAnswersAjax.tpl');
		$answers->includeAjaxFooter();
		die();
	}
if ($answers->isFormPOSTed($_REQUEST, 'postYourComment'))
	{
		ob_start();
		$answers->sanitizeFormInputs($_REQUEST);
		$answers->updateComment($answers->getFormField('comment_id'));

		$answers->setFormField('success', $answers->getFormField('success'));
		$answers->setCommonSuccessMsg($LANG['answers_comment_edited_successfully']);
		$answers->setPageBlockShow('block_msg_form_success');
		$answers->populateAjaxCommentList($answers->getFormField('comment_id'));
		$answers->includeAjaxHeader();
		setTemplateFolder('admin/');
		$smartyObj->display('commentAnswersAjax.tpl');
		$answers->includeAjaxFooter();
		die();
		//Redirect2URL($CFG['site']['url'].'admin/viewAnswers.php?msg=5&qid='.$answers->getFormField('c_qid'));
	}
// Default page block
$answers->setAllPageBlocksHide();
$answers->updateQuestionViews();
#$answers->setPageBlockShow('form_search');
$answers->title = $LANG['open_question'];
$title_image = 'open_question';
if ($answers->chkIsValidQuestion())
	{
		if ($answers->isFormPOSTed($_REQUEST, 'deletemoreattachments'))
			{
				if (!isMember())
					{
						echo 'Session Expired. <a href="'.$CFG['auth']['login_url'].'?r">Login to continue..!</a>';
						die();
					}
				ob_start();

				$comment_id = $answers->getFormField('attachment_id');
				$attachment_name = $answers->getFormField('attachment_name');
				$answers->deleteMoreAttachments($comment_id, $attachment_name);

			}

		if ($answers->question_details['status'] == 'Resolved')
			{
				$answers->title = $LANG['resolved_question'];
				$title_image = 'resolved_question';
			}
		else
			{
				$answers->title = $LANG['open_question'];
				$title_image = 'open_question';
			}

		$answers->setPageBlockShow('form_question');
		$answers->setPageBlockShow('form_answers');
		$answers->hidden_array = array();
		if ($answers->isFormGETed($_GET, 'action'))
			{
				switch($answers->getFormField('action'))
					{
						case 'reply':
							if ($answers->question_details['status'] == 'Open')
								{
									$answers->setPageBlockHide('form_question');
									$answers->setPageBlockHide('form_answers');
									$answers->setPageBlockShow('form_add');
									$answers->title = $LANG['what_is_your_answer'];
									$title_image = 'what_is_your_answer';
								}
							else
								{
									$answers->setPageBlockShow('block_msg_form_error');
									$answers->setCommonErrorMsg($LANG['answers_err_not_open']);
								}
							break;

						case 'abusequestion':
							if ($answers->isValidFormInputs() AND $answers->question_details['user_id'] != $CFG['user']['user_id'])
								{
									$answers->setPageBlockHide('form_question');
									$answers->setPageBlockHide('form_answers');
									$answers->setPageBlockShow('form_abuse_question');
									$answers->title = $LANG['report_abuse'];
									$title_image = 'report_abuse';
								}
							else
								{
									$answers->setAllPageBlocksHide();
									$answers->setPageBlockShow('block_msg_form_error');
									$answers->setCommonErrorMsg($LANG['err_tip_invalid_action']);
								}
							break;
						case 'abuseanswer':
							if ($answers->isValidFormInputs() AND $answers->answer_details['user_id'] != $CFG['user']['user_id'])
								{
									$answers->setPageBlockHide('form_question');
									$answers->setPageBlockHide('form_answers');
									$answers->setPageBlockShow('form_abuse_answer');
									$$answers->title = $LANG['report_abuse'];
									$title_image = 'report_abuse';
								}
							else
								{
									$answers->setAllPageBlocksHide();
									$answers->setPageBlockShow('block_msg_form_error');
									$answers->setCommonErrorMsg($LANG['err_tip_invalid_action']);
								}
							break;

						case 'edit':
							$answers->chkIsNotEmpty('aid', $LANG['err_tip_compulsory']);
							if ($answers->isValidFormInputs())
								{
									$answers->action = 'delete_answer';
									$answers->hidden_array = array('aid');
									$answers->confirm_message = $LANG['confirm_delete_message'];
									$answers->setPageBlockShow('form_confirm');
								}
							else
								{
									$answers->setAllPageBlocksHide();
									$answers->setPageBlockShow('block_msg_form_error');
									$answers->setPageBlockShow('form_question');
									$answers->setPageBlockShow('form_answers');
									$answers->setCommonErrorMsg($LANG['err_tip_invalid_action']);
								}
							break;
					} // switch
			}
	if ($answers->isFormPOSTed($_POST, 'delete_add'))
		{
			switch($answers->getFormField('act'))
				{
					case 'delete':
						$answers->chkIsNotEmpty('aid', $LANG['err_tip_compulsory']);
						$ans_array = explode(',',$answers->getFormField('aid'));
						foreach($ans_array as $value)
							{
								if ($answers->chkIsValidAnswer($value) and $answers->isValidFormInputs())
									{
										$answers->deleteAnswers($CFG['db']['tbl']['questions'], $CFG['db']['tbl']['answers'], $CFG['db']['tbl']['users_ans_log'], $value);
									}
							}
						$answers->setPageBlockShow('block_msg_form_success');
						$answers->setCommonSuccessMsg($LANG['answers_deleted_successfully']);

						break;
					case 'deleteQuestion':
						$answers->deleteQuestion();
						Redirect2URL($CFG['site']['relative_url'].'manageAnswers.php?delmsg=1');
						break;
					case 'deleteQuestionVideo':
						$answers->deleteQuestionVideo('video_id');
						Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=delquesvideo');
						break;
					case 'deleteQuestionAudio':
						$answers->deleteQuestionAudio('audio_id');
						Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=delquesaudio');
						break;
					case 'deleteQuestion_ExtVideo':
						$answers->deleteQuestionVideo('external_video_id');
						Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=delquesextvideo');
						break;
					case 'deleteQuestion_ExtAudio':
						$answers->deleteQuestionAudio('external_audio_id');
						Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=delquesextaudio');
						break;
					case 'deletevideo':
						$answers->chkIsNotEmpty('aid', $LANG['err_tip_compulsory']);
						if ($answers->isValidFormInputs())
							{
								$answers->updateAnswerVideoStatus($answers->getFormField('aid'));
								$answers->setPageBlockShow('block_msg_form_success');
								$answers->setCommonSuccessMsg($LANG['common_video_deleted']);
							}
						else
							{
								$answers->setCommonErrorMsg($LANG['common_msg_error_sorry']);
								$answers->setPageBlockShow('block_msg_form_error');
							}
						break;
					case 'deleteaudio':
						$answers->chkIsNotEmpty('aid', $LANG['err_tip_compulsory']);
						if ($answers->isValidFormInputs())
							{
								$answers->updateAnswerAudioStatus($answers->getFormField('aid'));
								$answers->setPageBlockShow('block_msg_form_success');
								$answers->setCommonSuccessMsg($LANG['common_audio_deleted']);
							}
						else
							{
								$answers->setCommonErrorMsg($LANG['common_msg_error_sorry']);
								$answers->setPageBlockShow('block_msg_form_error');
							}
						break;
					case 'deleteExtvideo':
						$answers->updateAnswerVideoStatus($answers->getFormField('aid'), 'external_video_id');
						$answers->setPageBlockShow('msg_form_success');
						$answers->setCommonErrorMsg($LANG['successfully_external_video_deleted']);
						break;
					case 'deleteExtaudio':
						$answers->updateAnswerAudioStatus($answers->getFormField('aid'), 'external_audio_id');
						$answers->setPageBlockShow('msg_form_success');
						$answers->setCommonErrorMsg($LANG['successfully_external_audio_deleted']);
						break;
					case 'deleteBestAnswer':
						if ($answers->chkIsValidAnswer($answers->getFormField('aid')) and $answers->isValidFormInputs())
							$answers->removeBestAnswer();
						$answers->setPageBlockShow('block_msg_form_success');
						$answers->setCommonSuccessMsg($LANG['best_answers_deleted_successfully']);
						Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=removebestans');
						break;
					case 'deleteAnswer':
						if ($answers->chkIsValidAnswer($answers->getFormField('aid')) and $answers->isValidFormInputs())
							{
								$answers->deleteAnswers($CFG['db']['tbl']['questions'], $CFG['db']['tbl']['answers'], $CFG['db']['tbl']['users_ans_log'], $answers->getFormField('aid'));
								$answers->removeBestAnswer();
							}
						$answers->setPageBlockShow('block_msg_form_success');
						$answers->setCommonSuccessMsg($LANG['answers_deleted_successfully']);
						Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=deleteans');
						break;
					case 'bestanswer':
						$answers->chkIsNotEmpty('aid', $LANG['err_tip_compulsory']);
						if ($answers->isValidFormInputs()  AND $answers->question_details['best_ans_id'] == 0)
							{
								$answers->updateBestAnswer();
								$answers->setPageBlockShow('block_msg_form_success');
								$answers->setPageBlockShow('form_question');
								$answers->setPageBlockShow('form_answers');
								$answers->setCommonSuccessMsg($LANG['answers_best_answer_added_successfully']);
								Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=addbestanswer');
							}
						else
							{
								$answers->setCommonErrorMsg($LANG['common_msg_error_sorry']);
								$answers->setPageBlockShow('block_msg_form_error');
							}
						break;
					case 'publishanswer':
						$answers->chkIsNotEmpty('aid', $LANG['err_tip_compulsory']);
						if ($answers->isValidFormInputs() AND $answers->question_details['status'] == 'Open' AND $answers->question_details['publish_status'] == 'No')
							{
								$answers->publishAnswer();
								$answers->setPageBlockShow('block_msg_form_success');
								$answers->setPageBlockShow('form_question');
								$answers->setPageBlockShow('form_answers');
								$answers->setCommonSuccessMsg($LANG['answers_published_successfully']);
								Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=published');
							}
						else
							{
								$answers->setCommonErrorMsg($LANG['common_msg_error_sorry']);
								$answers->setPageBlockShow('block_msg_form_error');
							}
						break;
					case 'resolve':
						$answers->resolveQuestion();
						$answers->question_details['status'] = 'Resolved';
						$answers->setPageBlockShow('block_msg_form_success');
						$answers->setCommonSuccessMsg($LANG['answers_resolved_successfully']);
						Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=resolved');
						break;
					case 'deletecomment':
						$comment_id = $answers->getFormField('comment_id');
						$answers->deleteComment($comment_id);
						$answers->setPageBlockShow('block_msg_form_success');
						$answers->setCommonSuccessMsg($LANG['answers_resolved_successfully']);
						Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=resolved');
						break;

				}
		}
	if ($answers->isFormPOSTed($_POST, 'abuse_question'))
		{
			$answers->chkIsNotEmpty('reason', $LANG['err_tip_compulsory']);
			if ($answers->isValidFormInputs() and $answers->question_details['user_id'] != $CFG['user']['user_id'])
				{
					$answers->updateAbuseQuestion();
					$answers->setPageBlockShow('block_msg_form_success');
					$answers->setPageBlockShow('form_question');
					$answers->setPageBlockShow('form_answers');
					$answers->setCommonSuccessMsg($LANG['answers_question_abused_successfully']);
					Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=2');
				}
			else
				{
					$answers->setCommonErrorMsg($LANG['common_msg_error_sorry']);
					$answers->setPageBlockShow('block_msg_form_error');
				}
		}
	if ($answers->isFormPOSTed($_POST, 'abuse_answer'))
		{
			$answers->chkIsNotEmpty('reason', $LANG['err_tip_compulsory']);
			if ($answers->isValidFormInputs() and $answers->answer_details['user_id'] != $CFG['user']['user_id'])
				{
					$answers->updateAbuseAnswer();
					$answers->setPageBlockShow('block_msg_form_success');
					$answers->setPageBlockShow('form_question');
					$answers->setPageBlockShow('form_answers');
					$answers->setCommonSuccessMsg($LANG['answers_answer_abused_successfully']);
					Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=3');
				}
			else
				{
					$answers->setCommonErrorMsg($LANG['common_msg_error_sorry']);
					$answers->setPageBlockShow('block_msg_form_error');
				}
		}
	if ($answers->isFormPOSTed($_POST, 'submit'))
		{
			$answers->chkIsNotEmpty('answer', $LANG['err_tip_compulsory']);
			if ($answers->question_details['status'] != 'Open')
				{
					$answers->setPageBlockShow('block_msg_form_error');
					$answers->setCommonErrorMsg($LANG['answers_err_not_open']);
				}
			if ($answers->isValidFormInputs())
				{
					$answers->addAnswer();
					$answers->setCommonSuccessMsg($LANG['answers_added_successfully']);
					$answers->setPageBlockShow('block_msg_form_success');
					Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid').'&msg=1');
				}
			else
				{
					$answers->setCommonErrorMsg($LANG['common_msg_error_sorry']);
					$answers->setPageBlockShow('block_msg_form_error');
				}
		}
	if ($answers->isFormPOSTed($_POST, 'cancel'))
		{
			Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$answers->getFormField('qid'));
		}
	if ($answers->isFormGETed($_GET, 'msg'))
		{
			switch($answers->getFormField('msg'))
				{
					case 2:
						$answers->setCommonSuccessMsg($LANG['answers_question_abused_successfully']);
						break;
					case 3:
						$answers->setCommonSuccessMsg($LANG['answers_answer_abused_successfully']);
						break;
					case 4:
						$answers->setCommonSuccessMsg($LANG['answers_question_edited_successfully']);
						break;
					case 5:
						$answers->setCommonSuccessMsg($LANG['answers_comment_edited_successfully']);
						break;
					case 'removebestans':
						$answers->setCommonSuccessMsg($LANG['best_answers_deleted_successfully']);
						break;
					case 'deleteans':
						$answers->setCommonSuccessMsg($LANG['answers_deleted_successfully']);
						break;
					case 'resolved':
						$answers->setCommonSuccessMsg($LANG['answers_resolved_successfully']);
						break;
					case 'delquesvideo':
						$answers->setCommonSuccessMsg($LANG['question_video_deleted_successfully']);
						break;
					case 'delquesaudio':
						$answers->setCommonSuccessMsg($LANG['question_audio_deleted_successfully']);
						break;
					case 'delquesextvideo':
						$answers->setCommonErrorMsg($LANG['successfully_external_video_deleted']);
						break;
					case 'delquesextaudio':
						$answers->setCommonErrorMsg($LANG['successfully_external_audio_deleted']);
						break;
					case 'addbestanswer':
						$answers->setCommonSuccessMsg($LANG['answers_best_answer_added_successfully']);
						break;
					case 'published':
						$answers->setCommonSuccessMsg($LANG['answers_published_successfully']);
						break;
					default:
						$answers->setCommonSuccessMsg($LANG['answers_added_successfully']);
						break;
				} // switch
			$answers->setPageBlockShow('block_msg_form_success');
		}
	}
else
	{
		$answers->setCommonErrorMsg($LANG['common_msg_error_sorry']);
		$answers->setPageBlockShow('block_msg_form_error');
	}
//<<<<<<<---------------code ends-------------///
if ($answers->isShowPageBlock('form_question'))
	{
		$answers->form_question['delete_hidden_arr'] = array();
		$answers->form_question['attach_style'] = '';
		$answers->form_question['attach_hidden_arr'] = array('start','qid');
	}

if ($answers->isShowPageBlock('form_search'))
	{
		$answers->form_search['search_cat_arr'] = array("1" => $LANG['login_user_name'], "2" => $LANG['search_type_email'],
													"3" => $LANG['open_questions'], "4" => $LANG['common_resolved_questions'],
													"5" => $LANG['search_type_blocked'], "6" => $LANG['questions'],
													"7" => $LANG['search_type_tags'], "8" => $LANG['categories']);
	}

if ($answers->isShowPageBlock('form_question'))
	{
		$answers->form_question['displayQuestionDetails_arr'] = $answers->displayQuestionDetails();
	}

if ($answers->isShowPageBlock('form_answers'))
	{
		$answers->setTableNames(array($CFG['db']['tbl']['answers'].' as a', $CFG['db']['tbl']['users'].' as u'));
		$answers->setReturnColumns(array('a.ans_id, a.user_id, a.answer, a.video_id, a.external_video_id, a.external_audio_id, a.ques_id, a.status, a.audio_id, a.source, a.votes, a.abuse_count, UNIX_TIMESTAMP(date_answered) as date_answered'.
						', u.'.$answers->getUserTableField('user_id').' as img_user_id, '.$answers->getUserTableFields(array('image_path', 'gender', 't_height', 't_width','photo_server_url', 'photo_ext'), false).$answers->getUserTableField('display_name').' as answered_by'));

		$answers->setFormField('orderby_field', 'a.ans_id');
		$answers->setFormField('orderby', 'DESC');
		$answers->buildSelectQuery();
		$answers->buildConditionQuery();
		$answers->buildSortQuery();
		$answers->buildQuery();
		#$answers->printQuery();
		$answers->executeQuery();
		$answers->form_answers['displayAllAnswers_arr'] = $answers->displayAllAnswers();

		if ($answers->isResultsFound())
			{
				$answers->form_answers['pagingArr'] = array();
				if ($answers->getFormField('qid'))
					$answers->form_answers['pagingArr'] = array('qid');

				$smartyObj->assign('smarty_paging_list', $answers->populatePageLinksGET($answers->getFormField('start'), $answers->form_answers['pagingArr']));
				$answers->form_answers['confirm_delete'] = nl2br($answers->LANG['confirm_delete_message']);
			}
	}
$answers->confirm['hidden_arr1'] = array('comment_id');
//--------------------Page block templates begins-------------------->>>>>//
//include the header file
$answers->includeHeader();
//include the content of the page
setTemplateFolder('admin/', $CFG['admin']['index']['anova_module']);
$smartyObj->display('viewAnswers.tpl');
?>
<script type="text/javascript" language="javascript">
	var block_arr= new Array('selMsgConfirm','selMsgConfirm1', 'selDelAttachconfirm', 'lightwindow_contents');

	function showdiv(divid)
		{
			document.getElementById[divid].style.display = '';
		}
	function chkMessage(message,form)
		{
			var comm = document.getElementById(message).value
			if(comm=='' || comm == null)
				{
					alert_manual("<?php echo $LANG['enter_proper_message'];?>");
				}
			else
				return 0;

		}
	function checkifAlreadyOpen()
		{
			 var a = document.getElementsByTagName("textarea").length;
			 if(a > 0)
			 	{
					alert_manual('<?php echo $LANG['close_previous'];?>');
					return false;
				}
			return true;
		}

</script>
<?php
//<<<<<<<<<---------Page block template ends--------------------------//
$answers->includeFooter();
?>
