<?php
set_time_limit(0);
//-------------- Class AnswerFormHandler begins --------------->>>>>//
/**
 *
 * @category	###Visual Answers###
 * @package		###answers###
 * @author 		shankar_76ag08
 * @copyright	Copyright (c) 2010 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id:  $
 * @since 		2008-12-19
 */
class AnswerFormHandler extends VideoUploadLib
	{
		public $question_details = array();
		public $question_attachmentsArray = array();
		public $answer_attachment_count = 0;
		public $_dir_path = '../';
		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function chkIsValidQuestion()
		    {
				$this->chkIsNotEmpty('title', $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.total_answer, q.votes, q.pcat_id, q.cat_id, q.best_ans_id, q.description, q.total_stars, q.tags, q.total_views, q.publish_status, q.question, UNIX_TIMESTAMP(date_asked) as date_asked'.
						', q.video_id, q.external_video_id, q.audio_id, q.external_audio_id, '.$this->getUserTableField('display_name').' as asked_by, u.'.$this->getUserTableField('user_id').' as img_user_id,'.$this->getUserTableFields(array('t_height', 'name', 't_width', 's_height', 's_width','photo_server_url', 'photo_ext')).' , '.$this->getUserTableFields(array('image_path', 'gender'), false).'q.status, q.user_id'.
						', IF(status=\'Open\' AND date_closed>=NOW(), 1, 0) is_open, TIMEDIFF(date_closed, NOW()) as date_closed'.
						', q.total_videos, q.total_audios, q.seo_title 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 q.status IN (\'Open\', \'Resolved\')'.
						' AND u.'.$this->getUserTableField('usr_status').'=\'Ok\' AND q.seo_title='.$this->dbObj->Param('title');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['title']));
				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();
				$this->fields_arr['qid'] = $this->question_details['ques_id'];
				$this->fields_arr['seo_title'] = $this->question_details['seo_title'];
				$this->question_details['total_allowed_answers'] = $this->question_details['total_answer'];
				$this->previous_arr = $this->showAnotherQuestion();
				$this->next_arr = $this->showAnotherQuestion(1);
				return true;
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function chkIsValidAnswer()
		    {
				$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.user_id, a.answer, a.source, a.video_id, a.external_video_id, a.audio_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($this->fields_arr['aid']));
				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;
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function displayBestAnswer()
		    {
				if ($this->question_details['best_ans_id'])
					{
						$displayBestAnswer_arr = array();
						$sql = 'SELECT a.ans_id, a.user_id, a.votes, a.answer, a.video_id, a.external_video_id, a.audio_id, a.external_audio_id, a.source, UNIX_TIMESTAMP(date_answered) as date_answered'.
								', u.'.$this->getUserTableField('user_id').' as img_user_id, '.$this->getUserTableFields(array('image_path', 'gender', 't_height', 't_width', 's_height', 's_width','photo_server_url', 'photo_ext', 'name'), 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();
						$displayBestAnswer_arr['best_ans_id'] = $this->question_details['best_ans_id'];

						$displayBestAnswer_arr['record'] = $row;
						$displayBestAnswer_arr['populateCommentList'] = $this->populateCommentList($this->question_details['best_ans_id']);
						$displayBestAnswer_arr['row_answer_manual'] = nl2br(wordWrapManual($row['answer'], $this->CFG['admin']['answer']['line_length']));
						$displayBestAnswer_arr['ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Answer_'.$row['video_id'], '?pg=Answer_'.$row['video_id']);
						$displayBestAnswer_arr['ans_view_video']['on_click'] = 'best_video_'.$displayBestAnswer_arr['best_ans_id'];
						$displayBestAnswer_arr['ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Answer_'.$row['audio_id'], '?pg=Answer_'.$row['audio_id']);
						$displayBestAnswer_arr['ans_view_audio']['on_click'] = 'best_audio_'.$displayBestAnswer_arr['best_ans_id'];
				        $displayBestAnswer_arr['row_source_manual'] = nl2br(wordWrapManual($row['source'], $this->CFG['admin']['answer']['line_length']));
						$displayBestAnswer_arr['myanswers']['url'] = getMemberUrl($row['user_id'], $row['name']);
						$displayBestAnswer_arr['row_answered_by_manual'] = stripString($row['answered_by'], $this->CFG['username']['short_length']);
				        if (chkExternalVideoAllowed('answer') and $row['external_video_id'])
							{
				        		$displayBestAnswer_arr['ext_ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Answer_'.$row['external_video_id'], '?pg=Answer_'.$row['external_video_id']);
				        		$displayBestAnswer_arr['ext_ans_view_video']['on_click'] = 'ext_video_add_best_'.$displayBestAnswer_arr['best_ans_id'];
				        	}
				        if (chkExternalAudioAllowed('answer') and $row['external_audio_id'])
							{
					        	$displayBestAnswer_arr['ext_ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Answer_'.$row['external_audio_id'], '?pg=Answer_'.$row['external_audio_id']);
					        	$displayBestAnswer_arr['ext_ans_view_audio']['on_click'] = 'ext_audio_add_best_'.$displayBestAnswer_arr['best_ans_id'];
					        }
						$displayBestAnswer_arr['facebook_user_details'] = '';
						if ($this->CFG['admin']['module']['facebook'])
							{
								$displayBestAnswer_arr['facebook_user_details'] = $this->fetchFacebookUserDetails($this->question_details['best_ans_id']);
							}

						$displayBestAnswer_arr['has_attachment'] = false;
						if ($this->CFG['admin']['attachments_answers']['allowed'] AND $this->hasMoreAttachments($this->question_details['best_ans_id'], 'Answer'))
							{
								$displayBestAnswer_arr['has_attachment'] = true;
								$displayBestAnswer_arr['attachment_count'] = count($this->repliesArray);
								$extern = strtolower(substr($this->repliesArray[0]['attachment_name'], strrpos($this->repliesArray[0]['attachment_name'], '.')+1));
								$attachment_original_file_name = getImageName($this->repliesArray[0]['attachment_id']).$this->CFG['admin']['ans_pictures']['large_name'].'.'.$extern;
								$displayBestAnswer_arr['img_id'] = 'Answer_'.$this->question_details['best_ans_id'].'_'.$this->repliesArray[0]['attachment_id'];
								$displayBestAnswer_arr['attachment_path'] = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'].'&amp;imgdetail='.$displayBestAnswer_arr['img_id'], $this->fields_arr['seo_title'].'/?imgdetail='.$displayBestAnswer_arr['img_id']);
								$displayBestAnswer_arr['image_large_path'] = $this->repliesArray[0]['photo_server_url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$attachment_original_file_name;
							}

						return $displayBestAnswer_arr;
					}
				return false;
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function showAnotherQuestion($next='')
		    {
				$condition = '<';
				$orderby = 'DESC';
				$caption = $this->LANG['common_paging_previous'];
				$clsNoBorder = '';
				$content_arr = array();
				$showAnotherQuestion_val = '';
				if($next)
					{
						$caption = $this->LANG['common_paging_next'];
						$condition = '>';
						$orderby = 'ASC';
						$clsNoBorder = 'clsNoBorder';
					}

				$sql = 'SELECT ques_id, seo_title FROM '.$this->CFG['db']['tbl']['questions'].
						' WHERE ques_id'.$condition.$this->dbObj->Param('qid');
				if ($this->question_details['is_open'])
					$sql .= ' AND status=\'Open\' AND date_closed>=NOW()';
				else
					$sql .= ' AND (status NOT IN(\'Blocked\',\'ToActivate\') AND date_closed<NOW())';

				$sql .= ' ORDER BY ques_id '.$orderby.' 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())
					{
						$row = $rs->FetchRow();
						$showAnotherQuestion_val = '<p class="'.$clsNoBorder.'"><a href="'.getAnovaUrl('answer', '?title='.$row['seo_title'], $row['seo_title'].'/').'">'.$caption.'</a></p>';
						$content_arr['class'] = $clsNoBorder;
						$content_arr['url'] = '<a href="'.getAnovaUrl('answer', '?title='.$row['seo_title'], $row['seo_title'].'/').'">'.$caption.'</a>';
					}
				else
					{
						$showAnotherQuestion_val = '<p class="'.$clsNoBorder.'">'.$caption.'</p>';
						$content_arr['class'] = $clsNoBorder;
						$content_arr['url'] = '<span>'.$caption.'</span>';
					}

				return $content_arr;
		    }

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function isQuestionOpen()
			{
				return ($this->question_details['is_open'])?true:false;
			}

		/**
		 * AnswerFormHandler::incrementViews()
		 *
		 * @return
		 */
		public function incrementViews()
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].
						' SET total_views=total_views+1, latest_viewed=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);
			}


		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function displayQuestionDetails()
		    {
				//To display open and resolved questions

				if (!$this->question_details)
					return false;

				$this->overRideConfigs(false);
				$displayQuestionDetails_arr = array();

				$displayQuestionDetails_arr['video_plural'] = $this->LANG['video'];
				$displayQuestionDetails_arr['audio_plural'] = $this->LANG['common_total_audio'];
				$displayQuestionDetails_arr['answer_plural'] = $this->LANG['common_total_answer'];
				$displayQuestionDetails_arr['views_plural'] = $this->LANG['common_total_view'];
				$displayQuestionDetails_arr['audio_class'] = 'clsNoBorder';
				$displayQuestionDetails_arr['video_class'] = '';
				$displayQuestionDetails_arr['bestAnsClass'] = '';

				if($this->question_details['total_videos']!= 1) $displayQuestionDetails_arr['video_plural'] = $this->LANG['common_total_videos'];
				if($this->question_details['total_audios']!= 1) $displayQuestionDetails_arr['audio_plural'] = $this->LANG['common_total_audios'];
				if($this->question_details['total_answer']!= 1) $displayQuestionDetails_arr['answer_plural'] = $this->LANG['answers'];
				if($this->question_details['total_views']!= 1) $displayQuestionDetails_arr['views_plural'] = $this->LANG['common_total_views'];
				if($this->question_details['video_id'])	$displayQuestionDetails_arr['video_class'] = 'clsNoBorder';
				if($this->question_details['audio_id'])	$displayQuestionDetails_arr['video_class'] = '';
				if($this->question_details['best_ans_id'])	$displayQuestionDetails_arr['bestAnsClass'] = 'clsBestAnswerQuestion';

				$video_audio_count = '';
				$video_audio_count .= (chkIsVideoAllowed('answer') OR chkExternalVideoAllowed('answer'))?$this->question_details['total_videos'].' '.$displayQuestionDetails_arr['video_plural'].' | ':'';
				$video_audio_count .= (chkIsAudioAllowed('answer') OR chkExternalAudioAllowed('answer'))?$this->question_details['total_audios'].' '.$displayQuestionDetails_arr['audio_plural'].' | ':'';
				$video_audio_count = substr($video_audio_count, 0, strrpos($video_audio_count, '|'));
				$video_audio_count = trim($video_audio_count);
				$video_audio_count = $video_audio_count?'('.$video_audio_count.')':'';
				$displayQuestionDetails_arr['video_audio_count'] = $video_audio_count;

				$common_answer_url = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/', 'members');

				$displayQuestionDetails_arr['replySpanQuesIDId'] = 'replySpanQuesID_'.$this->question_details['ques_id'];
				$displayQuestionDetails_arr['viewSpanQuesId'] = 'viewSpanQuesId'.$this->question_details['ques_id'];
				$displayQuestionDetails_arr['selReplyQuesId'] = 'selReplyQuesId'.$this->question_details['ques_id'];
				$displayQuestionDetails_arr['selViewReplyQuesId'] = 'selViewReplyQuesId'.$this->question_details['ques_id'];
				$this->question_details['image_id'] = 'questions';

				$displayQuestionDetails_arr['has_attachment'] = false;
				if ($this->CFG['admin']['attachments_questions']['allowed'] AND $this->hasMoreAttachments($this->question_details['ques_id']))
					{
						$displayQuestionDetails_arr['has_attachment'] = true;
						$displayQuestionDetails_arr['attachment_count'] = count($this->repliesArray);
						$extern = strtolower(substr($this->repliesArray[0]['attachment_name'], strrpos($this->repliesArray[0]['attachment_name'], '.')+1));
						$attachment_original_file_name = getImageName($this->repliesArray[0]['attachment_id']).$this->CFG['admin']['ans_pictures']['large_name'].'.'.$extern;
						$displayQuestionDetails_arr['img_id'] = 'Question_'.$this->question_details['ques_id'].'_'.$this->repliesArray[0]['attachment_id'];
						$displayQuestionDetails_arr['attachment_path'] = getAnovaUrl('answer', '?title='.$this->question_details['seo_title'].'&amp;imgdetail='.$displayQuestionDetails_arr['img_id'], $this->question_details['seo_title'].'/?imgdetail='.$displayQuestionDetails_arr['img_id']);
						$displayQuestionDetails_arr['image_large_path'] = $this->repliesArray[0]['photo_server_url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$attachment_original_file_name;
					}

				$displayQuestionDetails_arr['question_manual'] = wordWrapManual($this->question_details['question'], 45);
				$displayQuestionDetails_arr['ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Question_'.$this->question_details['video_id'], '?pg=Question_'.$this->question_details['video_id']);
				$displayQuestionDetails_arr['ans_view_video']['on_click'] = 'ques_video_'.$this->getFormField('qid');

				$displayQuestionDetails_arr['ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Question_'.$this->question_details['audio_id'], '?pg=Question_'.$this->question_details['audio_id']);
				$displayQuestionDetails_arr['ans_view_audio']['on_click'] = 'ques_audio_'.$this->getFormField('qid');

  				$displayQuestionDetails_arr['ext_ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Question_'.$this->question_details['external_video_id'], '?pg=Question_'.$this->question_details['external_video_id']);
  				$displayQuestionDetails_arr['ext_ans_view_video']['on_click'] = 'external_video_ques_'.$this->getFormField('qid');
				$displayQuestionDetails_arr['ext_ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Question_'.$this->question_details['external_audio_id'], '?pg=Question_'.$this->question_details['external_audio_id']);
				$displayQuestionDetails_arr['ext_ans_view_audio']['on_click'] = 'external_audio_ques_'.$this->getFormField('qid');

				$displayQuestionDetails_arr['description_manual'] = nl2br(wordWrapManual($this->question_details['description'], $this->CFG['admin']['description']['line_length']));

	          	$displayQuestionDetails_arr['tags'] = $this->question_details['tags'];
	          	$displayQuestionDetails_arr['tags_array'] = explode(' ', $this->question_details['tags']);

	          	$displayQuestionDetails_arr['row'] = array();
	          	$inc=0;
          		foreach($displayQuestionDetails_arr['tags_array'] as $tagAnsPg_arr)
					{
						$displayQuestionDetails_arr['row'][$inc]['url']	=	getAnovaUrl('questions','?view=search&amp;tags='.$tagAnsPg_arr, 'search/?tags='.$tagAnsPg_arr);
						$displayQuestionDetails_arr['row'][$inc]['tag']	=	$tagAnsPg_arr;
						$inc++;
					}

				$displayQuestionDetails_arr['anchor'] = 'resolve';

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

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

          		$displayQuestionDetails_arr['myanswers']['url'] = getMemberUrl($this->question_details['user_id'], $this->question_details['name']);
				$displayQuestionDetails_arr['asked_by_manual'] = stripString($this->question_details['asked_by'], $this->CFG['username']['short_length']);

				$displayQuestionDetails_arr['answer']['url'] = getAnovaUrl('answer', '?action=view&title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/');

				$displayQuestionDetails_arr['email_answers']['url'] = getAnovaUrl('emailanswers', '?title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/');

				$displayQuestionDetails_arr['answer_member']['url'] = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/', 'members');

				$displayQuestionDetails_arr['favorite_answers']['url'] = getAnovaUrl('favoriteanswers');

				$displayQuestionDetails_arr['login_answer_member']['url'] = getUrl('login', '?light_url='.$displayQuestionDetails_arr['answer_member']['url'], '?light_url='.$displayQuestionDetails_arr['answer_member']['url']);

				$displayQuestionDetails_arr['questions_member']['url'] = getAnovaUrl('questions', '?view=ask&amp;cid='.$this->fields_arr['qid'], 'ask/'.$this->fields_arr['qid'].'/', 'members');

				$displayQuestionDetails_arr['questionBadgeUrl'] = getQuestionBadgeUrl($this->fields_arr['qid']);

				if ($displayQuestionDetails_arr['questionBadgeUrl'])
					{
						$displayQuestionDetails_arr['badgeUrlWithoutScript'] = getQuestionBadgeUrl($this->fields_arr['qid'], false);
						$displayQuestionDetails_arr['badgeUrlWithoutScript'] .= ($this->CFG['feature']['rewrite_mode']== 'htaccess')?('?content=2'):('&amp;content=2');
						$displayQuestionDetails_arr['answers_badge_embed_hint'] = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $this->LANG['answers_badge_embed_hint']);
					}

				if ($this->CFG['admin']['question']['ratings'])
					{
						$displayQuestionDetails_arr['question_url'] = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/');

						$displayQuestionDetails_arr['getQuestionRatings'] = $this->getQuestionRatings($this->CFG['db']['tbl']['users_stared_question'],
																								$this->CFG['db']['tbl']['questions'],
																								$this->fields_arr['qid'],
																								$this->question_details['user_id'],
																								$this->CFG['site']['project_path_relative'],
																								$this->CFG['site']['relative_url'],
																								$displayQuestionDetails_arr['question_url']);
						$displayQuestionDetails_arr['payQuestionRatings'] = false;
						if(chkIsPaymentAlertMessageAllowed() and chkIsPaymentAllowed('payment_questions'))
							{
								if(!$this->CFG['admin']['paymentmodule']['rate_ques'])
									{
										$displayQuestionDetails_arr['payQuestionRatings'] = true;
										$displayQuestionDetails_arr['getQuestionRatings']['payment_alert_url'] = getAnovaUrl('paymentalertwindow', '?msg=rateques', '?msg=rateques', 'root');
									}
							}
					}

				$displayQuestionDetails_arr['displayBestAnswer'] = $this->displayBestAnswer();
				$displayQuestionDetails_arr['login_answer_reply']['url'] = '';
				if ($this->isQuestionOpen())
					{
						if ($this->question_details['user_id'] != $this->CFG['user']['user_id'])
							{
								$displayQuestionDetails_arr['onclick_action'] = '';
								if ($this->CFG['user']['user_id'])
									$displayQuestionDetails_arr['onclick_action'] = 'onClick="Effect.toggle(\'subAnsPostForm\', \'BLIND\'); return false;"';
								$answer_reply_url = getAnovaUrl('replyanswer', '?action=reply&amp;title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/', 'members');
								$displayQuestionDetails_arr['answer_reply']['url'] = $answer_reply_url;
								$displayQuestionDetails_arr['login_answer_reply']['url'] = getUrl('login', '?light_url='.$common_answer_url, '?light_url='.$common_answer_url, 'root');
								if ($this->question_details['total_answer'])
									{
										$displayQuestionDetails_arr['submit_answer_text'] = $this->LANG['answers_this_question'];

									}
								else
									{
										$displayQuestionDetails_arr['submit_answer_text'] = $this->LANG['be_the_first_one'];
									}
							}
				}

				$upgrade = '<a href="'.getAnovaUrl('paymentupgrade').'">'.$this->LANG['answers_upgrade'].'</a>';
				if(!chkIsPaymentUpgradeAllowed())
					$upgrade = $this->LANG['inform_site_admin'];

				$this->LANG['info_limit_exceeded_to_ask_questions'] = str_ireplace('VAR_UPGRADE', $upgrade, $this->LANG['info_limit_exceeded_to_ask_questions']);
				$this->LANG['info_limit_exceeded_to_view_answers'] = str_ireplace('VAR_UPGRADE', $upgrade, $this->LANG['info_limit_exceeded_to_view_answers']);
				$this->LANG['info_limit_exceeded_to_view_bestanswer'] = str_ireplace('VAR_UPGRADE', $upgrade, $this->LANG['info_limit_exceeded_to_view_bestanswer']);
				$this->LANG['info_limit_login_to_view_bestanswer'] = str_ireplace('VAR_LOGIN', '<a href="'.$displayQuestionDetails_arr['login_answer_reply']['url'].'" class="lightwindow">'.$this->LANG['login'].'</a>' ,$this->LANG['info_limit_login_to_view_bestanswer']);
				$this->LANG['info_limit_login_to_view_answer'] = str_ireplace('VAR_LOGIN', '<a href="'.$displayQuestionDetails_arr['login_answer_reply']['url'].'" class="lightwindow">'.$this->LANG['login'].'</a>' ,$this->LANG['info_limit_login_to_view_answer']);
				$this->LANG['info_limit_signup_to_view_answer'] = str_ireplace('VAR_SIGNUP', '<a href="'.getUrl('signup', '', '', 'root').'">'.$this->LANG['signup'].'</a>' ,$this->LANG['info_limit_signup_to_view_answer']);
				$this->LANG['info_login_to_post_answer'] =  str_ireplace('VAR_LOGIN', '<a id="ques_answer" href="'.$displayQuestionDetails_arr['login_answer_member']['url'].'"  onclick="'.$this->getBrowser('ques_answer').'">'.$this->LANG['login'].'</a>' ,$this->LANG['info_login_to_post_answer']);

				return $displayQuestionDetails_arr;
		    }

		/**
		 * AnswerFormHandler::postAnswersForm()
		 *
		 * @param mixed $for
		 * @return
		 */
		public function postAnswersForm($for)
			{
				global $smartyObj;
				if(chkIsPaymentAllowed('payment_answers'))
					$this->overRideConfigs();

				$postAnswersForm_arr = array();
				$postAnswersForm_arr['for'] = $for;
				$postAnswersForm_arr['style_add_video'] = $postAnswersForm_arr['style_add_external_video'] = '';
				$postAnswersForm_arr['style_delete_video'] = $postAnswersForm_arr['style_delete_external_video'] = 'style="display:none"';
				$postAnswersForm_arr['style_preview_video'] = $postAnswersForm_arr['style_preview_external_video'] = 'style="display:none"';
				$postAnswersForm_arr['video_preview']['url'] = $postAnswersForm_arr['default_video_preview']['url'] = getAnovaUrl('anspreviewvideo', '?pg=Answer_'.$this->getFormField('rid'), '?pg=Answer_'.$this->getFormField('rid'));
				$postAnswersForm_arr['external_video_onclick'] = 'return showVideoExternalPreview();';
				$postAnswersForm_arr['external_video_preview']['url'] = $this->getCurrentUrl();

				if($this->fields_arr['video'] or $this->fields_arr['video_id'])
					{
						$postAnswersForm_arr['style_delete_video'] = '';
						$postAnswersForm_arr['style_preview_video'] = '';
						$postAnswersForm_arr['style_add_video'] = 'style="display:none"';
						if ($this->fields_arr['video_id'])
							$postAnswersForm_arr['video_preview']['url'] = getAnovaUrl('ansviewvideo', '?pg=Answer_'.$this->getFormField('video_id'), '?pg=Answer_'.$this->getFormField('video_id'));
						if ($this->fields_arr['video'])
							$postAnswersForm_arr['video_preview']['url'] = getAnovaUrl('anspreviewvideo', '?pg=Answer_'.$this->getFormField('video'), '?pg=Answer_'.$this->getFormField('video'));
					}
				if($this->fields_arr['video_external_flv_url'] or $this->fields_arr['file_extern'] or $this->fields_arr['external_video_id'])
					{
						$postAnswersForm_arr['style_delete_external_video'] = '';
						$postAnswersForm_arr['style_preview_external_video'] = '';
						$postAnswersForm_arr['style_add_external_video'] = 'style="display:none"';

						if (!$this->fields_arr['video_external_flv_url'] AND !$this->fields_arr['file_extern'])
							{
								if ($this->fields_arr['external_video_id'] AND $external_video_details = $this->getExternalVideoDetails($this->fields_arr['external_video_id']))
									{
										if ($external_video_details['video_status'] == 'Ok' AND $external_video_details['video_encoded_status'] == 'Yes')
											{
												$postAnswersForm_arr['external_video_onclick'] = getBrowser('video');
												$postAnswersForm_arr['external_video_preview']['url']= getAnovaUrl('ansviewvideo', '?pg=Answer_'.$this->getFormField('external_video_id'), '?pg=Answer_'.$this->getFormField('external_video_id'));
											}
									}
							}
					}
				$postAnswersForm_arr['style_add_audio'] = $postAnswersForm_arr['style_add_external_audio'] = '';
				$postAnswersForm_arr['style_delete_audio'] = $postAnswersForm_arr['style_delete_external_audio'] = 'style="display:none"';
				$postAnswersForm_arr['style_preview_audio'] = $postAnswersForm_arr['style_preview_external_audio'] = 'style="display:none"';
				$postAnswersForm_arr['audio_preview']['url'] = $postAnswersForm_arr['default_audio_preview']['url'] = getAnovaUrl('anspreviewaudio', '?pg=Answer_'.$this->getFormField('rid'), '?pg=Answer_'.$this->getFormField('rid'));
				$postAnswersForm_arr['external_audio_onclick'] = 'return showAudioExternalPreview();';
				$postAnswersForm_arr['external_audio_preview']['url'] = $this->getCurrentUrl();

				if($this->fields_arr['audio'] or $this->fields_arr['audio_id'])
					{
						$postAnswersForm_arr['style_delete_audio'] = '';
						$postAnswersForm_arr['style_preview_audio'] = '';
						$postAnswersForm_arr['style_add_audio'] = 'style="display:none"';
						if ($this->fields_arr['audio_id'])
							$postAnswersForm_arr['audio_preview']['url'] = getAnovaUrl('ansviewaudio', '?pg=Answer_'.$this->getFormField('audio_id'), '?pg=Answer_'.$this->getFormField('audio_id'));
						if ($this->fields_arr['audio'])
							$postAnswersForm_arr['audio_preview']['url']  = getAnovaUrl('anspreviewaudio', '?pg=Answer_'.$this->getFormField('audio'), '?pg=Answer_'.$this->getFormField('audio'));
					}
				if($this->fields_arr['audio_external_url'] or $this->fields_arr['audio_extern'] or $this->fields_arr['external_audio_id'])
					{
						$postAnswersForm_arr['style_delete_external_audio'] = '';
						$postAnswersForm_arr['style_preview_external_audio'] = '';
						$postAnswersForm_arr['style_add_external_audio'] = 'style="display:none"';

						if (!$this->fields_arr['audio_external_url'] AND !$this->fields_arr['audio_extern'])
							{
								if ($this->fields_arr['external_audio_id'] AND $external_audio_details = $this->getExternalAudioDetails($this->fields_arr['external_audio_id']))
									{
										if ($external_audio_details['audio_status'] == 'Ok' AND $external_audio_details['audio_encoded_status'] == 'Yes')
											{
												$postAnswersForm_arr['external_audio_onclick'] = getBrowser('audio', 'height');
												$postAnswersForm_arr['external_audio_preview']['url'] = getAnovaUrl('ansviewaudio', '?pg=Answer_'.$this->getFormField('external_audio_id'), '?pg=Answer_'.$this->getFormField('external_audio_id'));
											}
									}
							}
					}

				if($this->CFG['admin']['answers']['point_notification'] && $this->CFG['admin']['reply_answers']['allowed'] && !$this->fields_arr['aid'])
					{
						$postAnswersForm_arr['earn_points_details_info'] = str_ireplace('VAR_POINTS', $this->CFG['admin']['reply_answers']['points'], $this->LANG['earn_points_details_info']);
					}

				$postAnswersForm_arr['form_action'] = getAnovaUrl('replyanswer', '?action=reply&amp;title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/', 'members');
			    //$askQuestions_arr['populateHidden_arr'] = array('rid', 'video', 'video_external_flv_url', 'flv_upload_type', 'file_extern', 'audio', 'audio_external_url', 'audio_extern', 'video_id', 'external_video_id', 'audio_id', 'external_audio_id', 'old_category', 'old_sub_category');
				$postAnswersForm_arr['hidden_arr'] = array('rid', 'video', 'video_id', 'external_video_id', 'video_external_flv_url', 'flv_upload_type', 'file_extern', 'audio', 'audio_id', 'external_audio_id', 'audio_external_url', 'audio_extern');
				$postAnswersForm_arr['question_manual'] = wordWrapManual($this->question_details['question'], $this->CFG['admin']['question']['line_length']);

				$postAnswersForm_arr['getAttachments'] = '';
				if ($this->fields_arr['aid'])
					{
						if($this->CFG['admin']['attachments_answers']['allowed'])
							$postAnswersForm_arr['getAttachments'] = $this->getAttachments();
					}

				$postAnswersForm_arr['allowed_formats'] = implode(",",$this->CFG['admin']['attachments']['format_arr']);
				if($postAnswersForm_arr['allowed_formats'] == '')
					$postAnswersForm_arr['allowed_formats'] = 'jpg,gif,png';
				$allowed_size = $this->CFG['admin']['attachments']['max_size'];
				$postAnswersForm_arr['allowed_size'] = str_ireplace('VAR_SIZE', $allowed_size, $this->LANG['attachment_size_tip']);
				$postAnswersForm_arr['attach_style'] = '';

				if($this->answer_attachment_count == $this->CFG['admin']['attachments_allowed']['count'])
					$postAnswersForm_arr['attach_style'] = 'style="display:none;"';

		  		if(chkIsAllowedModule(array('payment')))
					{
						if(chkIsPaymentAllowed('payment_picture') && !$this->fields_arr['aid'])
							$this->fields_arr['picturelimit'] = $this->CFG['plan']['plan_picture_post_count'];
						else if(chkIsPaymentAllowed('payment_picture') && $this->fields_arr['aid'])
						{
						  	$this->fields_arr['picturelimit'] = $this->CFG['plan']['plan_picture_post_count'] - $this->answer_attachment_count;
						}
						else
							$this->fields_arr['picturelimit'] = $this->CFG['admin']['attachments_allowed']['count'];

						if($this->fields_arr['picturelimit'] == $this->CFG['plan']['unlimited'])
							$this->fields_arr['picturelimit'] = $this->CFG['admin']['attachments_allowed']['count'];
					}
				else
					{
						$this->fields_arr['picturelimit'] = $this->CFG['admin']['attachments_allowed']['count'];
				  	}

				$postAnswersForm_arr['attachments_allowed_manual'] = str_ireplace('VAR_COUNT', $this->fields_arr['picturelimit'] ,$this->LANG['attachment_allowed_tip']);

		  		$postAnswersForm_arr['allowed_formats_manual'] = str_ireplace('VAR_FORMAT', $postAnswersForm_arr['allowed_formats'], $this->LANG['attachment_format_tip']);

				if (chkIsVideoAllowed('answer'))
					{
						if(chkIsAllowedModule(array('payment')))
							{
								if(isset($this->CFG['admin']['paymentmodule']['video']) AND $this->CFG['admin']['paymentmodule']['video'])
									$postAnswersForm_arr['video_upload']['url'] = getAnovaUrl('videoupload', '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);
								else
									$postAnswersForm_arr['video_upload']['url'] = getAnovaUrl('paymentalertwindow', '?msg=video', '?msg=video', 'root');
							}
						else
							$postAnswersForm_arr['video_upload']['url'] = getAnovaUrl('videoupload', '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);
					}
				if (chkExternalVideoAllowed('answer'))
					{
						if(chkIsAllowedModule(array('payment')))
							{
								if(isset($this->CFG['admin']['paymentmodule']['video']) AND $this->CFG['admin']['paymentmodule']['video'])
									$postAnswersForm_arr['external_video_upload']['url'] = getAnovaUrl('externalvideoupload', '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);
								else
									$postAnswersForm_arr['external_video_upload']['url'] = getAnovaUrl('paymentalertwindow', '?msg=video', '?msg=video', 'root');
							}
						else
							$postAnswersForm_arr['external_video_upload']['url'] = getAnovaUrl('externalvideoupload', '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);
					}
				if (chkIsAudioAllowed('answer'))
					{
						if(chkIsAllowedModule(array('payment')))
							{
								if(isset($this->CFG['admin']['paymentmodule']['audio']) AND $this->CFG['admin']['paymentmodule']['audio'])
									$postAnswersForm_arr['audio_upload']['url'] = getAnovaUrl('audioupload', '?rid='.$this->fields_arr['rid'].'AUD', '?rid='.$this->fields_arr['rid'].'AUD');
								else
									$postAnswersForm_arr['audio_upload']['url'] = getAnovaUrl('paymentalertwindow', '?msg=audio', '?msg=audio', 'root');
							}
						else
							$postAnswersForm_arr['audio_upload']['url'] = getAnovaUrl('audioupload', '?rid='.$this->fields_arr['rid'].'AUD', '?rid='.$this->fields_arr['rid'].'AUD');
					}
				if (chkExternalAudioAllowed('answer'))
					{
						if(chkIsAllowedModule(array('payment')))
							{
								if(isset($this->CFG['admin']['paymentmodule']['audio']) AND $this->CFG['admin']['paymentmodule']['audio'])
									$postAnswersForm_arr['external_audio_upload']['url'] = getAnovaUrl('externalaudioupload', '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);
								else
									$postAnswersForm_arr['external_audio_upload']['url'] = getAnovaUrl('paymentalertwindow', '?msg=audio', '?msg=audio', 'root');
							}
						else
							$postAnswersForm_arr['external_audio_upload']['url'] = getAnovaUrl('externalaudioupload', '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);
					}

				if(chkIsPaymentAlertMessageAllowed() and chkIsPaymentAllowed('payment_answers'))
					{
						$req_count = $this->getPlanLogForAnswer();
						$req_today_count = $this->getPlanLogForAnswerPerDay();
						$req_count = $req_count < 0?'0':$req_count;
						$req_today_count = $req_today_count < 0?'0':$req_today_count;

						if($req_count === $this->CFG['plan']['unlimited_text'])
							$postAnswersForm_arr['total_notify'] = $this->CFG['plan']['unlimited_text'];
						elseif(chkIsPaymentUpgradeAllowed())
						  {
							$postAnswersForm_arr['total_notify'] = str_ireplace('VAR_LIMIT', $req_count, $this->LANG['total_notify_upgrade']);
							$postAnswersForm_arr['total_notify'] = str_ireplace('VAR_UPGRADE', '<a href="'.getAnovaUrl('paymentupgrade', '', '', 'members').'">'.$this->LANG['answers_upgrade'].'</a>', $postAnswersForm_arr['total_notify']);
						  }
						else
							$postAnswersForm_arr['total_notify'] = str_ireplace('VAR_LIMIT', $req_count, $this->LANG['total_notify_admin']);

						if($req_today_count === $this->CFG['plan']['unlimited_text'])
							$postAnswersForm_arr['today_notify'] = $this->CFG['plan']['unlimited_text'];
						elseif(chkIsPaymentUpgradeAllowed())
						  {
							$postAnswersForm_arr['today_notify'] = str_ireplace('VAR_LIMIT', $req_today_count, $this->LANG['today_notify_upgrade']);
							$postAnswersForm_arr['today_notify'] = str_ireplace('VAR_UPGRADE', '<a href="'.getAnovaUrl('paymentupgrade', '', '', 'members').'">'.$this->LANG['answers_upgrade'].'</a>', $postAnswersForm_arr['today_notify']);
						  }
						else
							$postAnswersForm_arr['today_notify'] = str_ireplace('VAR_LIMIT', $req_today_count, $this->LANG['today_notify_admin']);

					}

				$smartyObj->assign('postAnswersForm_arr', $postAnswersForm_arr);
				setTemplateFolder('members/', $this->CFG['admin']['index']['anova_module']);
				$smartyObj->display('postAnswersForm.tpl');

			}

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

				if($this->question_details['user_id'] != $this->CFG['user']['user_id'])
						$this->sql_condition .= ' AND a.status=\'Active\'';

				if ($this->CFG['admin']['ignore_user'])
					{
						$this->sql_condition .= ' AND NOT EXISTS (SELECT 1 FROM '.$this->CFG['db']['tbl']['user_ignored'].' AS ui WHERE ui.user_id='.$this->CFG['user']['user_id'].' AND ui.ignored_id=a.user_id)';
					}

				if(chkIsAllowedModule(array('payment')) && chkIsPaymentAllowed('payment_answers'))
					{
						$last_answer_id = $this->getLastAnswer();
						$cond = $this->fields_arr['orderby']=='DESC'?'>=':'<=';
						if($last_answer_id)
							$this->sql_condition .= ' AND a.ans_id'.$cond.$last_answer_id;
					}
			}

		/**
		 * To sort the query
		 *
		 * @access public
		 * @return void
		 **/
		public function buildSortQuery()
			{
				$this->sql_sort = $this->fields_arr['orderby_field'].' '.$this->fields_arr['orderby'];
			}

		public function getLastAnswer()
			{
				$total_allowed_answers = $this->question_details['total_answer']-$this->CFG['plan']['plan_viewans_perques'];
				$total_allowed_answers = $total_allowed_answers<0?'0':$total_allowed_answers;
				$this->question_details['total_allowed_answers'] = $total_allowed_answers;

				$upgrade = '<a href="'.getAnovaUrl('paymentupgrade').'">'.$this->LANG['answers_upgrade'].'</a>';
				if(!chkIsPaymentUpgradeAllowed())
					$upgrade = $this->LANG['inform_site_admin'];
				$this->LANG['upgrade_answers_msg'] = str_ireplace('VAR_UPGRADE', $upgrade, $this->LANG['upgrade_answers_msg']);

				$sql = 'SELECT a.ans_id 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=\''.addslashes($this->fields_arr['qid']).'\' AND a.ans_id!=\''.addslashes($this->question_details['best_ans_id']).'\'';

				if($this->question_details['user_id'] != $this->CFG['user']['user_id'])
						$sql .= ' AND a.status=\'Active\'';

				if ($this->CFG['admin']['ignore_user'])
					{
						$sql .= ' AND NOT EXISTS (SELECT 1 FROM '.$this->CFG['db']['tbl']['user_ignored'].' AS ui WHERE ui.user_id='.$this->CFG['user']['user_id'].' AND ui.ignored_id=a.user_id)';
					}
				$sql .= ' ORDER BY '.$this->fields_arr['orderby_field'].' '.$this->fields_arr['orderby'];
				if(is_numeric($this->CFG['plan']['plan_viewans_perques']))
					$sql .= ' LIMIT '.$this->CFG['plan']['plan_viewans_perques'];

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

				if ($rs->PO_RecordCount())
					{
						while($row = $rs->FetchRow())
							{
								$last_answer_id = $row['ans_id'];
							}
						return $last_answer_id;
					}
				return false;
			}
		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function displayAllAnswers()
			{
				//Query to display recent and popular questions
				if (!$this->isResultsFound())
					{
						return ;
					}
				$displayAllAnswers_arr = array();
				$id_cnt = $this->fields_arr['start'];
				$i = 0;
				$inc=1;
				while($row = $this->fetchResultRecord())
					{
						$i++;
						$displayAllAnswers_arr[$inc]['record'] = $row;
						$displayAllAnswers_arr[$inc]['clsOddOrEvenQuestion'] = 'clsEvenQuestion';
						if ($i%2)
							$displayAllAnswers_arr[$inc]['clsOddOrEvenQuestion'] = 'clsOddQuestion';
						$displayAllAnswers_arr[$inc]['anchor'] = 'abuseAnswer'.$row['ans_id'];
						$displayAllAnswers_arr[$inc]['ansId'] = $row['ans_id'];
						$displayAllAnswers_arr[$inc]['ans_votes']['on_click_plus'] = 'ans_vote_plus'.$row['ans_id'];
						$displayAllAnswers_arr[$inc]['ans_votes']['on_click_minus'] = 'ans_vote_minus'.$row['ans_id'];
						$displayAllAnswers_arr[$inc]['populateCommentList'] = $this->populateCommentList($row['ans_id']);
						$displayAllAnswers_arr[$inc]['row_answer_manual'] = nl2br(wordWrapManual($row['answer'], $this->CFG['admin']['answer']['line_length']));
		        		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']);
								$displayAllAnswers_arr[$inc]['ans_view_video']['on_click'] = 'ans_video_'.$displayAllAnswers_arr[$inc]['ansId'];

		        			}
		        		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']);
								$displayAllAnswers_arr[$inc]['ans_view_audio']['on_click'] = 'ans_audio_'.$displayAllAnswers_arr[$inc]['ansId'];

		        			}
		        		if (chkExternalVideoAllowed('answer') and $row['external_video_id'])
		        			{
								$displayAllAnswers_arr[$inc]['ext_ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Answer_'.$row['external_video_id'], '?pg=Answer_'.$row['external_video_id']);
								$displayAllAnswers_arr[$inc]['ext_ans_view_video']['on_click'] = 'external_video_ans_'.$displayAllAnswers_arr[$inc]['ansId'];

							}
						if (chkExternalAudioAllowed('answer') and $row['external_audio_id'])
							{
								$displayAllAnswers_arr[$inc]['ext_ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Answer_'.$row['external_audio_id'], '?pg=Answer_'.$row['external_audio_id']);
								$displayAllAnswers_arr[$inc]['ext_ans_view_audio']['on_click'] = 'external_audio_ans_'.$displayAllAnswers_arr[$inc]['ansId'];
							}
		        		if ($row['source'])
							{
		        				$displayAllAnswers_arr[$inc]['row_source_manual'] = nl2br(wordWrapManual($row['source'], $this->CFG['admin']['answer']['line_length']));
		        			}

		        		$displayAllAnswers_arr[$inc]['facebook_user_details'] = '';
						if ($this->CFG['admin']['module']['facebook'])
							{
								$displayAllAnswers_arr[$inc]['facebook_user_details'] = $this->fetchFacebookUserDetails($row['ans_id']);
							}

						$displayAllAnswers_arr[$inc]['myanswers']['url'] = getMemberUrl($row['user_id'], $row['name']);
						$displayAllAnswers_arr[$inc]['row_answered_by_manual'] = stripString($row['answered_by'], $this->CFG['username']['short_length']);

						$displayAllAnswers_arr[$inc]['answer']['url'] = getAnovaUrl('answer', '?action=view&amp;title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/');
	          			if ($this->CFG['admin']['abuse_answers']['allowed'] AND !$this->CFG['user']['user_id'] AND $this->CFG['user']['user_id'] != $row['user_id'] AND $this->isQuestionOpen())
						  	{
		          				$displayAllAnswers_arr[$inc]['answer_members']['url'] = getAnovaUrl('answer', '?action=view&amp;title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/', 'members');
		          				$displayAllAnswers_arr[$inc]['report']['url'] = getUrl('login', '?light_url='.$displayAllAnswers_arr[$inc]['answer_members']['url'], '?light_url='.$displayAllAnswers_arr[$inc]['answer_members']['url']);
		          				$displayAllAnswers_arr[$inc]['report']['on_click'] = 'ans_report_'.$row['ans_id'];
							}
      					if ($row['user_id'] == $this->CFG['user']['user_id'] and $this->isQuestionOpen())
						  	{
      							if ($this->CFG['admin']['answer']['edit'])
								  	{
	        							$displayAllAnswers_arr[$inc]['answer_edit']['url'] = getAnovaUrl('editanswer', '?action=edit&amp;title='.$this->fields_arr['seo_title'].'&amp;aid='.$row['ans_id'], $this->fields_arr['seo_title'].'/?aid='.$row['ans_id'], 'members');
    								}
    							if ($this->CFG['admin']['answer']['delete'])
									{
    									$displayAllAnswers_arr[$inc]['answer_delete']['url'] = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/');
    								}
    						}

						$displayAllAnswers_arr[$inc]['has_attachment'] = false;
						if ($this->CFG['admin']['attachments_answers']['allowed'] AND $this->hasMoreAttachments($row['ans_id'], 'Answer'))
							{
								$displayAllAnswers_arr[$inc]['has_attachment'] = true;
								$displayAllAnswers_arr[$inc]['attachment_count'] = count($this->repliesArray);
								$extern = strtolower(substr($this->repliesArray[0]['attachment_name'], strrpos($this->repliesArray[0]['attachment_name'], '.')+1));
								$attachment_original_file_name = getImageName($this->repliesArray[0]['attachment_id']).$this->CFG['admin']['ans_pictures']['large_name'].'.'.$extern;
								$displayAllAnswers_arr[$inc]['img_id'] = 'Answer_'.$row['ans_id'].'_'.$this->repliesArray[0]['attachment_id'];
								$displayAllAnswers_arr[$inc]['attachment_path'] = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'].'&amp;imgdetail='.$displayAllAnswers_arr[$inc]['img_id'], $this->fields_arr['seo_title'].'/?imgdetail='.$displayAllAnswers_arr[$inc]['img_id']);
								$displayAllAnswers_arr[$inc]['image_large_path'] = $this->repliesArray[0]['photo_server_url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$attachment_original_file_name;
							}

						$displayAllAnswers_arr[$inc]['id_cnt'] = $id_cnt;

			    		if ($this->CFG['admin']['answer']['ratings'])
							{

								$displayAllAnswers_arr[$inc]['question_url'] = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/', 'members');
								$displayAllAnswers_arr[$inc]['getAnswersRatings'] = $this->getAnswersRatings($this->CFG['db']['tbl']['users_stared_answer'],
																									$this->CFG['db']['tbl']['answers'],
																									$row['ans_id'], $row['user_id'],
																									$this->CFG['site']['project_path_relative'],
																									$this->CFG['site']['relative_url'], $id_cnt,
																									$displayAllAnswers_arr[$inc]['question_url']);
								$id_cnt += 4;

			    			}
						$displayAllAnswers_arr[$inc]['commentSpanIDId'] = 'commentSpanID_'.$row['ans_id'];

						$inc++;
					} // while

				return $displayAllAnswers_arr;
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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();
							}
					}
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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);
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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('uid');
				$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('uid').
								', 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();
							}
					}
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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);
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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 ;
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function updateBestAnswer()
		    {
				$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']);
					}
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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->fields_arr['seo_title'], $this->fields_arr['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));

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

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function resolveQuestion()
		    {
				if ($this->isQuestionOpen())
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].
								' SET status=\'Resolved\', date_closed = NOW()'.
								' WHERE user_id='.$this->dbObj->Param('uid').
								' AND ques_id='.$this->dbObj->Param('qid');
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id'], $this->fields_arr['qid']));
						if (!$rs)
						        trigger_db_error($this->dbObj);
					}
				return ;
		    }

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function deleteQuestion()
			{
				//Change the video and audio status
				$this->updateQuestionVideoStatus($this->question_details['video_id']);
				$this->updateQuestionVideoStatus($this->question_details['external_video_id']);
				$this->updateQuesitionAudioStatus($this->question_details['audio_id']);
                $this->updateQuesitionAudioStatus($this->question_details['external_audio_id']);
                $this->deleteQuestionsComment();
				//Delete question
				$sql = 'DELETE FROM '.$this->CFG['db']['tbl']['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);

				$sql = 'SELECT ans_id, video_id, external_video_id, audio_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->updateAnswerVideoStatus($row['external_video_id']);
							$this->updateAnswerAudioStatus($row['audio_id']);
							$this->updateAnswerAudioStatus($row['external_audio_id']);
							$this->commonDeleteAttachments('Answer', $row['ans_id']);
						} // while
					}

				//Decrement the total_ans count and points for users who posted answer against this question and attachment delete
				$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);

				//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);

				//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($this->CFG['user']['user_id']));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				//Delete Attachments for question
				if($this->CFG['admin']['attachments_questions']['allowed'])
					$this->fetchAndDeleteAttachments('Question', $this->fields_arr['qid']);
				//Decrement tag_count
				$this->updateDeletedQuestionsTagCount($this->question_details['tags']);
			}

		/**
		 * AnswerFormHandler::fetchAndDeleteAttachments()
		 *
		 * @param mixed $type
		 * @param mixed $content_id
		 * @return
		 */
		public function fetchAndDeleteAttachments($type, $content_id)
		    {
                $sql = 'SELECT attachment_id, attachment_name FROM '.$this->CFG['db']['tbl']['attachments'].
                        ' WHERE content_id = '.$this->dbObj->Param('content_id').
                        ' AND content_type = '.$this->dbObj->Param('type');
                $stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($content_id, $type));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						while($row = $rs->FetchRow()){
                            $extern = strtolower(substr($row['attachment_name'], strrpos($row['attachment_name'], '.')+1));
							$attach_name = getImageName($row['attachment_id']).$this->CFG['admin']['ans_pictures']['large_name'].'.'.$extern;
                            $this->deleteMoreAttachments($row['attachment_id'], $attach_name);
						} // while
					}
		    }

		/**
		 * 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 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);

							//Delete Attachment for each answer while deleting a question
							if($this->CFG['admin']['attachments_answers']['allowed'])
                            	$this->fetchAndDeleteAttachments('Answer', $row['ans_id']);
						} // while
					}
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		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);
					}
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function updateAnswer()
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['answers'].
						' SET answer='.$this->dbObj->Param('answer').
						', source='.$this->dbObj->Param('source').
						', video_id='.$this->dbObj->Param('video_id').
						', external_video_id='.$this->dbObj->Param('external_video_id').
						', audio_id='.$this->dbObj->Param('audio_id').
						', external_audio_id='.$this->dbObj->Param('external_audio_id').
						' WHERE user_id='.$this->dbObj->Param('uid').
						' AND ques_id='.$this->dbObj->Param('qid').
						' AND ans_id='.$this->dbObj->Param('aid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['answer'],
														 $this->fields_arr['source'],
														 $this->fields_arr['video_id'],
														 $this->fields_arr['external_video_id'],
														 $this->fields_arr['audio_id'],
														 $this->fields_arr['external_audio_id'],
														 $this->CFG['user']['user_id'],
														 $this->fields_arr['qid'],
														 $this->fields_arr['aid']));
				if (!$rs)
				        trigger_db_error($this->dbObj);

				if((chkAllowedModule(array('video'))) AND ($this->fields_arr['video'] or ($this->fields_arr['video_id']==0)))
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_video'].' SET'.
								' video_status=\'Deleted\' WHERE'.
								' content_id='.$this->dbObj->Param('content_id').' AND'.
								' video_id='.$this->dbObj->Param('video_id').' AND'.
								' video_for=\'Answer\'';

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

						if($this->dbObj->Affected_Rows())
							{
								$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($this->fields_arr['qid']));
								    if (!$rs)
									    trigger_db_error($this->dbObj);
							}
					}

				if((chkExternalVideoAllowed('answer')) AND ($this->fields_arr['external_video_id']==0))
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_video'].' SET'.
								' video_status=\'Deleted\' WHERE'.
								' content_id='.$this->dbObj->Param('content_id').' AND'.
								' video_id='.$this->dbObj->Param('external_video_id').' AND'.
								' video_for=\'Answer\'';

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

						if($this->dbObj->Affected_Rows())
							{
								$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($this->fields_arr['qid']));
								    if (!$rs)
									    trigger_db_error($this->dbObj);
							}
					}

				if((chkAllowedModule(array('audio'))) AND ($this->fields_arr['audio'] or ($this->fields_arr['audio_id']==0)))
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_audio'].' SET'.
								' audio_status=\'Deleted\' WHERE'.
								' content_id='.$this->dbObj->Param('content_id').' AND'.
								' audio_id='.$this->dbObj->Param('audio_id').' AND'.
								' audio_for=\'Answer\'';

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

						if($this->dbObj->Affected_Rows())
							{
								$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($this->fields_arr['qid']));
								    if (!$rs)
									    trigger_db_error($this->dbObj);
							}
					}
				if((chkExternalAudioAllowed('answer')) AND ($this->fields_arr['external_audio_id']==0))
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_audio'].' SET'.
								' audio_status=\'Deleted\' WHERE'.
								' content_id='.$this->dbObj->Param('content_id').' AND'.
								' audio_id='.$this->dbObj->Param('external_audio_id').' AND'.
								' audio_for=\'Answer\'';

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

						if($this->dbObj->Affected_Rows())
							{
								$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($this->fields_arr['qid']));
								    if (!$rs)
									    trigger_db_error($this->dbObj);
							}
					}
				$this->fields_arr['content_id'] = $this->fields_arr['aid'];
				$this->addNewVideo();
				$this->addNewAudio();
                if($this->fields_arr['video_external_flv_url'] or $this->fields_arr['file_extern'])
					$this->addExternalVideo('Answer');
				if($this->fields_arr['audio_external_url'] or $this->fields_arr['audio_extern'])
					$this->addExternalAudio('Answer');
				$this->addAttachments();
				return ;
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function addAnswer()
		    {
				if ($this->isQuestionOpen())
					{
						$this->fields_arr['content_id'] = $this->insertAnswer();
						if($this->question_details['publish_status']=='Yes')
							{
								$this->updateQuestion();
								$this->updateUserAnswerLog();
							}
						$this->addNewVideo();
						$this->addExternalVideo('Answer');

						$this->addNewAudio();
                        $this->addExternalAudio('Answer');

						$this->addAttachments();
						$this->sendMailToAsker();
					}
		    }

		/**
		 * AnswerFormHandler::insertAnsVideoTable()
		 *
		 * @return
		 */
		public function insertAnsVideoTable()
			{
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['ans_video'].' SET'.
						' content_id='.$this->dbObj->Param('content_id').','.
						' user_id='.$this->dbObj->Param('user_id').','.
						' video_for=\'Answer\','.
						' video_ext=\'flv\','.
						' date_added=NOW(),'.
						' flv_upload_type=\'Normal\','.
						' video_encoded_status=\'Partial\'';

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

				return $this->dbObj->Insert_ID();
			}

		/**
		 * AnswerFormHandler::addNewVideo()
		 *
		 * @return
		 */
		public function addNewVideo()
			{
				if($this->fields_arr['video'])
					{
						$this->fields_arr['video_id'] = $this->insertAnsVideoTable();
						//added code for logging
						if($this->fp)
							{
								$log_str = 'Video Record created : '.$this->fields_arr['video_id']."\r\n";
								$this->writetoTempFile($log_str);
							}
						$video_name = getImageName($this->fields_arr['video_id']);

						$temp_dir = $this->_dir_path.$this->CFG['admin']['ans_videos']['temp_folder'];
						$this->chkAndCreateFolder($temp_dir);
						$temp_file = $temp_dir.$video_name.'.flv';

						$file_name = $this->CFG['admin']['video']['red5_flv_path'].$this->fields_arr['rid'].'.flv';
						copy($file_name, $temp_file);
						unlink($file_name);
						//added code for logging
						if($this->fp)
							{
								$log_str = 'Video stored in temp server : '.$temp_file."\r\n";
								$this->writetoTempFile($log_str);
							}

						$this->changeAnsVideoStatus($this->fields_arr['video_id'], 'No');
						if($this->CFG['admin']['ans_videos']['video_auto_encode'])
							{
								//added code for logging
								if($this->fp)
									{
										$log_str = 'Calling Video Encode \r\n';
										$this->writetoTempFile($log_str);
									}
								$this->videoEncode($this->fields_arr['video_id']);
							}

						$temp_dir = $this->_dir_path.$this->CFG['admin']['ans_videos']['temp_folder'];
						$temp_file = $temp_dir.$this->fields_arr['rid'].'.flv';
						if(file_exists($temp_file))
							unlink($temp_file);
					}
			}

		/**
		 * AnswerFormHandler::insertAnsAudioTable()
		 *
		 * @return
		 */
		public function insertAnsAudioTable()
			{
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['ans_audio'].' SET'.
						' content_id='.$this->dbObj->Param('content_id').','.
						' user_id='.$this->dbObj->Param('user_id').','.
						' audio_for=\'Answer\','.
						' audio_ext=\'flv\','.
						' date_added=NOW(),'.
						' audio_encoded_status=\'Partial\'';

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

				return $this->dbObj->Insert_ID();
			}

		/**
		 * AnswerFormHandler::addNewAudio()
		 *
		 * @return
		 */
		public function addNewAudio()
			{
				if($this->fields_arr['audio'])
					{
						$this->fields_arr['audio_id'] = $this->insertAnsAudioTable();
						//added code for logging
						if($this->fp)
							{
								$log_str = 'Audio Record created : '.$this->fields_arr['audio_id']."\r\n";
								$this->writetoTempFile($log_str);
							}
						$audio_name = getImageName($this->fields_arr['audio_id']);

						$temp_dir = $this->_dir_path.$this->CFG['admin']['ans_audios']['temp_folder'];
						$this->chkAndCreateFolder($temp_dir);
						$temp_file = $temp_dir.$audio_name.'.flv';

						$file_name = $this->CFG['admin']['video']['red5_flv_path'].$this->fields_arr['rid'].'AUD.flv';
						copy($file_name, $temp_file);
						unlink($file_name);
						//added code for logging
						if($this->fp)
							{
								$log_str = 'Audio stored in temp server : '.$temp_file."\r\n";
								$this->writetoTempFile($log_str);
							}

						$this->changeAnsAudioStatus($this->fields_arr['audio_id'], 'No');
						if($this->CFG['admin']['ans_audios']['audio_auto_encode'])
							{
								//added code for logging
								if($this->fp)
									{
										$log_str = 'Calling Audio Encode \r\n';
										$this->writetoTempFile($log_str);
									}
								$this->audioEncode($this->fields_arr['audio_id']);
							}

						$temp_dir = $this->_dir_path.$this->CFG['admin']['ans_audios']['temp_folder'];
						$temp_file = $temp_dir.$this->fields_arr['rid'].'AUD.flv';
						if(file_exists($temp_file))
							unlink($temp_file);
					}
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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()';

				if($this->question_details['publish_status']=='No')
					$sql.=	', status=\'ToActivate\'';

				$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 $this->dbObj->Insert_ID();
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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);
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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);
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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);
						$answers_reply_content = str_ireplace('VAR_USERNAME', '<a href="'.getMemberUrl($this->question_details['user_id'], $this->question_details['name']).'">'.$asker_details['display_name'].'</a>', $this->LANG['answers_reply_email_content']);
						$sender_name = '<a href="'.getMemberUrl($this->CFG['user']['user_id'], $this->CFG['user']['name']).'">'.$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->fields_arr['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']);
					}
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function sendMailToAnswerer()
		    {
				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']);

						$best_answers_content = str_ireplace('VAR_USERNAME', '<a href="'.getMemberUrl($answerer_details['user_id'], $answerer_details['name']).'">'.$answerer_details['display_name'].'</a>', $this->LANG['best_answer_email_content']);
						$sender_name = '<a href="'.getMemberUrl($this->CFG['user']['user_id'], $this->CFG['user']['name']).'">'.$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->fields_arr['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']);
					}
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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;
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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']);

						$abuse_question_content = str_ireplace('VAR_USERNAME', '<a href="'.getMemberUrl($asker_details['user_id'], $asker_details['name']).'">'.$asker_details['display_name'].'</a>', $this->LANG['abuse_question_email_content']);
						$sender_name = '<a href="'.getMemberUrl($this->CFG['user']['user_id'], $this->CFG['user']['name']).'">'.$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->fields_arr['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']);
					}
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		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']);

						$abuse_answers_content = str_ireplace('VAR_USERNAME', '<a href="'.getMemberUrl($answerer_details['user_id'], $answerer_details['name']).'">'.$answerer_details['display_name'].'</a>', $this->LANG['abuse_answer_email_content']);
						$sender_name = '<a href="'.getMemberUrl($this->CFG['user']['user_id'], $this->CFG['user']['name']).'">'.$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->fields_arr['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']);
					}
		    }

		/**
		 * 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());
			}

		/**
		 * get answers rating
		 *
		 * @param 		String $users_stared_question_table
		 * @param 		String $question_table
		 * @param 		integer $ques_id
		 * @param 		integer $user_id
		 * @param 		String $cfg_project_path_relative
		 * @return 		void
		 * @access 		public
		 */
		public function getQuestionRatings($users_stared_question_table, $question_table, $ques_id, $user_id, $cfg_project_path_relative, $relative_path, $question_url)
			{
				$start 	= 1000;
				$end 	= 1004;
				$ratingsTitle = array($this->LANG['rating_below_average'],
									  $this->LANG['rating_average'],
									  $this->LANG['rating_good'],
									  $this->LANG['rating_excellent']);

				$getQuestionRatings_arr = array();
				$getQuestionRatings_arr['start_count'] = $start;
				$getQuestionRatings_arr['end_count'] = $end;

				if (!isMember())
					{
						$getQuestionRatings_arr['login_question']['url'] = getUrl('login', '?light_url='.$question_url, '?light_url='.$question_url);
						$getQuestionRatings_arr['end'] = array();
						$pointer = 1;
						$ratingscnt = 0;
						for ($j=$start;$j<$end; $j++)
							{
								$getQuestionRatings_arr['end'][$pointer]['inc'] = $j+1;
								$getQuestionRatings_arr['end'][$pointer]['title'] = $ratingsTitle[$ratingscnt];
								$getQuestionRatings_arr['end'][$pointer]['pointer'] = $pointer.'tr';
								$getQuestionRatings_arr['end'][$pointer]['on_click'] = 'ques_rate_'.$pointer;
								$pointer++;
								$ratingscnt++;
							}
					}
				elseif($this->CFG['user']['user_id'] == $user_id)
					{
						//<span class="clsRateStars"><?php echo $this->LANG['you_cant_rate_your_question'];</span>
					}
				else
					{
						$sql = 'SELECT rating FROM '.$users_stared_question_table.' WHERE ques_id = '.$this->dbObj->Param($ques_id).
							   ' AND user_id = '.$this->dbObj->Param($this->CFG['user']['user_id']);

						$stmt = $this->dbObj->Prepare($sql);
						$result = $this->dbObj->Execute($stmt, array($ques_id, $this->CFG['user']['user_id']));
						if (!$result)
								trigger_db_error($this->dbObj);

						$rating = 0;

						$getQuestionRatings_arr['result_PO_RecordCount'] = $result->PO_RecordCount();
						if ($result->PO_RecordCount() OR !$this->isQuestionOpen())
							{

								$row['rating'] = 0;
								if ($result->PO_RecordCount())
									$row = $result->FetchRow();

								$getQuestionRatings_arr['record'] = $row;
								$getQuestionRatings_arr['start'] = array();
								$getQuestionRatings_arr['end'] = array();
								$rating = $row['rating'];
								$pointer = 1;
								$ratingscnt = 0;
								for ($i=$start;$i<$rating+$start; $i++)
									{
										$getQuestionRatings_arr['start'][$pointer]['inc'] = $i+1;
										$getQuestionRatings_arr['start'][$pointer]['title'] = $ratingsTitle[$ratingscnt];
										$getQuestionRatings_arr['start'][$pointer]['pointer'] = $pointer;

										$pointer++;
										$ratingscnt++;
									}

								for ($j=$i;$j<$end; $j++)
									{
										$getQuestionRatings_arr['end'][$pointer]['inc'] = $j+1;
										$getQuestionRatings_arr['end'][$pointer]['title'] = $ratingsTitle[$ratingscnt];
										$getQuestionRatings_arr['end'][$pointer]['pointer'] = $pointer;

										$pointer++;
										$ratingscnt++;
									}
							}
						else
							{
								$getQuestionRatings_arr['end'] = array();
								$pointer = 1;
								$ratingscnt = 0;
								for ($j=$start;$j<$end; $j++)
									{
										$getQuestionRatings_arr['end'][$pointer]['inc'] = $j+1;
										$getQuestionRatings_arr['end'][$pointer]['title'] =  $ratingsTitle[$ratingscnt];
										$getQuestionRatings_arr['end'][$pointer]['pointer'] = $pointer;

										$pointer++;
										$ratingscnt++;
									}
							}
					}
				$sql = 'SELECT COUNT(star_id) as cnt FROM '.$users_stared_question_table.' WHERE ques_id = '.$this->dbObj->Param($ques_id);
				$stmt = $this->dbObj->Prepare($sql);
				$result = $this->dbObj->Execute($stmt, array($ques_id));
				if (!$result)
						trigger_db_error($this->dbObj);
				// returns record id
				$row = $result->FetchRow();
				$rating_count = $row['cnt'];

				$sql = 'SELECT total_stars FROM '.$question_table.' WHERE ques_id = '.$this->dbObj->Param($ques_id);

				$stmt = $this->dbObj->Prepare($sql);
				$result = $this->dbObj->Execute($stmt, array($ques_id));
				if (!$result)
						trigger_db_error($this->dbObj);
				// returns record id
				$rating = 0;
				if ($result->PO_RecordCount())
					{
						$row = $result->FetchRow();
						$rating = $row['total_stars'];
					}
				$getQuestionRatings_arr['rating_count'] = $rating_count;
				$getQuestionRatings_arr['rating'] = $rating;
				return $getQuestionRatings_arr;
			}

		/**
		 * get answers rating
		 *
		 * @param 		String $users_stared_answer_table
		 * @param 		String $answers_table
		 * @param 		integer $ans_id
		 * @param 		integer $user_id
		 * @param 		String $cfg_project_path_relative
		 * @return 		void
		 * @access 		public
		 */
		public function getAnswersRatings($users_stared_answer_table, $answers_table, $ans_id, $user_id, $cfg_project_path_relative, $relative_path, $id_cnt, $question_url)
			{
				$getAnswersRatings_arr = array();
				$start = $id_cnt;
				$end = $id_cnt+4;
				$ratingsTitle = array($this->LANG['rating_below_average'],
									  $this->LANG['rating_average'],
									  $this->LANG['rating_good'],
									  $this->LANG['rating_excellent']);

				$getAnswersRatings_arr['start_count'] = $start;
				$getAnswersRatings_arr['end_count'] = $end;

				if (!isMember())
					{
						$getAnswersRatings_arr['login_question']['url'] = getUrl('login', '?light_url='.$question_url, '?light_url='.$question_url);
						$getAnswersRatings_arr['end'] = array();
						$pointer = 1;
						$ratingscnt = 0;
						//$inc = 1;
						for ($j=$start;$j<$end; $j++)
							{
								$getAnswersRatings_arr['end'][$pointer]['inc'] = $j+1;
								$getAnswersRatings_arr['end'][$pointer]['title'] = $ratingsTitle[$ratingscnt];
								$getAnswersRatings_arr['end'][$pointer]['pointer'] = $pointer;
								$getAnswersRatings_arr['end'][$pointer]['on_click'] = 'answer_rate_'.$ans_id.'_'.$pointer;;
								//$inc++;
								$pointer++;
								$ratingscnt++;
							}
					}
			elseif($this->CFG['user']['user_id'] == $user_id)
				{
					/*<span class="clsRateStars"><?php echo $this->LANG['you_cant_rate_your_answer'];?></span>*/
				}
			else
				{
					$sql = 'SELECT rating FROM '.$users_stared_answer_table.' WHERE ans_id = '.$this->dbObj->Param($ans_id).
						   ' AND user_id = '.$this->dbObj->Param($this->CFG['user']['user_id']);

					$stmt = $this->dbObj->Prepare($sql);
					$result = $this->dbObj->Execute($stmt, array($ans_id, $this->CFG['user']['user_id']));
					if (!$result)
							trigger_db_error($this->dbObj);

					$rating = 0;

					$getAnswersRatings_arr['result_PO_RecordCount'] = $result->PO_RecordCount();
					if ($result->PO_RecordCount() OR !$this->isQuestionOpen())
						{
							$row['rating'] = 0;
							if ($result->PO_RecordCount())
								$row = $result->FetchRow();

							$getAnswersRatings_arr['record'] = $row;
							$getAnswersRatings_arr['start'] = array();
							$getAnswersRatings_arr['end'] = array();
							$rating = $row['rating'];
							$pointer = 1;
							$ratingscnt = 0;
							for ($i=$start;$i<$rating+$start; $i++)
								{
									$getAnswersRatings_arr['start'][$pointer]['inc'] = $i+1;
									$getAnswersRatings_arr['start'][$pointer]['title'] = $ratingsTitle[$ratingscnt];
									$getAnswersRatings_arr['start'][$pointer]['pointer'] = $pointer;
									$pointer++;
									$ratingscnt++;
								}

							for ($j=$i;$j<$end; $j++)
								{
									$getAnswersRatings_arr['end'][$pointer]['inc'] = $j+1;
									$getAnswersRatings_arr['end'][$pointer]['title'] = $ratingsTitle[$ratingscnt];
									$getAnswersRatings_arr['end'][$pointer]['pointer'] = $pointer;
									$pointer++;
									$ratingscnt++;
								}
						}
					else
						{
							$getAnswersRatings_arr['end'] = array();
							$pointer = 1;
							$ratingscnt = 0;
							for ($j=$start;$j<$end; $j++)
								{
									$getAnswersRatings_arr['end'][$pointer]['inc'] = $j+1;
									$getAnswersRatings_arr['end'][$pointer]['title'] = $ratingsTitle[$ratingscnt];
									$getAnswersRatings_arr['end'][$pointer]['pointer'] = $pointer;
									$pointer++;
									$ratingscnt++;
								}
						}
				}
				$sql = 'SELECT COUNT(star_id) as cnt FROM '.$users_stared_answer_table.' WHERE ans_id = '.$this->dbObj->Param($ans_id);
				$stmt = $this->dbObj->Prepare($sql);
				$result = $this->dbObj->Execute($stmt, array($ans_id));
				if (!$result)
						trigger_db_error($this->dbObj);
				// returns record id
				$row = $result->FetchRow();
				$rating_count = $row['cnt'];

				$sql = 'SELECT total_stars FROM '.$answers_table.' WHERE ans_id = '.$this->dbObj->Param($ans_id);

				$stmt = $this->dbObj->Prepare($sql);
				$result = $this->dbObj->Execute($stmt, array($ans_id));
				if (!$result)
						trigger_db_error($this->dbObj);
				// returns record id
				$rating = 0;
				if ($result->PO_RecordCount())
					{
						$row = $result->FetchRow();
						$rating = $row['total_stars'];
					}
				$getAnswersRatings_arr['rating_count'] = $rating_count;
				$getAnswersRatings_arr['rating'] = $rating;
				return $getAnswersRatings_arr;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function chkIsAnswerOwner($err_tip='')
			{
				$sql = 'SELECT 1 FROM '.$this->CFG['db']['tbl']['answers'].
						' WHERE ans_id='.$this->dbObj->Param($this->fields_arr['aid']).
						' AND user_id='.$this->dbObj->Param($this->CFG['user']['user_id']).
						' AND ques_id='.$this->dbObj->Param($this->fields_arr['qid']);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['aid'],
														 $this->CFG['user']['user_id'],
														 $this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				$ok = true;
				if (!$rs->PO_RecordCount())
					{
						$ok = false;
						$this->setCommonErrorMsg($err_tip);
					}
				return $ok;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function deleteAnswer()
			{
				$this->updateAnswerVideoStatus($this->answer_details['video_id']);
				$this->updateAnswerVideoStatus($this->answer_details['external_video_id']);
				$this->updateAnswerAudioStatus($this->answer_details['audio_id']);
                $this->updateAnswerAudioStatus($this->answer_details['external_audio_id']);
				$this->deleteAnswersComment();

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

				//Decrement total_answers in questions table
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].
						' SET total_answer=total_answer-1'.
						' 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);

				//Decrement tot_ans in users_ans_log table
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
						' SET total_ans=total_ans-1'.
						' WHERE user_id='.$this->dbObj->Param($this->CFG['user']['user_id']);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id']));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				if ($this->CFG['admin']['reply_answers']['allowed'])
					{
						//Decrement total_points in users_ans_log table
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
								' SET total_points=total_points-'.$this->CFG['admin']['reply_answers']['points'].
								' WHERE user_id='.$this->dbObj->Param($this->CFG['user']['user_id']);
								#.' AND total_points >= '.$this->CFG['admin']['reply_answers']['points'];
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id']));
						if (!$rs)
							    trigger_db_error($this->dbObj);
					}

				//Delete Attachement for each deleted answer
				if($this->CFG['admin']['attachments_answers']['allowed'])
					$this->fetchAndDeleteAttachments('Answer', $this->fields_arr['aid']);
			}

		/**
		 * AnswerFormHandler::deleteAnswersComment()
		 *
		 * @return
		 */
		public function deleteAnswersComment()
			{
				$sql = 'DELETE FROM '.$this->CFG['db']['tbl']['question_comment'].
						' WHERE ans_id='.$this->dbObj->Param($this->fields_arr['aid']);

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

		/**
		 * AnswerFormHandler::deleteQuestionsComment()
		 *
		 * @return
		 */
		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);
			}


		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		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);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function updateQuesitionAudioStatus($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);
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function updateAnswerVideoStatus($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);

				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 = '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);
					}
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function updateAnswerAudioStatus($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);

				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 = '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::chkIsValidCaptureVideoFile()
		 *
		 * @return
		 */
		public function chkIsValidCaptureVideoFile()
			{
				$file_name = $this->CFG['admin']['video']['red5_flv_path'].$this->fields_arr['rid'].'.flv';
				//if($this->fields_arr['video']=$this->fields_arr['rid'])
				if($this->fields_arr['video']==$this->fields_arr['rid'])
					{
						if(is_file($file_name))
							return true;

						$this->fields_arr['video'] = '';
						return false;
					}
				if(is_file($file_name))
					unlink($file_name);
			}

		/**
		 * AnswerFormHandler::chkIsValidCaptureAudioFile()
		 *
		 * @return
		 */
		public function chkIsValidCaptureAudioFile()
			{
				$file_name = $this->CFG['admin']['video']['red5_flv_path'].$this->fields_arr['rid'].'AUD.flv';
				//if($this->fields_arr['audio']=$this->fields_arr['rid'])
				if($this->fields_arr['audio']==$this->fields_arr['rid'])
					{
						if(is_file($file_name)){
							return true;
							}

						$this->fields_arr['audio'] = '';
						return false;
					}
				if(is_file($file_name))
					unlink($file_name);
			}

		/**
		 * AnswerFormHandler::generateRandomId()
		 *
		 * @return
		 */
		public function generateRandomId()
			{
				$time = time();
				$this->fields_arr['rid'] = md5($time);
			}

		/**
		 * VideoUpload::changeVideoStatus()
		 *
		 * @param $video_id
		 * @return
		 **/
		public function changeAnsVideoStatus($video_id, $status)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_video'].' SET'.
						' video_encoded_status='.$this->dbObj->Param('video_encoded_status').
						' WHERE video_id='.$this->dbObj->Param('video_id');

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

		/**
		 * AudioUpload::changeAudioStatus()
		 *
		 * @param $audio_id
		 * @return
		 **/
		public function changeAnsAudioStatus($audio_id, $status)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_audio'].' SET'.
						' audio_encoded_status='.$this->dbObj->Param('audio_encoded_status').
						' WHERE audio_id='.$this->dbObj->Param('audio_id');

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

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		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::getAttachments()
		 *
		 * @return
		 */
		public function getAttachments()
			{
				$getAttachments_val = '';
				$getAttachments_arr = array();
				$sql = 'SELECT attachment_id, attachment_name, photo_server_url FROM '.$this->CFG['db']['tbl']['attachments'].
						' WHERE content_id='.$this->dbObj->Param($this->fields_arr['aid']).
						' AND content_type=\'Answer\' ORDER BY attachment_id';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['aid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						$attach_count = 0;

						while($row = $rs->FetchRow())
							{
								$getAttachments_arr[$attach_count]['record'] = $row;
								$getAttachments_arr[$attach_count]['img_id'] = 'Answer_'.$this->fields_arr['aid'].'_'.$row['attachment_id'];
								$getAttachments_arr[$attach_count]['attachment_path'] = getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'].'&imgdetail='.$getAttachments_arr[$attach_count]['img_id'], $this->fields_arr['seo_title'].'/?imgdetail='.$getAttachments_arr[$attach_count]['img_id']);
								$extern = strtolower(substr($row['attachment_name'], strrpos($row['attachment_name'], '.')+1));
								$getAttachments_arr[$attach_count]['attachment_file_name'] = getImageName($row['attachment_id']).$this->CFG['admin']['ans_pictures']['large_name'].'.'.$extern;
								$getAttachments_arr[$attach_count]['attachment_file_name_thumb'] = getImageName($row['attachment_id']).$this->CFG['admin']['ans_pictures']['thumb_name'].'.'.$extern;
								$getAttachments_arr[$attach_count]['anchor'] = 'seldel_'.$row['attachment_id'];
								$getAttachments_arr[$attach_count]['attachment']['url'] = $this->CFG['site']['url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$getAttachments_arr[$attach_count]['attachment_file_name'];
								$getAttachments_arr[$attach_count]['attachment']['url_thumb'] = $this->CFG['site']['url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$getAttachments_arr[$attach_count]['attachment_file_name_thumb'];
								$getAttachments_arr[$attach_count]['image_large_path'] = $row['photo_server_url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$getAttachments_arr[$attach_count]['attachment_file_name'];
								$attach_count++;
							} // while

						$this->answer_attachment_count = $attach_count;
					}
				return $getAttachments_arr;
			}

		/**
		 * 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);

				//deleting large and small images
				$small_name = substr($attach_name, 0, strrpos($attach_name, '.')-1);
				$extern = strtolower(substr($attach_name, strrpos($attach_name, '.')+1));

				$attachment_large_file = $this->CFG['admin']['ans_attachments_path'].$attach_name;
				$attachment_small_file = $this->CFG['admin']['ans_attachments_path'].$small_name.$this->CFG['admin']['ans_pictures']['small_name'].'.'.$extern;

				unlink($attachment_large_file);
				unlink($attachment_small_file);

			}

		/**
		 * AnswerFormHandler::chkValidFileType()
		 *
		 * @param mixed $field_name
		 * @param mixed $type
		 * @param string $err_tip
		 * @return
		 */
		public function chkValidFileType($field_name, $type, $err_tip = '')
			{
				$file_allowed_count = $this->CFG['admin']['attachments_allowed']['count'];
				for($i=0;$i<$file_allowed_count;$i++)
					{

						if(!isset($_FILES[$field_name]['name'][$i]) or  $_FILES[$field_name]['name'][$i] == '')
							continue;

						$extern = strtolower(substr($_FILES[$field_name]['name'][$i], strrpos($_FILES[$field_name]['name'][$i], '.')+1));

						if (!in_array($extern, $this->CFG['admin'][$type]['format_arr']))
							{
								$this->fields_err_tip_arr[$field_name] = $err_tip;
								return false;
							}
					}
				return true;
			}

		/**
		 * VideoUpload::chkValideFileSize()
		 *
		 * @param $field_name
		 * @param string $err_tip
		 * @return
		 **/
		public function chkValideFileSize($field_name, $type, $err_tip='')
			{
				$file_allowed_count = $this->CFG['admin']['attachments_allowed']['count'];
				for($i=0;$i<$file_allowed_count;$i++)
					{
						if(!isset($_FILES[$field_name]['name'][$i]) or  $_FILES[$field_name]['name'][$i] == '')
							continue;

						if($this->CFG['admin'][$type]['max_size'])
							{
								$max_size = $this->CFG['admin'][$type]['max_size']*1024*1024;
								if ($_FILES[$field_name]['size'][$i] == 0)
									{
										$this->fields_err_tip_arr[$field_name] = $this->LANG['err_tip_invalid_file'];
										return false;
									}
								if ($_FILES[$field_name]['size'][$i] > $max_size)
									{
										$this->fields_err_tip_arr[$field_name] = $err_tip;
										return false;
									}
							}
     				}
     			return true;
			}

		/**
		 * VideoUpload::chkErrorInFile()
		 *
		 * @param $field_name
		 * @param string $err_tip
		 * @return
		 **/
		public function chkErrorInFile($field_name, $err_tip='')
			{
				$file_allowed_count = $this->CFG['admin']['attachments_allowed']['count'];
				for($i=0;$i<$file_allowed_count;$i++)
					{
						if(!isset($_FILES[$field_name]['name'][$i]) or  $_FILES[$field_name]['name'][$i] == '')
							continue;

						if($_FILES[$field_name]['error'][$i])
							{
								$this->fields_err_tip_arr[$field_name] = $err_tip;
								return false;
							}
					}
				return true;
			}

		/**
		 * AnswerFormHandler::getServerDetailsForPhotos()
		 *
		 * @return
		 */
		public function getServerDetailsForPhotos()
			{
				$sql = 'SELECT server_url, ftp_server, ftp_usrename, ftp_password'.
						' FROM '.$this->CFG['db']['tbl']['server_settings'].
						' WHERE server_for=\'Ans_photo\' AND server_status=\'Yes\' LIMIT 0,1';
				// prepare sql
				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$rs = $this->dbObj->Execute($stmt);
				//raise user error... fatal
				if (!$rs)
				trigger_db_error($this->dbObj);
				$row = array();
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						$this->fields_arr['ftp_server'] = $row['ftp_server'];
						$this->fields_arr['ftp_usrename'] = $row['ftp_usrename'];
						$this->fields_arr['ftp_password'] = $row['ftp_password'];
						$this->fields_arr['server_url'] = $row['server_url'];
						return true;
					}
				return false;
			}

		/**
		 * PhotoUpload::storeImagesTempServer()
		 *
		 * @param $uploadUrl
		 * @param $extern
		 * @return
		 **/
		public function storePicturesTempServer($uploadUrl, $extern)
			{
				/*$this->imageObj->output_original($uploadUrl.'L.'.$extern, strtoupper($extern));
				$image_info = getImageSize($uploadUrl.'L.'.$extern);
				$this->L_WIDTH = $image_info[0];
				$this->L_HEIGHT = $image_info[1];*/

				if($this->CFG['admin']['ans_pictures']['small_name']=='S')
					{
						$this->imageObj->resize($this->CFG['admin']['ans_pictures']['small_width'], $this->CFG['admin']['ans_pictures']['small_height'], '-');
						$this->imageObj->output_resized($uploadUrl.'S.'.$extern, strtoupper($extern));
						$image_info = getImageSize($uploadUrl.'S.'.$extern);
						$this->S_WIDTH = $image_info[0];
						$this->S_HEIGHT = $image_info[1];
					}
				if($this->CFG['admin']['ans_pictures']['thumb_name']=='T')
					{
						$this->imageObj->resize($this->CFG['admin']['ans_photos']['thumb_width'], $this->CFG['admin']['ans_photos']['thumb_height'], '-');
						$this->imageObj->output_resized($uploadUrl.'T.'.$extern, strtoupper($extern));
						$image_info = getImageSize($uploadUrl.'T.'.$extern);
						$this->T_WIDTH = $image_info[0];
						$this->T_HEIGHT = $image_info[1];
					}
				if($this->CFG['admin']['ans_pictures']['large_name']=='L')
					{
						$this->imageObj->resize($this->CFG['admin']['ans_photos']['large_width'], $this->CFG['admin']['ans_photos']['large_height'], '-');
						$this->imageObj->output_resized($uploadUrl.'L.'.$extern, strtoupper($extern));
						$image_info = getImageSize($uploadUrl.'L.'.$extern);
						$this->L_WIDTH = $image_info[0];
						$this->L_HEIGHT = $image_info[1];
					}

				$wname = $this->CFG['admin']['ans_pictures']['large_name'].'_WIDTH';
				$hname = $this->CFG['admin']['ans_pictures']['large_name'].'_HEIGHT';
				$this->L_WIDTH = $this->$wname;
				$this->L_HEIGHT = $this->$hname;

				$wname = $this->CFG['admin']['ans_pictures']['small_name'].'_WIDTH';
				$hname = $this->CFG['admin']['ans_pictures']['small_name'].'_HEIGHT';
				$this->S_WIDTH = $this->$wname;
				$this->S_HEIGHT = $this->$hname;

				$wname = $this->CFG['admin']['ans_pictures']['thumb_name'].'_WIDTH';
				$hname = $this->CFG['admin']['ans_pictures']['thumb_name'].'_HEIGHT';
				$this->T_WIDTH = $this->$wname;
				$this->T_HEIGHT = $this->$hname;
			}

		/**
		 * QuestionFormHandler::addAttachments()
		 *
		 * @return
		 */
		 public function addAttachments()
		 	{
				$uploads_arr =array();
				$uploads_arr_original =array();
				$uploads_arr = $this->getFormField('uplarr');
				$uploads_arr_original = $this->getFormField('upl_original');
				$file_allowed_count = count($uploads_arr);

				for($i=0;$i<$file_allowed_count;$i++)
					{
						if($uploads_arr[$i] == '')
							continue;
						$extern = strtolower(substr($uploads_arr[$i], strrpos($uploads_arr[$i], '.')+1));
						$this->setFormField('photo_ext',$extern);
						$req_upl = explode('_', $uploads_arr[$i]);
						$temp_dir = 'files/uploads/';
						$def_req = $temp_dir.'temp_'.$req_upl[1].'_'.$req_upl[2].'.'.$extern;
						$imageObj = new ImageHandler($def_req);
						$this->setIHObject($imageObj);
						$temp_file =$temp_dir.'temp_'.$req_upl[1].'_'.$req_upl[2];
						$this->storePicturesTempServer($temp_file, $extern);

						$uploaded = false;
						$local_upload = true;
						$dir = $this->CFG['admin']['ans_attachments_path'];
						if($this->getServerDetailsForPhotos())
							{
								if($FtpObj = new FtpHandler($this->getFormField('ftp_server'),$this->getFormField('ftp_usrename'),$this->getFormField('ftp_password')))
									{
										$FtpObj->makeDirectory($dir);
										$FtpObj->changeDirectory($dir);

										$FtpObj->moveTo($temp_file.'.'.$extern, $dir.$image_name.'.'.$extern);
										unlink($temp_file.'.'.$extern);

										if($this->CFG['admin']['ans_pictures']['large_name']=='L')
											{
												$FtpObj->moveTo($temp_file.'L.'.$extern, $dir.$image_name.'L.'.$extern);
												unlink($temp_file.'L.'.$extern);
											}
										if($this->CFG['admin']['ans_pictures']['small_name']=='S')
											{
												$FtpObj->moveTo($temp_file.'S.'.$extern, $dir.$image_name.'S.'.$extern);
												unlink($temp_file.'S.'.$extern);

											}
										if($this->CFG['admin']['ans_pictures']['thumb_name']=='T')
											{
												$FtpObj->moveTo($temp_file.'T.'.$extern, $dir.$image_name.'T.'.$extern);
												unlink($temp_file.'T.'.$extern);
												$uploaded = true;
											}

										$this->setFormField('server_url',$this->getFormField('server_url'));
										$local_upload = false;
										return;
									}
							}
						if($local_upload)
							{
								$dir = $this->CFG['admin']['ans_attachments_path'];
								$this->chkAndCreateFolder($dir);
								$attachment_id = $this->createAttachmentRecord('');
								$uploadUrl = $dir.getImageName($attachment_id);

								if($this->CFG['admin']['ans_pictures']['large_name']=='L')
									{
										copy($temp_file.'L.'.$extern, $uploadUrl.'L.'.$extern);
										unlink($temp_file.'L.'.$extern);

									}
								if($this->CFG['admin']['ans_pictures']['small_name']=='S')
									{
										copy($temp_file.'S.'.$extern, $uploadUrl.'S.'.$extern);
										unlink($temp_file.'S.'.$extern);

									}
								if($this->CFG['admin']['ans_pictures']['thumb_name']=='T')
									{

										copy($temp_file.'T.'.$extern, $uploadUrl.'T.'.$extern);
										unlink($temp_file.'T.'.$extern);
										$uploaded = true;
									}

								$this->setFormField('server_url',$this->CFG['site']['url']);
							}

						if($uploaded)
							$this->updateAttachmentRecord($attachment_id, $uploads_arr_original[$i]);
					}
			}

		/**
		 * AnswerFormHandler::createAttachmentRecord()
		 *
		 * @param mixed $size
		 * @return
		 */
		public function createAttachmentRecord($size)
			{
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['attachments'].
						' SET content_type=\'Answer\''.
						', content_id='.$this->dbObj->Param('question').
						', attachment_size='.$this->dbObj->Param('size').
						', date_added=NOW()';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['content_id'], $size));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				return $this->dbObj->Insert_ID();
			}

		/**
		 * AnswerFormHandler::updateAttachmentRecord()
		 *
		 * @param mixed $aid
		 * @param mixed $file_path
		 * @return
		 */
		public function updateAttachmentRecord($aid, $file_path)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['attachments'].
						' SET attachment_name='.$this->dbObj->Param('question').
						' ,photo_server_url='.$this->dbObj->Param('server_url').
						' WHERE attachment_id='.$this->dbObj->Param('id');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($file_path, $this->fields_arr['server_url'], $aid));
				if (!$rs)
				        trigger_db_error($this->dbObj);
			}

		/**
		 * AnswerFormHandler::addQuestionComment()
		 *
		 * @param mixed $for
		 * @return
		 */
		public function addQuestionComment($for)
			{
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['question_comment'].
						' SET ques_id='.$this->dbObj->Param('c_qid').
						', ans_id='.$this->dbObj->Param('c_ans_id').
						', user_id='.$this->CFG['user']['user_id'].
						', comment='.$this->dbObj->Param('user_comment').
						', comment_for='.$this->dbObj->Param('for').
						', date_added=NOW()';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->getFormField('c_qid'), $this->getFormField('c_ans_id'),addslashes($this->getFormField('user_comment')), $for));
				if (!$rs)
				        trigger_db_error($this->dbObj);
			}

		/**
		 * AnswerFormHandler::populateCommentList()
		 *
		 * @param mixed $c_ansid
		 * @return
		 */
		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']), $this->CFG['admin']['answer']['line_length']));
								$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'] = getMemberUrl($row['user_id'], $populateCommentList_arr[$inc]['user_details']['name']);
								$populateCommentList_arr[$inc]['msg'] = 'msg_'.$row['ans_id'];
								$populateCommentList_arr[$inc]['anchor'] = 'deleteComment'.$row['comment_id'];
								$inc++;
							}
					}
				return $populateCommentList_arr;
			}

		/**
		 * AnswerFormHandler::populateAjaxCommentList()
		 *
		 * @param mixed $c_ansid
		 * @return
		 */
		public function populateAjaxCommentList($c_ansid)
			{
				global $smartyObj, $LANG,$CFG ;

				$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);

				$populateAjaxCommentList_arr = array();
				$smartyObj->assign('answersurl', getAnovaUrl('answer', '?action=view&title='.$this->getFormField('c_seo_title'), $this->getFormField('c_seo_title').'/'));
				if($rs->PO_RecordCount())
					{
						$inc = 0;
						while($row = $rs->FetchRow())
							{
								$row['comment'] = nl2br(wordWrapManual(strip_slashes($row['comment']), $this->CFG['admin']['answer']['line_length']));
								$populateAjaxCommentList_arr[$inc]['record'] = $row;
								$populateAjaxCommentList_arr[$inc]['commentSpanIDId'] = 'commentSpanID_'.$row['comment_id'];
								$populateAjaxCommentList_arr[$inc]['user_details'] = $this->getUserDetails($row['user_id']);
								$populateAjaxCommentList_arr[$inc]['user_details']['image_id'] = 'comments_'.$row['comment_id'];
								$populateAjaxCommentList_arr[$inc]['myanswers']['url'] = getMemberUrl($row['user_id'], $populateAjaxCommentList_arr[$inc]['user_details']['name']);
								$populateAjaxCommentList_arr[$inc]['anchor'] = 'deleteComment'.$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('general/', $this->CFG['admin']['index']['anova_module']);
				$smartyObj->display('commentAnswersAjaxList.tpl');
			}

		/**
		 * AnswerFormHandler::checkIfCommentAdded()
		 *
		 * @param mixed $ans_id
		 * @return
		 */
		public function checkIfCommentAdded($ans_id)
			{
				$sql = 'SELECT comment_id FROM '.$this->CFG['db']['tbl']['question_comment'].
						' WHERE ans_id = '.$this->dbObj->Param('ans_id');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($ans_id));
				    if (!$rs)
					    trigger_db_error($this->dbObj);
				$count = $rs->PO_RecordCount();
				if($count > 0)
					return true;
				else
					return false;
			}

		/**
		 * AnswerFormHandler::checkIfReplyAllowed()
		 *
		 * @param mixed $ques_id
		 * @param mixed $ans_id
		 * @return
		 */
		public function checkIfReplyAllowed($ques_id, $ans_id)
			{
				$sql = 'SELECT comment_id FROM '.$this->CFG['db']['tbl']['question_comment'].
						' WHERE ques_id = '.$this->dbObj->Param('ques_id').
						' AND ans_id = '.$this->dbObj->Param('ans_id').
						' AND user_id = '.$this->dbObj->Param($this->CFG['user']['user_id']);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($ques_id, $ans_id, $this->CFG['user']['user_id']));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				$count = $rs->PO_RecordCount();
				if($count < $this->CFG['admin']['number_of_comments']['allowed'])
					return true;
				else
					return false;
			}

		/**
		 * AnswerFormHandler::isAnswerOwner()
		 *
		 * @param mixed $ans_id
		 * @return
		 */
		public function isAnswerOwner($ans_id)
			{
				$sql = 'SELECT user_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($ans_id));
			    if (!$rs)
				    trigger_db_error($this->dbObj);
				if($rs->PO_RecordCount())
					{
						$inc = 0;
						while($row = $rs->FetchRow()) {
							if ($row['user_id'] == $this->CFG['user']['user_id'])
								return true;
						}
					}
				return false;
			}

		/**
		 * AnswerFormHandler::deleteComment()
		 *
		 * @param mixed $comment_id
		 * @return
		 */
		public function deleteComment($comment_id)
			{
				$sql = 'DELETE from '.$this->CFG['db']['tbl']['question_comment'].
						' WHERE comment_id = '.$this->dbObj->Param($comment_id);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($comment_id));
				if (!$rs)
				    trigger_db_error($this->dbObj);
			}

		/**
		 * AnswerFormHandler::getTotalQuestionComments()
		 *
		 * @param mixed $qid
		 * @param mixed $ans_id
		 * @return
		 */
		public function getTotalQuestionComments($qid, $ans_id)
			{
				$sql = 'SELECT comment_id FROM '.$this->CFG['db']['tbl']['question_comment'].
						' WHERE ques_id = '.$this->dbObj->Param('qid').
						' AND comment_for =\'Question\' AND ans_id = '.$this->dbObj->Param('ans_id').
						' AND user_id = '.$this->CFG['user']['user_id'];
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($qid, $ans_id));
			    if (!$rs)
				    trigger_db_error($this->dbObj);
				$count = $rs->PO_RecordCount();
				if($count < $this->CFG['admin']['number_of_comments']['allowed'])
					return true;
				else
					return false;
			}

		/**
		 * AnswerFormHandler::getTotalAnswerComments()
		 *
		 * @param mixed $ans_id
		 * @return
		 */
		public function getTotalAnswerComments($ans_id)
	   		{
				$sql = 'SELECT comment_id FROM '.$this->CFG['db']['tbl']['question_comment'].
						' WHERE ans_id = '.$this->dbObj->Param('ans_id').' AND comment_for =\'Answer\''.
					  	' AND user_id = '.$this->dbObj->Param($this->CFG['user']['user_id']);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($ans_id, $this->CFG['user']['user_id']));
			    if (!$rs)
				    trigger_db_error($this->dbObj);
				$count = $rs->PO_RecordCount();
				if($count < $this->CFG['admin']['number_of_comments']['allowed'])
					return true;
				else
					return false;
			}

		/**
		 * AnswerFormHandler::chkQuestionOwnerPostedComments()
		 *
		 * @param mixed $ans_id
		 * @return
		 */
		public function chkQuestionOwnerPostedComments($ans_id)
	   		{
				$sql = 'SELECT comment_id FROM '.$this->CFG['db']['tbl']['question_comment'].
						' WHERE ans_id = '.$this->dbObj->Param('ans_id').' AND comment_for =\'Answer\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($ans_id));
			    if (!$rs)
				    trigger_db_error($this->dbObj);
				$count = $rs->PO_RecordCount();
				if($count > 0)
					return true;
				else
					return false;
			}

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

				if($rs->PO_RecordCount())
					{
						$category_title = '';
						while($row = $rs->FetchRow())
							{
								if($row['cat_name'] != '')
									$category_title.=$row['cat_name'].' - ';
							}
						return $category_title;
					}
			}

		/**
		 * AnswerFormHandler::getQuestionVotesCount()
		 *
		 * @param mixed $id
		 * @return
		 */
		public function getQuestionVotesCount($id)
			{
				$sql = 'SELECT votes from '.$this->CFG['db']['tbl']['questions'].
						' WHERE ques_id = '.$id;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
						trigger_db_error($this->dbObj);
				$row= $rs->fetchRow();
				return $row['votes'];
			}

	    /**
	     * AnswerFormHandler::getAnswerVotesCount()
	     *
	     * @param mixed $id
	     * @return
	     */
	    public function getAnswerVotesCount($id)
			{
				$sql = 'SELECT votes from '.$this->CFG['db']['tbl']['answers'].
						' WHERE ans_id = '.$id;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
						trigger_db_error($this->dbObj);
				$row= $rs->fetchRow();
				return $row['votes'];
			}
		public function totalPostedAnswerCount($user_id)
			{
				if(!chkIsPaymentAllowed('payment_answers'))
					return true;

				if(!$this->CFG['user']['user_id'])
					return;

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

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($user_id, $this->CFG['user']['last_paid_date']));
				if (!$rs)
				    trigger_db_error($this->dbObj);
				$numrows = $rs->PO_RecordCount();
				if($numrows < $this->CFG['plan']['plan_total_ans'] || $this->CFG['plan']['plan_total_ans'] == $this->CFG['plan']['unlimited'])
					return true;
				else
					return false;
			}
		public function todayPostedAnswerCount($user_id)
			{
				if(!chkIsPaymentAllowed('payment_answers'))
					return true;

				if(!$this->CFG['user']['user_id'])
					return;

				$sql = 'SELECT ans_id from '.$this->CFG['db']['tbl']['answers'].''.
				       ' WHERE user_id = '.$this->dbObj->Param($user_id).''.
					   ' AND DATE_FORMAT(date_answered, \''.$this->CFG['mysql_format']['date_time'].'\') >= DATE_FORMAT((select DATE_SUB(now(), INTERVAL 1 DAY)),\''.$this->CFG['mysql_format']['date_time'].'\')';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($user_id));
				if (!$rs)
				    trigger_db_error($this->dbObj);
				$numrows = $rs->PO_RecordCount();
				if($numrows < $this->CFG['plan']['plan_ans_perday'] || $this->CFG['plan']['plan_ans_perday'] == $this->CFG['plan']['unlimited'] )
					return true;
				else
					return false;
			}
		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function relatedQuestion()
			{
				global $smartyObj;

				$keywords = $this->removeDuplicateKeywords($this->question_details['tags'].' '.$this->question_details['question']);

				$randColumns = array('q.ques_id', 'q.total_answer', 'q.question', 'q.total_views', 'q.total_videos', 'q.total_audios');

				$sql = 'SELECT q.ques_id, q.question, q.seo_title, q.tags, q.description, q.pcat_id, q.cat_id, q.video_id, q.audio_id, q.best_ans_id, q.external_video_id, q.external_audio_id'.
						', q.total_answer, q.votes, q.total_stars, q.total_views, q.total_videos, q.total_audios'.
						', q.publish_status, UNIX_TIMESTAMP(date_asked) as date_asked, q.status, q.user_id, '.
						$this->getUserTableField('display_name').' AS asked_by, u.'.$this->getUserTableField('user_id').' AS img_user_id, '.
						$this->getUserTableFields(array('t_height', 'name', 't_width', 's_height', 's_width','photo_server_url', 'photo_ext', 'image_path', 'gender')).
						', IF(status=\'Open\' AND date_closed>=NOW(), 1, 0) is_open, TIMEDIFF(date_closed, NOW()) as date_closed'.
						' 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 q.status IN (\'Open\', \'Resolved\')'.
						' AND u.'.$this->getUserTableField('usr_status').'=\'Ok\' AND q.ques_id != '.$this->dbObj->Param($this->fields_arr['qid']).
						' AND ( '.getSearchRegularExpressionQuery($keywords, 'q.question').' OR '.getSearchRegularExpressionQuery($keywords, 'q.tags').' )'.
						' ORDER BY '.$randColumns[rand(0, count($randColumns)-1)].' LIMIT 0, 3';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
					    trigger_db_error($this->dbObj);

				$related_questions = array();
				if ($rs->PO_RecordCount())
					{
						$i = 0;
						while ($row = $rs->FetchRow()) {
							$row['clsOddOrEvenQuestion'] = ($i%2)? 'clsOddQuestion' : 'clsEvenQuestion';
							$row['answer_url'] = getAnovaUrl('answer', '?title='.$row['seo_title'], $row['seo_title'].'/');
							$row['question_manual'] = wordWrapManual($row['question'], $this->CFG['admin']['question']['line_length'], $this->CFG['admin']['question']['short_length']);
							$row['myanswers_url'] = getMemberUrl($row['user_id'], $row['name']);
							$row['asked_by'] = stripString($row['asked_by'], $this->CFG['username']['short_length']);

							$row['video_plural'] = ($row['total_videos']!= 1) ? $this->LANG['common_total_videos'] : $this->LANG['video'];
							$row['audio_plural'] = ($row['total_audios']!= 1) ? $this->LANG['common_total_audios'] : $this->LANG['common_total_audio'];
							$row['answer_plural'] = ($row['total_answer']!= 1) ? $this->LANG['answers'] : $this->LANG['common_total_answer'];
							$row['views_plural'] = ($row['total_views']!= 1) ? $this->LANG['common_total_views'] : $this->LANG['common_total_view'];

							$cat_id = ($row['cat_id']) ? $row['cat_id'] : $row['pcat_id'];
							$row['showCategoryName'] = $this->showCategoryName($cat_id);

							$row['audio_on_click'] = 'ques_audio_'.$row['audio_id'];
							$row['audio_url'] = getAnovaUrl('ansviewaudio', '?pg=Question_'.$row['audio_id'], '?pg=Question_'.$row['audio_id']);

							$row['video_on_click'] = 'ques_video_'.$row['video_id'];
							$row['video_url'] = getAnovaUrl('ansviewvideo', '?pg=Question_'.$row['video_id'], '?pg=Question_'.$row['video_id']);

							$row['ext_ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Question_'.$row['external_video_id'], '?pg=Question_'.$row['external_video_id']);
		  					$row['ext_ans_view_video']['on_click'] = 'external_video_ques_'.$row['ques_id'];

							$row['ext_ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Question_'.$row['external_audio_id'], '?pg=Question_'.$row['external_audio_id']);
							$row['ext_ans_view_audio']['on_click'] = 'external_audio_ques_'.$row['ques_id'];

							$row['has_attachment'] = false;
							if ($this->CFG['admin']['attachments_questions']['allowed'] && $attachment_details = $this->hasAnyAttachment($row['ques_id'], 'Question'))
								{
									$row['has_attachment'] = true;
									$extern = strtolower(substr($attachment_details['attachment_name'], strrpos($attachment_details['attachment_name'], '.')+1));
									$attachment_original_file_name = getImageName($attachment_details['attachment_id']).$this->CFG['admin']['ans_pictures']['large_name'].'.'.$extern;
									$row['img_id'] = 'Question_'.$row['ques_id'].'_'.$attachment_details['attachment_id'];
									$row['attachment_path'] = getAnovaUrl('answer', '?title='.$row['seo_title'].'&amp;imgdetail='.$row['img_id'], $row['seo_title'].'/?imgdetail='.$row['img_id']);
									$row['image_large_path'] = $attachment_details['photo_server_url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$attachment_original_file_name;
								}
							$i++;

							$related_questions[] = $row;
						}
					}
				$smartyObj->assign('related_questions', $related_questions);
				setTemplateFolder('general/', $this->CFG['admin']['index']['anova_module']);
				$smartyObj->display('relatedQuestions.tpl');
			}
	}
//<<<<<-------------- Class AnswerFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$answers = new AnswerFormHandler();
$answers->setPageBlockNames(array('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('search_question', '');
$answers->setFormField('answer', '');
$answers->setFormField('share_answer', '');
$answers->setFormField('source', '');
$answers->setFormField('action', '');
$answers->setFormField('content_id', '');
$answers->setFormField('reason', '');
$answers->setFormField('str', '');
$answers->setFormField('msg', '');
$answers->setFormField('video', '');
$answers->setFormField('video_id', '');
$answers->setFormField('external_video_id', '');
$answers->setFormField('audio', '');
$answers->setFormField('audio_id', '');
$answers->setFormField('external_audio_id', '');
$answers->setFormField('video_external_flv_url', '');
$answers->setFormField('flv_upload_type', '');
$answers->setFormField('file_extern', '');
$answers->setFormField('audio_external_url', '');
$answers->setFormField('audio_extern', '');
$answers->setFormField('rid', '');
$answers->setFormField('title', '');
$answers->setFormField('seo_title', '');
$answers->setFormField('picturelimit', '');
$answers->setFormField('attachments', '');
$answers->setFormField('attachment_id', '');
$answers->setFormField('attach_content_id', '');
$answers->setFormField('attachment_name', '');
$answers->setFormField('c_ans_id', '');
$answers->setFormField('user_comment', '');
$answers->setFormField('c_seo_title', '');
$answers->setFormField('c_qid', '');
$answers->setFormField('reply', '');
$answers->setFormField('user_reply', '');
$answers->setFormField('comment_id', '');
$answers->setFormField('vote_type', '');
$answers->setFormField('value', '');
$answers->setFormField('id', '');
$answers->setFormField('usrid', '');
$answers->setFormField('vote_id', '');
$answers->setFormField('ajax_page', '');
$answers->setFormField('update', '');
$answers->setFormField('vote_for', '');
$answers->setFormField('upl_original', array());
$answers->setFormField('uplarr', array());
$answers->setFormField('imgdetail', '');
$answers->setFormField('w', '');
$answers->setFormField('h', '');
$answers->setFormField('share_answer_session', (isset($_SESSION['share_answer']) ? $_SESSION['share_answer'] : ''));

if(isMember()){
	$answers->CFG['html']['page_id'] = 'member'.$answers->CFG['html']['page_id'];
	if(isset($_SESSION['share_answer']))
		unset($_SESSION['share_answer']);
}
$req_settings = '';
$cnt_format = count($CFG['admin']['attachments']['format_arr']);
if($cnt_format <= 0)
	{
		$req_settings = "*.jpg;*.jpeg;*.png; *.gif";
	}
else
	{
		for ($i=0;$i<$cnt_format;$i++) {
			$req_settings = $req_settings.'*.'.$CFG['admin']['attachments']['format_arr'][$i].';';
		}
	}
/*************Start navigation******/
$answers->numpg = $CFG['data_tbl']['numpg'];
$answers->setFormField('start', 0);
$answers->setFormField('numpg', $CFG['data_tbl']['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->fp = false;
$answers->sanitizeFormInputs($_REQUEST);
if($answers->getFormField('share_answer'))
	$answers->setFormField('answer', $answers->getFormField('share_answer'));
if ($answers->isFormGETed($_REQUEST, 'postYourAnswer'))
	{
		if ($answers->chkIsValidQuestion())
			{
				if (!isMember())
					{
						$_SESSION['url'] = getAnovaUrl('answer', '?title='.$answers->question_details['seo_title'], $answers->question_details['seo_title'].'/');
						$_SESSION['login_error'] = 'login_err_authorization_required';
						echo 'Session Expired. <a href="'.$CFG['auth']['login_url']['url'].'?r">Login to continue..!</a>';
						die();
					}
				$answers->setAllPageBlocksHide();
				$answers->chkIsNotEmpty('answer', $LANG['err_tip_compulsory']);
				if (!$answers->isQuestionOpen())
					$answers->setCommonErrorMsg($LANG['answers_err_not_open']);
				elseif (!$answers->isAllowedToAsk())
					$answers->setCommonErrorMsg($LANG['info_not_allowed_to_ask']);

				if ($answers->isValidFormInputs() && isMember())
					{
						if ($CFG['debug']['store_log'])
							{
								$answers->createErrorLogFile('answer');
							}

						if($answers->totalPostedAnswerCount($CFG['user']['user_id']))
				  			{

								if($answers->todayPostedAnswerCount($CFG['user']['user_id']))
									{
										$answers->addAnswer();

										//Unset session variable share_answer
										unset($_SESSION['share_answer']);

										if ($CFG['debug']['store_log'])
											{
												$answers->closeErrorLogFile();
											}
										$answers->setCommonSuccessMsg($LANG['answers_added_successfully']);
										$answers->setPageBlockShow('block_msg_form_success');
									}
								else
									{
										$answers->setPageBlockShow('block_msg_form_error');
										$answers->setCommonErrorMsg($LANG['info_not_allowed_to_ask_today']);
									}
							}
						else
							{
								$answers->setPageBlockShow('block_msg_form_error');
								$upgrade = '<a href="'.getAnovaUrl('paymentupgrade').'">'.$answers->LANG['answers_upgrade'].'</a>';
								if(!chkIsPaymentUpgradeAllowed())
									$upgrade = $LANG['inform_site_admin'];
								$LANG['info_limit_exceeded_to_ask_questions'] = str_ireplace('VAR_UPGRADE', $upgrade, $LANG['info_limit_exceeded_to_ask_questions']);
								$answers->setCommonErrorMsg($LANG['info_limit_exceeded_to_ask_questions']);
							}
					}
				else
					{
						$answers->setCommonErrorMsg($LANG['common_msg_error_sorry']);
						$answers->setPageBlockShow('block_msg_form_error');
					}
			}

		$answers->includeAjaxHeader();
		$answers->setTableNames(array($CFG['db']['tbl']['answers'].' as a', $CFG['db']['tbl']['users'].' as u'));
		$answers->setReturnColumns(array('a.ans_id', 'a.video_id', 'a.audio_id', 'a.external_video_id', 'a.external_audio_id', 'a.user_id', 'a.answer','a.votes', 'a.status', 'a.source', 'UNIX_TIMESTAMP(date_answered) as date_answered', 'u.'.$answers->getUserTableField('user_id').' as img_user_id', $answers->getUserTableFields(array('image_path','t_height', 't_width', 's_height', 's_width','photo_server_url', 'photo_ext', 'name')), $answers->getUserTableField('gender').' as gender', $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->executeQuery();

		$answers->form_answers['displayAllAnswers_arr'] = $answers->displayAllAnswers();
		if($answers->CFG['feature']['rewrite_mode'] == 'htaccess')
			$pagingArr = array();
		else
			$pagingArr = array('title');

		$smartyObj->assign('smarty_paging_list', $answers->populatePageLinksGET($answers->getFormField('start'), $pagingArr));
		$answers->setPageBlockShow('form_answers');
		setTemplateFolder('general/', $CFG['admin']['index']['anova_module']);
		$smartyObj->display('answer.tpl');
		$answers->includeAjaxFooter();
		die();
	}
if ($answers->isFormGETed($_REQUEST, 'imgdetail'))
	{
		if(isAjax())
			{
				$answers->includeAjaxHeader();
				if ($answers->chkIsValidQuestion())
					{
						$answers->displayImageGallery($answers->getFormField('imgdetail'));
					}
				$answers->includeAjaxFooter();
				die();
			}
	}
if ($answers->isFormGETed($_GET, 'vote_type'))
	{
		$answers->sanitizeFormInputs($_REQUEST);
		if (isMember())
			$answers->UpdateUserVote($answers->getFormField('vote_type'),  $answers->getFormField('value'), $answers->getFormField('usrid'), $answers->getFormField('id'));
		die();
	}
if ($answers->isFormGETed($_GET, 'update'))
	{
		$answers->sanitizeFormInputs($_REQUEST);
		if (!isMember())
			{
				?>
					<script language="javascript" type="text/javascript" defer="defer">
						var a  = "<?php echo $answers->getFormField('vote_id');?>";
						var langvote  = "langvote<?php echo $answers->getFormField('id');?>";
						$(a).innerHTML = "Session Expired!";
						$(langvote).innerHTML = "";
					</script>
				<?php
				die();
			}
		if($answers->getFormField('vote_for') == 'question')
			{
				$total_votes = $answers->getQuestionVotesCount($answers->getFormField('id'));
				$lang_vote = ($total_votes == 1)?$LANG['vote']:$LANG['helpful'];
				?>
					<script language="javascript" type="text/javascript" defer="defer">
						var a  = "<?php echo $answers->getFormField('vote_id');?>";
						var langvote  = "langvote<?php echo $answers->getFormField('id');?>";
						$(a).innerHTML = "<?php echo $total_votes;?>";
						$(langvote).innerHTML = "<?php echo $lang_vote;?>";
					</script>
				<?php
			}
		else
			{
				 $total_votes = $answers->getAnswerVotesCount($answers->getFormField('id'));
				 $lang_vote = ($total_votes == 1)?$LANG['vote']:$LANG['helpful'];
				?>
					<script language="javascript" type="text/javascript" defer="defer">
						var a  = "<?php echo $answers->getFormField('vote_id');?>";
						var langvote  = "langvote<?php echo $answers->getFormField('id');?>";
						$(a).innerHTML = "<?php echo $total_votes;?>";
						$(langvote).innerHTML = "<?php echo $lang_vote;?>";
					</script>
				<?php
			}
		ob_end_flush();
		die();
	}

$smartyObj->assign('reply', '');

if ($answers->isFormPOSTed($_REQUEST, 'showOptionToComment'))
	{
		ob_start();
		$answers->sanitizeFormInputs($_REQUEST);
		$showOptionToComment_arr = array();
		$c_ans_id = $answers->getFormField('c_ans_id');
		$commentSpanIDId = 'commentSpanID_'.$answers->getFormField('c_ans_id');
		if($answers->getFormField('reply') == 'reply')
			$showOptionToComment_arr['submit']['onclick'] =  getAnovaUrl('answer', '?action=view&ajax_page=true&reply=reply&c_qid='.$answers->getFormField('c_qid').'&postYourComment=1&title='.$answers->getFormField('c_seo_title'), $answers->getFormField('c_seo_title').'/?action=view&ajax_page=true&postYourComment=1', 'members');
		else
			$showOptionToComment_arr['submit']['onclick'] =  getAnovaUrl('answer', '?action=view&ajax_page=true&postYourComment=1&title='.$answers->getFormField('c_seo_title'), $answers->getFormField('c_seo_title').'/?action=view&ajax_page=true&postYourComment=1', 'members');
		$showOptionToComment_arr['cancel']['onclick'] = getAnovaUrl('answer', '?action=view&title='.$answers->getFormField('c_seo_title'),$answers->getFormField('c_seo_title').'/', 'members');
		$answers->setPageBlockShow('show_option_to_comment');
		$answers->includeAjaxHeader();
		$smartyObj->assign('showOptionToComment_arr', $showOptionToComment_arr);
		$smartyObj->assign('c_ans_id', $c_ans_id);
		$smartyObj->assign('commentSpanIDId', $commentSpanIDId);
		setTemplateFolder('general/', $CFG['admin']['index']['anova_module']);
		$smartyObj->display('commentAnswersAjax.tpl');
		$answers->includeAjaxFooter();
		die();
	}
if ($answers->isFormPOSTed($_REQUEST, 'cancelOptionToComment'))
	{
		ob_start();
		$answers->sanitizeFormInputs($_REQUEST);
		$answers->setPageBlockShow('cancel_option_to_comment');
		$answers->includeAjaxHeader();
		setTemplateFolder('general/', $CFG['admin']['index']['anova_module']);
		$smartyObj->display('commentAnswersAjax.tpl');
		$answers->includeAjaxFooter();
		die();
	}
if ($answers->isFormPOSTed($_REQUEST, 'postYourComment'))
	{
		ob_start();
		$answers->sanitizeFormInputs($_REQUEST);
		if ($answers->chkIsValidQuestion())
			{
				if (!isMember())
					{
						$_SESSION['url'] = getAnovaUrl('answer', '?title='.$answers->question_details['seo_title'], $answers->question_details['seo_title']);
						$_SESSION['login_error'] = 'login_err_authorization_required';
						echo 'Session Expired. <a href="'.$CFG['auth']['login_url']['url'].'?r">Login to continue..!</a>';
							?>
						<script defer="defer" language="javascript" type="text/javascript">
							function hideMsgBox()
								{
									var a =  <?php echo $answers->getFormField('c_ans_id');?>;
									document.getElementById("commentSpanID_"+ a).innerHTML = '';
								}
							hideMsgBox();
						</script>
						<?php
						die();
					}

				if($answers->getFormField('reply') == '')
					{
						$answers->addQuestionComment('Answer');
						if(!$answers->getTotalAnswerComments($answers->getFormField('c_ans_id')))
							{
						?>
						<script defer="defer" language="javascript" type="text/javascript">
							function hideAddCommentBox()
								{
									var a =  <?php echo $answers->getFormField('c_ans_id');?>;
									if(document.getElementById("addComment_"+a))
										document.getElementById("addComment_"+a).innerHTML = '';
									else
										document.getElementById("addReply_"+a).innerHTML = '';
								}
							hideAddCommentBox();
						</script>
						<?php
							}
					}
				else
					{
						$answers->addQuestionComment('Question');
						if(!$answers->getTotalQuestionComments($answers->getFormField('c_qid'), $answers->getFormField('c_ans_id')))
							{
						?>
						<script defer="defer" language="javascript" type="text/javascript">
							function hideAddReplyBox()
								{
									var a =  <?php echo $answers->getFormField('c_ans_id');?>;
									if(document.getElementById("addReply_"+a))
										document.getElementById("addReply_"+a).innerHTML = '';
									else
										document.getElementById("addComment_"+a).innerHTML = '';
								}
							hideAddReplyBox();
						</script>
						<?php
							}
					}
			}
		$answers->setFormField('success', 'success');
		$answers->setCommonSuccessMsg($LANG['answer_comments_success']);
		$answers->setPageBlockShow('block_msg_form_success');
		$answers->populateAjaxCommentList($answers->getFormField('c_ans_id'));
		?>
		<script defer="defer" language="javascript" type="text/javascript">
			function hideMsgBox()
				{
					var a =  <?php echo $answers->getFormField('c_ans_id');?>;
					document.getElementById("commentSpanID_"+ a).innerHTML = '';
				}
			hideMsgBox();
		</script>
		<?php
		$answers->includeAjaxHeader();
		setTemplateFolder('general/', $CFG['admin']['index']['anova_module']);
		$smartyObj->display('commentAnswersAjax.tpl');
		$answers->includeAjaxFooter();
		die();
	}
if(!$answers->getFormField('rid'))
	$answers->generateRandomId();
// Default page block
$answers->setAllPageBlocksHide();

$answers->title = $LANG['open_question'];
$cfg_title = $answers->title;
$valid_question = false;
if ($answers->isFormGETed($_GET, 'aid'))
	$answers->chkIsValidAnswer();
if ($answers->chkIsValidQuestion())
	{
		$valid_question = true;
		$answers->incrementViews();

		$answers->title = $LANG['open_question'];
		if (!$answers->isQuestionOpen())
			$answers->title = $LANG['resolved_question'];

		$cfg_title = $answers->question_details['question'];

		$answers->setPageBlockShow('form_question');
		$answers->setPageBlockShow('form_answers');

		if ($answers->isFormPOSTed($_REQUEST, 'deletemoreattachments'))
			{
				if (!isMember())
					{
						echo 'Session Expired. <a href="'.$CFG['auth']['login_url']['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);
				die();
			}

		if ($answers->isFormPOSTed($_POST, 'update_answer'))
			{
				if (!isMember())
					{
						$_SESSION['url'] = getAnovaUrl('answer', '?title='.$answers->getFormField('title'), $answers->getFormField('title'));
						$_SESSION['login_error'] = 'login_err_authorization_required';
						Redirect2URL(getUrl('login'));
					}
				$answers->title = $LANG['answers_edit_your_answer'];
				$cfg_title = $answers->title;
				$answers->chkIsNotEmpty('answer', $LANG['err_tip_compulsory']);
				if (!$answers->isQuestionOpen())
					$answers->setCommonErrorMsg($LANG['answers_err_not_open']);

				if(chkIsVideoAllowed('answer'))
					$answers->chkIsValidCaptureVideoFile();
				if(chkIsAudioAllowed('answer'))
					$answers->chkIsValidCaptureAudioFile();

				if ($answers->isValidFormInputs() && isMember())
					{
						$answers->updateAnswer();
						$answers->setCommonSuccessMsg($LANG['answers_updated_successfully']);
						$answers->setPageBlockShow('block_msg_form_success');
						Redirect2URL(getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title').'&msg=7', $answers->getFormField('seo_title').'/?msg=7'));
					}
				else
					{
						$answers->setPageBlockHide('form_question');
						$answers->setPageBlockHide('form_answers');
						$answers->setPageBlockShow('form_add');
						$answers->setCommonErrorMsg($LANG['common_msg_error_sorry']);
						$answers->setPageBlockShow('block_msg_form_error');
					}
			}
		else if ($answers->isFormPOSTed($_POST, 'confirm_action'))
			{
				if (!isMember())
					{
						$_SESSION['url'] = getAnovaUrl('answer', '?title='.$answers->question_details['seo_title'], $answers->question_details['seo_title'].'/');
						$_SESSION['login_error'] = 'login_err_authorization_required';
						Redirect2URL(getUrl('login'));
					}
				switch($answers->getFormField('action')){
					case 'resolve':
						$answers->title = $LANG['resolve_question'];
						$cfg_title = $answers->title;
						if ($answers->question_details['user_id'] == $CFG['user']['user_id'])
							{
								$answers->resolveQuestion();
								$answers->question_details['status'] = 'Resolved';
								$answers->setPageBlockShow('block_msg_form_success');
								$answers->setCommonSuccessMsg($LANG['answers_resolved_successfully']);
								Redirect2URL(getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title').'&msg=8', $answers->getFormField('seo_title').'/?msg=8'));
							}
						else
							{
								$answers->setAllPageBlocksHide();
								$answers->setPageBlockShow('block_msg_form_error');
								$answers->setCommonErrorMsg($LANG['err_tip_invalid_action']);
							}
						break;
					case 'delete':
						if ($answers->question_details['user_id'] == $CFG['user']['user_id'])
							{
								$answers->deleteQuestion();
								Redirect2URL(getAnovaUrl('questions', '?view=all&msg=3', 'all/?msg=3'));
							}
						else
							{
								$answers->setAllPageBlocksHide();
								$answers->setPageBlockShow('block_msg_form_error');
								$answers->setCommonErrorMsg($LANG['err_tip_invalid_action']);
							}
						break;
					case 'abusequestion':
						$answers->chkIsNotEmpty('reason', $LANG['err_tip_compulsory']);
						$answers->title = $LANG['report_abuse'];
						$cfg_title = $answers->title;
						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(getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title').'&msg=2', $answers->getFormField('seo_title').'/?msg=2'));
							}
						else
							{
								$answers->setPageBlockShow('block_msg_form_error');
							}
						break;
					case 'abuseanswer':
						$answers->chkIsNotEmpty('reason', $LANG['err_tip_compulsory']);
						$answers->title = $LANG['report_abuse'];
						$cfg_title = $answers->title;
						$answers->setFormField('aid', $answers->getFormField('content_id'));
						$answers->chkIsValidAnswer();
						if ($answers->isValidFormInputs())
							{
								$answers->updateAbuseAnswer();
								$answers->setPageBlockShow('block_msg_form_success');
								$answers->setPageBlockShow('form_question');
								$answers->setPageBlockShow('form_answers');
								$answers->setCommonSuccessMsg($LANG['answers_answer_abused_successfully']);
								Redirect2URL(getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title').'&msg=3', $answers->getFormField('seo_title').'/?msg=3'));
							}
						else
							{
								$answers->setPageBlockShow('block_msg_form_error');
							}
						break;
					case 'deleteanswer':
						$answers->chkIsNotEmpty('aid', $LANG['err_tip_compulsory'])and
							$answers->chkIsAnswerOwner($LANG['err_tip_invalid_action']);
						if ($answers->isValidFormInputs() AND $CFG['admin']['answer']['delete'])
							{
								$answers->chkIsValidAnswer();
								$answers->deleteAnswer();
								$answers->setPageBlockShow('block_msg_form_success');
								$answers->setCommonSuccessMsg($LANG['answers_answer_deleted_successfully']);
								Redirect2URL(getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title').'&msg=6', $answers->getFormField('seo_title').'/?msg=6'));
							}
						else
							{
								$answers->setPageBlockShow('block_msg_form_error');
							}

						break;
					case 'bestanswers':
						$answers->chkIsNotEmpty('aid', $LANG['err_tip_compulsory']);
						$answers->title = $LANG['best_answer'];
						$cfg_title = $answers->title;
						if ($answers->isValidFormInputs() and $CFG['user']['user_id'] == $answers->question_details['user_id']  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(getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title').'&msg=4', $answers->getFormField('seo_title').'/?msg=4'));
							}
						else
							{
								$answers->setPageBlockShow('block_msg_form_error');
							}
						break;
					case 'publishanswer':
						$answers->chkIsNotEmpty('aid', $LANG['err_tip_compulsory']);
						if ($answers->isValidFormInputs() and $CFG['user']['user_id'] == $answers->question_details['user_id'] 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(getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title').'&msg=9', $answers->getFormField('seo_title').'/?msg=9'));
							}
						else
							{
								$answers->setPageBlockShow('block_msg_form_error');
							}
						break;
				    case 'deletecomment':
							$comment_id = $answers->getFormField('comment_id');
							$answers->deleteComment($comment_id);
							$answers->setPageBlockShow('block_msg_form_success');
							$answers->setCommonSuccessMsg($LANG['answers_answer_deleted_successfully']);
							Redirect2URL(getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title').'&msg=10', $answers->getFormField('seo_title').'/?msg=10'));
						break;
				} // switch
			}
		else if ($answers->isFormPOSTed($_POST, 'submit'))
			{
				if (!isMember())
					{
						$_SESSION['url'] = getAnovaUrl('answer', '?title='.$answers->getFormField('title'), $answers->getFormField('title').'/');
						$_SESSION['login_error'] = 'login_err_authorization_required';
						Redirect2URL(getUrl('login'));
					}
				$answers->title = $LANG['answers_what_is_your_answer'];
				$cfg_title = $answers->title;
				$answers->chkIsNotEmpty('answer', $LANG['err_tip_compulsory']);
				if (!$answers->isQuestionOpen())
					$answers->setCommonErrorMsg($LANG['answers_err_not_open']);
				elseif (!$answers->isAllowedToAsk())
					$answers->setCommonErrorMsg($LANG['info_not_allowed_to_ask']);

				if(chkIsVideoAllowed('answer'))
					$answers->chkIsValidCaptureVideoFile();
				if(chkIsAudioAllowed('answer'))
					$answers->chkIsValidCaptureAudioFile();

				if ($answers->isValidFormInputs() && isMember())
					{
						if ($CFG['debug']['store_log'])
							{
								$answers->createErrorLogFile('answer');
							}

						if($answers->totalPostedAnswerCount($CFG['user']['user_id']))
				  			{

								if($answers->todayPostedAnswerCount($CFG['user']['user_id']))
									{
										$answers->addAnswer();
										if ($CFG['debug']['store_log'])
											{
												$answers->closeErrorLogFile();
											}
										$answers->setCommonSuccessMsg($LANG['answers_added_successfully']);
										$answers->setPageBlockShow('block_msg_form_success');
										Redirect2URL(getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title').'&msg=1', $answers->getFormField('seo_title').'/?msg=1'));
									}
								else
									{
										$answers->setPageBlockShow('block_msg_form_error');
										$answers->setCommonErrorMsg($LANG['info_not_allowed_to_ask_today']);
									}
							}
						else
							{
								$answers->setPageBlockShow('block_msg_form_error');
								$upgrade = '<a href="'.getAnovaUrl('paymentupgrade').'">'.$answers->LANG['answers_upgrade'].'</a>';
								if(!chkIsPaymentUpgradeAllowed())
									$upgrade = $LANG['inform_site_admin'];
								$LANG['info_limit_exceeded_to_ask_questions'] = str_ireplace('VAR_UPGRADE', $upgrade, $LANG['info_limit_exceeded_to_ask_questions']);
								$answers->setCommonErrorMsg($LANG['info_limit_exceeded_to_ask_questions']);
							}
					}
				else
					{
						$answers->setCommonErrorMsg($LANG['common_msg_error_sorry']);
						$answers->setPageBlockShow('block_msg_form_error');
					}
			}

		if ($answers->isFormGETed($_GET, 'action'))
			{
				if (!isMember())
					{
						$_SESSION['url'] = getAnovaUrl('answer', '?title='.$answers->getFormField('title'), $answers->getFormField('title').'/');
						$_SESSION['login_error'] = 'login_err_authorization_required';
						$_SESSION['share_answer'] = $answers->getFormField('share_answer');
						Redirect2URL(getUrl('login'));
					}
				switch($answers->getFormField('action')){
					case 'reply':
						if ($answers->isQuestionOpen())
							{
								$answers->setPageBlockHide('form_question');
								$answers->setPageBlockHide('form_answers');
								if ($answers->isAllowedToAsk())
									{
										if( $answers->question_details['user_id'] != $answers->CFG['user']['user_id'])
											{

												if($answers->totalPostedAnswerCount($CFG['user']['user_id']))
										  			{
														if($answers->todayPostedAnswerCount($CFG['user']['user_id']))
															$answers->setPageBlockShow('form_add');
														else
															{
																$answers->setPageBlockShow('block_msg_form_error');
																$answers->setCommonErrorMsg($LANG['info_not_allowed_to_ask_today']);
															}
													}
												else
													{
														$answers->setPageBlockShow('block_msg_form_error');
														$upgrade = '<a href="'.getAnovaUrl('paymentupgrade').'">'.$answers->LANG['answers_upgrade'].'</a>';
														if(!chkIsPaymentUpgradeAllowed())
															$upgrade = $LANG['inform_site_admin'];
														$LANG['info_limit_exceeded_to_ask_questions'] = str_ireplace('VAR_UPGRADE', $upgrade, $LANG['info_limit_exceeded_to_ask_questions']);
														$answers->setCommonErrorMsg($LANG['info_limit_exceeded_to_ask_questions']);
													}
											}
										else
											{
												Redirect2URL(getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title'), $answers->getFormField('seo_title').'/'));
											}
									}
								else
									{
										$answers->setPageBlockShow('block_msg_form_error');
										$answers->setCommonErrorMsg($LANG['info_not_allowed_to_ask']);
									}
								$answers->title = $LANG['answers_what_is_your_answer'];
								$cfg_title = $answers->title;
							}
						else
							{
								$answers->setPageBlockShow('block_msg_form_error');
								$answers->setCommonErrorMsg($LANG['answers_err_not_open']);
							}
						break;
					case 'edit':
						if ($answers->isValidFormInputs() AND $answers->isQuestionOpen() AND $answers->answer_details['user_id'] == $CFG['user']['user_id'])
							{
								$answers->setPageBlockHide('form_question');
								$answers->setPageBlockHide('form_answers');
								$answers->setPageBlockShow('form_add');

								$answers->setFormField('answer', $answers->answer_details['answer']);
								$answers->setFormField('source', $answers->answer_details['source']);
								$answers->setFormField('video_id', $answers->answer_details['video_id']);
								$answers->setFormField('external_video_id', $answers->answer_details['external_video_id']);
								$answers->setFormField('audio_id', $answers->answer_details['audio_id']);
								$answers->setFormField('external_audio_id', $answers->answer_details['external_audio_id']);

								$answers->title = $LANG['answers_edit_your_answer'];
								$cfg_title = $answers->title;
							}
						else
							{
								$answers->setPageBlockShow('block_msg_form_error');
								$answers->setCommonErrorMsg($LANG['err_tip_invalid_action']);
							}
						break;
				} // switch
			}
		if ($answers->isFormPOSTed($_POST, 'cancel'))
			{
				Redirect2URL(getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title'), $answers->getFormField('seo_title').'/'));
			}
		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_best_answer_added_successfully']);
						break;
					case 5:
						$answers->setCommonSuccessMsg($LANG['answers_updated_question_successfully']);
						break;
					case 6:
						$answers->setCommonSuccessMsg($LANG['answers_answer_deleted_successfully']);
						break;
					case 7:
						$answers->setCommonSuccessMsg($LANG['answers_updated_successfully']);
						break;
					case 8:
						$answers->setCommonSuccessMsg($LANG['answers_resolved_successfully']);
						break;
					case 9:
						$answers->setCommonSuccessMsg($LANG['answers_published_successfully']);
						break;
					case 10:
						$answers->setCommonSuccessMsg($LANG['comments_deleted_successfully']);
						break;
					default:
						if($answers->question_details['publish_status'] == 'No')
							$answers->setCommonSuccessMsg($LANG['answers_waiting_for_publish']);
						else
							$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');
		$cfg_title = '';
	}
//--------------------Page block templates begins-------------------->>>>>//
$CFG['site']['title'] = ($cfg_title)?($cfg_title.' - '.$CFG['site']['title']):$cfg_title;

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.video_id', 'a.external_video_id', 'a.audio_id', 'a.external_audio_id', 'a.user_id', 'a.answer','a.votes', 'a.status', 'a.source', 'UNIX_TIMESTAMP(date_answered) as date_answered', 'u.'.$answers->getUserTableField('user_id').' as img_user_id', $answers->getUserTableFields(array('image_path','t_height', 't_width', 's_height', 's_width','photo_server_url', 'photo_ext', 'name')), $answers->getUserTableField('gender').' as gender', $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->executeQuery();
		//$answers->printQuery();

		$answers->form_answers['displayAllAnswers_arr'] = $answers->displayAllAnswers();
		if($answers->CFG['feature']['rewrite_mode'] == 'htaccess')
			$pagingArr = array();
		else
			$pagingArr = array('title');

		$smartyObj->assign('smarty_paging_list', $answers->populatePageLinksGET($answers->getFormField('start'), $pagingArr));
	}

$answers->confirm['hidden_arr1'] = array('action', 'aid', 'comment_id');

$answers->confirm['form_action'] = getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title'), $answers->getFormField('seo_title').'/');
$answers->confirm['onclick_url'] = getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title'), $answers->getFormField('seo_title').'/?');
$answers->confirm['hidden_arr2'] = array('start','qid');
$answers->confirm['hidden_arr'] = array('action', 'content_id');

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

if($CFG['html']['meta']['appendable'] && $valid_question == true)
	{
		$cat_ids = '';
		if($answers->question_details['pcat_id'] != '')
			$cat_ids.= $answers->question_details['pcat_id'].",";
		if($answers->question_details['cat_id'] != '')
			$cat_ids.= $answers->question_details['cat_id'].",";
		$cat_ids = substr($cat_ids,0,strlen($cat_ids)-1);

		$question_category_title = $answers->getCategoryInfo($cat_ids);
		$text_to_add = html_entity_decode($answers->question_details['question']);

		$answers->appendMetaDetails($text_to_add, $question_category_title);
	}
$question_url = getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title'), $answers->getFormField('seo_title').'/');
$answers->login = getUrl('login', '?light_url='.$question_url, '?light_url='.$question_url);
$answers->answer_url = getAnovaUrl('answer', '?title='.$answers->getFormField('seo_title'), $answers->getFormField('seo_title').'/', 'members');
//--------------------Page block templates begins-------------------->>>>>//
//include the header file
$answers->includeHeader();
//include the content of the page
setTemplateFolder('general/', $CFG['admin']['index']['anova_module']);
$video_format_arr = '';
$audio_format_arr = '';
if(isset($CFG['admin']['ans_videos']['format_arr']) && $CFG['admin']['ans_videos']['format_arr'])
	$video_format_arr = implode(',', $CFG['admin']['ans_videos']['format_arr']);
if(isset($CFG['admin']['ans_audios']['format_arr']) && $CFG['admin']['ans_audios']['format_arr'])
	$audio_format_arr = implode(',', $CFG['admin']['ans_audios']['format_arr']);
?>
<script language="javascript" type="text/javascript">
var block_arr= new Array('selMsgConfirm', 'selDelMsgConfirm', 'selMsgAbuseConfirm', 'selDelAttachconfirm', 'selQuestionBadgeEmbed');
</script>
<?php
$smartyObj->display('answer.tpl');
?>
<?php if(chkExternalVideoAllowed('question') OR chkExternalVideoAllowed('answer') OR chkExternalAudioAllowed('question') OR chkExternalAudioAllowed('answer')) { ?>
<script language="javascript" type="text/javascript">
var video_extension = '<?php echo $video_format_arr;?>';
var audio_extension = '<?php echo $audio_format_arr;?>';
function thisMovie(movieName) {
  if (navigator.appName.indexOf ("Microsoft") !=-1) {
    return window.document[movieName]

  } else {
   return window.document[movieName]
  }
}
function createJSFCommunicatorObject(playerObj)
{
	fc = new JSFCommunicator(playerObj);
}
var onUploadComplete = function()
{
	var str = arguments[0];
	var index = str.lastIndexOf('.');
	str = str.substring(index+1);
	var video_extension_array = video_extension.split(",");
	var audio_extension_array = audio_extension.split(",");

	if (extensionLookup(video_extension_array, str)){
		$('file_extern').value = str;
		mediaType = 'Video';
		$('external_video_add').style.display = 'none';
		$('external_video_add1').style.display = 'none';
		$('external_video_add2').style.display = '';
		$('external_video_delete').style.display = '';
		if (($('external_video_preview'))) {
			$('external_video_preview').style.display = '';
			$('external_video_preview').href = externalVideoPreviewUrl;
			$('external_video_preview').onclick = showVideoExternalPreview;
			$('external_video_preview').removeClassName('lightwindow');
			$('external_video_preview').href= '#';
		}
	} else if (extensionLookup(audio_extension_array, str)) {
		$('audio_extern').value = str;
		mediaType = 'Audio';
		$('external_audio_add').style.display = 'none';
		$('external_audio_add1').style.display = 'none';
		$('external_audio_add2').style.display = '';
		$('external_audio_delete').style.display = '';
		if (($('external_audio_preview'))) {
			$('external_audio_preview').style.display = '';
			$('external_audio_preview').href = externalAudioPreviewUrl;
			$('external_audio_preview').onclick = showAudioExternalPreview;
			$('external_audio_preview').removeClassName('lightwindow');
			$('external_audio_preview').href= '#';
		}
	}
	ffMacOsCloseWindow();
}
function extensionLookup(mediaArray, extern) {
    for (var i = 0; i < mediaArray.length ; i++) {
        if (mediaArray[i] == extern) {
            return true;
        }
    }
    return false;
}
function onClickThis()
{
		fc.callFunction("_level0","uploadSelcted");
}
function showNormalUpload()
{
	var obj = document.getElementById('selUploadFlash');
	obj.style.display = 'none';
	var obj = document.getElementById('selUploadNormal');
	obj.style.display = '';
	return false;
}
function makeDisable()
{
	document.getElementById('Upload').disabled = true;
}
function makeEnable()
{
	//document.getElementById('Upload').disabled = false;
	//Upload.disabled = false;
}
</script>
<?php } ?>

<script language="javascript" type="text/javascript">
	var saveVideo = function(){
		$('video_add').style.display = 'none';
		$('video_delete').style.display = '';
		$('video_secnd').style.display = '';
		$('video_first').style.display = 'none';

		if (($('video_preview'))) {
			$('video_preview').style.display = '';
			$('video_preview').href = videoPreviewUrl;
		}
		$('video').value = $('rid').value;
		ffMacOsCloseWindow();
	}
	var removeVideo = function(){
		alert_manual('<?php echo $LANG['common_video_deleted'];?>');
		$('video_delete').style.display = 'none';
		$('video_secnd').style.display = 'none';
		$('video_first').style.display = '';
		if (($('video_preview'))) $('video_preview').style.display = 'none';
		$('video_add').style.display = '';
		$('video').value = '';
		$('video_id').value = '0';
		return false;
	}
	var removeExternalVideo = function(){
		alert_manual('<?php echo $LANG['successfully_external_video_deleted'];?>', 'external_video_delete', -50, -100);
		$('external_video_delete').style.display = 'none';
		if (($('external_video_preview'))) $('external_video_preview').style.display = 'none';
		$('external_video_add').style.display = '';
		$('external_video_add1').style.display = '';
		$('external_video_add2').style.display = 'none';
		$('video_external_flv_url').value = '';
		$('file_extern').value = '';
		$('external_video_id').value = '0';
		return false;
	}
	var confrimRemove = function(){
		var act_value = arguments[0];
		var anchorLink = arguments[1];
		var msg_confirm = arguments[2];
		var confirm_message = msg_confirm;
		$('confirmDelMessage').innerHTML = confirm_message;
		document.formDelConfirm.action.value = act_value;
		Confirmation('selDelMsgConfirm', 'formDelConfirm', Array(), Array(), Array());
		return false;
	}
	var doRemoveAction = function(){
		if (document.formDelConfirm.action.value == 'video')
			{
				removeVideo();
			}
		else
			removeAudio();
	}
	var deleteVideo = function(){
		ffMacOsCloseWindow();
	}
	var saveAudio = function(){
		$('audio_add').style.display = 'none';
		$('audio_delete').style.display = '';
		$('audio_secnd').style.display = '';
		$('audio_first').style.display = 'none';
		if (($('audio_preview'))) {
			$('audio_preview').style.display = '';
			$('audio_preview').href = audioPreviewUrl;
		}
		$('audio').value = $('rid').value;
		ffMacOsCloseWindow();
	}
	var removeAudio = function(){
		alert_manual('<?php echo $LANG['common_audio_deleted'];?>');
		$('audio_delete').style.display = 'none';
		$('audio_secnd').style.display = 'none';
		$('audio_first').style.display = '';
		if (($('audio_preview'))) $('audio_preview').style.display = 'none';
		$('audio_add').style.display = '';
		$('audio').value = '';
		$('audio_id').value = '0';
		return false;
	}
	var removeExternalAudio = function(){
		alert_manual('<?php echo $LANG['successfully_external_audio_deleted'];?>', 'external_audio_delete', -50, -100);
		$('external_audio_delete').style.display = 'none';
		if (($('external_audio_preview'))) $('external_audio_preview').style.display = 'none';
		$('external_audio_add').style.display = '';
		$('external_audio_add1').style.display = '';
		$('external_audio_add2').style.display = 'none';
		$('audio_external_url').value = '';
		$('audio_extern').value = '';
		$('external_audio_id').value = '0';
		return false;
	}
	var deleteAudio = function(){
		ffMacOsCloseWindow();
	}

	function toggleAnswer(spanObj, ansID){
		var moreObj = 'answermore'+ansID;
		var lessObj = 'answerless'+ansID;

		if ($(lessObj).style.display == 'none'){
			$(moreObj).hide();
			$(lessObj).show();
		}else{
			$(moreObj).show();
			$(lessObj).hide();
		}
		toggleNavBar();
	}
	var expand = true;
	var clicked = true;
	var toggleExpandAnswers = function(){
		if (clicked){
			//	clicked = false;
	     	for (var i=1; i<=commentsArray.length; i++){
	     		moreObj = 'answermore'+commentsArray[i];
	     		lessObj = 'answerless'+commentsArray[i];
	     		if ($(moreObj)){
	     			if (expand){
	     					$(moreObj).hide();
	     					$(lessObj).show();
	     				}else{
	     					$(moreObj).show();
	     					$(lessObj).hide();
	     				}
	     		}
	     	}
		expand = (expand)?false:true;
		//setTimeout('changeClickedStatus()', 2000);
		toggleNavBar();
		}
	}
	var changeClickedStatus = function(){
			toggleNavBar();
			clicked = true;
		}

	var removeId = 0;
	function add_more_upload(lang) {

		var id = removeId++;
		var imgdiv = $('tdID');
		var ptags = imgdiv.getElementsByTagName("p");
		var len = ptags.length;
		if(len > <?php echo $CFG['admin']['attachments_allowed']['count']+1;?>)
			$('brsBtn').style.display = 'none';

		if(len > <?php echo $CFG['admin']['attachments_allowed']['count']+2;?>)
			return;

		var rowTemplate = '<p class="clsAttachments" id="p_'+id+'"><input type="file" name="attachments[]" value=""> <a class="clsRemoveAttachment" href="#" onClick="removeThis('+id+');return false;">'+lang+'</a></p>';

		new Insertion.Before('brsBtn', rowTemplate);
	}

	function removeThis(id)	{
		var remId = id;
		$('p_'+remId).remove();
		$('brsBtn').style.display = '';
	}
	function chkMessage(message,form)
		{
			var comm = document.getElementById(message).value
			if(comm=='' || comm == null)
				{
					alert_manual("Enter Proper messsage");
				}
			else
				return 0;

		}
	function postShareAnswers()
		{
			document.forms.selFormReplyAnswers.submit();
		}
</script>
<?php
if($answers->isShowPageBlock('form_add') && $answers->question_details['user_id'] != $answers->CFG['user']['user_id'] && isMember() && $CFG['admin']['attachments_answers']['allowed'])
{
?>
<script language="javascript" type="text/javascript" defer="defer">
		var swfu;
		swfu = new SWFUpload({
			// Backend Settings
			upload_url: "<?php echo $CFG['site']['url'].$CFG['admin']['index']['anova_module'];?>/upload.php",
			post_params: {"PHPSESSID": "<?php echo session_id();?>"},

			// File Upload Settings
			file_size_limit : "<?php echo $CFG['admin']['attachments']['max_size'];?>",	// 2MB
			file_types : "<?php echo $req_settings;?>",
			file_types_description : "File Types ",
			file_upload_limit : "<?php echo $answers->getFormField('picturelimit');?>",
			file_queue_limit : "<?php echo $answers->getFormField('picturelimit');?>",


			// Event Handler Settings - these functions as defined in Handlers.js
			//  The handlers are not part of SWFUpload but are part of my website and control how
			//  my website reacts to the SWFUpload events.
			file_queue_error_handler : fileQueueError,
			file_dialog_complete_handler : fileDialogComplete,
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,

			// Button Settings
			button_image_url : "../root/images/screen_new/icon-uploadImage.gif",
			button_placeholder_id : "spanButtonPlaceholder",
			button_width: 50,
			button_height: 50,
			button_text : '',
			button_text_style : '.button { text-align:center; font-family: Helvetica, Arial, sans-serif; font-size: 12pt; font-weight:bold;} .buttonSmall { font-size: 10pt; }',
			button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			button_cursor: SWFUpload.CURSOR.HAND,


			// Flash Settings
			flash_url : "<?php echo $CFG['site']['url'].$CFG['admin']['index']['anova_module'];?>/js/swfupload/swfupload.swf",

			custom_settings : {
				upload_target : "divFileProgressContainer"
			},

			// Debug Settings
			debug: false
		});
</script>
<?php
  }

if(count($answers->getFormField('uplarr')) != 0  && $answers->isShowPageBlock('form_add') )
	{
	?>
		<script language="javascript" type="text/javascript">
			var required_array =  new Array();
			var required_ori_array =  new Array();
			var i = 0;
			var j= 0;
		</script>
		<?php
		$upl_count  =  count($answers->getFormField('uplarr'));
		$req_uploaded_array = $answers->getFormField('uplarr');
		$req_ori_uploaded_array = $answers->getFormField('upl_original');
		foreach ($req_uploaded_array as $value)
			{
			  ?>
			  	<script language="javascript" type="text/javascript">
					 required_array[i] = "<?php echo $value;?>";
					 i++;
				</script>
			  <?php
			}
		foreach ($req_ori_uploaded_array as $value)
			{

			  ?>
			  	<script language="javascript" type="text/javascript">
					 required_ori_array[j] = "<?php echo $value;?>";
					 j++;
				</script>
			  <?php
			}
		?>
			<script language="javascript" type="text/javascript">
				function checkElementPresent()
						{
							var thumbnails = document.getElementById("thumbnails");
							items = thumbnails.getElementsByTagName("img");
							if(items.length == 0)
								{
		                             var req_upl = '<?php echo $upl_count;?>';
									 for(i =0;i<req_upl;i++)
									 	{
											addImage(required_array[i]);
											addHiddenElement(required_array[i]);
											addHiddenElementForName(required_ori_array[i] , required_array[i])

										}
								}

						}
				checkElementPresent();
			</script>
		<?php
	}
//include the footer of the page
//<<<<<<--------------------Page block templates Ends--------------------//
$answers->includeFooter();
?>
