<?php
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/*

Simple Report Generation / Domain Display Kit for Watch My Domains SED

Copyright 2013, Softnik Technologies.

*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////
	
require_once("lib/php/config.check.php");
require_once("config.php");
require_once("lib/php/base.php");

/////////////////////////////////////////////////////////////////////////////////////////////////////////

# Only admin users can use this script.
# If user authentication is disabled, everyone is an admin user!

session_start();
check_authentication_login();
if(is_admin_user() == false)
{
	header("Location: " . get_base_path());
	exit;
}
doSessionSwipeIn();

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function emitCategoryNames()
{
	global $db_config_category_table;
	
	$sql = "SELECT * FROM  " . $db_config_category_table . " WHERE CategoryID != 1";
	$result = mysql_query($sql) or die("Connection Error: " . mysql_error());

	$catnames = "var categoryNames = [\n";
	while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
	{
		$catnames .= "'".$row['CategoryName'] . "',";
		
	}
	$catnames = trim($catnames, " ,\n\r\t");
	$catnames .= "];\n";
	if(!is_user_auth_enabled())
		$catnames .= "\t\tcustom_query = false;\n";
	else
		$catnames .= "\t\tcustom_query = true;\n";
	echo "\t\t<script type=\"text/javascript\">\n\t\t\t" . $catnames . "\t\t</script>\n";
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function emitReportColumnJS()
{
	global $db_config_tablecolumns_table, $db_allowed_domain_columns, $domain_table_date_fields, $domain_table_datetime_fields, $domain_table_text_fields;
	
	$tbnames[] = "report_columns_array";
	$jsDefault[0] = "registry_expiry;registrar_expiry;lookedup;status;registrar";
	
	$jsData[0] = "";
	
	connect_to_mysql_and_select_db();
	
	SetupAllowableFields();
	
	for($i = 0; $i < 1; $i++)
	{
		$result = mysql_query('SELECT * FROM ' . $db_config_tablecolumns_table . " WHERE name = '" . $tbnames[$i] . "'");
		if($result)
		{
			while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
			{
				$entry = trim($row['entry']);
				if($entry == "")
					$entry = $jsDefault[$i];
				$jsData[$i] = "domain;" . $entry;
			}
		}
		if($jsData[$i] == "")
			$jsData[$i] = "domain;" . $jsDefault[$i];
	}
?>
<script type="text/javascript">
<?php
	for($i = 0; $i < 1; $i++)
	{
?>
			var <?php echo $tbnames[$i]; ?> = [
<?php
		$parts = explode(";", $jsData[$i]);
		$j = 0;
		foreach($parts as $part)
		{
			$columns[0] = $part; // Label
			$columns[1] = strtolower(trim($part)); // Field Name
			$columns[1] = str_replace(" ","_", $columns[1]);
			$columns[2] = 100; // Width
			if($columns[1] == "domain") // For the domain column, the normal default width is 170.
				$columns[2] = 170;
			$columns[0] = getLabelFromFieldName($columns[0]);
			$status = get_column_label_and_width($columns[1], $columns[0], $columns[2]);
			
			$classname = strtolower($columns[1]);
			$classname = str_replace("_","-", $classname) . "-cell";
			
			if(count($columns) == 3 && in_array($columns[1], $db_allowed_domain_columns) && $columns[1] != "")
			{
				$append = "";
				if(strtolower($columns[1]) == "domain")
					$append = ",editable:true,editoptions:{readonly:true}";
				else if(in_array($columns[1], $domain_table_date_fields))
					$append = ",sorttype:\"date\", datefmt: \"d-m-YYYY\", editable:true,formatter:'date', formatoptions:{srcformat:\"Y-m-d\",newformat:\"d-M-Y\"}";
				else if(in_array($columns[1], $domain_table_datetime_fields))
					$append = ",sorttype:\"date\", editable:false, formatter:'date', formatoptions:{srcformat:\"Y-m-d H:i:s\",newformat:\"d-M-Y H:i:s\"}";
				else if(in_array($columns[1], $domain_table_text_fields))
					$append = ",editable:true";
				
				echo "\t\t\t{label:";
				echo "'" . addslashes($columns[0]) . "',";
				echo "name:'" . $columns[1] . "',";
				echo "width:'" . $columns[2] . "'";
				echo ",classes:\"dtcell $classname\"";
				echo $append;
				echo "}";
				if($j != (count($parts)-1))
					echo ",";
				echo "\n";
				$j++;
			}
		}
?>
			];
<?php
	}
?>
		</script>
<?php
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function get_base_dir()
{
	return realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function getTableColumnsForGroup()
{
	global $db_config_tablecolumns_table;
	
	$dgroup = "report_columns_array";
	$jsDefault = "registry_expiry;registrar_expiry;lookedup;status;registrar";
	
	$entry = "";
	$result = mysql_query('SELECT * FROM ' . $db_config_tablecolumns_table . " WHERE name = '" . $dgroup . "'");
	if($result)
	{
		while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
			$entry = trim($row['entry']);
	}
	if($entry == "")
		$entry = $jsDefault;
		
	$sqlColumns = explode(";", $entry);
			
	return $sqlColumns;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

function get_cid_from_category($category)
{
	$category = trim($category);
	if($category != "")
	{
		global $db_config_category_table;
		$sql = "select CategoryID from " . $db_config_category_table . " where CategoryName = '$category'";
		$idresults = mysql_query($sql) or die ("Error reading from database");  
		$row = mysql_fetch_array($idresults, MYSQL_ASSOC);
		if(count($row) == 1 && isset($row['CategoryID']))
			return $row['CategoryID'];
	}
	return 0;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

if(isset($_REQUEST['grid']))
{
	connect_to_mysql_and_select_db();
	
	//echo "<pre>";
	//print_r($_REQUEST);
	//logRequestData();
	
	$dnload = false;
	$fullcsv = false;
	$crlf = "\r\n";
	
	if(isset($_REQUEST['dnload']))
		$dnload = true;
	if(isset($_REQUEST['csv']))
		$fullcsv = true;
	if(isset($_REQUEST['unix']))
		$crlf = "\n";
	
	$catsql = "";
	if(isset($_REQUEST['cat']))
	{
		$catnames = urldecode($_REQUEST['cat']);
		$catlist = explode(",", $catnames);
		for($i = 0; $i < count($catlist); $i++)
		{
			$catname = trim($catlist[$i], "\r\n\t'()\"");
			$catname = validate_request_data($catname);
			$catid = get_cid_from_category($catname);
			#if($catid > 0)
			{
				if($catsql != "")
					$catsql .= " OR ";
				$catsql .= "(a.sid = b.sid AND b.CategoryID = $catid)";
			}
		}
	}
	
	$strsql = "";
	if(isset($_REQUEST['str']) && is_user_auth_enabled())
	{
		$strmatch = validate_request_data($_REQUEST['str']);
		$strmatch = str_replace("\'", "'", $strmatch);
		$strmatch = urldecode($strmatch);
		
		$strlist = explode(",", $strmatch);
		for($i = 0; $i < count($strlist); $i++)
		{
			$strname = trim($strlist[$i]);
			if($strname != "")
			{
				$ormatch = true;
				if(substr($strname, 0, 1) == "!")
				{
					$strname = substr($strname, 1);
					$ormatch = false;
				}
				if(!strstr($strname, "%"))
					$strname = "%" . $strname . "%";
				if($strsql != "")
				{
					if($ormatch)
						$strsql .= " OR ";
					else
						$strsql .= " AND ";
				}
				$strsql .= "(a.domain LIKE '$strname')";
			}
		}
	}

	$page = get_numeric_request_variable('page', 1);     // get the requested page
	$limit = get_numeric_request_variable('rows', 20); // get how many rows we want to have into the grid
	$sidx = get_indexed_request_variable('sidx', 'sid', $db_allowed_domain_columns); // get index row - i.e. user click to sort
	$sord = get_indexed_request_variable('sord', 'asc', array('asc', 'desc')); // get the direction
	
	global $db_config_domain_table, $db_config_catconnection_table;

	if(is_user_auth_enabled())
	{
		$usql = validate_request_data($_REQUEST['grid']);
		$usql = str_replace("\'", "'", $usql);
		$usql = urldecode($usql);
		$usql = parse_custom_sql_query($usql);
	}
	else
		$usql = "";
	
	if(stristr($usql, "drop "))
		$usql = "";
	if(stristr($usql, "delete "))
		$usql = "";
		
	$usql = trim($usql);
	if($catsql != "")
	{
		$catsql = "(" . $catsql . ")";
		if($usql != "")
			$usql .= " AND (" . $catsql . ")";
		else
			$usql = $catsql;
	}	
	$usql = trim($usql);
	
	if($strsql != "")
	{
		if($usql != "")
			$usql .= " AND (" . $strsql . ")";
		else
			$usql = $strsql;
	}	
	$usql = trim($usql);
		
	if($usql != "")
		$usql = " WHERE " . $usql;
	
	$sqlCount = "SELECT COUNT(DISTINCT a.sid) AS count FROM  $db_config_domain_table a ";
	if($catsql != "")
		$sqlCount .= ", $db_config_catconnection_table b ";
	$sqlCount .= $usql;
	//echo $sqlCount;
	
	//logToFile("php.log", $sqlCount);
	
	$result = mysql_query($sqlCount) or die("Connection Error: " . mysql_error());
	$row = mysql_fetch_array($result,MYSQL_ASSOC);
	$count = $row['count'];

	if( $count >0 ) {
		$total_pages = ceil($count/$limit);
	} else {
		$total_pages = 0;
	}
	if ($page > $total_pages) $page=$total_pages;
	$start = $limit*$page - $limit; // do not put $limit*($page - 1)
	
	$sqlColumns = getTableColumnsForGroup("");
	
	$sqtext = "a.sid, a.domain, ";
	foreach($sqlColumns as $sc)
		$sqtext .= "a." . $sc . ", ";
	$sqtext = trim($sqtext, ", ");
	
	//$SQL = "SELECT DISTINCT a.sid, a.domain, a.registry_expiry, a.registrar_expiry, a.lookedup, a.status, a.registrar FROM $db_config_domain_table a ";
	//$SQL = "SELECT DISTINCT " . $sqtext . " FROM $db_config_domain_table a ";
	$SQL = "SELECT DISTINCT a.* FROM $db_config_domain_table a ";
	
	if($catsql != "")
		$SQL .= ", $db_config_catconnection_table b ";
	$SQL .= $usql . " ORDER BY a.$sidx $sord";
	if($count > 0  && $dnload == false)
		$SQL .= " LIMIT $start , $limit";
		
	//logToFile("php.log", $SQL . "\n");
	
	$result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());

	if($dnload == false)
	{
		$responce = new stdClass();
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records = $count;
		$i=0;
		while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
		{
			$responce->rows[$i]['id']=$row['sid'];
			//$responce->rows[$i]['cell']=array($row['domain'],$row['registry_expiry'],$row['registrar_expiry'],$row['lookedup'],$row['status'],$row['registrar']);
			$darray = array();
			$darray[] = $row['domain'];
			foreach($sqlColumns as $sc)
				$darray[] = $row[$sc];
			$responce->rows[$i]['cell'] = $darray;
			$i++;
		}        
		echo json_encode($responce);
	}
	else
	{
		@ob_end_clean(); 

		if(ini_get('zlib.output_compression'))
			ini_set('zlib.output_compression', 'Off');
		$fname = "domain_names.csv";
		
		header('Content-Type: ' .  "text/csv");
		header('Content-Disposition: attachment; filename="'.$fname.'"');
		header("Content-Transfer-Encoding: binary");
		header('Accept-Ranges: bytes');

		header("Cache-control: private");
		header('Pragma: private');
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		
		$fh = fopen("php://temp", 'w+');
		
		$labelArrays = array();
		$labelArrays[] = 'Domain';
		foreach($sqlColumns as $sc)
		{
			$label = getLabelFromFieldName($sc);
			$width = 100;
			get_column_label_and_width($sc, $label, $width);
			$labelArrays[] = $label;
		}
		
		if($fullcsv)
			fputcsv($fh, $labelArrays); //array('Domain', 'Registry Expiry', 'Registrar Expiry', 'Lookedup At', 'Status', 'Registrar'));
		//else
		//	fputcsv($fh, array('Domain'));
			
		$i=0;
		while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
		{
			$darray = array();
			$darray[] = $row['domain'];
			foreach($sqlColumns as $sc)
				$darray[] = $row[$sc];
				
			if($fullcsv)
				$csvrow = $darray; //array($row['domain'], $row['registry_expiry'], $row['registrar_expiry'], $row['lookedup'], $row['status'], $row['registrar']);
			else
				$csvrow = array($row['domain']);
			fputcsv($fh, $csvrow);
			$i++;
		} 

		rewind($fh);
		echo stream_get_contents($fh);
		ftruncate($fh,0);
		fclose($fh);
	}
	exit;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	$jqtheme = get_theme_name("");
	$title = "";
	if($title == "")
		$title = "Domain Portfolio Manager - Simple Reports";
	$panesjs = "cfgpanes.js";

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
		<title><?php echo $title; ?></title>
		<meta http-equiv="Content-Language" content="en">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<link rel="shortcut icon" type="image/x-icon" href="lib/css/img/favicon.ico">
		
		<link type="text/css" href="lib/css/jqueryui/<?php echo $jqtheme; ?>/jquery-ui-1.8.7.custom.css" rel="stylesheet">
		<link type="text/css" href="lib/css/jqueryui/<?php echo $jqtheme; ?>/splitter.1.51.css" rel="stylesheet" media="screen">
		<link type="text/css" href="lib/css/jqueryui/splitter.1.51.css" rel="stylesheet" media="screen">
		<link type="text/css" href="lib/css/jqueryui/ui.jqgrid.css" rel="stylesheet" media="screen">

		<script type="text/javascript" src="lib/js/jquery/jquery-1.5.1.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/jquery.cookie.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/jquery-ui-1.8.7.noeffects.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/splitter.1.51.min.js"></script>
		<script type="text/javascript" src="lib/js/jquery/i18n/grid.locale-en.js"></script>
		<script type="text/javascript" src="lib/js/jquery/jquery.jqGrid.3.8.2.min.js"></script>
		
		<link type="text/css" href="lib/css/default.css" rel="stylesheet" media="all">
<?php
if(file_exists(get_base_dir() . "lib/css/custom.css"))
{
?>
		<link type="text/css" href="lib/css/custom.css" rel="stylesheet" media="all">
<?php
}
?>
		<link type="text/css" href="lib/css/<?php echo $jqtheme; ?>.css" rel="stylesheet" media="all">
		<script type="text/javascript" src="lib/js/buttons.js"></script>
		<style>
			body {min-width: 960px;}
			.controlbox label 
			{
				display: block;
				width: 150px;
				float: left;
				padding-top:2px;
				font-family: Trebuchet MS,Verdana,Arial,sans-serif; 
			}
			#bulktoolbox
			{
				min-height: 250px;	
			}
			button {height: 30px;}
		</style>
<?php emitReportColumnJS(); ?>
<?php emitCategoryNames(); ?>
		<script type="text/javascript">
		var domGridScrollOffset = 18;

		if(!$.browser.msie && !$.browser.mozilla)
			domGridScrollOffset = 56+18;
		function HandleEnterKey(e, submitid)
		{
			var keycode = (e.keyCode ? e.keyCode : (e.which ? e.which : e.charCode));
			if (keycode == 13)
			{
				if(submitid != "")
					$("#" + submitid).click();
				return false;
			}
			return true;
		}
		function reload_grid(dnload, onlynames)
		{
			var sql = $.trim($("#sql_text").val());
			var catnames = $("#cat_names").val();
			var strmatch = $("#str_match").val();
			
			var durl = "report.php?grid=" + encodeURIComponent(sql);
			if(catnames != "")
				durl += "&cat=" + catnames;
			if(strmatch != "")
				durl += "&str=" + encodeURIComponent(strmatch);
			if(dnload)
			{
				durl += "&dnload=1";
				if(!onlynames)
					durl += "&csv=1";
				//window.open(durl);
				window.location = durl;
			}
			//alert(durl);
			jQuery("#domain_table").setGridParam({url:durl});
			$("#domain_table").trigger("reloadGrid"); 
		}
		function addBulkToolButton()
		{
			$("#domain_table").navSeparatorAdd("#domain_pager",{})
			.navButtonAdd('#domain_pager',
			{
				caption:"", 
				buttonicon:"ui-icon-wrench", 
				onClickButton: function()
				{ 
					DoBulkAction();
					return false;
				}, 
				position:"last",
				title:'Bulk Tool...'
			});
		}

		function InitBulkToolDlg()
		{
			var catAddList = '<option value="' + '-' + '">' + '-' + '</option>';
			var catRemoveList = '<option value="' + '-' + '">' + '-' + '</option>';
			for (var i = 0; i < categoryNames.length; i++) 
			{
				catAddList += '<option value="' + categoryNames[i] + '">' + categoryNames[i] + '</option>';
				catRemoveList += '<option value="' + categoryNames[i] + '">' + categoryNames[i] + '</option>';
			}
			$('#bt-cat-add').html(catAddList);
			$('#bt-cat-delete').html(catRemoveList);
			var fieldsEdit = get_editable_columns();
			$('#bt-field-set').html(fieldsEdit);
			onBulkFieldChange();
		}
		
		function DoBulkAction()
		{
			var rowKey = jQuery("#domain_table").getGridParam("selarrrow"); 
			if(rowKey != null && rowKey.length > 0) 
			{
				if(rowKey.length == 1)
					$('#bt-domain-info').html("<p>" + rowKey.length + " domain selected.</p>");
				else
					$('#bt-domain-info').html("<p>" + rowKey.length + " domains selected.</p>");
				$('#dialog-bulk-action').dialog('open');
			}
		}
		
		function get_editable_columns()
		{
			var columns = jQuery("#domain_table").getGridParam("colModel");
			var colnum = columns.length;
			var showText = '<option value="f-none">-</option>\n';
			for(i = 0; i < colnum; i++)
			{
				if(columns[i].name != "rn" && columns[i].name != "cb" && columns[i].name != "r_h_disp" 
				&& columns[i].name != "notes_a" && columns[i].name != "notes_b" && columns[i].name != "notes_c" && columns[i].name != "notes_d")
				{
					var edt = columns[i].editoptions;
					var readonly = false;
					var editable = false;
					var label = columns[i].name;
					if(typeof columns[i].label !== 'undefined')
						label = columns[i].label;
					if(typeof columns[i].editable !== 'undefined')
						editable = columns[i].editable;
					if (typeof edt !== 'undefined') 
					{
						if (typeof edt.readonly !== 'undefined') 
							readonly = edt.readonly;
					}
					if(readonly === false && editable === true)
						showText += '<option value="f-' + columns[i].name + '">' + label + '</option>' + '\n';
				}
			}
			return showText;
		}
		
		function onBulkFieldChange()
		{
			var ftype = $("#bt-field-set").val().toLowerCase();
			if(ftype == "f-none")
				$("#field_set").attr('disabled', 'disabled'); 
			else
				$("#field_set").removeAttr('disabled'); 
		}
		
		function addCSVTableDownloadButton()
		{
			$("#domain_table").navSeparatorAdd("#domain_pager",{})
			.navButtonAdd('#domain_pager',
			{
				caption:"", 
				buttonicon:"ui-icon-arrowthickstop-1-s", 
				onClickButton: function()
				{ 
					$('#dialog-csv-download').dialog('open');
					return false;
				}, 
				position:"last",
				title:'Download CSV...'
			});
		}

		function csvWrapQuotes(ptext)
		{
			if(typeof ptext === 'undefined' || ptext == "" || ptext == null)
				return "";
			else
			{
				ptext = ptext.trim();
				if(ptext.indexOf("\"") > -1)
				{
					while (ptext.indexOf("\"") > -1)
						ptext = ptext.replace("\"", "{{^&}}")
					while (ptext.indexOf("{{^&}}") > -1)
						ptext = ptext.replace("{{^&}}", "\"\"")
					return '"' + ptext + '"';
				}
				if (ptext.indexOf(",") > -1 || ptext.indexOf("'") > -1)
				   return '"' + ptext + '"';
				 return ptext;
			}
		}

		function downloadRows(dlType)
		{
			var rowText = "";
			var tablecolumns = [];
			var columns = jQuery("#domain_table").getGridParam("colModel");
			var colnum = columns.length;
			
			if(dlType != "alldomainnames" && dlType != "selecteddomainnames")
			{
				for(i = 0; i < colnum; i++)
				{
					if(columns[i].name != "rn" && columns[i].name != "cb" && columns[i].name != "r_h_disp")
					{
						tablecolumns.push(columns[i].name);
						var label = columns[i].label;
						rowText += csvWrapQuotes(label);
						if(i !== (colnum-1))
							rowText += ",";
						else
							rowText += "\n";
					}
				}
			}
			
			var clen = tablecolumns.length;
			var rowKey;
			if(dlType == "selectedrows" || dlType == "selecteddomainnames")
				rowKey = jQuery("#domain_table").getGridParam("selarrrow");
			else if(dlType == "allrows" || dlType == "alldomainnames")
				rowKey  = jQuery("#domain_table").getDataIDs(); 
			var rl = rowKey.length;
			for(i = 0; i < rl; i++)
			{
				var rowData = jQuery("#domain_table").jqGrid ('getRowData', rowKey[i]);
				if(dlType != "alldomainnames" && dlType != "selecteddomainnames")
				{
					for(j = 0; j < clen; j++)
					{
						if (typeof tablecolumns[j] != 'undefined') 
						{
							var entry = rowData[tablecolumns[j]];
							rowText += csvWrapQuotes(entry);
						}
						else
							rowText += "-";
						if(j != (clen-1))
							rowText += ",";
						else
							rowText += "\n";
					}
				}
				else if(typeof rowData['domain'] != "undefined")
					rowText += rowData['domain'] + "\n";
			}
			
			var posturl = "lib/php/dnloadcsv.php";
			if(dlType == "alldomainnames" || dlType == "selecteddomainnames")
				posturl += "?txt";
			$("#csvdnload").append('<form id="exportform" action="' + posturl + '" method="post"><input type="hidden" id="exportdata" name="exportdata"></form>');
			$("#exportdata").val(rowText);
			$("#exportform").submit().remove();
			return true; 
		}
		
		function EnableCustomQuery()
		{
			if(custom_query == false)
			{
				$('#sql_text').val("Custom SQL is disabled because this installation is not password protected. Enable password protection to support custom SQL queries.");
				$('#sql_text').attr('disabled','disabled');
				$('#str_match').val("String match is disabled. See above.");
				$('#str_match').attr('disabled','disabled');
			}
		}

		$(function()
		{
			jQuery("#domain_table").jqGrid({
			url:'report.php?grid=',
			datatype: "json",
			altRows:true,
			altclass: "gridAltRowClass",
			scrollOffset: domGridScrollOffset,
			colModel: report_columns_array,
			rownumbers: true,
			rowNum:100,
			rowList:[50,100,250,500,1000,2000,3000,5000],
			height: '300',
			width: 960,
			pager: '#domain_pager',
			sortname: 'sid',
			viewrecords: true,
			sortorder: "desc",
			multiselect: true,
			multiboxonly:true,
			caption: "Domain Report Table"
			});
			jQuery("#domain_table").jqGrid('navGrid','#domain_pager',{search:false,edit:false,add:false,del:false});
			
			$("#domain_display_button").button().click(function() 
			{
				reload_grid(false, false);
			});
			$("#domain_download_button").button().click(function() 
			{
				reload_grid(true, true);
			});
			$("#csv_download_button").button().click(function() 
			{
				reload_grid(true, false);
			});
			
			$("#str_match").keydown(function(event) 
			{
				if(!HandleEnterKey(event, "domain_display_button"))
					return false;
			});
			$("#cat_names").keydown(function(event) 
			{
				if(!HandleEnterKey(event, "domain_display_button"))
					return false;
			});
			
			$("#BulkViewPane").splitter({
				splitHorizontal: true,
				outline: true,
				sizeTop: true,
				anchorToWindow: true,
				//cookie: "bulksplitter",
				//cookiePath: '/',
				accessKey: "I"
			});
			$("#bulktoolbox").bind('resize', function() { $("#domain_table").setGridHeight($("#bulkgrid").height()-100);	}).trigger('resize');
			$(window).bind('resize', function() {
				$("#domain_table").setGridWidth($(window).width()-20);
				$("#domain_table").setGridHeight($("#bulkgrid").height()-100);
			}).trigger('resize');
			
			addBulkToolButton();
			addCSVTableDownloadButton();
			InitBulkToolDlg();
			EnableCustomQuery();
			$( "#csv-download-radio" ).buttonset();
			
			$("#dialog-bulk-action").dialog(
			{
				resizable: false,
				autoOpen: false,
				width: 400,
				modal: true,
				buttons: 
				{
					Clear: function() {
						clear_form_elements("#bulk-action-form");
						$("#bt-notes-a").focus();
					},
					'OK': function() {
						var rowKey = jQuery("#domain_table").getGridParam("selarrrow"); 
						var lurl = "lib/php/bulktool.php?" + "id=" + rowKey;
						lurl += "&notes_a=" + $("#bt-notes-a").val();
						lurl += "&notes_b=" + $("#bt-notes-b").val();
						lurl += "&notes_c=" + $("#bt-notes-c").val();
						lurl += "&notes_d=" + $("#bt-notes-d").val();
						lurl += "&cat_add=" + $("#bt-cat-add").val();
						lurl += "&cat_delete=" + $("#bt-cat-delete").val();
						lurl += "&bt-field-set=" + $("#bt-field-set").val(); 
						lurl += "&field_set=" + $("#field_set").val();
						//alert(lurl);
						$.ajax({
							type: "GET",
							cache: false,
							url: lurl,
							success: function(html)
							{
								jQuery("#domain_table").trigger("reloadGrid"); 
							}
						});
						$(this).dialog('close');
					},
					Cancel: function() {
						$(this).dialog('close');
					}
				}
			});
			
			$("#dialog-csv-download").dialog(
			{
				resizable: false,
				autoOpen: false,
				width: 450,
				
				modal: true,
				buttons: {
					'Download': function(event) {
						event.preventDefault();
						downloadRows($("#csv-download-radio :radio:checked").attr('id'));
					},
					'Cancel': function() {
						$(this).dialog('close');
					}
					
				}
			});
			
			$("#bt-field-set").change(function() 
			{
				onBulkFieldChange();
			});
		});
		
		</script>
<?php
		if(get_main_logo_image() != "")
			echo "\t\t<style> .mainlogo {background-image: url('" . get_main_logo_image() . "');}</style>\n";
?>
</head>
<body>
	<div id="header">
		<div class="mainlogo">&nbsp;</div>
		<div class="navbar">
				<button id="menu"></button>
				&nbsp;&nbsp;
				<button id="pfolio"></button>
				&nbsp;&nbsp;
				<button id="runq"></button>
		<?php
			if(is_admin_user())
			{
		?>
				<button id="subdomains"></button>
				<button id="config"></button>
				<button id="appsetup"></button>
				<button id="admin"></button>
		<?php
			}
			show_link_buttons();
			if(is_user_auth_enabled())
			{
		?>
				&nbsp;&nbsp;
				<button id="logout"></button>
		<?php
			}
		?>
		</div>
		<div class="clear">&nbsp;</div>
	</div>
	
	<div id="BulkViewPane">
		<div id="bulktoolbox" style="margin:10px;">
			<div class="toolcontainer">
				<div class="controlbox" style="width:600px;float:left;position: relative; display:inline;">
					<p><label for "sql_text">Custom SQL</label> 
					<textarea id="sql_text" rows="5" style="width:400px;"></textarea></p>
					
					<p><label for "cat_names">Category Names</label>
					<input type="text" id="cat_names" name="cat_names" rows="5" value="" style="width:400px;"></p>
					
					<p><label for "str_match">String Match</label>
					<input type="text" id="str_match" name="str_match" rows="5" value="" style="width:400px;"></p>
					
					<p><label for "buttons">&nbsp;</label>
					<button id="domain_display_button" style="width:80px; font-size:62.5%;">Refresh</button>
					<button id="csv_download_button" style="width: 130px; font-size:62.5%;">Download (CSV)</button>
					<button id="domain_download_button" style="width:180px; font-size:62.5%;">Download Domain Names</button></p>
				</div>
				<div class="infobox" style="width:360px; font-size:85%; float:left; position: relative; display:inline;font-family:Tahoma,Verdana,Arial; text-align:justify">
					<p>Please see the documentation for details on how to use the custom SQL box.</p>
					<p>To find domains that belong to any of a number of categories, type in the different category names (seperated by commas).
					To find domains that contain specific words, type in the words into the 'String Match' box (separate different words with commas).</p>
					<p>You can use 'Basic App Setup' to select the columns that are displayed in the 'Domain Report Table' below.</p>
				</div>
				<div style="clear:both;"></div>
			</div>
		</div>
		<div id="bulkgrid" style="padding:10px;">
			<table id="domain_table"></table>
			<div id="domain_pager"></div>
		</div>
	</div>
	
	<div id="dialog-bulk-action" title="Bulk Action Tool">
		<form id="bulk-action-form">
			<div style="padding: 2px;">
				<h4>Bulk set data &amp; categorize selected domain(s).</h4>
				<br>
				<label for notes_a>Notes-A: &nbsp;</label>
				<input type="text" name="notes_a" id="bt-notes-a"><br><br>
				<label for notes_b>Notes-B: &nbsp;</label>
				<input type="text" name="notes_b" id="bt-notes-b"><br><br>
				<label for notes_c>Notes-C: &nbsp;</label>
				<input type="text" name="notes_b" id="bt-notes-c"><br><br>
				<label for notes_d>Notes-D: &nbsp;</label>
				<input type="text" name="notes_d" id="bt-notes-d"><br><br>
				<label for field_set><select id="bt-field-set"></select></label>
				<input type="text" name="field_set" id="field_set"><br><br>
				<br>
				
				<label for cat_add>Add to Category: &nbsp;</label>
				<select id="bt-cat-add">
				</select>
				<br><br>
				
				<label for cat_delete>Remove from Category: &nbsp;</label>
				<select id="bt-cat-delete">
				</select>
				<br><br>
				<div id="bt-domain-info"></div>
				<p class="warning">Please be careful with this tool. It is very easy to mistakenly overwrite the 
				note and other columns while using this. Double check all the entries before pressing 'OK'.</p>
			</div>
		</form>
	</div>
	
	<div id="dialog-csv-download" title="CSV File Download">
		<br>
		<h3 class="center">Select What To Download and then Click 'Download'</h3>
		<div id="csvdnload"></div>
		<br><br>
		<form>
			<div style="text-align:center;">
				<div id="csv-download-radio">
					<input type="radio" id="selectedrows" name="csv-download-radio"><label for="selectedrows">Selected Rows</label>
					<input type="radio" id="allrows" name="csv-download-radio" checked="checked"><label for="allrows">All Rows</label>
					<input type="radio" id="selecteddomainnames" name="csv-download-radio"><label for="selecteddomainnames">Selected Names</label>
					<input type="radio" id="alldomainnames" name="csv-download-radio"><label for="alldomainnames">All Names</label>
				</div>
			</div>
		</form>
		<br><br>
	</div>
		
</body>
</html>
<?php
?>
