<?php
/**
 * List edit members
 *
 * PHP version 5.0
 *
 * @category	Anova
 * @package		AnswersFormHandler
 * @author 		shankar_76ag08
 * @copyright	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id:
 * @since 		2008-12-23
 * @filesource
 **/
set_time_limit(0);
require_once('../../common/configs/config.inc.php'); //configurations

$CFG['lang']['include_files'][] = 'languages/%s/'.$CFG['admin']['index']['anova_module'].'/admin/manageAnswers.php';
$CFG['lang']['include_files'][] = 'languages/%s/common/email_notify.inc.php';
$CFG['html']['header'] = 'admin/html_header.php';
$CFG['html']['footer'] = 'admin/html_footer.php';

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

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

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

if ($CFG['admin']['module']['twitter'])
	require_once('../../twitterOAuth.php');
//compulsory
$CFG['site']['is_module_page'] = $CFG['admin']['index']['anova_module'];
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
/**
 * To include application top file
 */
require_once($CFG['site']['project_path'] . 'common/application_top.inc.php');


//------------------- Class AnswersFormHandler Begins ------->>>>>//
class AnswersFormHandler extends VideoUploadLib
	{
		/**
		 * @var object $current_user_id Current user id
		 */
		private $current_user_id;
		public $answer_attachment_count = 0;
		public $_dir_path = '../../';

		/**
		 * AnswersFormHandler::ConditionQueryNo Search()
		 *
		 * @return 		void
		 * @access		public
		**/
		public function ConditionQueryNoSearch()
			{
				$this->sql_condition .= ' q.user_id=u.'.$this->getUserTableField('user_id').' AND  u.usr_status = \'Ok\' ';

			}

		public function addSlashForPercentageOnly($value)
			{
				//$value = 'demo % ';'%%%';'% %%';%demo%';
				$value_rep = addslashes($value);
				$search_value = trim($value_rep);
				$str_arr = str_split($search_value);
				$percentage_avail = false;
				$slashed_value = '';
				foreach($str_arr as $str_val)
					{
						if($str_val == '%')
							{
								$percentage_avail = true;
								$slashed_value .= '\\'.$str_val;
							}
						else
							$slashed_value .= $str_val;
					}

				if($percentage_avail)
					return $slashed_value;

				return $value_rep;
			}
		/**
		 * AnswersFormHandler::ConditionQuery()
		 *
		 * @param       string $table
		 * @return 		void
		 * @access		public
		**/
		public function ConditionQuery()
			{
				$this->sql_condition = 'q.user_id=u.'.$this->getUserTableField('user_id').' AND  u.usr_status = \'Ok\'';
				$and = 1;
				if($this->fields_arr['search_name'])
					{
						if($this->fields_arr['search_cat'] == 1)
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  ' '.$this->getUserTableField('display_name').' LIKE \'%'.$this->addSlashForPercentageOnly($this->fields_arr['search_name']).'%\'';
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 2)
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  ' '.$this->getUserTableField('email').' like \'%'.addslashes($this->fields_arr['search_name']).'%\'';
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 3)//open questions
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  ' (status = \'Open\' AND date_closed>=NOW()) AND '.getSearchRegularExpressionQuery($this->fields_arr['search_name'], 'question');
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 4)//resloved questions
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  ' (q.status = \'Resolved\' OR q.date_closed<NOW()) AND '.getSearchRegularExpressionQuery($this->fields_arr['search_name'], 'question');
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 5)//blocked questions
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  ' status = \'Blocked\' AND '.getSearchRegularExpressionQuery($this->fields_arr['search_name'], 'question');
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 6)//question
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  getSearchRegularExpressionQuery($this->fields_arr['search_name'], 'question');
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 7)//tags
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  ' tags REGEXP \'[[:<:]]'.addslashes($this->fields_arr['search_name']).'[[:>:]]\'';
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 8)//categories
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .= $this->getCatIds($this->fields_arr['search_name']);
								//$this->sql_condition .=  ' (pcat_id ='.$this->fields_arr['search_name']'  OR cat_id IN (SELECT cat_id FROM '.$this->CFG['db']['tbl']['questions_category'].' WHERE cat_name LIKE \'%'.addslashes($this->fields_arr['search_name']).'%\'))';
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 9)//video questions
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  ' video_id!=0 AND (tags REGEXP \'[[:<:]]'.addslashes($this->fields_arr['search_name']).'[[:>:]]\' OR question REGEXP \'[[:<:]]'.addslashes($this->fields_arr['search_name']).'[[:>:]]\' OR '.$this->getUserTableField('display_name').' LIKE \'%'.addslashes($this->fields_arr['search_name']).'%\')';
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 10)//audio questions
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  ' audio_id!=0 AND (tags REGEXP \'[[:<:]]'.addslashes($this->fields_arr['search_name']).'[[:>:]]\' OR question REGEXP \'[[:<:]]'.addslashes($this->fields_arr['search_name']).'[[:>:]]\' OR '.$this->getUserTableField('display_name').' LIKE \'%'.addslashes($this->fields_arr['search_name']).'%\')';
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 11)//questions with best asnswer
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  ' best_ans_id!=0 AND '.getSearchRegularExpressionQuery($this->fields_arr['search_name'], 'question');
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 12)//questions with best asnswer
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  ' status = \'ToActivate\' AND '.getSearchRegularExpressionQuery($this->fields_arr['search_name'], 'question');
								$and = 1;
							}
						elseif($this->fields_arr['search_cat'] == 13)//questions with best asnswer
							{
								if($and == 1)
									$this->sql_condition .= ' AND ';
								$this->sql_condition .=  ' featured = \'Yes\' AND '.getSearchRegularExpressionQuery($this->fields_arr['search_name'], 'question');
								$and = 1;
							}
					}
				elseif($this->fields_arr['search_cat'] == 3)//open questions
					{
						if($and == 1)
							$this->sql_condition .= ' AND ';
						$this->sql_condition .=  ' (q.status = \'Open\' AND q.date_closed>=NOW())';
						$and = 1;
					}
				elseif($this->fields_arr['search_cat'] == 4)//resloved questions
					{
						if($and == 1)
							$this->sql_condition .= ' AND ';
						$this->sql_condition .=  ' (q.status NOT IN(\'Blocked\',\'ToActivate\') AND q.date_closed<NOW())';
						$and = 1;
					}
				elseif($this->fields_arr['search_cat'] == 5)//blocked questions
					{
						if($and == 1)
							$this->sql_condition .= ' AND ';
						$this->sql_condition .=  ' status = \'Blocked\'';
						$and = 1;
					}
				elseif($this->fields_arr['search_cat'] == 9)//video questions
					{
						if($and == 1)
							$this->sql_condition .= ' AND ';
						$this->sql_condition .=  ' video_id!=0';
						$and = 1;
					}
				elseif($this->fields_arr['search_cat'] == 10)//audio questions
					{
						if($and == 1)
							$this->sql_condition .= ' AND ';
						$this->sql_condition .=  ' audio_id!=0';
						$and = 1;
					}
				elseif($this->fields_arr['search_cat'] == 11)//questions with best asnswer
					{
						if($and == 1)
							$this->sql_condition .= ' AND ';
						$this->sql_condition .=  ' best_ans_id!=0';
						$and = 1;
					}
				elseif($this->fields_arr['search_cat'] == 12)//questions with best asnswer
					{
						if($and == 1)
							$this->sql_condition .= ' AND ';
						$this->sql_condition .=  ' (q.status = \'ToActivate\')';
						$and = 1;
					}
				elseif($this->fields_arr['search_cat'] == 13)//questions with featured
					{
						if($and == 1)
							$this->sql_condition .= ' AND ';
						$this->sql_condition .=  ' (q.featured = \'Yes\')';
						$and = 1;
					}
			}

		/**
		 * AnswersFormHandler::getCatIds()
		 *
		 * @param mixed $cat
		 * @return
		 */
		public function getCatIds($cat)
		    {
				$sql = 'SELECT cat_id, cat_name, parent_id FROM '.$this->CFG['db']['tbl']['questions_category'].
						' WHERE cat_name='.$this->dbObj->Param('search_name');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['search_name']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				$sub_qry = 'pcat_id=\'\'';
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						if (!$row['parent_id'])
							$sub_qry = '  (pcat_id='.$row['cat_id'].' OR cat_id IN ( SELECT cat_id FROM '.$this->CFG['db']['tbl']['questions_category'].' WHERE parent_id='.$row['cat_id'].'))';
						else
							$sub_qry = '  cat_id='.$row['cat_id'];
					}
				return $sub_qry;
		    }

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

		/**
		 * AnswersFormHandler::chkIsValidQuestion()
		 *
		 * @return
		 */
		public function chkIsValidQuestion()
		    {
				$this->chkIsNotEmpty('qid', $this->LANG['err_tip_compulsory']);
				if (!$this->isValidFormInputs())
					{
						$this->setCommonErrorMsg($this->LANG['err_tip_invalid_question_id']);
						return false;
					}
				//Query to display recent and popular questions
				$sql = 'SELECT q.ques_id, q.total_answer, q.user_id, q.votes, q.cat_id, q.pcat_id, q.publish_status, q.featured, q.tags, q.best_ans_id, q.seo_title, q.description, q.total_stars, q.question, UNIX_TIMESTAMP(date_asked) as date_asked'.
						', '.$this->getUserTableField('display_name').' as asked_by, '.$this->getUserTableFields(array('image_path', 'name', 'gender'), false).'q.status, q.user_id'.
						', video_id, external_video_id, audio_id, external_audio_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\', \'ToActivate\', \'Blocked\')'.
						' AND u.'.$this->getUserTableField('usr_status').'=\'Ok\' AND q.ques_id='.$this->dbObj->Param('qid');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid']));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				if (!$rs->PO_RecordCount())
					{
						$this->setCommonErrorMsg($this->LANG['err_tip_invalid_question_id']);
						return false;
					}
				$this->question_details = $rs->FetchRow();
				$this->fields_arr['old_category'] = $this->question_details['pcat_id'];
				$this->fields_arr['old_sub_category'] = $this->question_details['cat_id'];

				return true;
		    }

		/**
		 * AnswersFormHandler::setCategoryFormField()
		 *
		 * @return
		 */
		public function setCategoryFormField()
		    {
				$cat_id = $this->question_details['pcat_id'];
				if($this->question_details['cat_id'] > 0)
				$cat_id = $this->question_details['cat_id'];

				$sql = 'SELECT cat_id, parent_id FROM '.$this->CFG['db']['tbl']['questions_category'].' WHERE cat_id='.$this->dbObj->Param('cat_id');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($cat_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						$this->fields_arr['category'] = $row['cat_id'];
						if ($row['parent_id'])
							{
								$this->fields_arr['category'] = $row['parent_id'];
								$this->fields_arr['sub_category'] = $row['cat_id'];
							}
					}
		    }

		/**
		 * AnswersFormHandler::chkIsQuestionExists()
		 *
		 * @param mixed $field
		 * @param string $err_tip
		 * @return
		 */
		public function chkIsQuestionExists($field, $err_tip='')
		    {
				$sql = 'SELECT ques_id FROM '.$this->CFG['db']['tbl']['questions'].
						' WHERE question LIKE '.$this->dbObj->Param('question');
				if ($this->fields_arr['qid'])
					$sql .= ' AND ques_id != \''.addslashes($this->fields_arr['qid']).'\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr[$field]));
				if (!$rs)
				        trigger_db_error($this->dbObj);
				if (!$rs->PO_RecordCount())
					return true;
				$this->setCommonErrorMsg($err_tip);
				$this->setFormFieldErrorTip($field, $err_tip);
				return false;
		    }

		public function getTwitterUsersToken($user_id)
			{
				$sql = ' SELECT  auth_token, auth_secret_token  FROM '.$this->CFG['db']['tbl']['twitter_identity'].''.
				        ' WHERE user_id ='.$user_id;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					trigger_db_error($this->dbObj);
				$row = $rs->FetchRow();
				return $row;
			}


		/**
		 * AnswersFormHandler::updateQuestion()
		 *
		 * @return
		 */
		public function updateQuestion()
		    {
				$this->isCategoryExist();
				$this->setFormField('seo_title', $this->getSeoTitleForQuestion($this->fields_arr['question'], $this->fields_arr['qid']));

				$this->updateCategoryQuestionCount($this->fields_arr['old_category']);
				if ($this->fields_arr['old_sub_category'])
					$this->updateCategoryQuestionCount($this->fields_arr['old_sub_category']);

				$pcat_id = $this->fields_arr['category'];
				if ($this->fields_arr['sub_category'])
					$cat_id = $this->fields_arr['sub_category'];

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].
						' SET question='.$this->dbObj->Param('question').
						', seo_title='.$this->dbObj->Param('seo_title').
						', description='.$this->dbObj->Param('descriptions').
						', tags='.$this->dbObj->Param('tags').
						', featured='.$this->dbObj->Param('featured').
						', pcat_id='.$this->dbObj->Param('pcat_id').
						', cat_id='.$this->dbObj->Param('cat_id').
						', 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').
						', publish_status='.$this->dbObj->Param('publish').
						' WHERE ques_id='.$this->dbObj->Param('qid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['question'],
														 $this->fields_arr['seo_title'],
														 $this->fields_arr['descriptions'],
														 $this->fields_arr['tags'],
														 $this->fields_arr['featured'],
														 $this->fields_arr['category'],
														 $this->fields_arr['sub_category'],
														 $this->fields_arr['video_id'],
														 $this->fields_arr['external_video_id'],
														 $this->fields_arr['audio_id'],
														 $this->fields_arr['external_audio_id'],
														 $this->fields_arr['publish'],
														 $this->fields_arr['qid']));
				if (!$rs)
				        trigger_db_error($this->dbObj);

				if($this->CFG['admin']['module']['twitter'] && $this->chkTwitterUser($this->getFormField('ques_user_id')))
					{
						if($this->fields_arr['question'] != $this->getFormField('old_question'))
							{
								if($this->CFG['admin']['twitter_post_questions']['allowed'])
									{
									  $user_token =  $this->getTwitterUsersToken($this->getFormField('ques_user_id'));
									  $to = new TwitterOAuth($this->CFG['twitter']['consumer_key'], $this->CFG['twitter']['consumer_secret'], $user_token['auth_token'], $user_token['auth_secret_token']);
									  $content = $to->OAuthRequest('https://twitter.com/statuses/update.xml', array('status' => $this->fields_arr['question']), 'POST');
									  $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');
									  $xml = new SimpleXMLElement($content);
									  $t_ques_id = $xml->status->id;
									  $t_ques_text = trim($xml->status->text);
									  if($t_ques_id != '' && $t_ques_text != '')
										{
											$this->updateQuestionWithTwitterId($this->fields_arr['qid'], $t_ques_id, $t_ques_text);
										}
									}
							}
					}
				$this->increaseCategoryQuestionCount($this->fields_arr['category']);
				if ($this->fields_arr['sub_category'])
					$this->increaseCategoryQuestionCount($this->fields_arr['sub_category']);


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

						$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['qid'];
						if($this->fields_arr['video'])
							$this->addNewVideo();
						#die('here');
					}
				if((chkExternalVideoAllowed('question')) AND ($this->fields_arr['video_external_flv_url'] or $this->fields_arr['file_extern'] or $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=\'Question\'';

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

						$this->fields_arr['content_id'] = $this->fields_arr['qid'];
						if($this->fields_arr['video_external_flv_url'] or $this->fields_arr['file_extern'])
							$this->addExternalVideo('Question');
					}
				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_for=\'Question\'';

						$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['qid'];
						if($this->fields_arr['audio'])
							$this->addNewAudio();
					}
				if((chkExternalAudioAllowed('question')) AND ($this->fields_arr['audio_external_url'] or $this->fields_arr['audio_extern'] or $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=\'Question\'';

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

	            		$this->fields_arr['content_id'] = $this->fields_arr['qid'];

						if($this->fields_arr['audio_external_url'] or $this->fields_arr['audio_extern'])
							$this->addExternalAudio('Question');
					}
	            		$this->fields_arr['content_id'] = $this->fields_arr['qid'];
				$this->addAttachments();
				$this->modifyTags();
		    }
		public function getTwitterQuestionId($ques_id)
			{
				$sql = ' SELECT  twitter_ques_id FROM '.$this->CFG['db']['tbl']['questions'].''.
				        ' WHERE ques_id ='.$ques_id;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					trigger_db_error($this->dbObj);
				$row = $rs->FetchRow();
				return $row;
			}
		public function updateQuestionWithTwitterId($content_id, $twitter_id, $twitter_text)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].
						' SET twitter_ques_id ='.$this->dbObj->Param($twitter_id).
						' WHERE ques_id ='.$this->dbObj->Param($content_id).
						' AND question ='.$this->dbObj->Param($twitter_text);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($twitter_id, $content_id, $twitter_text ));
				if (!$rs)
						trigger_db_error($this->dbObj);

			}

		/**
		 * AnswersFormHandler::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->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->CFG['admin']['ans_videos']['temp_folder'];
						$temp_file = $temp_dir.$this->fields_arr['rid'].'.flv';
						if(file_exists($temp_file))
							unlink($temp_file);
					}
			}

		/**
		 * AnswersFormHandler::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->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->CFG['admin']['ans_audios']['temp_folder'];
						$temp_file = $temp_dir.$this->fields_arr['rid'].'AUD.flv';
						if(file_exists($temp_file))
							unlink($temp_file);
					}
			}

		/**
		 * AnswersFormHandler::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=\'Question\','.
						' 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();
			}

		/**
		 * AnswersFormHandler::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=\'Question\','.
						' audio_ext=\'flv\','.
						' date_added=NOW(),'.
						' audio_upload_type=\'Normal\','.
						' 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();
			}

		/**
		 * AnswersFormHandler::changeAnsVideoStatus()
		 *
		 * @param mixed $video_id
		 * @param mixed $status
		 * @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);
			}

		/**
		 * AnswersFormHandler::updateStatus()
		 *
		 * @param mixed $table_name
		 * @param mixed $status
		 * @return
		 */
		public function updateStatus($table_name, $status)
		    {
				if(!$this->fields_arr['ques_ids'])
					return ;

				$id = $this->fields_arr['ques_ids'];
				$this->updateQuestionCountForBlockUnblock($id, $status);

				$date_closed = '';
				if ($status == 'Open')
					$date_closed = ', date_closed = DATE_ADD(NOW(), INTERVAL '.$this->CFG['admin']['question']['open_days'].' DAY)';
				elseif ($status == 'Resolved')
					$date_closed = ', date_closed = NOW()';
				elseif ($status == 'Unblock')
					$status = 'Open';

				$sql = 'UPDATE '.$table_name.' SET status='.$this->dbObj->Param($status).$date_closed.' WHERE ques_id IN ('.$id.')'.
					' AND status !=\'ToActivate\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($status));
				if (!$rs)
				        trigger_db_error($this->dbObj);
		    }

		public function updateFeatured($table_name, $status)
		    {
				if(!$this->fields_arr['ques_ids'])
					return ;

				$id = $this->fields_arr['ques_ids'];

				$sql = 'UPDATE '.$table_name.' SET featured='.$this->dbObj->Param($status).' WHERE ques_id IN ('.$id.')'.
					' AND status !=\'ToActivate\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($status));
				if (!$rs)
				        trigger_db_error($this->dbObj);
		    }

		/**
		 * AnswersFormHandler::updateQuestionCountForBlockUnblock()
		 *
		 * @param mixed $ques_ids
		 * @param mixed $status
		 * @return
		 */
		public function updateQuestionCountForBlockUnblock($ques_ids, $status)
		    {
				/*Following will be executed only if we do block or unblock  questions*/
				//if($status != 'Blocked' AND $status != 'Unblock')
				//return ;
				if($status == 'Blocked')
					 { 	$s_status = ' !=\'Blocked\' AND status !=\'ToActivate\'';$q_update = '-';
					 }
				else {	$s_status = ' =\'Blocked\'';$q_update = '+';
					 }

				$sql = 'SELECT user_id, ques_id, status FROM '.$this->CFG['db']['tbl']['questions'].
						' WHERE ques_id IN ('.$ques_ids.') AND status'.$s_status;
				$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())
							{
								$sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
									' SET total_ques=total_ques'.$q_update.'1';
									if($this->CFG['admin']['ask_answers']['allowed'])
									$sql .= ', total_points=total_points'.$q_update.$this->CFG['admin']['ask_answers']['points'];
								$sql .= ', date_updated=NOW()'.
									' WHERE user_id='.$row['user_id'];

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

				return ;
		    }

		/**
		 * AnswersFormHandler::updateQuestionAndCategoryCountForPublish()
		 *
		 * @param mixed $ques_ids
		 * @param mixed $status
		 * @return
		 */
		public function updateQuestionAndCategoryCountForPublish($ques_ids, $status)
		    {
				/*Following will be executed only if we do publish  questions*/
				if($status != 'Publish')
				return ;

				$s_status = ' =\'ToActivate\'';

				$sql = 'SELECT user_id, ques_id, question, seo_title, description, pcat_id, cat_id, ques_id, tags, status FROM '.$this->CFG['db']['tbl']['questions'].
						' WHERE ques_id IN ('.$ques_ids.') AND status'.$s_status;
				$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())
							{
								$date_closed = ', date_asked= NOW(), date_closed = DATE_ADD(NOW(), INTERVAL '.$this->CFG['admin']['question']['open_days'].' DAY)';
								$update_status = 'Open';

								$updatesql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].' SET status='.$this->dbObj->Param($update_status).$date_closed.' WHERE ques_id IN ('.$row['ques_id'].')';
								$updatesqlstmt = $this->dbObj->Prepare($updatesql);
								$updatesqlrs = $this->dbObj->Execute($updatesqlstmt, array($update_status));
								if (!$updatesqlrs)
								        trigger_db_error($this->dbObj);



								$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 .= ', date_updated=NOW()'.
									' WHERE user_id='.$row['user_id'];
								$stmt = $this->dbObj->Prepare($sql);
								$user_logs = $this->dbObj->Execute($stmt);
								if (!$user_logs)
							       	trigger_db_error($this->dbObj);

							       if($row['pcat_id'])
									$this->increaseCategoryQuestionCount($row['pcat_id']);
								if($row['cat_id'])
									$this->increaseCategoryQuestionCount($row['cat_id']);

								if($row['tags'])
									$this->updateTags($row['tags']);

								$this->sendPublishedMailAlert($row['user_id'], 'Question', $row['seo_title'], $row['question'], $row['description']);
							}
						//die('here');
					}
				return ;
		    }

		/**
		 * AnswersFormHandler::increaseCategoryQuestionCount()
		 *
		 * To update questions count
		 *
		 * @param mixed $cat_id
		 * @return
		 */
		public function increaseCategoryQuestionCount($cat_id)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions_category'].
						' SET total_questions=total_questions+1'.
						' WHERE cat_id='.$this->dbObj->Param($cat_id);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($cat_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 * AnswersFormHandler::deleteQuestions()
		 *
		 * @param mixed $table_name
		 * @param mixed $answers_table
		 * @param mixed $users_ans_log_table
		 * @return
		 */
		public function deleteQuestions($table_name, $answers_table, $users_ans_log_table)
		    {
				if(!$this->fields_arr['ques_ids'])
					return ;

				$id = $this->fields_arr['ques_ids'];

				$sql = 'SELECT user_id, video_id, status, best_ans_id, external_video_id, audio_id, external_audio_id, pcat_id, cat_id, tags FROM '.$table_name.' WHERE ques_id IN ('.$id.')';
				$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()){

							if($row['status'] != 'ToActivate')
								{

									if($row['status'] != 'Blocked')
										{
											$sql = 'UPDATE '.$users_ans_log_table.' 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_user_log = $this->dbObj->Execute($stmt, array($row['user_id']));
												if (!$rs_user_log)
									        			trigger_db_error($this->dbObj);
									       }

									$this->updateCategoryQuestionCount($row['pcat_id']);
									if ($row['cat_id'])
										$this->updateCategoryQuestionCount($row['cat_id']);

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

							//Change the video and audio status
							$this->updateQuestionVideoStatus($row['video_id']);
							$this->updateQuestionVideoStatus($row['external_video_id']);
							$this->updateQuestionAudioStatus($row['audio_id']);
							$this->updateQuestionAudioStatus($row['external_audio_id']);
							if ($row['best_ans_id'])
								$this->decreaseBestAnswerCount($row['best_ans_id']);
							//to delete attachments
							if($this->CFG['admin']['attachments_questions']['allowed'])
								$this->commonDeleteAttachments('Question', $this->fields_arr['ques_ids']);
							$this->deleteQuestionsComment($this->fields_arr['ques_ids']);
						} // while
					}

				$sql = 'DELETE FROM '.$table_name.' WHERE ques_id IN ('.$id.')';

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

				$sql = 'SELECT user_id, video_id, external_video_id, ans_id, audio_id, external_audio_id FROM '.$answers_table.' WHERE ques_id IN ('.$id.')';
				$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()){
							$sql = 'UPDATE '.$users_ans_log_table.' SET total_ans=total_ans-1'.
									' WHERE user_id='.$this->dbObj->Param('uid');

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

							$this->updateAnswerVideoStatus($row['video_id']);
							$this->updateAnswerVideoStatus($row['external_video_id']);
							$this->updateAnswerAudioStatus($row['audio_id']);
							$this->updateAnswerAudioStatus($row['external_audio_id']);
							//to delete attachments
							if($this->CFG['admin']['attachments_answers']['allowed'])
								$this->commonDeleteAttachments('Answer', $row['ans_id']);

						} // while
					}

				$sql = 'DELETE FROM '.$answers_table.' WHERE ques_id IN ('.$id.')';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
				        trigger_db_error($this->dbObj);
		    }

		/**
		 * AnswersFormHandler::deleteQuestionsComment()
		 *
		 * @param mixed $id
		 * @return
		 */
		public function deleteQuestionsComment($id)
			{
				$sql = 'DELETE FROM '.$this->CFG['db']['tbl']['question_comment'].
						' WHERE ques_id IN ('.$id.')';

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

		/**
		 * AnswersFormHandler::decreaseBestAnswerCount()
		 *
		 * @param mixed $bid
		 * @return
		 */
		public function decreaseBestAnswerCount($bid)
			{
				if ($bid and $this->CFG['admin']['best_answers']['allowed'])
					{

						$best_sql = 'SELECT user_id FROM '.$this->CFG['db']['tbl']['answers'].' WHERE ans_id='.$bid;
						$best_stmt = $this->dbObj->Prepare($best_sql);
						$best_rs = $this->dbObj->Execute($best_stmt);
						if (!$best_rs)
						        trigger_db_error($this->dbObj);

						if ($best_rs->PO_RecordCount()){
								$best_row = $best_rs->FetchRow();
								$best_ans_userid = $best_row['user_id'];
							}

						$sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
								' SET total_best_ans = total_best_ans - 1'.
								' WHERE user_id='.$this->dbObj->Param($best_ans_userid);
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($best_ans_userid));
						if (!$rs)
							    trigger_db_error($this->dbObj);
					}
			}

		/**
		 * AnswersFormHandler::updateCategoryQuestionCount()
		 *
		 * To update questions count
		 *
		 * @param mixed $cat_id
		 * @return
		 */
		public function updateCategoryQuestionCount($cat_id)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions_category'].
						' SET total_questions=total_questions-1'.
						' WHERE cat_id='.$this->dbObj->Param($cat_id).
						' AND total_questions>0';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($cat_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

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

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

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

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

		/**
		 * AnswersFormHandler::updateAnswerVideoStatus()
		 *
		 * @param mixed $video_id
		 * @return
		 */
		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);
			}

		/**
		 * AnswersFormHandler::updateAnswerAudioStatus()
		 *
		 * @param mixed $audio_id
		 * @return
		 */
		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);
			}

		/**
		 * AnswersFormHandler::abuseQuestions()
		 *
		 * @return
		 */
		public function abuseQuestions()
		    {
				if(!$this->fields_arr['ques_ids'])
					return ;

				$id = '';
				$eques_id = explode(',',$this->fields_arr['ques_ids']);
				foreach($eques_id as $ques_id)
					{
						$id .= '\''.$ques_id.'\',';
						$this->updateAbuseQuestion($ques_id);
					}
				$id = substr($id, 0, strrpos($id, ','));
		    }

		/**
		 * AnswersFormHandler::updateAbuseQuestion()
		 *
		 * @param mixed $ques_id
		 * @return
		 */
		public function updateAbuseQuestion($ques_id)
		    {
				$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($ques_id,
														 $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').
								', date_abused=NOW()';
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($ques_id, $this->CFG['user']['user_id']));
						if (!$rs)
						        trigger_db_error($this->dbObj);

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

		/**
		 * AnswersFormHandler::updateQuestionAbuseCount()
		 *
		 * @param mixed $ques_id
		 * @return
		 */
		public function updateQuestionAbuseCount($ques_id)
		    {
				$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($ques_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
		    }

		/**
		 * AnswersFormHandler::getQuestionDetails()
		 *
		 * @param integer $ques_id
		 * @return
		 */
		public function getQuestionDetails($ques_id=0)
		    {
				$sql = 'SELECT user_id, seo_title, question FROM '.$this->CFG['db']['tbl']['questions'].' WHERE ques_id='.$this->dbObj->Param('qid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($ques_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				$this->question_details = $rs->FetchRow();
		    }

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

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

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

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

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

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

		/**
		 * AnswersFormHandler::getCategoryName()
		 *
		 * @param mixed $pcat_id
		 * @param mixed $scat_id
		 * @return
		 */
		public function getCategoryName($pcat_id, $scat_id)
		    {
				$cat_id = $pcat_id;
				if($scat_id > 0)
					$cat_id = $scat_id;

				$sql = 'SELECT cat_name FROM '.$this->CFG['db']['tbl']['questions_category'].' WHERE cat_id='.$this->dbObj->Param('cid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($cat_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				$row = array('cat_name'=>'');
				if ($rs->PO_RecordCount())
					$row = $rs->FetchRow();
				return $row['cat_name'];
		    }

		/**
		 * AnswersFormHandler::deleteQuestionVideo()
		 *
		 * @return
		 */
		public function deleteQuestionVideo($field_name)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_video'].' SET'.
						' video_status=\'Deleted\' WHERE video_id='.$this->dbObj->Param('content_id').' AND'.
						' video_for=\'Question\'';

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

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].' SET'.
						' '.$field_name.'=\'0\' WHERE '.$field_name.'='.$this->dbObj->Param('video_id');

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

		/**
		 * AnswersFormHandler::deleteQuestionAudio()
		 *
		 * @return
		 */
		public function deleteQuestionAudio($field_name)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['ans_audio'].' SET'.
						' audio_status=\'Deleted\' WHERE audio_id='.$this->dbObj->Param('content_id').' AND'.
						' audio_for=\'Question\'';

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

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions'].' SET'.
						' '.$field_name.'=\'0\' WHERE '.$field_name.'='.$this->dbObj->Param('audio_id');

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

		/**
		 * AnswersFormHandler::populateSearchOptions()
		 *
		 * @return
		 */
		public function populateSearchOptions()
			{
				$populateSearchOptions_arr = array();
				foreach($this->search_options as $key=>$value)
					{
						//$selected = ($highlight_search==$key)?'SELECTED':'';
						$populateSearchOptions_arr[$key] = $value;
					}
				return $populateSearchOptions_arr;
			}

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

		/**
		 * AnswersFormHandler::chkIsValidCaptureVideoFile()
		 *
		 * @return
		 */
		public function chkIsValidCaptureVideoFile()
			{
				//for testing

				$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;
								#die('here');
							}

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

		/**
		 * AnswersFormHandler::chkIsValidCaptureAudioFile()
		 *
		 * @return
		 */
		public function chkIsValidCaptureAudioFile()
			{
				//for testing

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

		/**
		 * AnswersFormHandler::getVideoAudioCount()
		 *
		 * @param mixed $qid
		 * @return
		 */
		public function getVideoAudioCount($qid)
			{
				$sql = 'SELECT ans_id, video_id, audio_id FROM '.
						$this->CFG['db']['tbl']['answers'].' WHERE ques_id='.$qid.
						' AND (video_id != 0 OR audio_id <> 0)';
				#echo $sql;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
				        trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						return true;

					}
			}

		/**
		 * AnswersFormHandler::printQuery()
		 *
		 * @return
		 */
		public function printQuery()
			{
				//echo $this->sql;
			}

		/**
		 * AnswersFormHandler::sendPublishedMailAlert()
		 *
		 * @param mixed $userid
		 * @param mixed $mailtype
		 * @param mixed $mail_content_seo
		 * @param mixed $mail_content
		 * @param mixed $content_description
		 * @return
		 */
		public function sendPublishedMailAlert($userid, $mailtype, $mail_content_seo, $mail_content, $content_description)
			{
				$toDetails = $this->getUserDetailsFromUsersTable($this->CFG['db']['tbl']['users'], $userid);
				$site_link = "<a target=\"_blank\" href=\"".URL($this->CFG['site']['url'])."\">".URL($this->CFG['site']['url'])."</a>";

				if($mailtype == 'Question')
					{

						$url_link = getAnovaUrl('answer', '?title='.$mail_content_seo, $mail_content_seo.'/', 'root');
						$quesiton_link = "<a target=\"_blank\" href=\"".$url_link."\">".$mail_content."</a>";
						$subject = $this->getMailContent($this->LANG['question_publish_subject'], array('VAR_USERNAME'=>$toDetails['display_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['question_publish_message'], array('VAR_USERNAME'=>$toDetails['display_name'], 'VAR_SITENAME'=>$this->CFG['site']['name'], 'VAR_DESCRIPTION_OF_QUESTION'=>$content_description, 'VAR_QUESTION'=>$quesiton_link, 'VAR_LINK'=>$site_link));
					}

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

		/**
		 * AnswersFormHandler::populateSubCategoriesCount()
		 *
		 * @param mixed $cid
		 * @param mixed $scid
		 * @return
		 */
		public function populateSubCategoriesCount($cid, $scid)
		   	{
				$sql = 'SELECT count(cat_id) as count FROM '.
					$this->CFG['db']['tbl']['questions_category'].
					' WHERE parent_id='.$this->dbObj->Param('cid').
					' AND parent_id!=0'.
					' AND status=\'1\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($cid));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						return $row['count'];
					}
				else
					{
						return 0;
					}
	    	}

		/**
		 * AnswersFormHandler::isCategoryExist()
		 *
		 * @return
		 */
		public function isCategoryExist()
			{

				if($this->fields_arr['category'] == 'new')
					{

						$sql = 'SELECT cat_id as count FROM '.$this->CFG['db']['tbl']['questions_category'].' WHERE'.
							' parent_id=0 AND cat_name='.$this->dbObj->Param($this->fields_arr['new_status_hidden']);
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['new_status_hidden']));
						if (!$rs)
								trigger_db_error($this->dbObj);

						$row = $rs->FetchRow();
						if ($row['count'])
							{
								$this->fields_arr['category'] = $row['count'];
							}
						else
							{
								$this->setFormField('cat_seo_title', $this->getSeoTitleForQuestionCategory($this->getFormField('new_status_hidden'), $this->getFormField('category')));
								$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['questions_category'].
									' SET cat_name='.$this->dbObj->Param('category').
									', seo_title='.$this->dbObj->Param('seo_title').
									', status=\'1\''.
									', date_added=NOW()';

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

					}
				if($this->fields_arr['sub_category'] == 'new')
					{

						$this->setFormField('subcat_seo_title', $this->getSeoTitleForQuestionCategory($this->getFormField('new_substatus_hidden'), $this->getFormField('sub_category')));
						$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['questions_category'].
							' SET cat_name='.$this->dbObj->Param('category').
							', seo_title='.$this->dbObj->Param('seo_title').
							', parent_id='.$this->dbObj->Param('parent_id').
							', status=\'1\''.
							', date_added=NOW()';
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['new_substatus_hidden'],
																 $this->fields_arr['subcat_seo_title'],
																 $this->fields_arr['category']
																 ));
						if (!$rs)
								trigger_db_error($this->dbObj);
						$this->fields_arr['sub_category'] = $this->dbObj->Insert_ID();

						$has_child = '1';
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['questions_category'].
							' SET has_child='.$this->dbObj->Param($has_child).
							' WHERE cat_id='.$this->dbObj->Param($this->fields_arr['category']);
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($has_child, $this->fields_arr['category']));
						if (!$rs)
							    trigger_db_error($this->dbObj);

					}
			}

		/**
		 * AnswersFormHandler::getAttachments()
		 *
		 * @return
		 */
		public function getAttachments()
			{
				$getAttachments_arr = array();
				$sql = 'SELECT attachment_id, attachment_name, photo_server_url FROM '.$this->CFG['db']['tbl']['attachments'].
					' WHERE content_id='.$this->fields_arr['qid'].' AND content_type=\'Question\' ORDER BY attachment_id';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						$attach_count = 0;
						$inc=1;
						while($row = $rs->FetchRow())
							{
								$getAttachments_arr[$inc]['record'] = $row;
								$extern = strtolower(substr($row['attachment_name'], strrpos($row['attachment_name'], '.')+1));
								$getAttachments_arr[$inc]['attachment_file_name'] = getImageName($row['attachment_id']).$this->CFG['admin']['ans_pictures']['large_name'].'.'.$extern;
								$getAttachments_arr[$inc]['attachment_file_name_thumb'] = getImageName($row['attachment_id']).$this->CFG['admin']['ans_pictures']['thumb_name'].'.'.$extern;
								$getAttachments_arr[$inc]['img_id'] = 'Question_'.$this->fields_arr['qid'].'_'.$row['attachment_id'];
								$getAttachments_arr[$inc]['attachment_path'] = $this->CFG['site']['relative_url'].'viewAnswers.php?qid='.$this->fields_arr['qid'].'&imgdetail='.$getAttachments_arr[$inc]['img_id'];
								$getAttachments_arr[$inc]['image_large_path'] = $row['photo_server_url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$getAttachments_arr[$inc]['attachment_file_name'];
								$getAttachments_arr[$inc]['anchor'] = 'seldel_'.$row['attachment_id'];
								$getAttachments_arr[$inc]['attachment']['url'] = $this->CFG['site']['url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$getAttachments_arr[$inc]['attachment_file_name'];
								$getAttachments_arr[$inc]['attachment']['url_thumb'] = $this->CFG['site']['url'].$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$getAttachments_arr[$inc]['attachment_file_name_thumb'];

								$attach_count++;
								$inc++;

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

		/**
		 * AnswersFormHandler::deleteMoreInfos()
		 *
		 * @param mixed $aid
		 * @param mixed $aname
		 * @return
		 */
		public function deleteMoreInfos($aid, $aname)
			{
				$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($aname, 0, strrpos($aname, '.')-1);
				$extern = strtolower(substr($aname, strrpos($aname, '.')+1));

				$attachment_large_file = '../../'.$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$aname;
				$attachment_small_file = '../../'.$this->CFG['admin']['index']['anova_module'].'/'.$this->CFG['admin']['ans_attachments_path'].$small_name.$this->CFG['admin']['ans_pictures']['small_name'].'.'.$extern;
				unlink($attachment_large_file);
				unlink($attachment_small_file);
			}

		/**
		 * AnswersFormHandler::chkFileNameIsNotEmpty()
		 *
		 * @param mixed $field_name
		 * @param string $err_tip
		 * @return
		 */
		public function chkFileNameIsNotEmpty($field_name, $err_tip = '')
			{
				if(!isset($_FILES[$field_name]['name']) or !$_FILES[$field_name]['name'])
					{
						$this->setFormFieldErrorTip($field_name,$err_tip);
						return false;
					}
				return true;
			}

		/**
		 * AnswersFormHandler::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;
			}

		/**
		 * AnswersFormHandler::chkValideFileSize()
		 *
		 * @param mixed $field_name
		 * @param mixed $type
		 * @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;
			}

		/**
		 * AnswersFormHandler::chkErrorInFile()
		 *
		 * @param mixed $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;
			}

		/**
		 * AnswersFormHandler::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;
			}

		/**
		 * AnswersFormHandler::storePicturesTempServer()
		 *
		 * @param mixed $uploadUrl
		 * @param mixed $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];*/
				//echo '<br>size<br>'.$image_info[1];
				//die('hard');
				//GET SMALL IMAGE
				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;
			}

		/**
		 * AnswersFormHandler::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 = '../../'.$this->CFG['admin']['index']['anova_module'].'/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);
												$uploaded = true;
											}
										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']['index']['anova_module'].'/'.$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]);
							unlink('../../'.$this->CFG['admin']['index']['anova_module'].'/'.$uploads_arr[$i]);
							unlink($temp_dir.'temp_'.$req_upl[1].'_'.$req_upl[2].'.'.$extern);
					}
			}

		/**
		 * AnswersFormHandler::createAttachmentRecord()
		 *
		 * @param mixed $size
		 * @return
		 */
		public function createAttachmentRecord($size)
			{
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['attachments'].
						' SET content_type=\'Question\''.
						', 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();
			}

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

		/**
		 * AnswersFormHandler::updateTags()
		 *
		 * @param mixed $qtags
		 * @return
		 */
		public function updateTags($qtags)
			{
				$tags = explode(' ', $qtags);
				foreach($tags as $eachTag){
					if (trim($eachTag) == '') continue;
					if ($this->isTagExists($eachTag))
						$this->updateTagCount($eachTag);
					else
						$this->insertTagCount($eachTag);
				}
			}

		/**
		 * AnswersFormHandler::isTagExists()
		 *
		 * @param mixed $tagname
		 * @param mixed $minus
		 * @return
		 */
		public function isTagExists($tagname, $minus=false)
			{
				$condition = ' ';
				if($minus)
					$condition = ' total_count > 0 AND ';
				$sql = 'SELECT 1 FROM '.$this->CFG['db']['tbl']['tags'].
						' WHERE'.$condition.'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);
				$ok = false;
				if ($rs->PO_RecordCount())
					$ok = true;
				return $ok;
			}

		/**
		 * AnswersFormHandler::updateTagCount()
		 *
		 * @param mixed $tagname
		 * @param mixed $minus
		 * @return
		 */
		public function updateTagCount($tagname, $minus=false)
			{
				$countAction = '+';
				if($minus)
					$countAction = '-';

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['tags'].
						' SET total_count=total_count'.$countAction.'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);
			}

		/**
		 * AnswersFormHandler::insertTagCount()
		 *
		 * @param mixed $tagname
		 * @return
		 */
		public function insertTagCount($tagname)
			{
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['tags'].
						' SET tag_name='.$this->dbObj->Param($tagname).
						', total_count=1';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($tagname));
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 * AnswersFormHandler::modifyTags()
		 *
		 * @return
		 */
		public function modifyTags()
			{
				$tags = explode(' ', $this->fields_arr['tags']);
				$old_tags = explode(' ',$this->question_details['tags']);
				$tags_to_decrement = array_diff($old_tags, $tags);
				$tags_to_increment = array_diff($tags, $old_tags);

				if(!empty($tags_to_increment))
					{
						foreach($tags_to_increment as $eachTag)
							{
								if (trim($eachTag) == '') continue;
								if ($this->isTagExists($eachTag))
									$this->updateTagCount($eachTag);
								else
									$this->insertTagCount($eachTag);
							}
					}

				if(!empty($tags_to_decrement))
					{
						foreach($tags_to_decrement as $removableTag)
							{
								if (trim($removableTag) == '') continue;
								$this->updateTagCount($removableTag, $minus=true);
							}
					}
			}

		/**
		 * AnswersFormHandler::updateDeletedQuestionsTagCount()
		 *
		 * @param mixed $tags
		 * @return
		 */
		public function updateDeletedQuestionsTagCount($tags)
			{
				$tags_arr = explode(' ', $tags);
				foreach($tags_arr as $tagname)
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['tags'].
							' SET total_count=total_count-1'.
							' WHERE tag_name='.$this->dbObj->Param($tagname);
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($tagname));
						if (!$rs)
					    		trigger_db_error($this->dbObj);
					}
			}
		public function chkTwitterUser($user_id)
			{
				$sql = ' SELECT * FROM '.$this->CFG['db']['tbl']['twitter_identity'].''.
					   ' WHERE user_id = '.$user_id;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
				        trigger_db_error($this->dbObj);
				$numrows = $rs->PO_RecordCount();
				if($numrows >0)
					return true;
				else
					return false;
			}

		/**
		 * AnswersFormHandler::getTabIndex()
		 *
		 * @return
		 **/
		 public function getTabIndex()
			{
				return $this->tab_index += 5;
			}
	}
//<<<<<-------------------- Class AnswersFormHandler Ends ------------------------//
//------------------------- Code Begins ---------------------------------->>>>>//
$questions = new AnswersFormHandler();
$questions->left_navigation_div = 'anovaAnswers';
$questions->fp = false;
$questions->setLang(array('sort_ascending' => $LANG['list_sort_ascending'],
						'sort_descending' => $LANG['list_sort_descending']
						));
$questions->setPageBlockNames(array('list_records', 'form_edit', 'show_form_search', 'show_form_confirm'));
$questions->setAllPageBlocksHide();
$questions->setColumnSortUrl($_SERVER['REQUEST_URI']);

$questions->setSearchFormFieldNames('start', 'numpg', 'dsc', 'asc'); //, 'q');
$questions->setFormField('search_name', '');
$questions->setFormField('search_cat', '');
$questions->setFormField('action', '');
$questions->setFormField('qid', '');
$questions->setFormField('f', '');
$questions->setFormField('question', '');
$questions->setFormField('descriptions', '');
$questions->setFormField('category', '');
$questions->setFormField('old_category', '');
$questions->setFormField('sub_category', '');
$questions->setFormField('old_sub_category', '');
$questions->setFormField('new_status_hidden', '');
$questions->setFormField('new_substatus_hidden', '');
$questions->setFormField('video', '');
$questions->setFormField('external_video_id', '');
$questions->setFormField('audio', '');
$questions->setFormField('video_id', '');
$questions->setFormField('audio_id', '');
$questions->setFormField('external_audio_id', '');
$questions->setFormField('video_external_flv_url', '');
$questions->setFormField('flv_upload_type', '');
$questions->setFormField('file_extern', '');
$questions->setFormField('audio_external_url', '');
$questions->setFormField('audio_extern', '');
$questions->setFormField('rid', '');
$questions->setFormField('sort', 'date');
$questions->setFormField('order', '');
$questions->setFormField('uname', '');
$questions->setFormField('tags', '');
$questions->setFormField('act', '');
$questions->setFormField('with', '');
$questions->setFormField('type', '');
$questions->setFormField('more_questions', '');
$questions->setFormField('tags', '');
$questions->setFormField('publish', 'Yes');
$questions->setFormField('featured', 'No');
$questions->setFormField('ques_ids', array());
$questions->setFormField('asc', '');
$questions->setFormField('dsc', '');
$questions->setFormField('start', 0);
$questions->setFormField('act', '');
$questions->setFormField('mode', '');
$questions->setFormField('sort_act', '');
$questions->setFormField('attachments', '');
$questions->setFormField('attachment_id', '');
$questions->setFormField('attachment_name', '');
$questions->setFormField('photo_server_url', '');
$questions->setFormField('ques_user_id', '');
$questions->setFormField('upl_original', array());
$questions->setFormField('uplarr', array());
$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].';';
			}
	}
$questions->paging_arr = array('orderby_field', 'orderby');

$questions->setFormField('numpg', $CFG['data_tbl']['numpg']);
$questions->setMinRecordSelectLimit($CFG['data_tbl']['min_record_select_limit']);
$questions->setMaxRecordSelectLimit($CFG['data_tbl']['max_record_select_limit']);
$questions->setNumPerPageListArr($CFG['data_tbl']['numperpage_list_arr']);

$questions->member_url = $CFG['site']['relative_url'].$CFG['redirect']['member'].'/';
$questions->setTableNames(array($CFG['db']['tbl']['questions'].' as q', $CFG['db']['tbl']['users'].' as u'));
$questions->setReturnColumns(array('ques_id', 'u.usr_status', 'q.user_id', 'q.video_id', 'q.audio_id', 'q.external_video_id', 'q.external_audio_id', 'q.pcat_id', 'q.cat_id', 'q.votes', 'q.abuse_count', 'q.publish_status', 'q.featured', 'q.tags', 'q.total_answer', $questions->getUserTableFields(array('name', 'display_name')), 'question', 'total_stars', 'UNIX_TIMESTAMP(date_asked) as date_asked', 'TIMEDIFF(date_closed, NOW()) as date_closed', 'CASE when status=\'Open\' AND date_closed>=NOW() then \''.$LANG['common_open'].'\' when status=\'ToActivate\' then \''.$LANG['common_unpublished'].'\' when status=\'Blocked\' then \''.$LANG['common_blocked'].'\' ELSE \''.$LANG['common_resolved'].'\' END status', 'video_id', 'audio_id', 'q.total_videos', 'q.total_audios'));
$questions->setFormField('orderby_field', 'ques_id');
$questions->setFormField('orderby', 'DESC');
$questions->search_options = array(1=>$LANG['question_owner'], 2=>$LANG['search_type_email'],
									3=>$LANG['open_questions'], 4=>$LANG['common_resolved_questions'],
									5=>$LANG['search_type_blocked'], 6=>$LANG['search_type_all']);
if ($CFG['admin']['module']['video'])
	$questions->search_options[9] = $LANG['common_video_question_title'];
if ($CFG['admin']['module']['audio'])
	$questions->search_options[10] = $LANG['common_audio_question_title'];
$questions->search_options[11] = $LANG['search_type_with_best_answer'];
$questions->search_options[12] = $LANG['search_type_unpublished'];
$questions->search_options[13] = $LANG['common_featured_questions'];


$questions->sanitizeFormInputs($_REQUEST);
if($questions->getFormField('f'))
	$questions->setFormField('f', 'v');

if(!$questions->getFormField('rid'))
	$questions->generateRandomId();

$questions->buildSelectQuery();

if ($questions->isFormPOSTed($_REQUEST, 'deletemoreattachments'))
	{
		if (!isMember())
			{
				echo 'Session Expired. <a href="'.$CFG['auth']['login_url'].'?r">Login to continue..!</a>';
				die();
			}
		ob_start();

		$comment_id = $questions->getFormField('attachment_id');
		$attachment_name = $questions->getFormField('attachment_name');
		$questions->deleteMoreInfos($comment_id, $attachment_name);

		die();
	}
if ($questions->isFormGETed($_GET, 'delmsg'))
	{
		$questions->setPageBlockShow('block_msg_form_success');
		$questions->setCommonSuccessMsg($LANG['question_deleted_succesfully']);
	}

if($questions->isFormPOSTed($_POST, 'todo'))
	{
		$questions->setAllPageBlocksHide();
		$num_selected = count($questions->getFormField('ques_ids'));
		if($num_selected > 0)
			{
				$questions->setPageBlockShow('show_form_confirm');
				$questions->ConditionQuery();
			}
    }
elseif($questions->isFormPOSTed($_POST, 'action') and $questions->getFormField('ques_ids') and  $questions->getFormField('sort_act'))
	{
		//die($questions->getFormField('ques_ids'));
		if($questions->getFormField('action') == 'publish_question')
			{
     			$questions->updateQuestionAndCategoryCountForPublish($questions->getFormField('ques_ids'), 'Publish');
     			$LANG['question_status_updated_succesfully'] = $LANG['question_status_published_succesfully'];
			}
		elseif($questions->getFormField('action') == 'block_question')
			{
                    $questions->updateStatus($CFG['db']['tbl']['questions'], 'Blocked');
                    $LANG['question_status_updated_succesfully'] = $LANG['question_status_blocked_succesfully'];
               }
		elseif($questions->getFormField('action') == 'open_question')
			{
                    $questions->updateStatus($CFG['db']['tbl']['questions'], 'Open');
                    $LANG['question_status_updated_succesfully'] = $LANG['question_status_opened_succesfully'];
               }
		elseif($questions->getFormField('action') == 'resolve_question')
			{
                    $questions->updateStatus($CFG['db']['tbl']['questions'], 'Resolved');
                    $LANG['question_status_updated_succesfully'] = $LANG['question_status_resolved_succesfully'];
               }
		elseif($questions->getFormField('action') == 'delete_question')
			{
                    $questions->deleteQuestions($CFG['db']['tbl']['questions'], $CFG['db']['tbl']['answers'], $CFG['db']['tbl']['users_ans_log']);
                    $LANG['question_status_updated_succesfully'] = $LANG['question_status_deleted_succesfully'];
               }
		elseif($questions->getFormField('action') == 'abuse_question')
			{
                    $questions->abuseQuestions();
                    $LANG['question_status_updated_succesfully'] = $LANG['question_status_abused_succesfully'];
               }
		elseif($questions->getFormField('action') == 'unblock_question')
			{
                    $questions->updateStatus($CFG['db']['tbl']['questions'], 'Unblock');
                    $LANG['question_status_updated_succesfully'] = $LANG['question_status_unblocked_succesfully'];
               }
        elseif($questions->getFormField('action') == 'feature_question')
			{
                    $questions->updateFeatured($CFG['db']['tbl']['questions'], 'Yes');
                    $LANG['question_status_updated_succesfully'] = $LANG['question_status_featured_succesfully'];
               }
        elseif($questions->getFormField('action') == 'remove_feature')
			{
                    $questions->updateFeatured($CFG['db']['tbl']['questions'], 'No');
                    $LANG['question_status_updated_succesfully'] = $LANG['question_status_feature_removed_succesfully'];
               }

		$questions->ConditionQuery();
		$questions->setCommonSuccessMsg($LANG['question_status_updated_succesfully']);
		$questions->setPageBlockShow('block_msg_form_success');
	}
elseif($questions->isFormPOSTed($_POST, 'go') || $questions->isFormPOSTed($_REQUEST, 'search_cat'))
	{
		$questions->ConditionQuery();
		$questions->paging_arr = array('search_cat', 'search_name');
	}
elseif(($questions->isFormPOSTed($_POST, 'dcancel')) OR ($questions->isFormGETed($_GET, 'change')))
	{
		$questions->ConditionQuery();
		$questions->setPageBlockShow('form_edit');
	}
elseif(($questions->isFormPOSTed($_POST, 'cancel')))
	{
		Redirect2URL($CFG['site']['relative_url'].'manageAnswers.php');
	}
elseif(($questions->isFormPOSTed($_POST, 'submit')))
	{
		$questions->chkIsValidQuestion();
		if($CFG['admin']['question']['duplicates'])
			{
				$questions->chkIsNotEmpty('question', $LANG['err_tip_compulsory']);
			}
		else
			{
				$questions->chkIsNotEmpty('question', $LANG['err_tip_compulsory'])	and
					$questions->chkIsQuestionExists('question', $LANG['questions_err_exists_already']);
			}
		if ($CFG['admin']['category']['mandatory'])
			$questions->chkIsNotEmpty('category', $LANG['err_tip_compulsory']);
		if ($CFG['admin']['description']['mandatory'])
			$questions->chkIsNotEmpty('descriptions', $LANG['err_tip_compulsory']);

		if (isset($_FILES['attachments']) and $_FILES['attachments']['tmp_name'])
			{
				$questions->chkValidFileType('attachments', 'attachments', $LANG['err_tip_invalid_file_type']) and
					$questions->chkValideFileSize('attachments','attachments',$LANG['err_tip_invalid_file_size']) and
						$questions->chkErrorInFile('attachments', $LANG['err_tip_invalid_file']);
			}

		if (chkIsVideoAllowed('question'))
			$questions->chkIsValidCaptureVideoFile();
		if (chkIsAudioAllowed('question'))
			$questions->chkIsValidCaptureAudioFile();

		if ($questions->isValidFormInputs())
			{
				if ($CFG['debug']['store_log'])
					{
						$temp_dir = '../'.$CFG['admin']['logfile_path'];
						$questions->chkAndCreateFolder($temp_dir);
						$temp_file_path = $temp_dir.$CFG['user']['user_id'].$type.'.txt';
						$questions->fp = fopen($temp_file_path, 'w');
					}
				$questions->updateQuestion();
				if ($CFG['debug']['store_log'])
					{
						$questions->closeErrorLogFile();
					}
				if($questions->getFormField('f')=='v')
					Redirect2URL($CFG['site']['relative_url'].'viewAnswers.php?qid='.$questions->getFormField('qid').'&msg=4');

				Redirect2URL($CFG['site']['relative_url'].'manageAnswers.php?msg=1');
			}
		else
			{
				$questions->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				$questions->setPageBlockShow('block_msg_form_error');
				$questions->setPageBlockShow('form_edit');
			}
		$questions->ConditionQuery();
	}
elseif(($questions->isFormGETed($_GET, 'qid') AND $questions->chkIsValidQuestion()))
	{
		$questions->setPageBlockShow('form_edit');
		$questions->setFormField('question', $questions->question_details['question']);
		$questions->setFormField('descriptions', $questions->question_details['description']);
		$questions->setCategoryFormField();
        $questions->setFormField('video_id', $questions->question_details['video_id']);
		$questions->setFormField('external_video_id', $questions->question_details['external_video_id']);
		$questions->setFormField('audio_id', $questions->question_details['audio_id']);
		$questions->setFormField('external_audio_id', $questions->question_details['external_audio_id']);
		$questions->setFormField('tags', $questions->question_details['tags']);
		$questions->setFormField('publish', $questions->question_details['publish_status']);
		$questions->setFormField('featured', $questions->question_details['featured']);
		$questions->setFormField('ques_user_id', $questions->question_details['user_id']);
		$questions->getFormField('ques_user_id');
		$questions->ConditionQuery();
	}
else
	$questions->ConditionQueryNoSearch();
if ($questions->isFormGETed($_GET, 'msg'))
	{
		$questions->setPageBlockShow('block_msg_form_success');
		$questions->setCommonSuccessMsg($LANG['question_updated_succesfully']);
	}

if($questions->isFormPOSTed($_POST, 'act'))
	{
		switch($questions->getFormField('act'))
			{
				case 'deletevideo':
					$questions->deleteQuestionVideo('video_id');
					$questions->setPageBlockShow('block_msg_form_success');
					$LANG['delete_success_message'] = $LANG['delete_video_success'];
					$questions->setCommonSuccessMsg($LANG['delete_success_message']);
					break;

				case 'deleteaudio':
					$questions->deleteQuestionAudio('audio_id');
					$questions->setPageBlockShow('block_msg_form_success');
					$LANG['delete_success_message'] = $LANG['delete_audio_success'];
					$questions->setCommonSuccessMsg($LANG['delete_success_message']);
					break;
				case 'delete_external_video':
					$questions->deleteQuestionVideo('external_video_id');
                    $questions->setPageBlockShow('msg_form_delete_success');
					$LANG['delete_success_message'] = $LANG['delete_video_success'];
					break;

				case 'delete_external_audio':
					$questions->deleteQuestionAudio('external_audio_id');
                    $questions->setPageBlockShow('msg_form_delete_success');
					$LANG['delete_success_message'] = $LANG['delete_audio_success'];
					break;
			}
	}

$questions->buildSortQuery();
$questions->buildQuery();
$questions->printQuery();
$questions->executeQuery();

if(!$questions->isFormGETed($_GET, 'qid'))
	{
		$questions->setPageBlockShow('list_records');
	}

if($questions->getFormField('mode')== 'search')
	{
		$questions->setAllPageBlocksHide();
		$questions->setPageBlockShow('show_form_search');
		$questions->LANG['member_title'] = $LANG['member_search_title'];
	}
//<<<<<<<---------------code ends-------------///
$questions->show_form_confirm['hidden_arr'] = array('start', 'numpg','search_name','search_cat');
$questions->categories_arr = $questions->populateCategories();
$questions->sub_categories_arr = '';
if($questions->getFormField('category'))
	{
		$questions->sub_categories_arr = $questions->populateSubCategories($questions->getFormField('category'));
	}

if ($questions->isShowPageBlock('form_edit'))
	{
		$questions->LANG['member_title'] = $LANG['member_edit_title'];
		$questions->form_edit['hidden_arr'] = array('rid', 'video', 'video_external_flv_url', 'file_extern', 'audio', 'audio_external_url', 'audio_extern', 'video_id', 'external_video_id', 'audio_id', 'external_audio_id', 'f', 'old_category', 'old_sub_category');
        $questions->form_edit['video']['style_add_video'] = $questions->form_edit['video']['style_add_external_video'] = $style_add_video = $style_add_external_video = '';
		$questions->form_edit['video']['style_delete_video'] = $questions->form_edit['video']['style_delete_external_video'] = 'style="display:none"';
		$questions->form_edit['video']['style_preview_video'] = $questions->form_edit['video']['style_preview_external_video'] = 'style="display:none"';
		$questions->form_edit['video']['video_preview_url'] = $questions->form_edit['video']['video_default_preview_url'] = getAnovaUrl('anspreviewvideo', '?pg=Question_'.$questions->getFormField('rid'), '?pg=Question_'.$questions->getFormField('rid'), 'members');
		$questions->form_edit['video']['video_not_encoded_info'] = $LANG['video_not_encoded_info'];
		$questions->form_edit['video']['external_video_onclick'] = 'return showVideoExternalPreview();';
		$questions->form_edit['video']['external_video_preview_url'] = $_SERVER['REQUEST_URI'];

		if($questions->getFormField('video') or $questions->getFormField('video_id'))
			{
				$questions->form_edit['video']['style_delete_video'] = '';
				$questions->form_edit['video']['style_preview_video'] = '';
				$questions->form_edit['video']['style_add_video'] = 'style="display:none"';
				if ($questions->getFormField('video_id'))
					$questions->form_edit['video']['video_preview_url'] = getAnovaUrl('ansviewvideo', '?pg=Question_'.$questions->getFormField('video_id'), '?pg=Question_'.$questions->getFormField('video_id'), 'members');
				if ($questions->getFormField('video'))
					$questions->form_edit['video']['video_preview_url'] = getAnovaUrl('anspreviewvideo', '?pg=Question_'.$questions->getFormField('video'), '?pg=Question_'.$questions->getFormField('video'), 'members');
			}
		if($questions->getFormField('video_external_flv_url') or $questions->getFormField('file_extern') or $questions->getFormField('external_video_id'))
			{
				$questions->form_edit['video']['style_delete_external_video'] = $style_delete_external_video = '';
				$questions->form_edit['video']['style_preview_external_video'] = $style_preview_external_video = '';
				$questions->form_edit['video']['style_add_external_video'] = $style_add_external_video = 'style="display:none"';

				if (!$questions->getFormField('video_external_flv_url') AND !$questions->getFormField('file_extern'))
					{
						if ($questions->getFormField('external_video_id') AND $external_video_details = $questions->getExternalVideoDetails($questions->getFormField('external_video_id')))
							{
								if ($external_video_details['video_status'] == 'Ok' AND $external_video_details['video_encoded_status'] == 'Yes')
									{
										$questions->form_edit['video']['external_video_onclick'] = $external_video_onclick = getBrowser('video');
										$questions->form_edit['video']['external_video_preview_url'] = $external_video_preview_url = getAnovaUrl('ansviewvideo', '?pg=Question_'.$questions->getFormField('external_video_id'), '?pg=Question_'.$questions->getFormField('external_video_id').'/', 'members');
									}
							}
					}
			}
		$questions->form_edit['audio']['style_add_audio'] = $questions->form_edit['audio']['style_add_external_audio'] = '';
		$questions->form_edit['audio']['style_delete_audio'] = $questions->form_edit['audio']['style_delete_external_audio'] = 'style="display:none"';
		$questions->form_edit['audio']['style_preview_audio'] = $questions->form_edit['audio']['style_preview_external_audio'] = 'style="display:none"';
		$questions->form_edit['audio']['audio_default_preview_url'] = $questions->form_edit['audio']['audio_preview_url'] = getAnovaUrl('anspreviewaudio', '?pg=Question_'.$questions->getFormField('rid'), '?pg=Question_'.$questions->getFormField('rid'), 'members');
		$questions->form_edit['audio']['audio_not_encoded_info'] = $audio_not_encoded_info = $LANG['audio_not_encoded_info'];
		$questions->form_edit['audio']['external_audio_onclick'] = $external_audio_onclick = 'return showAudioExternalPreview();';
		$questions->form_edit['audio']['external_audio_preview_url'] = $external_audio_preview_url = $_SERVER['REQUEST_URI'];
		if($questions->getFormField('audio') or $questions->getFormField('audio_id'))
			{
				$questions->form_edit['audio']['style_delete_audio'] = '';
				$questions->form_edit['audio']['style_preview_audio'] = '';
				$questions->form_edit['audio']['style_add_audio'] = 'style="display:none"';
				if ($questions->getFormField('audio_id'))
					$questions->form_edit['audio']['audio_preview_url'] = getAnovaUrl('ansviewaudio', '?pg=Question_'.$questions->getFormField('audio_id'), '?pg=Question_'.$questions->getFormField('audio_id'), 'members');
				if ($questions->getFormField('audio'))
					$questions->form_edit['audio']['audio_preview_url'] = getAnovaUrl('anspreviewaudio', '?pg=Question_'.$questions->getFormField('audio'), '?pg=Question_'.$questions->getFormField('audio'), 'members');
			}
		if($questions->getFormField('audio_external_url') or $questions->getFormField('audio_extern') or $questions->getFormField('external_audio_id'))
			{
				$questions->form_edit['audio']['style_delete_external_audio'] = $style_delete_external_audio = '';
				$questions->form_edit['audio']['style_preview_external_audio'] = $style_preview_external_audio = '';
				$questions->form_edit['audio']['style_add_external_audio'] = $style_add_external_audio = 'style="display:none"';
				if (!$questions->getFormField('audio_external_url') AND !$questions->getFormField('audio_extern'))
					{
						if ($questions->getFormField('external_audio_id') AND $external_audio_details = $questions->getExternalAudioDetails($questions->getFormField('external_audio_id')))
							{
								if ($external_audio_details['audio_status'] == 'Ok' AND $external_audio_details['audio_encoded_status'] == 'Yes')
									{
										$questions->form_edit['audio']['external_audio_onclick'] = $external_audio_onclick = getBrowser('audio', 'height');
										$questions->form_edit['audio']['external_audio_preview_url'] = $external_audio_preview_url = getAnovaUrl('ansviewaudio', '?pg=Question_'.$questions->getFormField('external_audio_id'), '?pg=Question_'.$questions->getFormField('external_audio_id').'/', 'members');
									}
							}
					}
			}
		if ($CFG['admin']['attachments_questions']['allowed'] && $questions->getFormField('qid'))
			$questions->form_edit['getAttachments_arr'] = $questions->getAttachments();

	    	$allowed_formats = implode(",",$CFG['admin']['attachments']['format_arr']);
			if($allowed_formats == '')
					$allowed_formats = 'jpg,gif,png';
			$allowed_size = $CFG['admin']['attachments']['max_size'];
	      	$questions->form_edit['attach_style'] = '';

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

		$questions->form_edit['attachment_allowed_tip_manual'] = str_ireplace('VAR_COUNT', $CFG['admin']['attachments_allowed']['count'] ,$LANG['attachment_allowed_tip']);
		$questions->form_edit['attachment_format_tip_manual'] = str_ireplace('VAR_FORMAT', $allowed_formats, $LANG['attachment_format_tip']);
		$questions->form_edit['attachment_size_tip_manual'] = str_ireplace('VAR_SIZE', $allowed_size, $LANG['attachment_size_tip']);
		$questions->form_edit['video_upload_url'] = getAnovaUrl('videoupload', '?rid='.$questions->getFormField('rid'), '?rid='.$questions->getFormField('rid'), 'members');
		$questions->form_edit['audio_upload_url'] = getAnovaUrl('audioupload', '?rid='.$questions->getFormField('rid').'AUD', '?rid='.$questions->getFormField('rid').'AUD', 'members');

		$questions->form_edit['videoupload_url']	=	getAnovaUrl('videoupload', '?rid='.$questions->getFormField('rid'),  '?rid='.$questions->getFormField('rid').'/', 'members');
		$questions->form_edit['externalvideoupload_url']	=	getAnovaUrl('externalvideoupload', '?rid='.$questions->getFormField('rid'), '?rid='.$questions->getFormField('rid'), 'members');
		$questions->form_edit['audioupload_url']	=	getAnovaUrl('audioupload', '?rid='.$questions->getFormField('rid').'AUD', '?rid='.$questions->getFormField('rid').'AUD', 'members');
		$questions->form_edit['externalaudioupload_url']	=	getAnovaUrl('externalaudioupload', '?rid='.$questions->getFormField('rid'), '?rid='.$questions->getFormField('rid'), 'members');
		$questions->form_edit['description_manual'] = stripslashes($questions->getFormField('descriptions'));
	}

if ($questions->isShowPageBlock('show_form_search'))
	{
		$questions->populateSearchOptions_arr = $questions->populateSearchOptions();
	}

if ($questions->isShowPageBlock('list_records'))
	{
		$questions->list_records_confirm_arr = array('start', 'numpg', 'orderby_field', 'orderby', 'search_cat', 'search_name');
		if($questions->isFormPOSTed($_REQUEST, 'search_cat'))
			{
				$questions->paging_arr = array('search_cat', 'search_name', 'orderby_field', 'orderby');
			}
		$smartyObj->assign('smarty_paging_list', $questions->populatePageLinksGET($questions->getFormField('start'), $questions->paging_arr));
		$tab = 4000;

		if($questions->isResultsFound())
			{
				$questions->list_records = array();
				$inc = 1;
				while($questions->fetchResultRecord())
					{
						$questions->list_records[$inc]['ques_id'] = $questions->getColumnValue('ques_id');
						$questions->list_records[$inc]['anchor'] = 'selConPos_'.$questions->getColumnValue('video_id');
						$questions->list_records[$inc]['question_manual'] = wordWrapManual($questions->getColumnValue('question'), 50);
						$questions->list_records[$inc]['display_name_manual'] = stripString($questions->getColumnValue('display_name'), $CFG['username']['short_length']);
						$questions->list_records[$inc]['video_id'] = $questions->getColumnValue('video_id');
						$questions->list_records[$inc]['audio_id'] = $questions->getColumnValue('audio_id');
						$questions->list_records[$inc]['external_video_id'] = $questions->getColumnValue('external_video_id');
						$questions->list_records[$inc]['external_audio_id'] = $questions->getColumnValue('external_audio_id');
						$questions->list_records[$inc]['getCategoryName'] = $questions->getCategoryName($questions->getColumnValue('pcat_id'),$questions->getColumnValue('cat_id'));
						$questions->list_records[$inc]['tags'] = $questions->getColumnValue('tags');
						$questions->list_records[$inc]['votes'] = $questions->getColumnValue('votes');
						$questions->list_records[$inc]['total_answer'] = $questions->getColumnValue('total_answer');
						$questions->list_records[$inc]['total_videos'] = $questions->getColumnValue('total_videos');
						$questions->list_records[$inc]['total_audios'] = $questions->getColumnValue('total_audios');
						$questions->list_records[$inc]['abuse_count'] = $questions->getColumnValue('abuse_count');
						$questions->list_records[$inc]['status'] = $questions->getColumnValue('status');
						$questions->list_records[$inc]['date_asked'] = $questions->getColumnValue('date_asked');

						$questions->list_records[$inc]['featured'] = $questions->getColumnValue('featured');
						$questions->list_records[$inc]['feature_class'] = ($questions->list_records[$inc]['featured'] == 'Yes')?'clsUserQuestions':'';
						$questions->list_records[$inc]['ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Question_'.$questions->getColumnValue('video_id'), '?pg=Question_'.$questions->getColumnValue('video_id'), 'members');
						$questions->list_records[$inc]['ans_view_video']['on_click'] = 'video_add'.$questions->getColumnValue('video_id');
						$questions->list_records[$inc]['ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Question_'.$questions->getColumnValue('audio_id'), '?pg=Question_'.$questions->getColumnValue('audio_id'), 'members');
						$questions->list_records[$inc]['ans_view_audio']['on_click'] = 'audio_add'.$questions->getColumnValue('audio_id');

						$inc++;
				   	}
			}
		$questions->action_arr = array(""=>$LANG['common_select_action'], "block_question" => $LANG['common_block'], "unblock_question" => $LANG['common_unblock'],
       								"open_question" => $LANG['common_open'], "resolve_question" => $LANG['common_resolve'],
									"delete_question" => $LANG['common_delete'], "abuse_question" => $LANG['common_abuse'],
									"publish_question" => $LANG['common_publish'], "feature_question" => $LANG['common_feature'],
									"remove_feature" => $LANG['common_remove_feature']);
	}
//-----------------Page block template begins-------->>>>///
//include the header file
$questions->includeHeader();
//include the content of the page
setTemplateFolder('admin/', $CFG['admin']['index']['anova_module']);
$smartyObj->display('manageAnswers.tpl');
$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 type="text/javascript" language="javascript">
	var block_arr= new Array('selMsgConfirm', 'selDelInfoconfirm', 'selMsgConfirmList');
	var replace_url = '<?php echo $CFG['site']['url'];?>login.php';
	var please_select_action = '<?php echo $LANG['please_select_action'];?>';
	var confirm_message = '';
	function getAction()
		{
			var act_value = document.selMemberForum.action.value;
			if(act_value)
				{
					switch(act_value)
					{

							case 'block_question':
								confirm_message = '<?php echo $LANG['are_you_sure_want_to_block_the_question'];?>';
								break;
							case 'unblock_question':
								confirm_message = '<?php echo $LANG['are_you_sure_want_to_unblock_the_question'];?>';
								break;
							case 'open_question':
								confirm_message = '<?php echo $LANG['are_you_sure_want_to_open_the_question'];?>';
								break;
							case 'resolve_question':
								confirm_message = '<?php echo $LANG['are_you_sure_want_to_resolve_the_question'];?>';
								break;
							case 'delete_question':
								confirm_message = '<?php echo $LANG['are_you_sure_want_to_delete_the_question'];?>';
								break;
							case 'abuse_question':
								confirm_message = '<?php echo $LANG['are_you_sure_want_to_abuse_the_question'];?>';
								break;
							case 'publish_question':
								confirm_message = '<?php echo $LANG['are_you_sure_want_to_publish_the_question'];?>';
								break;
							case 'feature_question':
								confirm_message = '<?php echo $LANG['are_you_sure_want_to_feature_the_question'];?>';
								break;
							case 'remove_feature':
								confirm_message = '<?php echo $LANG['are_you_sure_want_to_remove_the_feature'];?>';
								break;
					}
					$('msgConfirmText').innerHTML = confirm_message;
					document.msgConfirmform.action.value = act_value;
					document.msgConfirmform.act.value = '';
					Confirmation('selMsgConfirm', 'msgConfirmform', Array('ques_ids'), Array(multiCheckValue), Array('value'),'selMemberForum');
				}
				else{
						alert_manual(please_select_action);
					}
		}
</script>
<?php if(chkExternalVideoAllowed('question') OR chkExternalVideoAllowed('answer') OR chkExternalAudioAllowed('question') OR chkExternalAudioAllowed('answer')) { ?>
<script language="Javascript" src="<?php echo $CFG['site']['url'];?>js/JSFCommunicator.js"></script>
<script language="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 = '';
		if (($('video_preview'))) {
			$('video_preview').style.display = '';
			$('video_preview').href = videoPreviewUrl;
		}
		$('video_secnd').style.display = '';
		$('video_first').style.display = 'none';
		$('video').value = $('rid').value;
		ffMacOsCloseWindow();
	}
	var removeVideo = function(){
		alert_manual('<?php echo $LANG['common_video_deleted'];?>');
		$('video_delete').style.display = 'none';
		if (($('video_preview'))) $('video_preview').style.display = 'none';
		$('video_add').style.display = '';
		$('video').value = '';
		$('video_id').value = '0';
		$('video_secnd').style.display = 'none';
		$('video_first').style.display = '';
		return false;
	}
	var removeExternalVideo = function(){
		alert_manual('<?php echo $LANG['successfully_external_video_deleted'];?>', 'external_video_delete');
		$('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];
		if(arguments.length>=4)
			add_top_position = arguments[4];
		if(arguments.length>=6)
			add_left_position = arguments[5];

		var confirm_message = msg_confirm;

		$('confirmMessage').innerHTML = confirm_message;
		document.formConfirm.action.value = act_value;
		Confirmation('selMsgConfirmList', 'formConfirm', Array(), Array(), Array());

		return false;
	}
	var doRemoveAction = function(){
		if (document.formConfirm.action.value == 'external_video')
			removeExternalVideo();
		else if (document.formConfirm.action.value == 'external_audio')
			removeExternalAudio();
		else if (document.formConfirm.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');
		$('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();
	}
	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 = '';
	}
</script>
<?php  if ($questions->isShowPageBlock('form_edit')) { ?>
<script language="javascript"  type="text/javascript" >
	var index = document.selFormAskQuestion.category.options.length;
	var firstSelected = document.selFormAskQuestion.category.selectedIndex
	var firstSelected_sub = document.selFormAskQuestion.sub_category.selectedIndex

	function addNewStatusMessage(selObj ){
		var val = selObj.value;
		var sample = '<?php echo $LANG['account_profile_javascript_new_status_sample'];?>';
		if( val.indexOf('add')==0){
			var newStatus = prompt('<?php echo $LANG['account_profile_javascript_new_status'];?>', sample );
			if (newStatus!=null && newStatus!=sample && newStatus.length>0){
				newStatus = newStatus.substring(0, 25);
				document.selFormAskQuestion.category.options[index] = new Option(newStatus, 'new' , true, 'selected');
				document.selFormAskQuestion.new_status_hidden.value = newStatus;

			}else{
				document.selFormAskQuestion.category.options[firstSelected].selected = 'selected';
			}
		}
	}

	function addNewSubStatusMessage(selObj ){
		var val = selObj.value;
		var index_sub = $('option_length').value;
		var sample = '<?php echo $LANG['account_profile_javascript_new_substatus_sample'];?>';
		if( val.indexOf('add')==0){
			var newStatus = prompt('<?php echo $LANG['account_profile_javascript_new_substatus'];?>', sample );
			if (newStatus!=null && newStatus!=sample && newStatus.length>0){
				newStatus = newStatus.substring(0, 25);
				$( 'sub_category' ).options[$( 'sub_category' ).options.length] = new Option ( newStatus, 'new' , true, 'selected');
				document.selFormAskQuestion.new_substatus_hidden.value = newStatus;

			}else{
				document.selFormAskQuestion.sub_category.options[firstSelected_sub].selected = 'selected';
			}
		}
	}

</script>
<?php if ($CFG['admin']['attachments_questions']['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 $CFG['admin']['attachments_allowed']['count'];?>",
				file_queue_limit : "<?php echo $CFG['admin']['attachments_allowed']['count'];?>",


				// 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 : "images/SmallSpyGlassWithTransperancy_17x18.png",
				button_placeholder_id : "spanButtonPlaceholder",
				button_width: 200,
				button_height: 18,
				button_text : '<span class="button">Select Images <span class="buttonSmall"></span></span>',
				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
		}
	}
?>
<?php
if((count($questions->getFormField('uplarr')) != 0 ) && $questions->isShowPageBlock('form_edit'))
	{
	?>
		<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($questions->getFormField('uplarr'));
		$req_uploaded_array = $questions->getFormField('uplarr');
		$req_ori_uploaded_array = $questions->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
	}
//<<<<<<<<<---------Page block template ends--------------------------//
$questions->includeFooter();
?>