<?php
/*
	Usage by dates, countries, totals.
*/
	
	// If no id default to front page.
	if(!isset($_REQUEST["id"])) { return "pub_default"; }

	// Get detail given year/month
	$show_date = 'all years';
	if(isset($_REQUEST["year"]) and $_REQUEST["year"]>2002) {
		if(isset($_REQUEST["month"]) and $_REQUEST["month"]>=1 and $_REQUEST["month"]<=12) { 
			$dt = strtotime($_REQUEST["month"]."/1/".$_REQUEST["year"]);
			$show_date = date("F Y",$dt);
		} else {
			$show_date = $_REQUEST["year"];	
			$_REQUEST["month"] = 0;
		}
	} else {
		$_REQUEST["year"] = 0;
		$_REQUEST["month"] = 0;
	}
	if(isset($_REQUEST["range"])) {
		// Work out current date
		if($_REQUEST["range"]=='4w') {
			$show_date = 'past 4 weeks';
		}
	} else {
		$_REQUEST["range"] = '';
	}
	// by country
	// NJS 2006-06-14: Added archive name as argument.
	$country_abstracts = $sql->getCountryEprintType($GLOBALS["config_vars"]["archivename"],$_REQUEST["year"], $_REQUEST["month"], $_REQUEST["range"], 'abstract', $_REQUEST["id"]);
	$country_downloads = $sql->getCountryEprintType($GLOBALS["config_vars"]["archivename"],$_REQUEST["year"], $_REQUEST["month"], $_REQUEST["range"], 'download', $_REQUEST["id"]);
	
	// NJS 2006-01-18: Calculate total number of countries.
	$total_download_countries = count($country_downloads);
	$total_abstract_countries = count($country_abstracts);
	
	$GLOBALS["db_values"] = merge_countries($country_abstracts, $country_downloads);
	// title
	// NJS 2006-06-14: Added archive name as argument.
	$title = $sql->getTitle($GLOBALS["config_vars"]["archivename"],$_REQUEST["id"]);
	// by type
	$type_count = $sql->getAbstractDownload($GLOBALS["config_vars"]["archivename"],$_REQUEST["year"], $_REQUEST["month"], $_REQUEST["range"], 'download', $_REQUEST["id"]);
	// by date
	// NJS 2006-06-14: Added archive name as argument.
	$month_downloads = $sql->getCumulativeUsageType($GLOBALS["config_vars"]["archivename"],$_REQUEST["id"],'download');
	$month_abstracts = $sql->getCumulativeUsageType($GLOBALS["config_vars"]["archivename"],$_REQUEST["id"],'abstract');
	$month_tally = merge_dates($month_abstracts,$month_downloads);


	/* NJS 2007-01-31
	   Calculate the length of the largest bar for the country
	   downloads histogram.
	   
	   This was refactored from inc.html.show_detail_eprint.php.
	   
	   Arguments:	$mode		either 'country' (count only real countries)
	   							or 'bot' (count only bots/crawlers)
	   
	   Returns:	integer
	*/
	function getMaxCount ( $mode )
	{
		$max = 0;
		
		for ( $rs = 0; $rs < count( $GLOBALS["db_values"] ); $rs++ )
		{
			/* If we're in country mode, skip all bot entries (country
			   code starts with 'X@'). If we're in bot mode, skip
			   all country entries (country code *doesn't* start with
			   'X@').
			*/
			$cc = substr( $GLOBALS["db_values"][$rs]["country_code"], 0, 2 );
			if ( ( $mode == 'country' ) && ( $cc == 'X@' ) ) continue;
			if ( ( $mode == 'bot' ) && ( $cc != 'X@' ) ) continue;
			
			// Check abstracts...
			$abs = $GLOBALS["db_values"][$rs]["country_abstracts"];
			if ( $abs > $max )
			{
				$max = $abs;
			}

			// ...then downloads.
			$dl = $GLOBALS["db_values"][$rs]["country_downloads"];
			if ( $dl > $max )
			{
				$max = $dl;
			}
		}
		return $max;
	}
	
	
	/* NJS 2007-02-02
	   Output a "country" downloads histogram. This function only
	   generates rows (<tr>) of the table; the enclosing <table> element
	   must be output by the caller.
	   
	   This was refactored from inc.html.show_detail_eprint.php.
	   Note that while this is *very* similar to the equivalent
	   function in inc.fns.cumulative_usage_country.php, it is
	   not *quite* identical! (A good candidate for future
	   refactoring?) In particular, the "count" columns in this
	   table span two columns each, not one.
	   
	   Arguments:	$mode		either 'country' (display only real countries)
	   							or 'bot' (display only bots/crawlers)
	   				$max_count	length (number of hits) of longest bar
	   				$max_width	maximum width in pixels of a bar
	   
	   Returns:	void
	*/
	function generateCountryTable ( $mode, $max_count, $max_width )
	{
		// NJS 2006-01-18: Accumulate total number of downloads and views.
		$total_downloads = 0;
		$total_abstracts = 0;
		$abstract_countries = array();
		$download_countries = array();
		/* NJS 2007-02-07
		   Keep an independent count of the row number so that we can
		   highlight them properly. We can't just use the loop counter
		   $rs below because we skip certain rows according to which
		   mode we're in, so $rs will appear to skip unpredictably.
		*/
		$row = 0;
	
		for ( $rs = 0; $rs < count( $GLOBALS["db_values"] ); $rs++ )
		{
			/* If we're in country mode, skip all bot entries (country
			   code starts with 'X@'). If we're in bot mode, skip
			   all country entries (country code *doesn't* start with
			   'X@').
			*/
			$ccode = $GLOBALS["db_values"][$rs]["country_code"];
			$cc = substr( $ccode, 0, 2 );
			if ( ( $mode == 'country' ) && ( $cc == 'X@' ) ) continue;
			if ( ( $mode == 'bot' ) && ( $cc != 'X@' ) ) continue;
			
			// NJS 2006-01-18: Accumulate total number of downloads and views.
			// NJS 2007-01-31: Record countries in a bitmap so we can easily count them later.
			$abs = $GLOBALS["db_values"][$rs]["country_abstracts"];
			$dl = $GLOBALS["db_values"][$rs]["country_downloads"];
			$total_abstracts += $abs;
			$total_downloads += $dl;
			if ( $abs > 0 )
			{
				$abstract_countries[$ccode] = 1;
			}
			if ( $dl > 0 )
			{
				$download_countries[$ccode] = 1;
			}
		
			if ($GLOBALS["db_values"][$rs]["country_name"]=='') { $GLOBALS["db_values"][$rs]["country_name"]='unknown'; }
			if ($GLOBALS["db_values"][$rs]["country_name"]=='N/A') { $GLOBALS["db_values"][$rs]["country_name"]='unknown'; }
			// NJS 2005-12-15: subtly highlight every alternate row
			print '<tr';
			if ($row++ % 2) print ' style="background-color:#EDF3FE;"';
			print '><td>';
			
			// select a flag
			// NJS 2005-12-15 make flags and country names links to detail page
			$ccode = strtolower($ccode);
			$c_flag = 'flags18x14/' . $ccode . '.png';
			// NJS 2006-06-14: Only generate a link if there are actually
			// some downloads.
			if ( $dl > 0 )
				print '<a href="' . $_SERVER['PHP_SELF'] .
					'?action=show_detail_country;code=' . $ccode . '">';
			if (file_exists($c_flag)) {
				print '<img border="0" src="'. $c_flag . '" width="18" height="14" alt="'. $ccode . '" />';
			} else {
				print '<img border="0" src="flags18x14/unknown.png" width="18" height="14" alt="' . $ccode . '" />';
			};
			if ( $dl > 0 )
				print '</a>';
			
			print '</td><td style="font-size:small;border-right:1px solid #dddddd;">';
			// NJS 2006-06-14: Only generate a link if there are actually
			// some downloads.
			if ( $dl > 0 )
				print '<a href="' . $_SERVER['PHP_SELF'] .
				'?action=show_detail_country;code=' . $ccode . '">';
			print $GLOBALS["db_values"][$rs]["country_name"];
			if ( $dl > 0 )
				print '</a>';
			print '</td><td colspan="2" align="right" style="font-size:small;border-right:1px solid #dddddd;">'.
				( ( $abs > 0 ) ? $abs : '' ).
				'</td><td colspan="2" align="right" style="font-size:small;border-right:1px solid #dddddd;">' . 
				( ( $dl > 0 ) ? $dl : '' ).
				'</td>';
	
			$cur_count = $abs;
			$col_width = (int) ($cur_count/$max_count * $max_width);
			if ( $abs > 0 ) $col_width = max($col_width,1);
			print '<td align="left"><img src="bars/hh.png" alt="views" height="9" width="'. 
				$col_width . 
				'" /><br />';
	
			$cur_count = $dl;
			$col_width = (int) ($cur_count/$max_count * $max_width);
			if ($dl > 0) $col_width = max($col_width,1);
			print '<img src="bars/hp.png" alt="views" height="9" width="'. 
				$col_width . 
				'" /></td></tr>';
		}
		
		// NJS 2006-01-18: Display grand totals.
		print '<tr><th rowspan="2" colspan="2" style="background-color:#cccccc;">Grand Totals:</th>
		<th colspan="2" align="right" style="background-color:#66ddee;">'.
		$total_abstracts.
		'</th>
		<th colspan="3" align="left" style="background-color:#cccccc;"> abstract';
		if ( $mode == 'country' )
		{
			print ' views originating from '.
			count($abstract_countries).
			' distinct countries</th></tr>';
		}
		else
		{
			print 's indexed</th></tr>';
		}
		print '<tr><th colspan="2" align="right" style="background-color:#cccccc;">&nbsp;</th>
		<th colspan="2" align="right" style="background-color:#4477dd;color:#ffffff;">'.
		$total_downloads.
		'</th><th align="left" style="background-color:#cccccc;"> full text ';
		if ($mode == 'country' )
		{
			print 'downloads originating from '.
			count($download_countries).
			' distinct countries</th></tr>';
		}
		else
		{
			print 'documents indexed</th></tr>';
		}
	}
	
?>
