<?php

class AKB_STATS extends AdminView
{
	var $countSql;

	var $paginationRowStart;

	var $paginationLink;

	/**
	* ShowStatsQuestions
	* Get a summary of the questions, their visibility, and if they were
	* submitted by a user or not
	*
	* @return void
	*/
	function ShowStatsQuestions() {
		if (!$_SESSION['user']->verify('stats', 'viewarticle')) {
			$this->NoPermission();
			return ;
		}
		$this->GetQuestionsSummary();
		$this->GetSubscribers();
		$this->GetRatingSummary();
		$this->GetCategoriesSummary();
		$this->GetMostPopularCategories();
		$this->GetPopularAuthors();
		$this->GetMostPopularQuestions();

		require_once("includes/charts/charts.php");

		//Most Popular Questions Chart
		$chart_url = $GLOBALS['pathToKB']."/admin/admin_stat_chart.php?".session_name()."=".session_id()."&type=MostPopularQuestionsFull&totalposvotes=".$GLOBALS['TotalPos']."&totalnegvotes=".$GLOBALS['TotalNeg'];
		$GLOBALS['chartPopularQuestions'] = InsertChart($GLOBALS['pathToKB'] . '/admin/includes/charts/charts.swf', $GLOBALS['pathToKB'] . '/admin/includes/charts/charts_library', $chart_url, "100%", 250, 'FFFFFF', false, 'J1XIJUMEW9L.HSK5T4Q79KLYCK07EK');

		$GLOBALS['StatsTitle'] = GetLang("QuestionStatistics");
		$GLOBALS['StatsIntro'] = GetLang("StatsQuestionIntro");

		$GLOBALS['BreadcrumEntries'][GetLang('Statistics')] = "";
		$GLOBALS['BreadcrumEntries'][$GLOBALS['StatsTitle']] = "";

		$GLOBALS['Show_Tab'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TabJS');

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('stats.questions');
		$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
	}

	/**
	*	Return a fromdate and todate between which to show stats
	*/
	function CalculateCalendarRestrictions($calendarinfo=array())
	{

		$rightnow = time();
		$today = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
		$yesterday = mktime(0, 0, 0, date("m"), date("d")-1, date("Y"));

		if(isset($calendarinfo["DateType"])) {

			switch(strtolower($calendarinfo["DateType"])) {
				case "today": {
					$startdate = $today;
					$enddate = $rightnow;
					break;
				}
				case "yesterday": {
					$startdate = $yesterday;
					$enddate = $today;
					break;
				}
				case "last24hours": {
					$startdate = $rightnow - 86400;
					$enddate = $rightnow;
					break;
				}
				case "last7days": {
					$startdate = mktime(0, 0, 0, date("m"), date("d") - 7, date("Y"));
					$enddate = $rightnow;
					break;
				}
				case "last30days": {
					$startdate = mktime(0, 0, 0, date("m"), date("d")-30, date("Y"));
					$enddate = $rightnow;
					break;
				}
				case "thismonth": {
					$startdate = mktime(0, 0, 0, date("m"), 1, date("Y"));
					$enddate = $rightnow;
					break;
				}
				case "lastmonth": {
					$startdate = mktime(0, 0, 0, date("m")-1, 1, date("Y"));
					$enddate = mktime(0, 0, 0, date("m"), 1, date("Y"));
					break;
				}
				case "alltime": {
					$startdate = 0;
					$enddate = $rightnow;
					break;
				}
				case "custom": {
					$startdate = mktime(0, 0, 0, $calendarinfo["From"]["Mth"], $calendarinfo["From"]["Day"], $calendarinfo["From"]["Yr"]);
					$enddate = mktime(23, 59, 59, $calendarinfo["To"]["Mth"], ($calendarinfo["To"]["Day"]), $calendarinfo["To"]["Yr"]);
					break;
				}
			}
		}
		else {
			// Default to last 30 days
			$startdate = mktime(0, 0, 0, date("m"), date("d")-30, date("Y"));
			$enddate = $rightnow;
		}

		return array("start" => $startdate,
		"end" => $enddate
		);
	}


	/**
	*	Get a list of date types as option tags
	*/
	function _GetCalendarDateTypesAsOptions($Selected = "", $DisplayCustom = true)
	{
		$output = "";
		$date_types = array("Today" => GetLang('Today'),
		"Yesterday" => GetLang('Yesterday'),
		"Last24Hours" => GetLang('Last24Hours'),
		"Last7Days" => GetLang('Last7Days'),
		"Last30Days" => GetLang('Last30Days'),
		"ThisMonth" => GetLang('ThisMonth'),
		"AllTime" => GetLang('AllTime'),
		"Custom" => GetLang('Custom')
		);
		
		if (!$DisplayCustom) {
			array_pop($date_types);
		}

		foreach($date_types as $val=>$text) {
			if($val == $Selected) {
				$sel = 'selected="selected"';
			}
			else {
				$sel = "";
			}

			$output .= sprintf("<option value='%s' %s>%s</option>", $val, $sel, $text);
		}
		return $output;
	}

	/**
	* ShowStatsUsers
	* Get a summary of the questions, their visibility, and if they were
	* submitted by a user or not
	*
	* @return void
	*/
	function ShowStatsUsers() {
		if (!$_SESSION['user']->verify('stats', 'viewuser')) {
			$this->NoPermission();
			return;
		}
		
		$this->GetUsersSummary();
		$this->GetPopularAuthors();
		$this->GetPopularAuthors(false);

		require_once("includes/charts/charts.php");

		//User Chart Breakdown
		$chart_url = $GLOBALS['pathToKB']."/admin/admin_stat_chart.php?".session_name()."=".session_id()."&type=UserSummary&ActiveUsers=".$GLOBALS['ActiveUsers']."&InactiveUsers=".$GLOBALS['InactiveUsers'];
		$GLOBALS['chartUsers'] = InsertChart($GLOBALS['pathToKB'] . '/admin/includes/charts/charts.swf', $GLOBALS['pathToKB'] . '/admin/includes/charts/charts_library', $chart_url, "100%", 250, 'FFFFFF', false, 'J1XIJUMEW9L.HSK5T4Q79KLYCK07EK');

		$GLOBALS['StatsTitle'] = GetLang("UserStatistics");
		$GLOBALS['StatsIntro'] = GetLang("StatsUserIntro");

		$GLOBALS['BreadcrumEntries'][GetLang('Statistics')] = "";
		$GLOBALS['BreadcrumEntries'][$GLOBALS['StatsTitle']] = "";
		
		if(isset($_POST["Calendar"])) {
			$cal = $this->CalculateCalendarRestrictions($_POST["Calendar"]);
			$GLOBALS["CurrentDate"] = $_POST["Calendar"]["DateType"];
		}
		else {
			$cal = $this->CalculateCalendarRestrictions();
			$GLOBALS["CurrentDate"] = "Last30Days";
		}

		$GLOBALS["CalendarDateTypeOptions"] = $this->_GetCalendarDateTypesAsOptions($GLOBALS["CurrentDate"]);

		// Set the global variables for the select boxes
		$from_stamp = $cal["start"];
		$to_stamp = $cal["end"];

		$from_days = $from_stamp / 86400;
		$to_days = $to_stamp / 86400;
		$num_days = floor($to_days - $from_days)+1;

		$from_day = date("d", $from_stamp);
		$from_month = date("m", $from_stamp);
		$from_year = date("Y", $from_stamp);

		$to_day = date("d", $to_stamp);
		$to_month = date("m", $to_stamp);
		$to_year = date("Y", $to_stamp);


		$GLOBALS["ArticlePerUserFromDays"] = $this->_GetDayOptions($from_day);
		$GLOBALS["ArticlePerUserFromMonths"] = $this->_GetMonthOptions($from_month);
		$GLOBALS["ArticlePerUserFromYears"] = $this->_GetYearOptions($from_year);

		$GLOBALS["ArticlePerUserToDays"] = $this->_GetDayOptions($to_day);
		$GLOBALS["ArticlePerUserToMonths"] = $this->_GetMonthOptions($to_month);
		$GLOBALS["ArticlePerUserToYears"] = $this->_GetYearOptions($to_year);

		$_SESSION['ArticlePerUserFromStamp'] = $from_stamp;
		$_SESSION['ArticlePerUserToStamp'] = $to_stamp;

		$this->GetArticlePerUser();

		if(isset($_POST["currentTab"])) {
			$GLOBALS["CurrentTab"] = (int)$_POST["currentTab"];
		}
		else {
			$GLOBALS["CurrentTab"] = 0;
		}

		$GLOBALS['Show_Tab'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TabJS');

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('stats.users');
		$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();

	}

	/**
	* ShowStatsCategories
	* Get a summary of the questions, their visibility, and if they were
	* submitted by a user or not
	*
	* @return void
	*/
	function ShowStatsCategories() {
		if (!$_SESSION['user']->verify('stats', 'viewcategory')) {
			$this->NoPermission();
			return ;
		}

		$this->GetCategoriesSummary();
		$this->GetMostPopularCategories();

		require_once("includes/charts/charts.php");

		//User Chart Breakdown
		if ($GLOBALS['MostPopularChartSArray']) {
			$chart_url = $GLOBALS['pathToKB']."/admin/admin_stat_chart.php?".session_name()."=".session_id()."&type=CategorySummary&catarray=".$GLOBALS['MostPopularChartSArray'];
			$GLOBALS['chartPopularCategories'] = InsertChart($GLOBALS['pathToKB'] . '/admin/includes/charts/charts.swf', $GLOBALS['pathToKB'] . '/admin/includes/charts/charts_library', $chart_url, "100%", 250, 'FFFFFF', false, 'J1XIJUMEW9L.HSK5T4Q79KLYCK07EK');
		}

		$GLOBALS['StatsTitle'] = GetLang("CategoryStatistics");
		$GLOBALS['StatsIntro'] = GetLang("StatsCategoryIntro");

		$GLOBALS['BreadcrumEntries'][GetLang('Statistics')] = "";
		$GLOBALS['BreadcrumEntries'][$GLOBALS['StatsTitle']] = "";

		$GLOBALS['Show_Tab'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TabJS');

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('stats.categories');
		$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();

	}

	/**
	* ShowStatsSearch
	* Get a summary of the questions, their visibility, and if they were
	* submitted by a user or not
	*
	* @return void
	*/
	function ShowStatsSearches() {
		if (!$_SESSION['user']->verify('stats', 'viewsearch')) {
			$this->NoPermission();
			return ;
		}

		$this->GetSearchSummaryData();

		$GLOBALS['StatsTitle'] = GetLang("SearchStatistics");
		$GLOBALS['StatsIntro'] = GetLang("StatsSearchIntro");

		$GLOBALS['Show_Tab'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TabJS');

		$GLOBALS['BreadcrumEntries'][GetLang('Statistics')] = "";
		$GLOBALS['BreadcrumEntries'][$GLOBALS['StatsTitle']] = "";

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('stats.searches');
		$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();

	}

	/**
	* GetQuestionsSummary
	* Get a summary of the questions, their visibility, and if they were
	* submitted by a user or not
	*
	* @return void
	*/
	function GetQuestionsSummary()
	{

		$GLOBALS["VisibleQuestions"] = 0;
		$GLOBALS["HiddenQuestions"] = 0;
		$GLOBALS["TotalQuestions"] = 0;

		// Get the normal questions summary
		$query = "SELECT visible, count(*) as num
				FROM ".$GLOBALS['tablePrefix']."questions
				GROUP by visible";

		$results = $GLOBALS['AKB_DB']->Query($query);

		while ($row = $GLOBALS['AKB_DB']->Fetch($results)) {
			switch ($row['visible']) {
				case '0':
				$GLOBALS["HiddenQuestions"] = $row['num'];
				$GLOBALS["TotalQuestions"] += $row['num'];
				break;
				case '1':
				$GLOBALS["VisibleQuestions"] = $row['num'];
				$GLOBALS["TotalQuestions"] += $row['num'];
				break;
			}
		}

		// Get the submitted questions summary
		$query = "select count(*)
				from ".$GLOBALS['tablePrefix']."submittedquestions";

		$GLOBALS["SubmittedQuestions"] = $GLOBALS['AKB_DB']->FetchOne($query);
		$GLOBALS["TotalQuestions"] += $GLOBALS["SubmittedQuestions"];
	}

	/**
	* GetCategoriesSummary
	* Get a summary of the categories by if its a root node or not
	*
	* @return void
	*/
	function GetCategoriesSummary()
	{
		$GLOBALS["SubCats"] = 0;
		$GLOBALS["RootCats"] = 0;
		$GLOBALS["TotalCats"] = 0;

		$query = "SELECT CASE WHEN parentid IN (0)
				THEN '1'
				ELSE '0'
				END as isroot, count(*) as num
				FROM ".$GLOBALS['tablePrefix']."categories
				GROUP by parentid 
				ORDER BY parentid DESC
				"
		;
		
		$results = $GLOBALS['AKB_DB']->Query($query);

		while ($row = $GLOBALS['AKB_DB']->Fetch($results)) {
			switch ($row['isroot']) {
				case '0':
				$GLOBALS["SubCats"] = $row['num'];
				$GLOBALS["TotalCats"] += $row['num'];
				break;
				case '1':
				$GLOBALS["RootCats"] = $row['num'];
				$GLOBALS["TotalCats"] += $row['num'];
				break;
			}
		}
	}

	/**
	* GetUsersSummary
	* Get a summary of the users by status
	*
	* @return void
	*/
	function GetUsersSummary()
	{
		$GLOBALS["ActiveUsers"] = 0;
		$GLOBALS["InactiveUsers"] = 0;
		$GLOBALS["TotalUsers"] = 0;

		$query = "SELECT status, count(*) as num
				FROM ".$GLOBALS['tablePrefix']."users
				GROUP BY status";

		$results = $GLOBALS['AKB_DB']->Query($query);

		while ($row = $GLOBALS['AKB_DB']->Fetch($results)) {
			switch ($row['status']) {
				case '0':
				$GLOBALS["InactiveUsers"] = $row['num'];
				$GLOBALS["TotalUsers"] += $row['num'];
				break;
				case '1':
				$GLOBALS["ActiveUsers"] = $row['num'];
				$GLOBALS["TotalUsers"] += $row['num'];
				break;
			}
		}
	}

	function GetRatingSummary() {

		$query = "
				SELECT 
					SUM(views) as totalqv,
					SUM(posvotes) as pvs,
					SUM(negvotes) as nvs
				FROM
					".$GLOBALS["tablePrefix"]."questions
			";

		$result = $GLOBALS['AKB_DB']->query($query);
		$rsArray = $GLOBALS['AKB_DB']->Fetch($result);

		$GLOBALS['TotalPos'] = $rsArray['pvs'];
		$GLOBALS['TotalNeg'] = $rsArray['nvs'];
		$GLOBALS['TotalRatedQuestions'] = $GLOBALS['TotalPos'] + $GLOBALS['TotalNeg'];
		$GLOBALS['TotalViews'] = $rsArray['totalqv'];
	}

	function GetSubscribers() {
		$query = "
				SELECT 
					COUNT(subscriberid) as scount
				FROM
					".$GLOBALS["tablePrefix"]."subscribers
			";

		$result = $GLOBALS['AKB_DB']->query($query);
		$rsArray = $GLOBALS['AKB_DB']->Fetch($result);

		$GLOBALS['TotalSubscribers'] = $rsArray['scount'];
	}

	/**
	* GetMostViewedQuestions
	* Get a list of the questions which have been viewed the most times
	*
	*
	* @return void
	*/
	function GetMostViewedQuestions()
	{
		$GLOBALS['MostViewedQuestions'] = '';

		$query = sprintf("select questionid, title, views from %squestions where views > 0 order by views desc ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_MOST_VIEWED_QUESTIONS);
		$result = $GLOBALS['AKB_DB']->Query($query);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['Text'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$link = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');

				$views = ($row['views'] == 1) ? GetLang("Views") : GetLang("Views");
				$GLOBALS['Item'] = $link . ' ('. number_format($row['views']) . ' ' . $views. ')';
				$GLOBALS["MostViewedQuestions"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
			}
		} else {
			$GLOBALS['Item'] = GetLang("StatNoPopularQuestions");
			$GLOBALS['MostViewedQuestions'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostViewedQuestionsFull
	* Get a list of the questions which have been viewed the most times to be displayed in a table.
	*
	*
	* @return void
	*/		
	function GetMostViewedQuestionsFull($direction="d",$currentPage=1,$field="views")
	{
		$GLOBALS['MostViewedQuestionsFull'] = '';
		$GLOBALS['CurrentPageNumber'] = $currentPage;

		$sql_modifier = ($direction == "d") ? "DESC" : "ASC";

		$countQuery = sprintf("select COUNT(questionid) as thecount FROM %squestions WHERE views > 0",$GLOBALS["tablePrefix"]);

		$this->SetupPagination($countQuery,$currentPage);
		$query = sprintf("select questionid, title, score, views, posvotes, negvotes from %squestions where views > 0 order by ".$field." ".$sql_modifier." ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit($this->paginationRowStart, AKB_STAT_PAGE_ROWS);
		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_row");
		$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {

			$GLOBALS["RowData"] = "";

			//Build the row data
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['FHref'] = $GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['FText'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['FQViews'] = $row['views'];
				$GLOBALS['FScore'] = $row['score'];
				$GLOBALS['FPosvotes'] = $row['posvotes'];
				$GLOBALS['FNegvotes'] = $row['negvotes'];

				$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
			}

			//Intro Sentence
			$GLOBALS['AmountFullConst'] = STATS_NUM_MOST_VIEWED_QUESTIONS_FULL;
			$GLOBALS['TrailingString'] = GetLang("MostViewedQuestions");

			//Put it all togethor
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_table");
			$GLOBALS["MostViewedQuestionsFull"] = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
		} else {
			$GLOBALS['Item'] = GetLang("StatNoQuestionsViewed");
			$GLOBALS['MostViewedQuestionsFull'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostPopularQuestions
	* Get a list of the questions which have the highest score
	*
	* @return void
	*/
	function GetMostPopularQuestions()
	{
		$GLOBALS['MostPopularQuestions'] = '';
		// Get the most popular questions
		$query = sprintf("select questionid, title from %squestions where score > 0 order by score desc ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_MOST_POPULAR_QUESTIONS);
		
		$result = $GLOBALS['AKB_DB']->Query($query);

		$firstTime = true;

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['Text'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$link = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');

				$GLOBALS['Item'] = $link;
				$GLOBALS['MostPopularQuestions'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');

				if ($firstTime) {
					$GLOBALS['MostPopularQuestion'] = $GLOBALS['Text'];
					$firstTime = false;
				}
			}
		} else {
			$GLOBALS['Item'] = GetLang('StatNoPopularQuestions');
			$GLOBALS['MostPopularQuestions'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostPopularQuestionsFull
	* Get a list of the questions which have the highest score
	*
	* @return void
	*/
	function GetMostPopularQuestionsFull($direction="d",$currentPage=1,$field="score")
	{
		//Setup Remote Vars
		$GLOBALS['MostPopularQuestionsFull'] = '';
		$GLOBALS['CurrentPageNumber'] = $currentPage;

		$chart_url = "";

		$sql_modifier = ($direction == "d") ? "DESC" : "ASC";

		$countQuery = sprintf("select COUNT(questionid) as thecount FROM %squestions WHERE score > 0",$GLOBALS["tablePrefix"]);

		$this->SetupPagination($countQuery,$currentPage);
		$query = sprintf("select questionid, title, score, views, posvotes, negvotes from %squestions where score > 0 order by score ".$sql_modifier." ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit($this->paginationRowStart, AKB_STAT_PAGE_ROWS);

		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_row");
		$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {

			$GLOBALS['RowData'] = "";

			//Build the row data
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['FHref'] = $GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['FText'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['FQViews'] = $row['views'];
				$GLOBALS['FScore'] = $row['score'];
				$GLOBALS['FPosvotes'] = $row['posvotes'];
				$GLOBALS['FNegvotes'] = $row['negvotes'];

				$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
			}

			//Intro Sentence
			$GLOBALS['AmountFullConst'] = STATS_NUM_MOST_POPULAR_QUESTIONS_FULL;
			$GLOBALS['TrailingString'] = GetLang("MostPopularQuestions");

			//Put it all togethor
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_table");
			$GLOBALS["MostPopularQuestionsFull"] = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
		} else {
			$GLOBALS['Item'] = GetLang("StatNoPopularQuestions");
			$GLOBALS['MostPopularQuestionsFull'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostPopularQuestionsFull
	* Get a list of the questions which have the highest score
	*
	* @return void
	*/
	function GetLeastPopularQuestionsFull()
	{
		$GLOBALS['LeastPopularQuestionsFull'] = '';

		$query = sprintf("select questionid, title, score, views from %squestions where score < 0 order by score desc ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_LEAST_POPULAR_QUESTIONS_FULL);

		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_row");
		$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {

			$GLOBALS['RowData'] = "";

			//Build the row data
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['FHref'] = $GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['FText'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['FQViews'] = $row['views'];
				$GLOBALS['FScore'] = $row['score'];

				$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
			}

			//Intro Sentence
			$GLOBALS['AmountFullConst'] = STATS_NUM_LEAST_POPULAR_QUESTIONS_FULL;
			$GLOBALS['TrailingString'] = GetLang("LeastPopularQuestions");

			//Put it all togethor
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_table");
			$GLOBALS["LeastPopularQuestionsFull"] = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
		} else {
			$GLOBALS['Item'] = GetLang("StatNoPopularQuestions");
			$GLOBALS['LeastPopularQuestionsFull'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostPopularCategories
	* Get the categories which have questions which have been viewed the most
	*
	* @return void
	*/
	function GetMostPopularCategories()
	{
		$GLOBALS['MostPopularCategories'] = '';
		$GLOBALS['MostPopularChartSArray'] = "";

		$query = "SELECT c.categoryid, c.name, SUM(views) as num
				FROM ".$GLOBALS['tablePrefix']."categories c, ".$GLOBALS['tablePrefix']."categoryassociations a, ".$GLOBALS['tablePrefix']."questions q
				WHERE c.categoryid = a.categoryid
				AND q.questionid = a.questionid
				GROUP BY c.categoryid, c.name
				ORDER BY num DESC
				";
		$query .= $GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_MOST_POPULAR_CATEGORIES);
		$firstTime = true;

		$popArray = array();

		$result = $GLOBALS['AKB_DB']->Query($query);
		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['Href'] = GetUrl('category', $row['categoryid']);
				$GLOBALS['Text'] = htmlspecialchars($row['name'], ENT_QUOTES, $GLOBALS['charset']);

				$link = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');
				$view = ($row['num'] == 1) ? GetLang("View") : GetLang("Views");
				$GLOBALS['Item'] = $link . ' ('. number_format($row['num']) . ' ' . $view. ')';
				$GLOBALS["MostPopularCategories"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');

				if ($firstTime) {
					$GLOBALS['MostPopularCategory'] = $GLOBALS['Text'];
					$firstTime = false;
				}

				$popArray[$GLOBALS['Text']] = $row['num'];
			}

			if ($popArray) {
				$GLOBALS['MostPopularChartSArray'] = urlencode(serialize($popArray));
			} else {
				$GLOBALS['MostPopularChartSArray'] = false;
			}
		} else {
			$GLOBALS['Item'] = GetLang('StatNoPopularCategories');
			$GLOBALS['MostPopularCategories'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostPopularCategories
	* Get the categories which have questions which have been viewed the most
	*
	* @return void
	*/		
	function GetMostPopularCategoriesFull($direction,$page,$field) {
		$GLOBALS['MostPopularCategoriesFull'] = '';
		$countQuery = "SELECT c.categoryid, max(name) as name, SUM(views) as num
				FROM ".$GLOBALS['tablePrefix']."categories c, ".$GLOBALS['tablePrefix']."categoryassociations a, ".$GLOBALS['tablePrefix']."questions q
				WHERE c.categoryid = a.categoryid
				AND q.questionid = a.questionid
				GROUP BY c.categoryid
			";

		$countResult = $GLOBALS['AKB_DB']->Query($countQuery);

		$this->SetupPagination(false,$page,$GLOBALS['AKB_DB']->CountResult($countQuery));

		$query = "SELECT c.categoryid, max(name) as name, SUM(views) as num
				FROM ".$GLOBALS['tablePrefix']."categories c, ".$GLOBALS['tablePrefix']."categoryassociations a, ".$GLOBALS['tablePrefix']."questions q
				WHERE c.categoryid = a.categoryid
				AND q.questionid = a.questionid
				GROUP BY c.categoryid
				ORDER BY num DESC
				";
		$query .= $GLOBALS['AKB_DB']->AddLimit($this->paginationRowStart, AKB_STAT_PAGE_ROWS);

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.categories.category_row");
		$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

		$result = $GLOBALS['AKB_DB']->Query($query);
		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {

			$GLOBALS['RowData'] = "";

			//Build the row data
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['CategoryName'] = $row['name'];
				$GLOBALS['CategoryViews'] = $row['num'];
				$GLOBALS['CategoryHref'] = GetUrl('category', $row['categoryid']);
				$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
			}
		} else {
			$GLOBALS['Item'] = GetLang("StatNoPopularQuestions");
			$GLOBALS['MostPopularCategoriesFull'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostEmailedQuestions
	* Get the questions which have been sent to a friend the most
	*
	* @return void
	*/
	function GetMostEmailedQuestions()
	{
		$GLOBALS['MostEmailedQuestions'] = '';

		// Get the most emailed questions
		$query = sprintf("select * from %squestions where emailed > 0 order by emailed desc ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_MOST_EMAILED_QUESTIONS);
		
		$result = $GLOBALS['AKB_DB']->Query($query);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['Text'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$link = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');

				$email = ($row['emailed'] == 1) ? GetLang("Email") : GetLang("Emails");
				$GLOBALS['Item'] = $link . ' ('. number_format($row['emailed']) . ' ' . $email. ')';
				$GLOBALS["MostEmailedQuestions"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
			}
		} else {
			$GLOBALS['Item'] = GetLang('StatNoEmailedQuestions');
			$GLOBALS['MostEmailedQuestions'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
		* GetMostDiscuessedQuestions
		* Get the number of comments per question
		*
		* @return void
		*/
	function GetMostDiscussedQuestions()
	{
		$GLOBALS['MostDiscussedQuestions'] = '';

		// Get the most discussed questions
		$query = "SELECT q.questionid, title, COUNT(commentid) as num
				FROM ".$GLOBALS['tablePrefix']."comments c, ".$GLOBALS['tablePrefix']."questions q
				WHERE q.questionid=c.questionid
				GROUP BY q.questionid
				ORDER BY num DESC";

		$result = $GLOBALS['AKB_DB']->Query($query);
		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['Text'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);

				$link = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');
				$comment = ($row['num'] == 1) ? GetLang("Comment") : GetLang("Comments");
				$GLOBALS['Item'] = $link . ' ('. number_format($row['num']) . ' ' . $comment. ')';
				$GLOBALS["MostDiscussedQuestions"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
			}
		} else {
			$GLOBALS['Item'] = GetLang('StatNoComments');
			$GLOBALS["MostDiscussedQuestions"] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostDiscussedQuestionsFull
	* Get the number of comments per question to be displayed in a table.
	*
	* @return void
	*/
	function GetMostDiscussedQuestionsFull($currentPage) {
		$GLOBALS['MostDiscussedQuestionsFull'] = '';

		// Get the most discussed questions
		$countQuery = "
				SELECT q.questionid, title, COUNT(commentid) as num
				FROM ".$GLOBALS['tablePrefix']."comments c, ".$GLOBALS['tablePrefix']."questions q
				WHERE q.questionid=c.questionid
				GROUP BY q.questionid, title
			";

		$resultCount = $GLOBALS['AKB_DB']->Query($countQuery);
		$GLOBALS['AKB_DB']->CountResult($countQuery);

		$this->SetupPagination(false,$currentPage,$GLOBALS['AKB_DB']->CountResult($countQuery));

		$query = $countQuery."ORDER BY num DESC ";
		$query .= $GLOBALS['AKB_DB']->AddLimit($this->paginationRowStart, AKB_STAT_PAGE_ROWS);
		
		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_row_users");
		$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {

			$GLOBALS['RowData'] = "";

			//Build the row data
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['FHref'] = $GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['FText'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['FComments'] = $row['num'];

				$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
			}

			//Intro Sentence
			$GLOBALS['AmountFullConst'] = STATS_NUM_MOST_DISCUSSED_QUESTIONS_FULL;
			$GLOBALS['TrailingString'] = GetLang("MostDiscussedQuestions");

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_table.comments");
			$GLOBALS["MostDiscussedQuestionsFull"] = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
		} else {
			$GLOBALS['Item'] = GetLang("StatNoComments");
			$GLOBALS['MostDiscussedQuestionsFull'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostPopularAuthors
	* Get a list of the most popular authors
	*
	* @return void
	*/
	function GetPopularAuthors($most_popular=true)
	{
		//If $most_popular is false then its least popular.
		//We need to alter the templates replacements and the SQL data.
		if ($most_popular) {
			$global_ident = "MostPopularAuthors";
			$sql_modifier = ">";
			$sql_order = "DESC";
			$lang_none = "StatNoPopularAuthors";
		} else {
			$global_ident = "LeastPopularAuthors";
			$sql_modifier = "<";
			$sql_order = "ASC";
			$lang_none = "StatNoLeastPopularAuthors";
		}

		$GLOBALS[$global_ident] = '';

		$arrAuthors = array();
		$query =" select u.userid, username, firstname, lastname, sum(score) as score
				from ".$GLOBALS['tablePrefix']."questions q, ".$GLOBALS['tablePrefix']."users u
				WHERE q.userid=u.userid
				AND score ".$sql_modifier." 0
				group by u.userid, username, firstname, lastname 
				order by score
				".$sql_order." ";
		$query .= $GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_MOST_POPULAR_AUTHORS);


		$result = $GLOBALS['AKB_DB']->Query($query);

		$firstTime = true;

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				if (trim($row['firstname']) != '' || trim($row['lastname']) != '') {
					$GLOBALS['Item'] = $row['firstname'].' '.$row['lastname'];
					$GLOBALS[$global_ident] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
				} else {
					$GLOBALS['Item'] = $row['username'];
					$GLOBALS[$global_ident] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
				}
				if ($firstTime) {
					$GLOBALS['MostPopularAuthor'] = $GLOBALS['Item'];
					$firstTime = false;
				}
			}
		} else {
			$GLOBALS['Item'] = GetLang($lang_none);
			$GLOBALS[$global_ident] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostPopularAuthorsFull
	* Get a list of the most popular authors
	*
	* @return void
	*/
	function GetMostPopularAuthorsFull($direction="d",$currentPage=1,$field="views")
	{
		// Get the most popular authors
		$arrAuthors = array();

		$sql_modifier = ($direction == "d") ? "DESC" : "ASC";

		$countQuery = "select u.userid, username, firstname, lastname, email, count(q.userid) as qscore, sum(score) as score
				from ".$GLOBALS['tablePrefix']."questions q, ".$GLOBALS['tablePrefix']."users u
				WHERE q.userid=u.userid
				AND score > 0
				group by u.userid, username, firstname, lastname, email
				
			";

		$countResult = $GLOBALS['AKB_DB']->Query($countQuery);

		$this->SetupPagination(false,$currentPage,$GLOBALS['AKB_DB']->CountResult($countQuery));

		$query = "select u.userid, username, firstname, lastname, email, count(q.userid) as qscore, sum(score) as score
				from ".$GLOBALS['tablePrefix']."questions q, ".$GLOBALS['tablePrefix']."users u
				WHERE q.userid=u.userid
				AND score > 0
				group by u.userid, username, firstname, lastname, email
				order by ".$field."
				".$sql_modifier." ";
		$query .= $GLOBALS['AKB_DB']->AddLimit($this->paginationRowStart,AKB_STAT_PAGE_ROWS);

		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.users.user_row_author");
		$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			$GLOBALS['RowData'] = "";

			//Build the row data
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				if (trim($row['firstname']) != '' || trim($row['lastname']) != '') {
					$GLOBALS['Username'] = $row['firstname'].' '.$row['lastname'];
				} else {
					$GLOBALS['Username'] = $row['username'];
				}

				$GLOBALS['Email'] = $row['email'];
				$GLOBALS['Numarticles'] = $row['qscore'];
				$GLOBALS['Score'] = $row['score'];

				$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
			}
		}
	}

	/**
	* GetPopularAuthorsFull
	* Get a list of the most popular overall all
	*
	* @return void
	*/
	function GetTopCommentersFull($direction,$page,$field) {
		$GLOBALS['TopCommenters'] = '';

		$arrAuthors = array();

		$countQuery = "
				SELECT 
					COUNT(commentid) as comment_count 
				FROM 
					".$GLOBALS['tablePrefix']."comments
				GROUP BY email			
			";

		$countResult = $GLOBALS['AKB_DB']->Query($countQuery);

		$this->SetupPagination(false,$page,$GLOBALS['AKB_DB']->CountResult($countQuery));

		$query = "
				SELECT 
					MAX(name) as name, email, COUNT(commentid) as comment_count 
				FROM 
					".$GLOBALS['tablePrefix']."comments
				WHERE
					email != ''
				GROUP BY email
				ORDER BY comment_count DESC ";
		$query .= $GLOBALS['AKB_DB']->AddLimit($this->paginationRowStart, AKB_STAT_PAGE_ROWS);

		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.users.user_row_commenter");
		$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			$GLOBALS['RowData'] = "";

			//Build the row data
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				if ($row['name']) {
					$GLOBALS['CEmail'] = '<a href="mailto:'.htmlspecialchars($row['email'], ENT_QUOTES, $GLOBALS['charset']).'?subject='.sprintf(GetLang('GeneralFeedbackReplySubject'), $GLOBALS['knowledgebaseName']).'">'.htmlspecialchars($row['email'], ENT_QUOTES, $GLOBALS['charset']).'</a>';
				} else {
					$GLOBALS['CEmail'] = GetLang("NotGiven");
				}
				$GLOBALS['CName'] = htmlspecialchars($row['name'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['CommentCount'] = (int)$row['comment_count'];

				$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
			}
		} else {
			$GLOBALS['Item'] = GetLang('StatNoPopularAuthors');
			$GLOBALS['TopCommenters'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostPopularSearchesFull
	* Get a list of the most popular searches overall
	*
	* @return void
	*/
	function GetMostPopularSearchesFull($direction,$page,$field)
	{
		$sql_modifier = ($direction == "d") ? "DESC" : "ASC";

		$countQuery = sprintf("select COUNT(searchstring) as scount from %ssearchhistory", $GLOBALS["tablePrefix"]);

		$this->SetupPagination($countQuery,$page);

		$query = sprintf("select searchstring, amount from %ssearchhistory order by ".$field." ".$sql_modifier." ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit($this->paginationRowStart, AKB_STAT_PAGE_ROWS);
		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.searches.search_row");
		$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			$GLOBALS['RowData'] = "";

			//Build the row data
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['SearchTerm'] = htmlentities($row['searchstring']);
				$GLOBALS['Amount'] = $row['amount'];

				$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
			}
		}
	}

	/**
	* GetSearchSummaryData
	* Populate search summary global variable data.
	*
	* @return void
	*/
	function GetSearchSummaryData() {
		$GLOBALS['MostPopularSearchTerm'] = "";
		$GLOBALS['MostPopularFailedSearchTerm'] = "";

		//Successful
		$query = sprintf("select searchstring from %ssearchhistory order by amount desc ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit(0, 1);
		
		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['MostPopularSearchTerm'] = htmlentities($GLOBALS['AKB_DB']->FetchOne($result));

		//Failed
		$query = sprintf("select searchstring, amount from %ssearchhistory where numresults = 0 order by amount desc ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_MOST_POPULAR_FAILED_SEARCHES_FULL);
		
		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['MostPopularFailedSearchTerm'] = htmlentities($GLOBALS['AKB_DB']->FetchOne($result));
	}

	/**
	* GetMostPopularSearches
	* Get a list of the most popular searches overall
	*
	* @return void
	*/
	function GetMostPopularSearches()
	{
		$GLOBALS['MostPopularSearches'] = '';

		$query = sprintf("select searchstring, amount from %ssearchhistory order by amount desc ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_MOST_POPULAR_SEARCHES);
		$result = $GLOBALS['AKB_DB']->Query($query);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['Href'] = GetUrl('search', $row['searchstring']);
				$GLOBALS['Text'] = htmlspecialchars($row['searchstring'], ENT_QUOTES, $GLOBALS['charset']);

				$search = ($row['amount'] == 1) ? GetLang("Search") : GetLang("Searches");

				$link = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');
				$GLOBALS['Item'] = $link . ' ('. number_format($row['amount']) . ' ' . $search. ')';
				$GLOBALS["MostPopularSearches"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');

			}
		} else {
			$GLOBALS['Item'] = GetLang('StatNoPopularSearches');
			$GLOBALS['MostPopularSearches'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostPopularFailedSearches
	* Get a list of searches that returned 0 results
	*
	* @return void
	*/
	function GetMostPopularFailedSearches()
	{
		$GLOBALS['MostPopularFailedSearches'] = '';

		$query = sprintf("select searchstring, amount from %ssearchhistory where numresults = 0 order by amount desc ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_MOST_POPULAR_FAILED_SEARCHES);
		$result = $GLOBALS['AKB_DB']->Query($query);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$search = ($row['amount'] == 1) ? GetLang("Search") : GetLang("Searches");
				$GLOBALS['Item'] = htmlspecialchars($row['searchstring'], ENT_QUOTES, $GLOBALS['charset'])." (".number_format($row['amount']).' '. $search.")";
				$GLOBALS["MostPopularFailedSearches"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
			}
		} else {
			$GLOBALS['Item'] = GetLang('StatNoFailedSearches');
			$GLOBALS['MostPopularFailedSearches'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetMostPopularSearchesFull
	* Get a list of the most popular searches overall
	*
	* @return void
	*/
	function GetMostPopularFailedSearchesFull($direction,$page,$field)
	{
		$sql_modifier = ($direction == "d") ? "DESC" : "ASC";

		$countQuery = sprintf("select COUNT(searchstring) as scount from %ssearchhistory where numresults = 0", $GLOBALS["tablePrefix"]);

		$this->SetupPagination($countQuery,$page);

		$query = sprintf("select searchstring, amount from %ssearchhistory where numresults = 0 order by ".$field." ".$sql_modifier." ", $GLOBALS["tablePrefix"]);
		$query .= $GLOBALS['AKB_DB']->AddLimit($this->paginationRowStart, AKB_STAT_PAGE_ROWS);
		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.searches.search_row");
		$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			$GLOBALS['RowData'] = "";

			//Build the row data
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['SearchTerm'] = htmlentities($row['searchstring']);
				$GLOBALS['Amount'] = $row['amount'];

				$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
			}
		}
	}

	/**
	* GetHighestRatedQuestions
	*
	* Get the list of questions that have been rated the highest
	*
	* @return bool
	*/
	function GetHighestRatedQuestions()
	{
		$GLOBALS['HighestRatedQuestions'] = '';

		$query = 'SELECT title, questionid, posvotes, negvotes, posvotes - negvotes as score
			FROM '.$GLOBALS['tablePrefix'].'questions
			WHERE (
				posvotes > 0
				OR negvotes > 0
			)
			ORDER BY score DESC ';

		$query .= $GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_HIGHEST_RATED_QUESTIONS);

		$result = $GLOBALS['AKB_DB']->Query($query);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				//Build the list data
				$GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['Text'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$link = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');

				$GLOBALS['Item'] = $link.' ('.number_format($row['score']).' '.GetLang('OverallScore').')';;
				$GLOBALS["HighestRatedQuestions"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
			}

		} else {
			$GLOBALS['Item'] = GetLang('StatNoRatedQuestions');
			$GLOBALS['HighestRatedQuestions'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetHighestRatedQuestions
	*
	* Get the list of questions that have been rated the highest
	*
	* @return bool
	*/
	function GetHighestRatedQuestionsFull($direction="d",$currentPage=1,$field="posvotes")
	{
		$GLOBALS['HighestRatedQuestionsFull'] = '';

		$sql_modifier = ($direction == "d") ? "DESC" : "ASC";

		$countQuery = "SELECT COUNT(questionid) as qcount FROM ".$GLOBALS['tablePrefix']."questions WHERE posvotes > 0 OR negvotes > 0";

		$this->SetupPagination($countQuery,$currentPage);

		$query = 'SELECT title, questionid, posvotes, negvotes, views, score
			FROM '.$GLOBALS['tablePrefix'].'questions
			WHERE (
				posvotes > 0
				OR negvotes > 0
			)
			GROUP BY title, questionid, posvotes, negvotes, views, score
			ORDER BY '.$field.' '.$sql_modifier. ' ';

		$query .= $GLOBALS['AKB_DB']->AddLimit($this->paginationRowStart, AKB_STAT_PAGE_ROWS);

		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_row");
		$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

		$GLOBALS['RowData'] = "";

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				//Build the row data
				$GLOBALS['FHref'] = $GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['FText'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['FQViews'] = $row['views'];
				$GLOBALS['FScore'] = $row['score'];

				$GLOBALS['FPosvotes'] = $row['posvotes'];
				$GLOBALS['FNegvotes'] = $row['negvotes'];

				$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
			}

			//Intro Sentence - Table
			$GLOBALS['AmountFullConst'] = STATS_NUM_MOST_DISCUSSED_QUESTIONS_FULL;
			$GLOBALS['TrailingString'] = GetLang("HighestRatedQuestions");

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_table");
			$GLOBALS["HighestRatedQuestionsFull"] = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
		} else {
			$GLOBALS['Item'] = GetLang('StatNoRatedQuestions');
			$GLOBALS['HighestRatedQuestionsFull'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetLowestRatedQuestions
	*
	* Get the list of questions that have been rated the lowest
	*
	* @return bool
	*/
	function GetLowestRatedQuestions()
	{
		$GLOBALS['LowestRatedQuestions'] = '';

		$query = 'SELECT title, questionid, posvotes, negvotes, posvotes - negvotes as score
			FROM '.$GLOBALS['tablePrefix'].'questions
			WHERE (
				posvotes > 0
				OR negvotes > 0
			)
			ORDER BY score ASC
			'.$GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_LOWEST_RATED_QUESTIONS);

		$result = $GLOBALS['AKB_DB']->Query($query);

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['Text'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$link = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');

				$GLOBALS['Item'] = $link.' ('.number_format($row['score']).' '.GetLang('OverallScore').')';;
				$GLOBALS["LowestRatedQuestions"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
			}
		} else {
			$GLOBALS['Item'] = GetLang('StatNoRatedQuestions');
			$GLOBALS['LowestRatedQuestions'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetLowestRatedQuestions
	*
	* Get the list of questions that have been rated the lowest
	*
	* @return bool
	*/
	function GetLowestRatedQuestionsFull()
	{
		$GLOBALS['LowestRatedQuestionsFull'] = '';

		$query = 'SELECT title, questionid, posvotes, negvotes, views, posvotes - negvotes as score
			FROM '.$GLOBALS['tablePrefix'].'questions
			WHERE (
				posvotes > 0
				OR negvotes > 0
			)
			GROUP BY questionid
			ORDER BY score ASC ';

		$query .= $GLOBALS['AKB_DB']->AddLimit(0, STATS_NUM_HIGHEST_RATED_QUESTIONS_FULL);

		$result = $GLOBALS['AKB_DB']->Query($query);

		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_row");
		$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

		$GLOBALS['RowData'] = "";

		if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				//Build the row data
				$GLOBALS['FHref'] = $GLOBALS['Href'] = GetUrl('question', $row['questionid']);
				$GLOBALS['FText'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['FQViews'] = $row['views'];
				$GLOBALS['FScore'] = $row['score'];

				$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
			}

			//Intro Sentence - Table
			$GLOBALS['AmountFullConst'] = STATS_NUM_MOST_DISCUSSED_QUESTIONS_FULL;
			$GLOBALS['TrailingString'] = GetLang("LowestRatedQuestions");

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.questions.question_table");
			$GLOBALS["LowestRatedQuestionsFull"] = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
		} else {
			$GLOBALS['Item'] = GetLang('StatNoRatedQuestions');
			$GLOBALS['LowestRatedQuestionsFull'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('ListItem');
		}
	}

	/**
	* GetArticlePerUser
	*
	* Get the list of users and number of articles posted
	*
	* @return void
	*/
	function GetArticlePerUser($direction="d",$currentPage=1,$field="postingcount", $graphHeight=430)
	{
		// Get the most popular authors
		$arrAuthors = array();
		$whereClause = '';
		if (isset($_SESSION['ArticlePerUserFromStamp']) && isset($_SESSION['ArticlePerUserToStamp'])) {
			$from = date('Y-m-d 00:00:00', $_SESSION['ArticlePerUserFromStamp']);
			$to = date('Y-m-d 23:59:00', $_SESSION['ArticlePerUserToStamp']);
			$whereClause = "AND (q.lastupdated >= '$from' and q.lastupdated <= '$to' OR q.lastupdated is null)";
		}

		$sql_modifier = ($direction == "d") ? "DESC" : "ASC";

		$countQuery =
		"SELECT u.userid, u.firstname, u.lastname, u.username, u.email, count(q.userid) as postingcount, sum(q.score) as score"
		." FROM ".$GLOBALS['tablePrefix']."users u"
		." LEFT JOIN ".$GLOBALS['tablePrefix']."questions q on q.userid = u.userid"
		." WHERE 1=1"
		." $whereClause"
		." GROUP BY u.userid, u.firstname, u.lastname, u.username, u.email"
		." ORDER BY $field, u.firstname, u.lastname, u.username"
		." $sql_modifier"
		;

		$countResult = $GLOBALS['AKB_DB']->Query($countQuery);

		$GLOBALS['TotalAuthors'] = $GLOBALS['AKB_DB']->CountResult($countQuery);
		$GLOBALS['TotalArticles'] = 0;

		if ($GLOBALS['TotalAuthors'] > 20 || $GLOBALS['TotalAuthors'] < 1) {

			$GLOBALS['ArticlePerUserDisplay'] = '
								<div id="REMOTE_TopPosters"></div>
			
								<script>
									REMOTE_admin_table(
										\'REMOTE_TopPosters\',
										\'remote/remote_admin_table.php\',
										\'TopPosters\',
										\'d\',
										\'postingcount\',
										1
									);
								</script>
							</div>
							';
			
			$GLOBALS['NoArticlesPosted'] = '';
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate("stats.users.user_row_posted");
			$tempRowStr = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);

			if ($GLOBALS['TotalAuthors'] > 0) {
				$GLOBALS['RowData'] = "";
				//Build the row data
				while ($row = $GLOBALS['AKB_DB']->Fetch($countResult)) {
					$GLOBALS['StatsUsersUsername'] = $row['username'];
					$GLOBALS['StatsUsersTotalPostedArticles'] = $row['postingcount'];
					$GLOBALS['StatsUsersEmail'] = $row['email'];
					$GLOBALS['StatsUsersFullname'] = GetLang('NA');
					$GLOBALS['StatsUsersTotalScored'] = $row['score'];
					if (trim($row['firstname']) != '' || trim($row['lastname']) != '') {
						$GLOBALS['StatsUsersFullname'] = $row['firstname'] .' '. $row['lastname'];
					}

					$GLOBALS['RowData'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true,$tempRowStr);
					$GLOBALS['TotalArticles'] += $row['postingcount'];
				}
			} else {
				$GLOBALS['params'] = ' height="22" colspan="4" ';
				$GLOBALS['message'] = GetLang('StatNoArticlesPosted');
				$GLOBALS['NoArticlesPosted'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('TableRowMessage');
			}

		} else {
			while ($row = $GLOBALS['AKB_DB']->Fetch($countResult)) {
				
				$GLOBALS['StatsUsersUsername'] = $row['username'];
				$GLOBALS['TotalArticles'] += $row['postingcount'];
			}
			$GLOBALS['ArticlePerUserDisplay'] = '
				<script type="text/javascript">
				// <![CDATA[		
						var so = new SWFObject("includes/amcharts/amcolumn/amcolumn.swf", "amcolumn", "100%", "'.$graphHeight.'", "8", "#FFFFFF");
						so.addVariable("path", "includes/amcharts/");
						so.addVariable("settings_file", escape("includes/amcharts/amcolumn/articleperuser_settings.xml"));
						so.addVariable("data_file", escape("index.php?ToDo=statsUserPerArticlesXml&from='.$_SESSION['ArticlePerUserFromStamp'].'&to='.$_SESSION['ArticlePerUserToStamp'].'"));
						so.addVariable("preloader_color", "#999999");
						so.write("flashcontent1");
				// ]]>
				</script>
			';
		}
		$GLOBALS['GraphTitle'] = GetLang('StatArticlesPostedTitle');

	}

	/**
	* HandleRemoteStats
	*
	* A junction point for all remote (Ajax) request for any statistics
	*
	* @return string (HTML)
	*/		
	function HandleRemoteStats() {

		$todo 		= $_GET['todo'];
		$direction 	= $_GET['direction'];
		$field 		= $_GET['field'];
		$page 		= (int)@$_GET['page'];

		$allowed_fields_array = array(
		"views",
		"score",
		"posvotes",
		"negvotes",
		"comment",
		"qscore",
		"email",
		"amount",
		"searchstring",
		"comment_count",
		"postingcount"
		);

		if (!in_array($field,$allowed_fields_array)) {
			trigger_error("REMOTE FATAL ERROR -- ".$field);
		}

		if ($page == 0) {
			$page = 1;
		}

		$GLOBALS['RemoteURL'] = ADMIN_TABLE_REMOTE_URL;
		$GLOBALS['ATTODO'] = $todo;
		$GLOBALS['CurrentPageNumber'] = $page;

		//Set the Pagination link for switching between pages.
		$this->paginationLink = "
				javascript: REMOTE_admin_table('
					REMOTE_".$todo."',
					'".ADMIN_TABLE_REMOTE_URL."',
					'".$todo."',
					'".$direction."',
					'".$field."',
					'__BUILDNAV_PAGENUMBER__'
				);
			";

		switch ($todo) {
			case "MostViewedQuestionsFull":
			$tableTemplate = "stats.questions.question_table";
			$this->GetMostViewedQuestionsFull($direction,$page,$field);

			$this->CreateRandomGlobals(4);

			break;

			case "MostPopularQuestionsFull":
			$tableTemplate = "stats.questions.question_table";
			$this->GetMostPopularQuestionsFull($direction,$page,$field);

			$this->CreateRandomGlobals(4);

			break;

			case "HighestRatedQuestionsFull":
			$tableTemplate = "stats.questions.question_table";
			$this->GetHighestRatedQuestionsFull($direction,$page,$field);

			$this->CreateRandomGlobals(4);

			break;

			case "MostDiscussedQuestionsFull":
			$tableTemplate = "stats.questions.question_table.comments";
			$this->GetMostDiscussedQuestionsFull($page);

			break;

			case "MostPopularAuthorsFull":
			$tableTemplate = "stats.users.user_table_author";
			$this->GetMostPopularAuthorsFull($direction,$page,$field);

			$this->CreateRandomGlobals(1);

			break;

			case "TopCommenters":
			$tableTemplate = "stats.users.user_table_commenter";
			$this->GetTopCommentersFull($direction,$page,$field);
			break;

			case "MostViewedCategories":
			$tableTemplate = "stats.categories.category_table";
			$this->GetMostPopularCategoriesFull($direction,$page,$field);
			break;

			case "MostPopularSearchesFull":
			$tableTemplate = "stats.searches.search_table";
			$this->GetMostPopularSearchesFull($direction,$page,$field);
			break;

			case "MostPopularFailedSearchesFull":
			$tableTemplate = "stats.searches.search_table";
			$this->GetMostPopularFailedSearchesFull($direction,$page,$field);
			break;

			case "TopPosters":
			$tableTemplate = "stats.users.user_table_posted";
			$this->GetArticlePerUser($direction,$page,$field);
			break;

			default:
			die("throw error here: ".$todo);
		}

		//Handle field selectors
		$GLOBALS['ThisField'] = "searchstring";
		$GLOBALS['searchstringUpDown'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortEE");

		$GLOBALS['ThisField'] = "amount";
		$GLOBALS['amountUpDown'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortEE");

		$GLOBALS['ThisField'] = "views";
		$GLOBALS['viewsUpDown'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortEE");

		$GLOBALS['ThisField'] = "score";
		$GLOBALS['scoreUpDown'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortEE");

		$GLOBALS['ThisField'] = "posvotes";
		$GLOBALS['posvotesUpDown'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortEE");

		$GLOBALS['ThisField'] = "negvotes";
		$GLOBALS['negvotesUpDown'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortEE");

		$GLOBALS['ThisField'] = "qscore";
		$GLOBALS['qscoreUpDown'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortEE");

		$GLOBALS['ThisField'] = "email";
		$GLOBALS['emailaddressUpDown'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortEE");

		$GLOBALS['ThisField'] = "email";
		$GLOBALS['emailUpDown'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortEE");

		$GLOBALS['ThisField'] = "postingcount";
		$GLOBALS['postingcountUpDown'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortEE");

		$GLOBALS['ThisField'] = "username";
		$GLOBALS['usernameUpDown'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortEE");

		//Handle chosen field selector
		$GLOBALS['ThisField'] = $field;
		if ($direction == "d") {
			$GLOBALS[$field.'UpDown'] 	= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortDE");
		} else {
			$GLOBALS[$field.'UpDown'] 	= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("RemoteSortED");
		}

		//Parse into main table template
		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate($tableTemplate);
		echo $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
	}

	/**
	* SetupPagination
	*
	* Setup the pagination variables for the global Nav functionality.
	* This is based on the general function BuildNav, but slightly different logic to accomodate javascript links
	*
	* @return void
	*/				
	function SetupPagination($countQuery=false,$currentPage,$countRows=false) {
		if ($countQuery) {
			$result = $GLOBALS['AKB_DB']->Query($countQuery);
			$numRecords = $GLOBALS['AKB_DB']->FetchOne($result);
		} else {
			$numRecords = $countRows;
		}

		$numPages = ceil($numRecords / AKB_STAT_PAGE_ROWS);

		$this->paginationRowStart = ($currentPage == 1) ? 0 : ($currentPage * AKB_STAT_PAGE_ROWS) - (AKB_STAT_PAGE_ROWS-1)-1;

		$GLOBALS['PaginationNav'] = BuildNav($this->paginationLink, $numPages, $currentPage, "&amp;", true);
	}

	/**
	*	Return a list of days as option tags
	*/
	function _GetDayOptions($Selected=0)
	{
		$output = "";

		for($i = 1; $i <= 31; $i++) {
			if($Selected == $i) {
				$sel = 'selected="selected"';
			}
			else {
				$sel = "";
			}

			$output .= sprintf("<option value='%d' %s>%s</option>", $i, $sel, $i);
		}

		return $output;
	}

	/**
	*	Return a list of months as option tags
	*/
	function _GetMonthOptions($Selected=0)
	{
		$output = "";

		for($i = 1; $i <= 12; $i++) {
			if($Selected == $i) {
				$sel = 'selected="selected"';
			}
			else {
				$sel = "";
			}

			$stamp = mktime(0, 0, 0, $i, 1, 2000);
			$month = date("M", $stamp);
			$output .= sprintf("<option value='%d' %s>%s</option>", $i, $sel, $month);
		}

		return $output;
	}

	/**
	*	Return a list of years as option tags
	*/
	function _GetYearOptions($Selected=0)
	{

		$output = "";

		for($i = date("Y")-5; $i <= date("Y")+5; $i++) {
			if($Selected == $i) {
				$sel = 'selected="selected"';
			}
			else {
				$sel = "";
			}

			$output .= sprintf("<option value='%d' %s>%s</option>", $i, $sel, $i);
		}

		return $output;
	}

}
?>