<?php
//-------------- Class LoginFormHandler begins --------------->>>>>//
/**
 *
 * List all questions
 *
 * @category	Anova
 * @package		QuestionFormHandler
 * @author 		senthil_52ag05
 * @copyright	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id: $
 * @since 		2008-12-22
 */
set_time_limit(0);
class QuestionFormHandler extends VideoUploadLib
	{
		public $question_details = array();
		public $user_details = array();
		public $sql_condition;
		public $answer_attachment_count = 0;
		public $_dir_path = '../';
		/**
		 * QuestionFormHandler::storeSearchFields()
		 *
		 * @return
		 */
		public function storeSearchFields()
			{
				$allowed_fields_arr = array(
										'more_questions'=>$this->fields_arr['more_questions'],
										'type'=>$this->fields_arr['type'],
										'dname'=>$this->fields_arr['dname'],
										'tags'=>$this->fields_arr['tags'],
										'cat_id'=>$this->fields_arr['cat_id'],
										'cid'=>$this->fields_arr['cid'],
										'video'=>$this->fields_arr['video'],
										'audio'=>$this->fields_arr['audio'],
										'total_answer_from'=>$this->fields_arr['total_answer_from'],
										'total_answer_to'=>$this->fields_arr['total_answer_to'],
										'date_limits_to'=>$this->fields_arr['date_limits_to']
										);
				$allowed_fields_arr = serialize($allowed_fields_arr);

				if($this->CFG['user']['user_id'] != 0)
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['advanced_search'].' SET'.
								' answer = '.$this->dbObj->Param('answer').' WHERE'.
								' user_id = '.$this->dbObj->Param('user_id');
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($allowed_fields_arr, $this->CFG['user']['user_id']));
						    if (!$rs)
							    trigger_db_error($this->dbObj);
					}
				else
					{
						$_SESSION['advanced_search_values'] = 	$allowed_fields_arr;
					}

				//for text with & symbol fix..
				$_SESSION['more_questions'] = $this->fields_arr['more_questions'];
			}

		/**
		 * QuestionFormHandler::populateSearchFields()
		 *
		 * @return
		 */
		public function populateSearchFields()
			{
				if($this->fields_arr['so']=='adv')
					{
						if($this->CFG['user']['user_id'] != 0)
							{
								$sql = 'SELECT answer FROM '.$this->CFG['db']['tbl']['advanced_search'].
										' WHERE user_id='.$this->dbObj->Param('user_id');
								$stmt = $this->dbObj->Prepare($sql);
								$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id']));
							    if (!$rs)
								    trigger_db_error($this->dbObj);

								if($row = $rs->FetchRow())
									{
										if($row['answer'])
											{
												$search_fields_arr = unserialize($row['answer']);
												$this->fields_arr = array_merge($this->fields_arr, $search_fields_arr);
											}
									}
							}
						else
							{
								if(isset($_SESSION['advanced_search_values']) and !empty($_SESSION['advanced_search_values']))
									{
										$search_fields_arr = unserialize($_SESSION['advanced_search_values']);
										$this->fields_arr = array_merge($this->fields_arr, $search_fields_arr);
									}
							}

						//for text with & symbol fix..
						$_SESSION['more_questions'] = $this->fields_arr['more_questions'];
					}
			}

		/**
		 * QuestionFormHandler::buildConditionQuery()
		 *
		 * @return
		 */
		public function buildConditionQuery()
			{
				if($this->sql_condition)
					return $this->sql_condition;

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

				if ($this->fields_arr['related_question'])
					{
			    		$this->sql_condition .= ' AND question LIKE "' .'%'.$this->getFormField('related_question'). '%"'.
									 			 ' AND publish_status =\'Yes\''.
												 ' AND status NOT IN(\'Blocked\',\'ToActivate\',\'Deleted\')';
					}

				$condition = '';
				if ($this->fields_arr['cat'])
					{
						$condition .= $this->getCatIds($this->fields_arr['cat']);
					}

				switch($this->fields_arr['view']){
					case 'open':
						$condition .= ' AND (q.status = \'Open\' AND q.date_closed>=NOW())';
						break;
					case 'resolved':
						$condition .= ' AND (q.status NOT IN(\'Blocked\',\'ToActivate\') AND q.date_closed < NOW())';
						break;
					case 'recent':
						$condition .= ' AND (q.status = \'Open\' OR q.status = \'Resolved\')';
						break;
					case 'popular':
						$condition .= ' AND (q.status = \'Open\' OR q.status = \'Resolved\') AND total_views > 0 AND latest_viewed >= DATE_SUB(NOW(), INTERVAL '.$this->CFG['admin']['popular_days']['limit'].' DAY)';
						break;
					case 'answered':
						$condition .= ' AND ((q.status = \'Open\' OR q.status = \'Resolved\') AND q.total_answer>0)';
						break;
					case 'recentlyanswered':
						$condition .= ' AND ((q.status = \'Open\' OR q.status = \'Resolved\') AND q.total_answer>0)';
						break;
					case 'unanswered':
						$condition .= ' AND ((q.status = \'Open\' OR q.status = \'Resolved\') AND q.total_answer=0)';
						break;
					case 'best':
						$condition .= ' AND best_ans_id != 0';
						break;
					default:
						$condition .= ' AND (q.status = \'Open\' OR q.status = \'Resolved\')';
						break;
				} // switch


				if ($this->fields_arr['al'])
					{
						$case = strtolower(addslashes($this->fields_arr['al']));
						switch($case)
							{
								case '1':
									$condition .= ' AND (question REGEXP \'^[^a-z]\')';
									break;
								case 'all':
									break;
								default:
									$not_allowed_search_array = $this->CFG['admin']['not_allowed_chars'];
									$case = replaceCharacter($not_allowed_search_array, '-', $case);
									$case = addslashes($case);
									$condition .= ' AND (question REGEXP \'^'.$case.'\')';
							}
					}

				$search_conditon = '';
				if ($this->fields_arr['search_question'] && ($this->fields_arr['search_question'] != $this->LANG['search_for_questions']))
					{
						$search_conditon .= ' AND '.getSearchRegularExpressionQuery($this->fields_arr['search_question'], 'question');
						$search_conditon .=	' AND q.status IN (\'Open\', \'Resolved\')';
					}
				if ($this->fields_arr['more_questions'])
					$search_conditon .= ' AND '.getSearchRegularExpressionQuery($this->fields_arr['more_questions'], 'question');

				if ($this->fields_arr['dname'])
					$search_conditon .= ' AND '.$this->getUserTableField('display_name').' LIKE \'%'.addslashes($this->fields_arr['dname']).'%\'';

				if ($this->fields_arr['uname'])
					$search_conditon .= ' AND '.$this->getUserTableField('name').' LIKE \''.addslashes($this->fields_arr['uname']).'\'';

				if ($this->fields_arr['tags'])
					$search_conditon .= ' AND '.getSearchRegularExpressionQuery($this->fields_arr['tags'], 'tags');

				if ($this->fields_arr['cat_id'])
					$search_conditon .= ' AND (pcat_id=\''.addslashes($this->fields_arr['cat_id']).'\' OR cat_id=\''.addslashes($this->fields_arr['cat_id']).'\')';

				if ($this->fields_arr['total_answer_from'] >= 0 && $this->fields_arr['total_answer_from']!='')
					$search_conditon .= ' AND total_answer>=\''.addslashes($this->fields_arr['total_answer_from']).'\'';

				if ($this->fields_arr['total_answer_to']>=0 && $this->fields_arr['total_answer_to']!='')
					$search_conditon .= ' AND total_answer<=\''.addslashes($this->fields_arr['total_answer_to']).'\'';

				$date_condtion = '';
				switch($this->fields_arr['date_limits_to'])
					{
						case $this->LANG['search_option_today']:
							$date_condtion = 'DATE(q.date_asked) = date(NOW())';
							break;
						case $this->LANG['search_option_oneday']:
							$date_condtion = 'DATE_ADD(q.date_asked, INTERVAL 1 DAY) >= NOW()';
							break;
						case $this->LANG['search_option_oneweek']:
							$date_condtion = 'DATE_ADD(q.date_asked, INTERVAL 7 DAY) >= NOW()';
							break;
						case $this->LANG['search_option_onemonth']:
							$date_condtion = 'DATE_ADD(q.date_asked, INTERVAL 1 MONTH) >= NOW()';
							break;
						case $this->LANG['search_option_threemonths']:
							$date_condtion = 'DATE_ADD(q.date_asked, INTERVAL 3 MONTH) >= NOW()';
							break;
						case $this->LANG['search_option_sixmonths']:
							$date_condtion = 'DATE_ADD(q.date_asked, INTERVAL 6 MONTH) >= NOW()';
							break;
						case $this->LANG['search_option_oneyear']:
							$date_condtion = 'DATE_ADD(q.date_asked, INTERVAL 1 YEAR) >= NOW()';
							break;
					}

				if($date_condtion)
					$search_conditon .= ' AND '.$date_condtion;

				if ($this->fields_arr['video'])
					$search_conditon .= ' AND (q.video_id!=0 OR q.external_video_id!=0)';

				if ($this->fields_arr['audio'])
					$search_conditon .= ' AND (q.audio_id!=0 OR q.external_audio_id!=0)';

				if ($this->fields_arr['type'])
					{
						switch($this->fields_arr['type']){
							case 'Open':
								$search_conditon .= ' AND (q.status = \'Open\' AND q.date_closed>=NOW())';
								break;
							case 'Resolved':
								$search_conditon .= ' AND (q.status NOT IN(\'Blocked\',\'ToActivate\') AND q.date_closed < NOW())';
								break;
							case 'with Best Answers':
								$search_conditon .= ' AND (q.status NOT IN(\'Blocked\',\'ToActivate\') AND q.best_ans_id!=0)';
								break;
							case 'Answered':
								$search_conditon .= ' AND (q.status NOT IN(\'Blocked\',\'ToActivate\') AND q.total_answer!=0)';
								break;
							case 'Unanswered':
								$search_conditon .= ' AND (q.status NOT IN(\'Blocked\',\'ToActivate\') AND q.total_answer=0)';
								break;
							case 'Recently Answered':
								$search_conditon .= ' AND (q.status NOT IN(\'Blocked\',\'ToActivate\') AND q.total_answer>0)';
								break;
							default:
								$search_conditon .= ' AND q.status IN (\'Open\', \'Resolved\')';
						} // switch
					}
				elseif ($search_conditon)
					{
						$search_conditon .= ' AND q.status NOT IN(\'Blocked\',\'ToActivate\')';
					}

				if($this->fields_arr['opt'])
					{
						$search_conditon .= ' AND q.status IN (\'Open\', \'Resolved\')';
					}

				if ($search_conditon)
					$this->sql_condition .= $search_conditon;
				else
					$this->sql_condition .= $condition;

			}

		/**
		 * QuestionFormHandler::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 seo_title='.$this->dbObj->Param('cat');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['cat']));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				$sub_qry = '';
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						if (!$row['parent_id'])
							$sub_qry = ' AND (q.pcat_id='.$row['cat_id'].' OR q.cat_id IN ( SELECT cat_id FROM '.$this->CFG['db']['tbl']['questions_category'].' WHERE parent_id='.$row['cat_id'].'))';
						else
							$sub_qry = ' AND q.cat_id='.$row['cat_id'];
					}
				return $sub_qry;
		    }

		/**
		 * QuestionFormHandler::buildSortQuery()
		 *
		 * To sort the query
		 * @access public
		 * @return void
		 */
		public function buildSortQuery()
			{
				$append_condition = '';

				if($this->fields_arr['orderby_field'] == 'total_answer')
					$append_condition = ', ques_id'.' '.$this->fields_arr['orderby'];
				if ($this->fields_arr['view'] == 'popular')
					{
						$append_condition = ', total_views DESC';
					}
				elseif($this->fields_arr['view'] == 'recentlyanswered' || $this->fields_arr['type'] == 'Recently Answered' )
					{
						$this->fields_arr['orderby_field'] = 'date_answered';
					}
				$this->sql_sort = $this->fields_arr['orderby_field'].' '.$this->fields_arr['orderby'].$append_condition;
			}

		/**
		 * QuestionFormHandler::displayCategoryName()
		 *
		 * @param string $parent_id
		 * @return
		 */
		public function displayCategoryName($parent_id='')
		    {
				if ($this->fields_arr['cat'])
					{
						if($parent_id)
							{
								$cid = $parent_id;
								$sql = 'SELECT cat_name,seo_title FROM '.$this->CFG['db']['tbl']['questions_category'].' WHERE cat_id='.$this->dbObj->Param('cat');
							}
						else
							{
								$cid = $this->fields_arr['cat'];
								$sql = 'SELECT cat_name,parent_id FROM '.$this->CFG['db']['tbl']['questions_category'].' WHERE seo_title='.$this->dbObj->Param('cat');
							}
						$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;
							}
					}
				return false;
		    }

		/**
		 * QuestionFormHandler::chkIsValidQuestion()
		 *
		 * @return
		 */
		public function chkIsValidQuestion()
		    {

				$this->chkIsNotEmpty('qid', $this->LANG['err_tip_compulsory']);
				if (!$this->isValidFormInputs())
					{
						$this->setCommonErrorMsg($this->LANG['err_tip_invalid_question']);
						return false;
					}
				//Query to display recent and popular questions
				$sql = 'SELECT q.ques_id, q.total_answer, q.pcat_id, q.cat_id, q.video_id, q.external_video_id, q.external_audio_id, q.audio_id, q.best_ans_id, q.description, q.total_stars'.
						', q.question, q.seo_title, UNIX_TIMESTAMP(date_asked) as date_asked, q.status, q.publish_status, q.total_views, q.user_id, q.tags, q.total_videos, q.total_audios'.
						', IF(status=\'Open\' AND date_closed>=NOW(), 1, 0) is_open'.
						' FROM '.$this->CFG['db']['tbl']['questions'].' AS q'.
						' WHERE q.status IN (\'Open\', \'Resolved\')'.
						' AND q.ques_id='.$this->dbObj->Param('qid');

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

				if (!$rs->PO_RecordCount())
					{
						$this->setCommonErrorMsg($this->LANG['err_tip_invalid_question']);
						return false;
					}
				$this->question_details = $rs->FetchRow();
				$this->fields_arr['old_category'] = $this->question_details['pcat_id'];
				$this->fields_arr['old_sub_category'] = $this->question_details['cat_id'];

				if (!$this->question_details['is_open'])
					{
						$this->setCommonErrorMsg($this->LANG['questions_err_not_open_question']);
						return false;
					}
				return true;
		    }

		/**
		 * QuestionFormHandler::displayQuestionTabs()
		 *
		 * @return
		 */
		public function displayQuestionTabs()
		    {
				$displayQuestionTabs_arr = array();
				$cidQryN = $cidQryH = '';
				if ($this->fields_arr['video'])
					{
						$cidQryN .= 'video=1&amp;';
						$cidQryH .= 'video=1&amp;';
					}
				if ($this->fields_arr['audio'])
					{
						$cidQryN .= 'audio=1&amp;';
						$cidQryH .= 'audio=1&amp;';
					}
				if ($this->fields_arr['cat'])
					{
						$cidQryN .= 'cat='.$this->fields_arr['cat'].'&amp;';
						$cidQryH .= 'cat='.$this->fields_arr['cat'].'&amp;';
					}
				if ($this->fields_arr['al'])
					{
						$cidQryN .= 'al='.$this->fields_arr['al'].'&amp;';
						$cidQryH .= 'al='.$this->fields_arr['al'].'&amp;';
					}
				if ($this->fields_arr['related_question'])
					{
						$cidQryN .= 'related_question='.$this->fields_arr['related_question'].'&amp;';
						$cidQryH .= 'related_question='.$this->fields_arr['related_question'].'&amp;';
					}
				if ($cidQryH)
					$cidQryH = '?'.$cidQryH;
				if ($cidQryN)
					$cidQryN = '&amp;'.$cidQryN;

				$displayQuestionTabs_arr['allQuestionsLI'] = $displayQuestionTabs_arr['recentQuestionsLI'] = $displayQuestionTabs_arr['popularQuestionsLI'] = $displayQuestionTabs_arr['openQuestionsLI'] = $displayQuestionTabs_arr['resolvedQuestionsLI'] = $displayQuestionTabs_arr['answeredQuestionsLI'] = $displayQuestionTabs_arr['unansweredQuestionsLI'] = $displayQuestionTabs_arr['recentlyansweredLI'] = '';
				$clsLeftActiveQuestionsLink = 'clsLeftActiveQuestionsLink';
				if ($this->fields_arr['view'] == 'all')
					{
						$displayQuestionTabs_arr['allQuestionsLI'] = 'clsFirstQuestionLink '.$clsLeftActiveQuestionsLink;
					}
				elseif ($this->fields_arr['view'] == 'recent')
					{
						$displayQuestionTabs_arr['recentQuestionsLI'] = $clsLeftActiveQuestionsLink;
					}
				elseif ($this->fields_arr['view'] == 'popular')
					{
						$displayQuestionTabs_arr['popularQuestionsLI'] = $clsLeftActiveQuestionsLink;
					}
				elseif ($this->fields_arr['view'] == 'open')
					{
						$displayQuestionTabs_arr['openQuestionsLI'] = $clsLeftActiveQuestionsLink;
					}
				elseif ($this->fields_arr['view'] == 'resolved')
					{
						$displayQuestionTabs_arr['resolvedQuestionsLI'] = $clsLeftActiveQuestionsLink;
					}
				elseif ($this->fields_arr['view'] == 'answered')
					{
						$displayQuestionTabs_arr['answeredQuestionsLI'] = $clsLeftActiveQuestionsLink;
					}
				elseif ($this->fields_arr['view'] == 'unanswered')
					{
						$displayQuestionTabs_arr['unansweredQuestionsLI'] = $clsLeftActiveQuestionsLink;
					}
				elseif ($this->fields_arr['view'] == 'recentlyanswered')
					{
						$displayQuestionTabs_arr['recentlyansweredLI'] = $clsLeftActiveQuestionsLink;
					}

				$displayQuestionTabs_arr['all_questions']['url'] = getAnovaUrl('questions', '?view=all'.$cidQryN, 'all/'.$cidQryH);
				$displayQuestionTabs_arr['recent_questions']['url'] = getAnovaUrl('questions', '?view=recent'.$cidQryN, 'recent/'.$cidQryH);
				$displayQuestionTabs_arr['popular_questions']['url'] = getAnovaUrl('questions', '?view=popular'.$cidQryN, 'popular/'.$cidQryH);
				$displayQuestionTabs_arr['open_questions']['url'] = getAnovaUrl('questions', '?view=open'.$cidQryN, 'open/'.$cidQryH);
				$displayQuestionTabs_arr['resolved_questions']['url'] = getAnovaUrl('questions', '?view=resolved'.$cidQryN, 'resolved/'.$cidQryH);
				$displayQuestionTabs_arr['answered_questions']['url'] = getAnovaUrl('questions', '?view=answered'.$cidQryN, 'answered/'.$cidQryH);
				$displayQuestionTabs_arr['unanswered_questions']['url'] = getAnovaUrl('questions', '?view=unanswered'.$cidQryN, 'unanswered/'.$cidQryH);
				$displayQuestionTabs_arr['recentlyanswered']['url'] = getAnovaUrl('questions', '?view=recentlyanswered'.$cidQryN, 'recentlyanswered/'.$cidQryH);

				return $displayQuestionTabs_arr;
		    }

		/**
		 * QuestionFormHandler::populateQuestionType()
		 *
		 * @param string $highlight_type
		 * @return
		 */
		public function populateQuestionType($highlight_type='')
			{
				$populateQuestionType_arr = array();
				$type_array = array('All'=> $this->LANG['search_type_all'],
									'Open'=> $this->LANG['open_questions'],
									'Resolved'=> $this->LANG['common_resolved_questions'],
									'with Best Answers'=> $this->LANG['search_type_with_best_answer'],
									'Answered'=> $this->LANG['answered_questions'],
									'Recently Answered'=> $this->LANG['search_type_recently_answered'],
									'Unanswered'=> $this->LANG['search_type_unanswered']);

				foreach($type_array as $option=>$eachType)
					{
						$populateQuestionType_arr[$option] = $eachType;
					}
				return $populateQuestionType_arr;
			}

		/**
		 * QuestionFormHandler::displayAllQuestions()
		 *
		 * @return
		 */
		public function displayAllQuestions()
			{
				global $smartyObj;
				$pagingArr = array();
				if($this->CFG['feature']['rewrite_mode'] != 'htaccess')
					$pagingArr[] = 'view';
				if($this->getFormField('cat'))
					$pagingArr[] = 'cat';
				if ($this->getFormField('sort'))
					$pagingArr[] = 'sort';
				if ($this->getFormField('related_question'))
					$pagingArr[] = 'related_question';
				if ($this->getFormField('order'))
					$pagingArr[] = 'order';

				$sortQry = '';
				$search_options = array('search_question', 'so', 'adv_search', 'more_questions', 'type', 'uname', 'dname',
										'tags', 'cat_id', 'cid', 'cat', 'video', 'audio', 'total_answer_from',
										'total_answer_to','al', 'opt');

				foreach($search_options as $eachOption)
					{
						if ($this->fields_arr[$eachOption])
							{
								if ($eachOption == 'more_questions' || $eachOption == 'search_question')
								$this->setFormField($eachOption, ereg_replace('[?]','',$this->fields_arr[$eachOption]));
								$pagingArr[] = $eachOption;
								$sortQry .= '&amp;'.$eachOption.'='.$this->fields_arr[$eachOption];
							}
					}

				$view = $this->fields_arr['view'];
				$sort = $this->fields_arr['sort'];
				$order = $this->fields_arr['order'];
				$dateOrder = $ansOrder = 'a';
                $this->clsDate = $this->clsAnswer = '';

				if (!$this->isShowPageBlock('form_search_results') AND $this->isResultsFound() AND !$this->isShowPageBlock('form_best'))
					{
						$reverseOrder = ($order=='a')?'d':'a';
						$dateOrder = $ansOrder = 'd';
						$this->ansOrderClass = $this->dateOrderClass = $this->date_alt = $this->ans_alt = '';
						$orderByClass = ($order=='a')?'clsAsc':'clsDsc';

						if ($sort == 'date')
							{
								$dateOrder = $reverseOrder;
								$this->clsDate = 'clsActiveViewByLink';
								$this->dateOrderClass = $orderByClass;
							}
						elseif ($sort == 'ans')
							{
								$ansOrder = $reverseOrder;
								$this->clsAnswer = 'clsActiveViewByLink';
								$this->ansOrderClass = $orderByClass;
							}

						$this->date_alt = 'title="'.$this->LANG['questions_sortby_posted_date'].'"';
						$this->ans_alt = 'title="'.$this->LANG['questions_sortby_total_answers'].'"';
						$this->unanswered_questions_url = getAnovaUrl('questions', '?view='.$view.'&amp;sort=date&amp;order='.$dateOrder.$sortQry, $view.'/?sort=date&amp;order='.$dateOrder.$sortQry);
						$this->answered_url = getAnovaUrl('questions', '?view='.$view.'&amp;sort=ans&amp;order='.$ansOrder.$sortQry, $view.'/?sort=ans&amp;order='.$ansOrder.$sortQry);
					}

				if (!$this->isResultsFound())
					{
						$this->site_name_manual =  str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $this->LANG['question_no_search_results']);
						$this->questions_ask_url = getAnovaUrl('questions', '?view=ask', 'ask/');
						return ;
					}
				if($this->fields_arr['tags'])
					{
						$this->updateSearchCount($this->fields_arr['tags']);
					}
				$displayAllQuestions_arr = array();
				$i = 0;
				$inc=1;

				while($row = $this->fetchResultRecord())
					{
						$i++;
						$displayAllQuestions_arr[$inc]['record'] = $row;
						$displayAllQuestions_arr[$inc]['clsOddOrEvenQuestion'] = 'clsEvenQuestion';
						if ($i%2)
							$displayAllQuestions_arr[$inc]['clsOddOrEvenQuestion'] = 'clsOddQuestion';

						$displayAllQuestions_arr[$inc]['boldClass'] = 'clsNormal';
						if ($this->display_bold < ($i+1))
							$displayAllQuestions_arr[$inc]['boldClass'] = 'clsBold';

						$displayAllQuestions_arr[$inc]['iconClass'] = '';
						$displayAllQuestions_arr[$inc]['bestAnsClass'] = '';
						$displayAllQuestions_arr[$inc]['audio_class'] = 'clsNoBorder';
						$displayAllQuestions_arr[$inc]['video_class'] = '';
						$displayAllQuestions_arr[$inc]['answers_video_audio_icon'] = '';

						if($row['total_videos']!=0 && (chkIsVideoAllowed('answer') OR chkExternalVideoAllowed('answer')) && $row['total_audios']!=0 && (chkIsAudioAllowed('answer') OR chkExternalAudioAllowed('answer')))
							{
								$displayAllQuestions_arr[$inc]['iconClass'] = 'clsVideoAudioIcon ';
								$displayAllQuestions_arr[$inc]['answers_video_audio_icon'] = $this->LANG['answers_for_video_audio_available'];
							}
						elseif((chkIsVideoAllowed('answer') OR chkExternalVideoAllowed('answer')) && $row['total_videos'])
							{
								$displayAllQuestions_arr[$inc]['iconClass'] = 'clsVideoIcon ';
								$displayAllQuestions_arr[$inc]['answers_video_audio_icon'] = $this->LANG['answers_for_video_available'];
							}
						elseif((chkIsAudioAllowed('answer') OR chkExternalAudioAllowed('answer')) && $row['total_audios'])
							{
								$displayAllQuestions_arr[$inc]['iconClass'] = 'clsAudioIcon ';
								$displayAllQuestions_arr[$inc]['answers_video_audio_icon'] = $this->LANG['answers_for_audio_available'];
							}

						if($row['video_id']) $displayAllQuestions_arr[$inc]['video_class'] = 'clsNoBorder';
						if($row['audio_id']) $displayAllQuestions_arr[$inc]['video_class'] = '';

						$displayAllQuestions_arr[$inc]['ext_audio_class'] ='clsNoBorder';
						$displayAllQuestions_arr[$inc]['ext_video_class'] ='';

						if($row['external_video_id']) $displayAllQuestions_arr[$inc]['ext_video_class'] = 'clsNoBorder';
						if($row['external_audio_id']) $displayAllQuestions_arr[$inc]['ext_video_class'] = '';

						if($row['best_ans_id'])
							{
								$displayAllQuestions_arr[$inc]['bestAnsClass'] = ' clsBestAnswerQuestion';
								$displayAllQuestions_arr[$inc]['clsOddOrEvenQuestion'] = '';
							}
						if($this->isShowPageBlock('form_best') OR ($this->fields_arr['opt'] == 'bestans')) $displayAllQuestions_arr[$inc]['bestAnsClass'] = '';
						if($this->isShowPageBlock('form_best') OR ($this->fields_arr['opt'] == 'bestans'))
							{
								$displayAllQuestions_arr[$inc]['clsOddOrEvenQuestion'] = '';
							}

						$displayAllQuestions_arr[$inc]['attach_class'] = '';
						if($this->CFG['admin']['attachments_questions']['allowed'] && $this->hasAnyAttachment($row['ques_id'],'Question'))
							$displayAllQuestions_arr[$inc]['attach_class'] = 'clsQuestionAttachment';

						$displayAllQuestions_arr[$inc]['answer']['url'] = getAnovaUrl('answer', '?title='.$row['seo_title'], $row['seo_title'].'/');

						$displayAllQuestions_arr[$inc]['row_question_manual'] = wordWrapManual($row['question'], $this->CFG['admin']['question']['line_length'], $this->CFG['admin']['question']['short_length']);

						$displayAllQuestions_arr[$inc]['cat_id'] = $row['cat_id'];
						if (!$displayAllQuestions_arr[$inc]['cat_id'])
							$displayAllQuestions_arr[$inc]['cat_id'] = $row['pcat_id'];

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

						$displayAllQuestions_arr[$inc]['video_plural'] = $this->LANG['video'];
						$displayAllQuestions_arr[$inc]['audio_plural'] = $this->LANG['common_total_audio'];
						$displayAllQuestions_arr[$inc]['answer_plural'] = $this->LANG['common_total_answer'];
						$displayAllQuestions_arr[$inc]['views_plural'] = $this->LANG['common_total_view'];

						if($row['total_videos']!= 1) $displayAllQuestions_arr[$inc]['video_plural'] = $this->LANG['common_total_videos'];
						if($row['total_audios']!= 1) $displayAllQuestions_arr[$inc]['audio_plural'] = $this->LANG['common_total_audios'];
						if($row['total_answer']!= 1) $displayAllQuestions_arr[$inc]['answer_plural'] = $this->LANG['answers'];
						if($row['total_views']!= 1) $displayAllQuestions_arr[$inc]['views_plural'] = $this->LANG['common_total_views'];

						$displayAllQuestions_arr[$inc]['video_audio_count'] = '';
						$displayAllQuestions_arr[$inc]['video_audio_count'] .= (chkIsVideoAllowed('answer') OR chkExternalVideoAllowed('answer'))?$row['total_videos'].' '.$displayAllQuestions_arr[$inc]['video_plural'].' | ':'';
						$displayAllQuestions_arr[$inc]['video_audio_count'] .= (chkIsAudioAllowed('answer') OR chkExternalAudioAllowed('answer'))?$row['total_audios'].' '.$displayAllQuestions_arr[$inc]['audio_plural'].' | ':'';
						$displayAllQuestions_arr[$inc]['video_audio_count'] = substr($displayAllQuestions_arr[$inc]['video_audio_count'], 0, strrpos($displayAllQuestions_arr[$inc]['video_audio_count'], '|'));
						$displayAllQuestions_arr[$inc]['video_audio_count'] = trim($displayAllQuestions_arr[$inc]['video_audio_count']);
						$displayAllQuestions_arr[$inc]['video_audio_count'] = $displayAllQuestions_arr[$inc]['video_audio_count']?'('.$displayAllQuestions_arr[$inc]['video_audio_count'].')':'';

						$displayAllQuestions_arr[$inc]['ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Question_'.$row['video_id'], '?pg=Question_'.$row['video_id']);
						$displayAllQuestions_arr[$inc]['ans_view_video']['on_click'] = 'ques_video_'.$row['video_id'];

						$displayAllQuestions_arr[$inc]['ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Question_'.$row['audio_id'], '?pg=Question_'.$row['audio_id']);
						$displayAllQuestions_arr[$inc]['ans_view_audio']['on_click'] = 'ques_audio_'.$row['audio_id'];

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

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

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

						$displayAllQuestions_arr[$inc]['myanswers']['url'] = getMemberUrl($row['user_id'], $row['name']);
						$displayAllQuestions_arr[$inc]['row_asked_by_manual'] = stripString($row['asked_by'], $this->CFG['username']['short_length']);

						$displayAllQuestions_arr[$inc]['answer_members']['url'] = getAnovaUrl('answer', '?title='.$row['seo_title'], $row['seo_title'].'/', 'members');
						$displayAllQuestions_arr[$inc]['login_answer']['url'] = getUrl('login', '?light_url='.$displayAllQuestions_arr[$inc]['answer_members']['url'], '?light_url='.$displayAllQuestions_arr[$inc]['answer_members']['url'], 'root');
						$displayAllQuestions_arr[$inc]['login_answer']['on_click'] = 'ques_login_'.$row['video_id'];

						if($this->isShowPageBlock('form_best') OR ($this->fields_arr['opt'] == 'bestans'))
							{
								$displayAllQuestions_arr[$inc]['getBestAnswerForQuestion_arr'] = $this->getBestAnswerForQuestion($row['ques_id'], $row['best_ans_id'], $row['seo_title']);
							}

						$inc++;
					} // while

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

		/**
		 * QuestionFormHandler::askQuestions()
		 *
		 * @return
		 */
		public function askQuestions()
		    {
				global $QUES_SUGG_LANG ;
				$askQuestions_arr = array();
				//form action url
				$askQuestions_arr['form_action_url'] = $_SERVER['REQUEST_URI'];

				$askQuestions_arr['style_add_video'] = $askQuestions_arr['style_add_external_video']= '';
				$askQuestions_arr['style_delete_video'] = $askQuestions_arr['style_delete_external_video']= 'style="display:none"';
				$askQuestions_arr['style_preview_video'] = $askQuestions_arr['style_preview_external_video']= 'style="display:none"';
				$askQuestions_arr['video_preview_url'] = $askQuestions_arr['video_default_preview_url'] = getAnovaUrl('anspreviewvideo', '?pg=Question_'.$this->getFormField('rid'), '?pg=Question_'.$this->getFormField('rid'), 'members');
				$askQuestions_arr['video_not_encoded_info'] = $this->LANG['video_not_encoded_info'];
				$askQuestions_arr['external_video_onclick'] = 'return showVideoExternalPreview();';
				$askQuestions_arr['external_video_preview_url'] = $_SERVER['REQUEST_URI'];

				if($this->fields_arr['video'] or $this->fields_arr['video_id'])
					{
						$askQuestions_arr['style_delete_video'] = '';
						$askQuestions_arr['style_preview_video'] = '';
						$askQuestions_arr['style_add_video'] = 'style="display:none"';

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

						if (!$this->fields_arr['video_external_flv_url'] AND !$this->fields_arr['file_extern'])
							{
								if ($this->fields_arr['external_video_id'] AND $external_video_details = $this->getExternalVideoDetails($this->fields_arr['external_video_id']))
									{
										if ($external_video_details['video_status'] == 'Ok' AND $external_video_details['video_encoded_status'] == 'Yes')
											{
												$askQuestions_arr['external_video_onclick'] = getBrowser('video');
												$askQuestions_arr['external_video_preview_url'] = getAnovaUrl('ansviewvideo', '?pg=Question_'.$this->getFormField('external_video_id'), '?pg=Question_'.$this->getFormField('external_video_id'));
											}
									}
							}
					}


				$askQuestions_arr['style_add_audio'] = $askQuestions_arr['style_add_external_audio']= '';
				$askQuestions_arr['style_delete_audio'] = $askQuestions_arr['style_delete_external_audio']= 'style="display:none"';
				$askQuestions_arr['style_preview_audio'] = $askQuestions_arr['style_preview_external_audio']= 'style="display:none"';
				$askQuestions_arr['audio_preview_url'] = $askQuestions_arr['audio_default_preview_url'] = getAnovaUrl('anspreviewaudio', '?pg=Question_'.$this->getFormField('rid'), '?pg=Question_'.$this->getFormField('rid'));
				$askQuestions_arr['audio_not_encoded_info'] = $this->LANG['audio_not_encoded_info'];
				$askQuestions_arr['external_audio_onclick'] = 'return showAudioExternalPreview();';
				$askQuestions_arr['external_audio_preview_url'] = $_SERVER['REQUEST_URI'];


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

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

				$this->LANG['common_tag_size'] = str_ireplace('VAR_MIN_SIZE', $this->CFG['admin']['tag_min_size'], $this->LANG['common_tag_size']);
				$this->LANG['common_tag_size'] = str_ireplace('VAR_MAX_SIZE', $this->CFG['admin']['tag_max_size'], $this->LANG['common_tag_size']);

				if($this->CFG['admin']['question']['point_notification'] && $this->CFG['admin']['ask_answers']['allowed'] && !$this->fields_arr['qid'])
					{
						 $askQuestions_arr['earn_points_details_info'] = str_ireplace('VAR_POINTS', $this->CFG['admin']['ask_answers']['points'], $this->LANG['questions_earn_points_details_info']);
					}

               $askQuestions_arr['populateHidden_arr'] = array('rid', 'video', 'video_external_flv_url', 'flv_upload_type', 'file_extern', 'audio', 'audio_external_url', 'audio_extern', 'video_id', 'external_video_id', 'audio_id', 'external_audio_id', 'old_category', 'old_sub_category');

				if ($this->fields_arr['qid'])
					{
						$askQuestions_arr['question_manual'] = wordWrapManual($this->getFormField('question'), 40);
					}
				$askQuestions_arr['getAttachments_arr'] = '';
			   if ($this->fields_arr['qid'])
					{
						if($this->CFG['admin']['attachments_questions']['allowed'])
							$askQuestions_arr['getAttachments_arr'] = $this->getAttachments();
					}

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

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

				$askQuestions_arr['picturecount'] = str_ireplace('VAR_COUNT', $this->CFG['admin']['attachments_allowed']['count'] ,$this->LANG['attachment_allowed_tip']);



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

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

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

				$askQuestions_arr['attachment_format_tip_manual'] = str_ireplace('VAR_FORMAT', $allowed_formats, $this->LANG['attachment_format_tip']);
  				$askQuestions_arr['attachment_size_tip_manual'] = str_ireplace('VAR_SIZE', $allowed_size, $this->LANG['attachment_size_tip']);

			  	if($this->CFG['admin']['question_suggest']['allowed'] && $this->fields_arr['cid'] =='')
					{
						$askQuestions_arr['descriptions_manual'] = stripslashes($this->getFormField('descriptions'));
					}
				else
					{
						$askQuestions_arr['descriptions_manual'] = stripslashes($this->getFormField('descriptions'));
					}

				if (chkIsVideoAllowed('question'))
					{
						if(chkIsAllowedModule(array('payment')))
							{
								if(isset($this->CFG['admin']['paymentmodule']['video']) AND $this->CFG['admin']['paymentmodule']['video'])
									$askQuestions_arr['video_upload_url'] = getAnovaUrl('videoupload', '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);
								else
									$askQuestions_arr['video_upload_url'] = getAnovaUrl('paymentalertwindow', '?msg=video', '?msg=video', 'root');
							}
						else
							$askQuestions_arr['video_upload_url'] = getAnovaUrl('videoupload', '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);
					}
				if (chkExternalVideoAllowed('question'))
					{
						if(chkIsAllowedModule(array('payment')))
							{
								if(isset($this->CFG['admin']['paymentmodule']['video']) AND $this->CFG['admin']['paymentmodule']['video'])
									$askQuestions_arr['external_video_upload_url'] = getAnovaUrl('externalvideoupload', '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);
								else
									$askQuestions_arr['external_video_upload_url'] = getAnovaUrl('paymentalertwindow', '?msg=video', '?msg=video', 'root');
							}
						else
							$askQuestions_arr['external_video_upload_url'] = getAnovaUrl('externalvideoupload', '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);

					}


				if (chkIsAudioAllowed('question'))
					{
						if(chkIsAllowedModule(array('payment')))
							{
								if(isset($this->CFG['admin']['paymentmodule']['audio']) AND $this->CFG['admin']['paymentmodule']['audio'])
									$askQuestions_arr['audio_upload_url'] = getAnovaUrl('audioupload', '?rid='.$this->fields_arr['rid'].'AUD', '?rid='.$this->fields_arr['rid'].'AUD');
								else
									$askQuestions_arr['audio_upload_url'] = getAnovaUrl('paymentalertwindow', '?msg=audio', '?msg=audio', 'root');
							}
						else
							$askQuestions_arr['audio_upload_url'] = getAnovaUrl('audioupload', '?rid='.$this->fields_arr['rid'].'AUD', '?rid='.$this->fields_arr['rid'].'AUD');
					}
				if (chkExternalAudioAllowed('question'))
					{
						if(chkIsAllowedModule(array('payment')))
							{
								if(isset($this->CFG['admin']['paymentmodule']['audio']) AND $this->CFG['admin']['paymentmodule']['audio'])
									$askQuestions_arr['external_audio_upload_url'] = getAnovaUrl('externalaudioupload',  '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);
								else
									$askQuestions_arr['external_audio_upload_url'] = getAnovaUrl('paymentalertwindow', '?msg=audio', '?msg=audio', 'root');
							}
						else
							$askQuestions_arr['external_audio_upload_url'] = getAnovaUrl('externalaudioupload',  '?rid='.$this->fields_arr['rid'], '?rid='.$this->fields_arr['rid']);
					}

				$askQuestions_arr['is_feature'] = true;
				if(chkIsPaymentAllowed('payment_questions'))
					{
						$total_asked_featured = $this->getFeaturedQuestionCount();
						if($this->CFG['plan']['plan_featured_ques_count'] != $this->CFG['plan']['unlimited'])
							{
								$askQuestions_arr['is_feature'] = ($total_asked_featured < $this->CFG['plan']['plan_featured_ques_count'])?true:false;
							}

						if($this->CFG['plan']['plan_featured_ques_count'] == '0')
							{
								$this->LANG['feature_limit_info'] = $this->LANG['feature_limit_not_allowed_info'];
							}

						if(chkIsPaymentAlertMessageAllowed())
							{
								$req_count = $this->getPlanLogForQuestion();
								$req_today_count = $this->getPlanLogForQuestionPerDay();
								$req_count = $req_count < 0?'0':$req_count;
								$req_today_count = $req_today_count < 0?'0':$req_today_count;

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

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

							}
					}

				return $askQuestions_arr;
		    }

		public function getFeaturedQuestionCount()
			{
				$sql = 'SELECT ques_id FROM '.$this->CFG['db']['tbl']['questions'].
				       ' WHERE featured=\'Yes\' AND user_id = '.$this->dbObj->Param('user_id').
					   ' AND date_asked >= '.$this->dbObj->Param('last_paid_date');

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

				$feature_count = $rs->PO_RecordCount();

				return $feature_count;
			}

		/**
		 * QuestionFormHandler::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->dbObj->Param($this->fields_arr['qid']).' AND content_type=\'Question\' ORDER BY attachment_id';
				$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())
					{
						$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]['gallery'] = 'Question_'.$this->fields_arr['qid'];
								$getAttachments_arr[$inc]['attachment_path'] = getAnovaUrl('questions', '?view=ask&cid='.$this->fields_arr['cid'].'&imgdetail='.$getAttachments_arr[$inc]['img_id'], 'ask/?cid='.$this->fields_arr['cid'].'&imgdetail='.$getAttachments_arr[$inc]['img_id']);
								$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'];
								$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'];

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

		/**
		 * QuestionFormHandler::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']['ans_attachments_path'].$aname;
				$attachment_small_file = $this->CFG['admin']['ans_attachments_path'].$small_name.$this->CFG['admin']['ans_pictures']['small_name'].'.'.$extern;

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

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

		/**
		 * QuestionFormHandler::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');
				$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);
				return false;
		    }

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

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

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

		/**
		 * QuestionFormHandler::changeAnsAudioStatus()
		 *
		 * @param mixed $audio_id
		 * @param mixed $status
		 * @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);
			}
		/**
		 * QuestionFormHandler::chkFileNameIsNotEmpty()
		 *
		 * @param string $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;
			}

		/**
		 * QuestionFormHandler::chkValidFileType()
		 *
		 * @param $field_name
		 * @param $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;
			}

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

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


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

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

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

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

		public function updateQuestionInFaceBook($ques_id = '')
			{
				$appapikey = $this->CFG['facebook']['api_key'];
				$appsecret = $this->CFG['facebook']['appsecret'];

				$facebook = new Facebook($appapikey, $appsecret);

				if( $has_permission = $facebook->api_client->users_hasAppPermission("publish_stream") )
					{
						$message = $this->fields_arr['question'];
						$attachment = array( 'name' => $this->CFG['site']['name'],
											 'href' => $this->CFG['site']['url']
										);

						$action_links = array( array('text' => $message, 'href' => getAnovaUrl('answer', '?title='.$this->fields_arr['seo_title'], $this->fields_arr['seo_title'].'/')));

						$attachment = json_encode($attachment);
						$action_links = json_encode($action_links);

						$post_id = $facebook->api_client->stream_publish($message, $attachment, $action_links);

						if($post_id)
							$this->updateFacebookPostId($ques_id, $post_id);
					}
			}

		/**
		 * QuestionFormHandler::addQuestion()
		 *
		 * @return
		 */
		public function addQuestion()
		    {
				$this->isCategoryExist();
				$this->setFormField('seo_title', $this->getSeoTitleForQuestion($this->fields_arr['question'], $this->fields_arr['qid']));
				$this->fields_arr['content_id'] = $this->insertQuestion();

				$this->addNewVideo();
				$this->addExternalVideo('Question');
				$this->addNewAudio();
				$this->addExternalAudio('Question');

				if($this->CFG['admin']['question_auto_publish']['allowed'])
					{
						$this->updateUserAnswerLog();
						$this->updateCategoryQuestionCount($this->fields_arr['category']);
						if ($this->fields_arr['sub_category'])
							$this->updateCategoryQuestionCount($this->fields_arr['sub_category']);
						$this->updateTags();

						if(chkAllowedModule(array('facebook')) AND $this->isFacebookUser()){
							//Update question in facebook
							$this->updateQuestionInFaceBook($this->fields_arr['content_id']);
						}
					}

				$this->addAttachments();
		    }

		/**
		 * QuestionFormHandler::addAttachments()
		 *
		 * @return
		 */

		 public function addAttachments()
		 	{
				$uploads_arr =array();
				$uploads_arr_original =array();
				$uploads_arr = $this->getFormField('uplarr');
				$uploads_arr_original = $this->getFormField('upl_original');
				$file_allowed_count = count($uploads_arr);

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

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

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

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

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

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

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

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

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

						if($uploaded)
							$this->updateAttachmentRecord($attachment_id, $uploads_arr_original[$i]);
							unlink($uploads_arr[$i]);
							unlink($temp_dir.'temp_'.$req_upl[1].'_'.$req_upl[2].'.'.$extern);
					}
			}


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

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

		/**
		 * QuestionFormHandler::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);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($cat_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 * QuestionFormHandler::decreaseCategoryQuestionCount()
		 *
		 * @param mixed $cat_id
		 * @return
		 */
		public function decreaseCategoryQuestionCount($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);
			}

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

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

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function updateTags()
			{
				$tags = explode(' ', $this->fields_arr['tags']);
				foreach($tags as $eachTag){
					if (trim($eachTag) == '') continue;
					if ($this->isTagExists($eachTag))
						$this->updateTagCount($eachTag);
					else
						$this->insertTagCount($eachTag);
				}
			}

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

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

		/**
		 * QuestionFormHandler::updateSearchCount()
		 *
		 * @param mixed $tags
		 * @return
		 */
		public function updateSearchCount($tags)
			{
				$tags = trim($tags);
				while(strpos($tags, '  '))
					{
						$tags = str_replace('  ', ' ', $tags);
					}
				$tags = addslashes($tags);
				$tags_arr = explode(' ', $tags);

				foreach($tags_arr as $tagname)
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['tags'].
								' SET search_count=search_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);
					}
			}

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

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

		/**
		 * QuestionFormHandler::updateQuestion()
		 *
		 * @return
		 */
		public function updateQuestion()
			{
				$this->fields_arr['tags'] = $this->removeDuplicateKeywords($this->fields_arr['tags']);

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

				$this->isCategoryExist();

				$cat_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 description='.$this->dbObj->Param('descriptions').
						', tags='.$this->dbObj->Param('tags').
						', publish_status='.$this->dbObj->Param('publish').
						', 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').
						' WHERE ques_id='.$this->dbObj->Param('qid').
						' AND user_id='.$this->dbObj->Param('uid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['descriptions'],
														 $this->fields_arr['tags'],
														 $this->fields_arr['publish'],
														 $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['qid'],
														 $this->CFG['user']['user_id']));
				if (!$rs)
				        trigger_db_error($this->dbObj);

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

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

						$this->fields_arr['content_id'] = $this->fields_arr['qid'];
						if($this->fields_arr['video'])
							$this->addNewVideo();
					}
				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_id='.$this->dbObj->Param('audio_id').' AND'.
								' audio_for=\'Question\'';

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['qid'], $this->question_details['audio_id']));
						    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->updateCategoryQuestionCount($this->fields_arr['category']);
				if ($this->fields_arr['sub_category'])
					$this->updateCategoryQuestionCount($this->fields_arr['sub_category']);

				$this->fields_arr['content_id'] = $this->fields_arr['qid'];
				$this->addAttachments();
				$this->modifyTags();
				return ;
			}

		/**
		 * QuestionFormHandler::insertQuestion()
		 *
		 * @return
		 */
		public function insertQuestion()
		    {
				$this->fields_arr['tags'] = $this->removeDuplicateKeywords($this->fields_arr['tags']);

				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['questions'].
						' SET user_id='.$this->dbObj->Param('uid').
						', question='.$this->dbObj->Param('question').
						', seo_title='.$this->dbObj->Param('seo_title').
						', description='.$this->dbObj->Param('descriptions').
						', tags='.$this->dbObj->Param('tags').
						', publish_status='.$this->dbObj->Param('publish').
						', pcat_id='.$this->dbObj->Param('pcat_id').
						', cat_id='.$this->dbObj->Param('cat_id');

				if($this->CFG['admin']['question_auto_publish']['allowed'])
					{
						$sql .= ', date_asked=NOW()'.
						        ', date_closed=DATE_ADD(NOW(), INTERVAL '.$this->CFG['admin']['question']['open_days'].' DAY)';
					}
				else
					{
						$sql .= ', status=\'ToActivate\'';
					}

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id'],
														 $this->fields_arr['question'],
														 $this->fields_arr['seo_title'],
														 $this->fields_arr['descriptions'],
														 $this->fields_arr['tags'],
														 $this->fields_arr['publish'],
														 $this->fields_arr['category'],
														 $this->fields_arr['sub_category']));
				if (!$rs)
				        trigger_db_error($this->dbObj);

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

		/**
		 * QuestionFormHandler::updateUserAnswerLog()
		 *
		 * @return
		 */
		public function updateUserAnswerLog()
		    {
				$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='.$this->dbObj->Param('uid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id']));
				if (!$rs)
				        trigger_db_error($this->dbObj);
		    }

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

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

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

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

		/**
		 * QuestionFormHandler::populateUserDetailsArr()
		 *
		 * @return
		 */
		public function populateUserDetailsArr()
			{
				$sql = 'SELECT '.$this->getUserTableFields(array('name', 'user_id')).' FROM '.
						$this->CFG['db']['tbl']['users'].' WHERE '.
						$this->getUserTableField('name').' = '.$this->dbObj->Param('name').' AND '.
						$this->getUserTableField('usr_status').'=\'OK\'';

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

				if($row = $rs->FetchRow())
					{
						$this->user_details = $row;
						return true;
					}
				return false;
			}

		/**
		 * QuestionFormHandler::getBestAnswerForQuestion()
		 *
		 * @param mixed $bestAnsQuesId
		 * @param mixed $bestAnsId
		 * @param mixed $seo_title
		 * @return
		 */
		public function getBestAnswerForQuestion($bestAnsQuesId, $bestAnsId, $seo_title)
			{
				if ($bestAnsId)
					{
						$sql = 'SELECT a.ans_id, a.user_id, a.answer, a.video_id, a.external_video_id, a.audio_id, a.external_audio_id, a.source, a.votes, UNIX_TIMESTAMP(date_answered) as date_answered'.
								', u.'.$this->getUserTableField('user_id').' as img_user_id, '.$this->getUserTableFields(array('name', 'image_path', 'gender', 't_height', 't_width', 's_height', 's_width','photo_server_url', 'photo_ext'), false).$this->getUserTableField('display_name').' as answered_by'.
								' FROM '.$this->CFG['db']['tbl']['answers'].' AS a , '.$this->CFG['db']['tbl']['users'].' AS u'.
								' WHERE a.user_id=u.'.$this->getUserTableField('user_id').
								' AND u.'.$this->getUserTableField('usr_status').'=\'Ok\''.
								' AND a.ques_id='.$this->dbObj->Param('qid').
								' AND a.ans_id='.$this->dbObj->Param('aid').
								' ORDER BY a.ans_id DESC';
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($bestAnsQuesId, $bestAnsId));
						if (!$rs)
						        trigger_db_error($this->dbObj);

						if (!$rs->PO_RecordCount())
							return ;

						$row = $rs->FetchRow();
						$best_ans_id = $bestAnsId;

						$getBestAnswerForQuestion_arr = array();
						$getBestAnswerForQuestion_arr['record'] = $row;

						$getBestAnswerForQuestion_arr['row_answer_manual'] = stripString(wordWrapManual($row['answer'], $this->CFG['admin']['question']['line_length'], $this->CFG['admin']['question']['short_length']), 125);
						$getBestAnswerForQuestion_arr['answer']['url'] = getAnovaUrl('answer', '?title='.$seo_title, $seo_title.'/');

        				$getBestAnswerForQuestion_arr['ans_view_video']['url'] = getAnovaUrl('ansviewvideo', '?pg=Answer_'.$row['video_id'], '?pg=Answer_'.$row['video_id']);
        				$getBestAnswerForQuestion_arr['ans_view_video']['on_click'] = 'best_video_'.$bestAnsId;
						$getBestAnswerForQuestion_arr['ans_view_audio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Answer_'.$row['audio_id'], '?pg=Answer_'.$row['audio_id']);
						$getBestAnswerForQuestion_arr['ans_view_audio']['on_click'] = 'best_audio_'.$bestAnsId;
						$getBestAnswerForQuestion_arr['ans_view_externalvideo']['url'] = getAnovaUrl('ansviewvideo', '?pg=Answer_'.$row['external_video_id'], '?pg=Answer_'.$row['external_video_id']);
						$getBestAnswerForQuestion_arr['ans_view_externalvideo']['on_click'] = 'best_ext_video_'.$bestAnsId;
						$getBestAnswerForQuestion_arr['ans_view_externalaudio']['url'] = getAnovaUrl('ansviewaudio', '?pg=Answer_'.$row['external_audio_id'], '?pg=Answer_'.$row['external_audio_id']);
						$getBestAnswerForQuestion_arr['ans_view_externalaudio']['on_click'] = 'best_ext_audio_'.$bestAnsId;
						$getBestAnswerForQuestion_arr['row_source_manual'] = nl2br(wordWrapManual($row['source'], $this->CFG['admin']['answer']['line_length']));

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

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

						return $getBestAnswerForQuestion_arr;
					}
			}

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

		/**
		 * QuestionFormHandler::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')
					{
						$sql = 'SELECT cat_id as count FROM '.$this->CFG['db']['tbl']['questions_category'].' WHERE'.
								' parent_id='.$this->fields_arr['category'].' AND cat_name='.$this->dbObj->Param($this->fields_arr['new_substatus_hidden']);
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['new_substatus_hidden']));
						if (!$rs)
								trigger_db_error($this->dbObj);

						$row = $rs->FetchRow();
						if ($row['count'])
							{
								$this->fields_arr['sub_category'] = $row['count'];
							}
						else
							{
								$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($cat_id);
								$stmt = $this->dbObj->Prepare($sql);
								$rs = $this->dbObj->Execute($stmt, array($has_child, $this->fields_arr['category']));
								if (!$rs)
									    trigger_db_error($this->dbObj);

							}
					}
			}

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

		public function totalPostedQuestionCount($user_id)
			{
				if(!chkIsPaymentAllowed('payment_questions'))
					return true;

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

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

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

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($user_id));
				if (!$rs)
				    trigger_db_error($this->dbObj);
				$numrows = $rs->PO_RecordCount();
				if($numrows < $this->CFG['plan']['plan_ques_perday'] || $this->CFG['plan']['plan_ques_perday'] == $this->CFG['plan']['unlimited'] )
					return true;
				else
					return false;
			}

		public function updateQuestionWithTwitterId($content_id, $twitter_id, $twitter_text)
			{
				echo $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);

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

			}
	}
//<<<<<-------------- Class LoginFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$questions = new QuestionFormHandler();
if ($CFG['admin']['module']['twitter'])
	{
		/* Consumer key from twitter */
		$consumer_key = $CFG['twitter']['consumer_key'];
		/* Consumer Secret from twitter */
		$consumer_secret = $CFG['twitter']['consumer_secret'];
	}
$questions->setPageBlockNames(array('form_search_results', 'form_advanced_search', 'form_add', 'form_all', 'form_popular', 'form_recent', 'form_open', 'form_resolved', 'form_answered', 'form_unanswered', 'form_best', 'form_users_questions', 'form_recently_answered'));

//default form fields and values...
$questions->setFormField('question', '');
$questions->setFormField('seo_title', '');
$questions->setFormField('featured', 'No');
$questions->setFormField('descriptions', '');
$questions->setFormField('search_question', '');
$questions->setFormField('tags', '');
$questions->setFormField('view', '');
$questions->setFormField('orderby_field', '');
$questions->setFormField('orderby', '');
$questions->setFormField('str', '');
$questions->setFormField('msg', '');
$questions->setFormField('cid', '');
$questions->setFormField('qid', '');
$questions->setFormField('category', '');
$questions->setFormField('sub_category', '');
$questions->setFormField('video', '');
$questions->setFormField('video_side', '');
$questions->setFormField('video_id', '');
$questions->setFormField('external_video_id', '');
$questions->setFormField('audio', '');
$questions->setFormField('audio_side', '');
$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('dname', '');
$questions->setFormField('tags', '');
$questions->setFormField('with', '');
$questions->setFormField('type', '');
$questions->setFormField('more_questions', '');
$questions->setFormField('so', 'min');//min-adv
$questions->setFormField('cat_id', '');
$questions->setFormField('total_answer_from', '');
$questions->setFormField('total_answer_to', '');
$questions->setFormField('date_limits_to', '');
$questions->setFormField('adv_search', '');
$questions->setFormField('opt', '');
$questions->setFormField('al', 'All');
$questions->setFormField('cat', '');
$questions->setFormField('publish', 'Yes');
$questions->setFormField('suggest', '');
$questions->setFormField('related_question', '');
$questions->setFormField('picturelimit', '');
$questions->setFormField('attachments', '');
$questions->setFormField('attachment_id', '');
$questions->setFormField('attachment_name', '');
$questions->setFormField('photo_server_url', '');
$questions->setFormField('new_status_hidden', '');
$questions->setFormField('new_substatus_hidden', '');
$questions->setFormField('old_category', '');
$questions->setFormField('old_sub_category', '');
$questions->setFormField('vote_type', '');
$questions->setFormField('value', '');
$questions->setFormField('id', '');
$questions->setFormField('usrid', '');
$questions->setFormField('voted', '');
$questions->setFormField('vote_id', '');
$questions->setFormField('ajax_page', '');
$questions->setFormField('update', '');
$questions->setFormField('ques_priority', 'Normal');
$questions->setFormField('index_question', '');
$questions->setFormField('upl_original', array());
$questions->setFormField('uplarr', array());
$questions->setFormField('imgdetail', '');
$questions->setFormField('w', '');
$questions->setFormField('h', '');
$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->searchOption_arr = array($LANG['search_option_allresult'] => $LANG['search_option_allresult'],
									  $LANG['search_option_today'] => $LANG['search_option_today'],
									  $LANG['search_option_oneday'] => $LANG['search_option_oneday'],
									  $LANG['search_option_oneweek'] => $LANG['search_option_oneweek'],
									  $LANG['search_option_onemonth'] => $LANG['search_option_onemonth'],
									  $LANG['search_option_threemonths'] => $LANG['search_option_threemonths'],
									  $LANG['search_option_sixmonths'] => $LANG['search_option_sixmonths'],
									  $LANG['search_option_oneyear'] => $LANG['search_option_oneyear']);

$questions->display_bold = 3;
$questions->title = $LANG['questions'];
$questions->fp = false;
/*************Start navigation******/
$questions->numpg = $CFG['data_tbl']['numpg'];
$questions->setFormField('start', 0);
$questions->setFormField('numpg', $CFG['data_tbl']['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']);
//Set tables and fields to return
$questions->setTableNames(array());
$questions->setReturnColumns(array());
//orderby field and orderby
$questions->setFormField('orderby_field', '');
$questions->setFormField('orderby', '');
/*************End navigation******/
$questions->sanitizeFormInputs($_REQUEST);

if ($questions->isFormGETed($_REQUEST, 'imgdetail'))
	{
		$questions->includeAjaxHeader();
		//if ($questions->chkIsValidQuestion())
			{
				$questions->displayImageGallery($questions->getFormField('imgdetail'), '', 'questions');
			}
		$questions->includeAjaxFooter();
		die();
	}


if ($questions->isFormGETed($_GET, 'vote_type'))
	{
		ob_start;
		$questions->sanitizeFormInputs($_REQUEST);
		if($questions->getFormField('voted')== '')
			{
				$questions->UpdateUserVote($questions->getFormField('vote_type'),  $questions->getFormField('value'), $questions->getFormField('usrid'), $questions->getFormField('id'));
			}
		ob_end_flush();
		die();
	}
if ($questions->isFormGETed($_GET, 'update'))
	{
		$questions->sanitizeFormInputs($_REQUEST);
		$total_votes = $questions->getQuestionVotesCount($questions->getFormField('id'));
		?>
		<script language="javascript" type="text/javascript" defer="defer">
			var a  = "<?php echo $questions->getFormField('vote_id');?>";
			$(a).innerHTML = "<?php echo $total_votes;?>";
		</script>
		<?php
		ob_end_flush();
		die();
	}

// Default page block
$questions->setAllPageBlocksHide();

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

switch($questions->getFormField('view'))
	{
		case 'ask':
			if (!isMember() && (!$questions->getFormField('cid')))
				{
					$_SESSION['url'] = getAnovaUrl('questions', '?view=ask', 'ask/');
					$_SESSION['login_error'] = 'login_err_authorization_required';
					Redirect2URL(getUrl('login'));
				}
			if(!$questions->getFormField('cid'))
			if ($questions->isAllowedToAsk())
				{
					if($questions->totalPostedQuestionCount($CFG['user']['user_id']))
					  {
						if($questions->todayPostedQuestionCount($CFG['user']['user_id']))
							{
								if (chkIsPaymentAllowed('payment_questions'))
									{
										$questions->overRideConfigs();
										$upgrade = '<a href="'.getAnovaUrl('paymentupgrade').'">'.$questions->LANG['questions_upgrade'].'</a>';
										if(!chkIsPaymentUpgradeAllowed())
											$upgrade = $LANG['inform_site_admin'];
										$questions->LANG['feature_limit_info'] = str_ireplace('VAR_UPGRADE', $upgrade, $questions->LANG['feature_limit_info']);
									}
								$questions->setPageBlockShow('form_add');
							}
						else
							{
								$questions->setPageBlockShow('block_msg_form_error');
								$questions->setCommonErrorMsg($LANG['info_not_allowed_to_ask_today']);
							}
					   }
					else
					   {
					   		$questions->setPageBlockShow('block_msg_form_error');
							$upgrade = '<a href="'.getAnovaUrl('paymentupgrade').'">'.$questions->LANG['questions_upgrade'].'</a>';
							if(!chkIsPaymentUpgradeAllowed())
									$upgrade = $LANG['inform_site_admin'];
							$LANG['info_limit_exceeded_to_ask_questions'] = str_ireplace('VAR_UPGRADE', $upgrade, $LANG['info_limit_exceeded_to_ask_questions']);
							$questions->setCommonErrorMsg($LANG['info_limit_exceeded_to_ask_questions']);
					   }
				}
			else
				{
					$questions->setPageBlockShow('block_msg_form_error');
					$questions->setCommonErrorMsg($LANG['info_not_allowed_to_ask']);
				}
			$questions->title = $LANG['ask_a_question'];
			break;
		case 'search':
			$questions->setPageBlockShow('form_search_results');
			if($questions->getFormField('video_side'))
				$questions->setFormField('video', $questions->getFormField('video_side'));
			if($questions->getFormField('audio_side'))
				$questions->setFormField('audio', $questions->getFormField('audio_side'));
			$users_no_records = '';
			$questions->title = $LANG['search_results'];
			$questions->search_home = '<a href="'.getAnovaUrl('questions').'">'.$LANG['questions'].'</a> - <span>'.$questions->title.'</span>';
			$uname = $questions->getUsersDisplayName($questions->getFormField('uname'));
			$opt = $questions->getFormField('opt');
			if ($uname and $opt)
				{
					$my_search_home = '<a href="'.getAnovaUrl('questions').'">'.$LANG['questions'].'</a> - '.$uname.' - <span>';
					$my_title = $uname.'\'s ';

					if($CFG['user']['user_id'] AND $CFG['user']['display_name'] == $uname)
						{
							$my_search_home = '<a href="'.getAnovaUrl('questions').'">'.$LANG['questions'].'</a> - <span>'.$LANG['common_my'].' ';
							$my_title = $LANG['common_my'].' ';
						}

					switch($opt)
						{
							case 'ans':
								$questions->search_home = $my_search_home.$LANG['answered_questions'];
								$users_no_records = $LANG['questions_no_answered_questions'];
								$questions->title = $my_title.$LANG['answered_questions'];
								break;
							case 'bestans':
								$questions->search_home = $my_search_home.$LANG['bestanswered_questions'];
								$users_no_records = $LANG['questions_no_bestanswered_questions'];
								$questions->title = $my_title.$LANG['bestanswered_questions'];
								break;
							case 'ques':
								$questions->search_home = $my_search_home.$LANG['asked_questions'];
								$users_no_records = $LANG['questions_no_asked_questions'];
								$questions->title = $my_title.$LANG['asked_questions'];
								break;
							case 'resolve':
								$questions->search_home = $my_search_home.$LANG['common_resolved_questions'];
								$users_no_records = $LANG['questions_no_resolved_questions'];
								$questions->title = $my_title.$LANG['common_resolved_questions'];
								break;
							case 'fav':
								$questions->search_home = $my_search_home.$LANG['favorite_questions'];
								$users_no_records = $LANG['questions_no_favorite_questions'];
								$questions->title = $my_title.$LANG['favorite_questions'];
								break;
						} // switch
					$questions->title.='';
					$LANG['questions_no_records'] = $users_no_records;
					$questions->setPageBlockShow('form_users_questions');
				}
			break;
		case 'open':
			$questions->setPageBlockShow('form_open');
			$questions->title = $LANG['questions'];
			break;
		case 'resolved':
			$questions->setPageBlockShow('form_resolved');
			$questions->title = $LANG['questions'];
			break;
		case 'recent':
			$questions->setPageBlockShow('form_recent');
			$questions->title = $LANG['questions'];
			break;
		case 'popular':
			$questions->setPageBlockShow('form_popular');
			$questions->title = $LANG['questions'];
			break;
		case 'answered':
			$questions->setPageBlockShow('form_answered');
			$questions->title = $LANG['questions'];
			break;
		case 'unanswered':
			$questions->setPageBlockShow('form_unanswered');
			$questions->title = $LANG['questions'];
			break;
		case 'best':
			$questions->setPageBlockShow('form_best');
			$questions->title = $LANG['common_best_answered_question'];
			break;
		case 'recentlyanswered':
			$questions->setPageBlockShow('form_recently_answered');
			$questions->title = $LANG['questions'];
			break;
		default:
			$questions->setPageBlockShow('form_all');
			$questions->title = $LANG['questions'];
			$questions->setFormField('view', 'all');
			break;
	} // switch

if($questions->getFormField('related_question') != '')
   $questions->title .= ' '.$LANG['having_with_the_word'].' "'.$questions->getFormField('related_question').'"';
elseif($questions->getFormField('al') != '1' and $questions->getFormField('al') != 'All')
   $questions->title .= ' '.$LANG['starts_with_alphabets'].' "'.$questions->getFormField('al').'"';
elseif($questions->getFormField('al') == '1')
   $questions->title .= ' '.$LANG['starts_without_alphabets'];

if($questions->getFormField('so') == 'adv' and !$questions->isFormGETed($_GET, 'adv_search') and !$questions->isFormGETed($_POST, 'adv_search'))
   $questions->search_home = '<a href="'.getAnovaUrl('questions').'">'.$LANG['questions'].'</a> - <span>'.$LANG['advance_search'].'</span>';

if ($questions->isFormPOSTed($_REQUEST, 'deletemoreattachments'))
	{
		if (!isMember())
			{
				echo 'Session Expired. <a href="'.$CFG['auth']['login_url']['url'].'?r">Login to continue..!</a>';
				die();
			}
		ob_start();
		$comment_id = $questions->getFormField('attachment_id');
		$attachment_name = $questions->getFormField('attachment_name');
		$questions->deleteMoreInfos($comment_id, $attachment_name);
		die();
	}
if ($questions->isFormPOSTed($_POST, 'submit'))
	{
		if (!isMember())
			{
				$_SESSION['url'] = getAnovaUrl('questions', '?view=ask', 'ask/');
				$_SESSION['login_error'] = 'login_err_authorization_required';
				Redirect2URL(getUrl('login'));
			}
		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 (!$questions->isAllowedToAsk())
			$questions->setCommonErrorMsg($LANG['info_not_allowed_to_ask']);

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

		if ($questions->isValidFormInputs())
			{
				if ($CFG['debug']['store_log'])
					{
						$questions->createErrorLogFile('question');
					}
				$questions->addQuestion();
				if ($CFG['debug']['store_log'])
					{
						$questions->closeErrorLogFile();
					}

				$questions->setCommonSuccessMsg($LANG['questions_added_successfully']);
				$questions->setPageBlockShow('block_msg_form_success');
                if($CFG['admin']['module']['twitter'] && $questions->IsTwitterUser())
					{
						if($questions->chkIsAllowedModule(array('twitter')) && $CFG['admin']['twitter_post_questions']['allowed'])
							{

							  if($_SESSION['oauth_token'] == '' || $_SESSION['oauth_token_secret'] == '' )
								{
									$tok = $questions->getTwitterAuth();
									$_SESSION['oauth_token'] = $tok['auth_token'];
									$_SESSION['oauth_token_secret'] = $tok['auth_secret_token'];
								}

							  $to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
							  $content = $to->OAuthRequest('https://twitter.com/statuses/update.xml', array('status' => $questions->getFormField('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 != '')
								{
									$questions->updateQuestionWithTwitterId($questions->getFormField('content_id'), $t_ques_id, $t_ques_text);
								}
							  // $content = $to->endSession();
							}
					}
				Redirect2URL(getAnovaUrl('questions', '?view=open&msg=1', 'open/?msg=1'));
			}
		else
			{
				$questions->setPageBlockShow('block_msg_form_error');
				$questions->setCommonErrorMsg($LANG['common_msg_error_sorry'].' '.$questions->getCommonErrorMsg());
			}
	}
else if ($questions->isFormPOSTed($_POST, 'update_question'))
	{
		if (!isMember())
			$questions->setCommonErrorMsg('');
		$questions->chkIsValidQuestion();

		if (!isMember())
			{
				$_SESSION['url'] = getAnovaUrl('answer', '?title='.$questions->question_details['seo_title'], $questions->question_details['seo_title'].'/');
				$_SESSION['login_error'] = 'login_err_authorization_required';
				Redirect2URL(getUrl('login'));
			}

		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 (chkIsVideoAllowed('question'))
			$questions->chkIsValidCaptureVideoFile();
		if (chkIsAudioAllowed('question'))
			$questions->chkIsValidCaptureAudioFile();

		if ($questions->isValidFormInputs())
			{
				if ($CFG['debug']['store_log'])
					{
						$questions->createErrorLogFile('question');
					}
				$questions->updateQuestion();
				if ($CFG['debug']['store_log'])
					{
						$questions->closeErrorLogFile();
					}
				$questions->setFormField('seo_title', $questions->question_details['seo_title']);
				$questions->setCommonSuccessMsg($LANG['questions_updated_successfully']);
				$questions->setPageBlockShow('block_msg_form_success');
				Redirect2URL(getAnovaUrl('answer', '?title='.$questions->getFormField('seo_title').'&msg=5', $questions->getFormField('seo_title').'/?msg=5'));
			}
		else
			{
				$questions->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				$questions->setPageBlockShow('block_msg_form_error');
				$questions->setFormField('question', $questions->question_details['question']);
			}
	}
else if ($questions->isFormGETed($_GET, 'cid'))
	{
		$questions->setAllPageBlocksHide();
		if ($questions->getFormField('view') == 'ask')
			{
				$questions->setFormField('qid', $questions->getFormField('cid'));
				if (!isMember())
					$questions->setCommonErrorMsg('');
				$questions->chkIsValidQuestion();

				if (!isMember())
					{
						$_SESSION['url'] = getAnovaUrl('answer', '?title='.$questions->question_details['seo_title'], $questions->question_details['seo_title'].'/');
						$_SESSION['login_error'] = 'login_err_authorization_required';
						Redirect2URL(getUrl('login'));
					}
				if($questions->question_details['user_id'] != $CFG['user']['user_id'])
					{
						Redirect2URL(getAnovaUrl('answer', '?title='.$questions->question_details['seo_title'], $questions->question_details['seo_title']));
					}

				if ($questions->isValidFormInputs())
					{
						$questions->setPageBlockShow('form_add');
						$questions->setFormField('question', $questions->question_details['question']);
						$questions->setFormField('seo_title', $questions->question_details['seo_title']);
						$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('descriptions', $questions->question_details['description']);
						$questions->setFormField('tags', $questions->question_details['tags']);
						$questions->setFormField('publish', $questions->question_details['publish_status']);
						$questions->setFormField('category', $questions->question_details['pcat_id']);
						$questions->setFormField('sub_category', $questions->question_details['cat_id']);
						$cat_id = $questions->question_details['cat_id'];
						if (!$cat_id)
							$cat_id = $questions->question_details['pcat_id'];
					}
				else
					{
						$questions->setPageBlockShow('block_msg_form_error');
					}
			}
	}
else if ($questions->isFormGETed($_GET, 'cat'))
	{
		$cat_name = $questions->displayCategoryName();
		$questions->title = $p_title = $questions->dir_title = '';
		if($cat_name['parent_id'])
			{
				$parent_catname = $questions->displayCategoryName($cat_name['parent_id']);
				$p_title = '<a href="'.getAnovaUrl('questions', '?cat='.$parent_catname['seo_title'], 'dir/'.$parent_catname['seo_title'].'/').'">'.$parent_catname['cat_name'].'</a> - ';
				$questions->title = $parent_catname['cat_name'].' - ';
			}

		$questions->setAllPageBlocksHide();
		$questions->setPageBlockShow('form_open');
		$questions->title .= $cat_name['cat_name'];

		if ($questions->title)
			{
				$questions->dir_title = '<a href="'.getAnovaUrl('questions').'">'.$LANG['questions'].'</a> - '.$p_title.'<span>'.$cat_name['cat_name'].'</span>';
				//$questions->title .= ' - '.$LANG['questions'];
				//$questions->dir_title .=  ' - '.$LANG['questions'];
			}
		else
			{
				$questions->setCommonErrorMsg($LANG['invalid_category']);
				$questions->setPageBlockShow('block_msg_form_error');
			}
	}
if ($questions->isFormPOSTed($_POST, 'cancel'))
	{
		if ($questions->getFormField('qid'))
			Redirect2URL(getAnovaUrl('answer', '?title='.$questions->getFormField('seo_title'), $questions->getFormField('seo_title').'/'));
		else
			Redirect2Url (getAnovaUrl('questions'));
	}
if ($questions->isFormGETed($_GET, 'msg'))
	{
		switch($questions->getFormField('msg')){
			case '1':
				if(!$CFG['admin']['question_auto_publish']['allowed'])
					$questions->setCommonSuccessMsg($LANG['questions_waiting_for_pubish']);
				else
					$questions->setCommonSuccessMsg($LANG['questions_added_successfully']);
				break;
			case '2':
				$questions->setCommonSuccessMsg($LANG['questions_updated_successfully']);
				break;
			case '3':
				$questions->setCommonSuccessMsg($LANG['questions_deleted_successfully']);
				break;
		} // switch
		$questions->setPageBlockShow('block_msg_form_success');
	}

$questions->setFormField('orderby_field', 'ques_id');
$questions->setFormField('orderby', 'DESC');
if ($questions->getFormField('sort') == 'ans')
	{
		$questions->setFormField('orderby_field', 'total_answer');
	}
if ($questions->getFormField('order') == 'a')
	{
		$questions->setFormField('orderby', 'ASC');
	}
if($questions->getFormField('so')=='adv' and !$questions->isFormPOSTed($_REQUEST, 'adv_search'))
	{
		$questions->populateSearchFields();
		$questions->setPageBlockHide('form_search_results');
		$questions->setAllPageBlocksHide();
		$questions->setPageBlockShow('form_advanced_search');
	}
if($questions->getFormField('so')=='adv' and $questions->getFormField('view')=='recent')
	{
		Redirect2URL(getAnovaUrl('questions', '?so=adv&view=search', 'search/?so=adv'));
	}
if($questions->isFormGETed($_GET, 'adv_search'))
	{
		$questions->populateSearchFields();
		$questions->setAllPageBlocksHide();
		$questions->setPageBlockShow('form_search_results');
	}
if($questions->isFormPOSTed($_POST, 'adv_search'))
	{
		$questions->getFormField('total_answer_from') AND
			$questions->chkIsNumeric('total_answer_from', $LANG['common_err_tip_numeric']);

		if ($questions->getFormField('total_answer_to'))
			{
				if (!$questions->chkIsNumeric('total_answer_to', $LANG['common_err_tip_numeric']))
					$questions->setFormFieldErrorTip('total_answer_from', $LANG['common_err_tip_numeric']);
			}

		if ($questions->isValidFormInputs())
			{
				$questions->setAllPageBlocksHide();
				$questions->storeSearchFields();
				$questions->setPageBlockShow('form_search_results');
			}
		else
			{
				$questions->setAllPageBlocksHide();
				$questions->setPageBlockShow('form_advanced_search');
				$questions->setPageBlockShow('block_msg_form_error');
				$questions->setCommonErrorMsg($LANG['err_msg_invalid_search_option']);
			}
	}

if(!$questions->isFormGETed($_GET, 'search_question'))
	 {
			   $_SESSION['search_question'] = $LANG['header_search_for_questions'];
	 }
if($questions->isFormPOSTed($_POST, 'search'))
	 {
			   $_SESSION['search_question'] = $questions->getFormField('search_question');
	 }
if($questions->isFormGETed($_GET, 'search_question'))
	 {
			    if(isset($_SESSION['search_question']) and $_SESSION['search_question'])
				    $questions->setFormField('search_question', $_SESSION['search_question']);
	 }

if($questions->isFormPOSTed($_REQUEST, 'opt'))
	{
		if($questions->populateUserDetailsArr())
			{
				switch($questions->getFormField('opt'))
					{
						case 'ans':
							$questions->setTableNames(array($CFG['db']['tbl']['questions'].' as q', $CFG['db']['tbl']['users'].' as u'));
							$questions->setReturnColumns(array('ques_id', 'q.question', 'q.votes', 'q.cat_id', 'q.total_answer', 'q.status', 'q.user_id', 'u.'.$questions->getUserTableField('user_id').' as img_user_id', $questions->getUserTableField('display_name').' as asked_by', $questions->getUserTableFields(array('image_path', 'gender', 't_height', 't_width','photo_server_url', 'photo_ext', 'name'), false).'question', 'total_stars', 'UNIX_TIMESTAMP(date_asked) as date_asked', 'video_id', 'audio_id', 'IF(status=\'Open\' AND date_closed>=NOW(), 1, 0) is_open', 'TIMEDIFF(date_closed, NOW()) as date_closed'));
							$questions->setFormField('orderby_field', 'q.ques_id');
							$questions->setFormField('orderby', 'DESC');
							$questions->sql_condition = 'q.user_id=u.'.$questions->getUserTableField('user_id').' AND q.status IN (\'Open\', \'Resolved\') AND u.'.$questions->getUserTableField('usr_status').'=\'Ok\'';
							$questions->sql_condition .= ' AND EXISTS (SELECT ques_id FROM '.$CFG['db']['tbl']['answers'].' AS a WHERE a.user_id=\''.addslashes($questions->user_details['user_id']).'\' AND q.ques_id = a.ques_id)';
							break;

						case 'bestans':
							$questions->setTableNames(array($CFG['db']['tbl']['questions'].' as q', $CFG['db']['tbl']['users'].' as u'));
							$questions->setReturnColumns(array('ques_id', 'q.question', 'q.cat_id','q.votes', 'q.total_answer', 'q.status', 'q.user_id', 'u.'.$questions->getUserTableField('user_id').' as img_user_id', $questions->getUserTableField('display_name').' as asked_by', $questions->getUserTableFields(array('image_path', 'gender', 't_height', 't_width','photo_server_url', 'photo_ext', 'name'), false).'question', 'total_stars', 'UNIX_TIMESTAMP(date_asked) as date_asked', 'video_id', 'audio_id', 'IF(status=\'Open\' AND date_closed>=NOW(), 1, 0) is_open', 'TIMEDIFF(date_closed, NOW()) as date_closed'));
							$questions->setFormField('orderby_field', 'q.ques_id');
							$questions->setFormField('orderby', 'DESC');
							$questions->sql_condition = 'q.user_id=u.'.$questions->getUserTableField('user_id').' AND q.status IN (\'Open\', \'Resolved\') AND u.'.$questions->getUserTableField('usr_status').'=\'Ok\'';
							$questions->sql_condition .= ' AND EXISTS (SELECT ques_id FROM '.$CFG['db']['tbl']['answers'].' AS a WHERE a.user_id=\''.addslashes($questions->user_details['user_id']).'\' AND q.ques_id = a.ques_id AND a.ans_id = q.best_ans_id)';
							break;

						case 'fav':
							$questions->setTableNames(array($CFG['db']['tbl']['questions'].' as q', $CFG['db']['tbl']['users'].' as u'));
							$questions->setReturnColumns(array('ques_id', 'q.question', 'q.cat_id', 'q.votes', 'q.total_answer', 'q.status', 'q.user_id', $questions->getUserTableField('display_name').' as asked_by', 'u.'.$questions->getUserTableField('user_id').' as img_user_id', $questions->getUserTableFields(array('image_path', 'gender', 't_height', 't_width','photo_server_url', 'photo_ext', 'name'), false).'question', 'total_stars', 'UNIX_TIMESTAMP(date_asked) as date_asked', 'video_id', 'audio_id', 'IF(status=\'Open\' AND date_closed>=NOW(), 1, 0) is_open', 'TIMEDIFF(date_closed, NOW()) as date_closed'));
							$questions->setFormField('orderby_field', 'q.ques_id');
							$questions->setFormField('orderby', 'DESC');
							$questions->sql_condition = 'q.user_id=u.'.$questions->getUserTableField('user_id').' AND q.status IN (\'Open\', \'Resolved\') AND u.'.$questions->getUserTableField('usr_status').'=\'Ok\'';
							$questions->sql_condition .= ' AND EXISTS (SELECT content_id FROM '.$CFG['db']['tbl']['user_bookmarked'].' AS uf WHERE uf.user_id=\''.addslashes($questions->user_details['user_id']).'\' AND q.ques_id = uf.content_id AND uf.content_type=\'Question\')';
							break;

						case 'resolve':
							$questions->setTableNames(array($CFG['db']['tbl']['questions'].' as q', $CFG['db']['tbl']['users'].' as u'));
							$questions->setReturnColumns(array('ques_id', 'q.question', 'q.cat_id', 'q.votes', 'q.total_answer', 'q.status', 'q.user_id', $questions->getUserTableField('display_name').' as asked_by', 'u.'.$questions->getUserTableField('user_id').' as img_user_id', $questions->getUserTableFields(array('image_path', 'gender', 't_height', 't_width','photo_server_url', 'photo_ext', 'name'), false).'question', 'total_stars', 'UNIX_TIMESTAMP(date_asked) as date_asked', 'video_id', 'audio_id', 'IF(status=\'Open\' AND date_closed>=NOW(), 1, 0) is_open', 'TIMEDIFF(date_closed, NOW()) as date_closed'));
							$questions->setFormField('orderby_field', 'q.ques_id');
							$questions->setFormField('orderby', 'DESC');
							$questions->sql_condition = 'q.user_id=u.'.$questions->getUserTableField('user_id').' AND q.status NOT IN(\'Blocked\',\'ToActivate\') AND date_closed < NOW() AND u.'.$questions->getUserTableField('usr_status').'=\'Ok\'';
							$questions->sql_condition .= ' AND q.user_id=\''.addslashes($questions->user_details['user_id']).'\'';

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

							break;
					}
			}
		$questions->setAllPageBlocksHide();
		$questions->setPageBlockShow('form_search_results');
		$questions->setPageBlockShow('form_users_questions');
	}

if ($questions->isShowPageBlock('form_all') OR $questions->isShowPageBlock('form_recent') OR $questions->isShowPageBlock('form_popular') OR $questions->isShowPageBlock('form_open') OR $questions->isShowPageBlock('form_resolved')OR $questions->isShowPageBlock('form_answered')OR $questions->isShowPageBlock('form_unanswered') OR $questions->isShowPageBlock('form_search_results') OR $questions->isShowPageBlock('form_best') OR $questions->isShowPageBlock('form_recently_answered') )
	{
		$questions->setTableNames(array($CFG['db']['tbl']['questions'].' as q', $CFG['db']['tbl']['users'].' as u'));
		$questions->setReturnColumns(array('ques_id', 'q.question', 'q.seo_title','q.votes', 'best_ans_id', 'q.total_answer', 'q.total_videos', 'q.total_audios', 'q.total_views', 'q.pcat_id', 'q.cat_id', 'q.status', 'q.user_id', $questions->getUserTableField('display_name').' as asked_by', 'u.'.$questions->getUserTableField('user_id').' as img_user_id', $questions->getUserTableFields(array('name', 'image_path', 'gender', 't_height', 't_width', 's_height', 's_width', 'photo_server_url', 'photo_ext'), false).'question', 'total_stars', 'UNIX_TIMESTAMP(date_asked) as date_asked', 'TIMEDIFF(date_closed, NOW()) as date_closed', 'IF(status=\'Open\' AND date_closed>=NOW(), 1, 0) is_open', 'video_id', 'external_video_id', 'audio_id', 'external_audio_id'));
		$questions->buildSelectQuery();
		$questions->buildConditionQuery();
		$questions->buildSortQuery();
		$questions->buildQuery();
		$questions->printQuery();
		$questions->executeQuery();
		$questions->block_displayAllQuestions_arr = array();
		$questions->block_displayAllQuestions_arr = $questions->displayAllQuestions();

		if (!$questions->isShowPageBlock('form_search_results') AND !$questions->isShowPageBlock('form_best'))
			{
            	$questions->block_displayQuestionTabs_arr = $questions->displayQuestionTabs();
			}
	}

if ($questions->isShowPageBlock('form_add'))
	{
		$questions->form_add['askQuestions_arr'] = $questions->askQuestions();
	}

if ($questions->isShowPageBlock('form_advanced_search'))
	{
		$questions->form_advanced_search_arr['populateQuestionType'] = $questions->populateQuestionType();
		$questions->form_advanced_search_arr['form_action'] = getAnovaUrl('questions', '?so=adv&amp;view=search', 'search/?so=adv');
	}
$questions->populateCategories_arr = $questions->populateCategories();
$questions->populateSubCategories_arr = $questions->populateSubCategories($questions->getFormField('category'));
$questions->deleteQuestionAttachments_onclick = getAnovaUrl('questions', '?view=ask&amp;cid='.$questions->getFormField('qid'), 'ask/'.$questions->getFormField('qid').'/');
$question_url = getAnovaUrl('questions', '?view='.$questions->getFormField('view'),  '?view='.$questions->getFormField('view'));
$questions->login = getUrl('login', '?light_url='.$question_url, '?light_url='.$question_url);

//<<<<--------------------Code Ends----------------------//
$CFG['html']['page_id'] .= $questions->getFormField('view');
$CFG['site']['title'] = $questions->title.' - '.$CFG['site']['title'];
//--------------------Page block templates begins-------------------->>>>>//
//include the header file
if($CFG['is']['ajax_page'] == true)
	{
		$questions->includeAjaxHeader();
	}
else
	$questions->includeHeader();
//include the content of the page
setTemplateFolder('general/', $CFG['admin']['index']['anova_module']);
$smartyObj->display('questions.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 language="javascript" type="text/javascript">
	var block_arr= new Array('selMsgConfirm', 'selDelInfoconfirm');
</script>
<?php if(chkExternalVideoAllowed('question') OR chkExternalVideoAllowed('answer') OR chkExternalAudioAllowed('question') OR chkExternalAudioAllowed('answer')) { ?>
<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 } ?>
<?php
	 if($CFG['admin']['question_suggest']['allowed'])
		{
			if($questions->getFormField('view')=='ask' && $questions->getFormField('cid')=='')
				{

					?>
					<script language="javascript" type="text/javascript" src="<?php echo $CFG['site']['url'].$CFG['admin']['index']['anova_module'].'/js/suggest.js';?>"></script>
					 <script language="javascript" type="text/javascript">
					 	<?php echo "var QUES_SUGG_LANG = ".php2js($QUES_SUGG_LANG);?>;
					</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('selMsgConfirm', '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_add')) { ?>
<script language="javascript" type="text/javascript">
var index = document.selFormAskQuestion.category.options.length;
var firstSelected = document.selFormAskQuestion.category.selectedIndex
//alert(index);
//var index_sub = document.selFormAskQuestion.sub_category.options.length;
//var index_sub = document.selFormAskQuestion.option_length.value;
var firstSelected_sub = document.selFormAskQuestion.sub_category.selectedIndex
//alert(index_sub);

	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_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);
				$( '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';
			}
		}
	}
<?php if (!$questions->getFormField('qid')) { ?>
		needLiveValidation('question',Array('Presence'));
<?php } ?>
<?php if ($CFG['admin']['description']['mandatory']) { ?>
		needLiveValidation('descriptions',Array('Presence'));
<?php } ?>
<?php if ($CFG['admin']['category']['mandatory']) { ?>
		needLiveValidation('category',Array('Presence'));
<?php } ?>
</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 $questions->getFormField('picturelimit');?>",
				file_queue_limit : "<?php echo $questions->getFormField('picturelimit');?>",

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

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

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

				custom_settings : {
					upload_target : "divFileProgressContainer"
				},

				// Debug Settings
				debug: false
			});
	</script>
<?php
		}
	}
if(count($questions->getFormField('uplarr')) != 0 )
	{
	?>
		<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
	}
//include the footer of the page
//<<<<<<--------------------Page block templates Ends--------------------//
if($CFG['is']['ajax_page'] == true)
	{
		//include the header file
		$questions->includeAjaxFooter();
	}
else
	{
		//includd the footer of the page
		$questions->includeFooter();
	}
?>