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

var current_selected_domain = "";
var current_lookup_type = "ip";

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

$(function()
{
	jQuery("#DomainHistoryTable").jqGrid({
		url: "../historygrid.php",
		datatype: "json",
		altRows:true,
		altclass: 'gridAltRowClass',
		scrollOffset: 18,
		rownumbers: true,
	   	colNames:['Domain'],
	   	colModel:[
			{name:'domain',width:25, align:"left",sortable:true, hidden:false, editable:false},
	   	],
	   	multiselect: false,
		//loadonce: true,
		sortname: 'tld',
		headertitles: true,
	   	caption: "Domains",
		pager: "#pagerDomainHistory",
		rowNum: 200,
		loadComplete: function()
		{
			jQuery("#ControlPane").trigger('resize');
			fixDomainDataGridSizes();
		},
		
		onSelectRow: function(ids) 	
		{
			selectDomain(ids);
		},
		
		onSelectAll: function() 	{}
	}).navGrid('#pagerDomainHistory',{add:false,edit:false,del:false,search:false});
	
	jQuery("#HistoryDataTable").jqGrid({
		url: "../historygrid.php?ecf=domain",
		datatype: "json",
		altRows:true,
		altclass: 'gridAltRowClass',
		scrollOffset: 18,
		rownumbers: true,
	   	colNames:['Domain', 'IP', 'Lookedup At'],
	   	colModel:[
			{label:'Domain', name:'domain',width:25, align:"left",sortable:true, hidden:false, editable:false},
			{label:'Value', name:'fvalue',width:25, align:"left",sortable:true, hidden:false, editable:false},
			{label:'Lookedup At', name:'Lookedup At',width:25, align:"left",sortable:true, hidden:false, editable:false}
	   	],
	   	multiselect: false,
		width: 300,
		//loadonce: true,
		sortname: 'tld',
		headertitles: true,
	   	caption: "Domains",
		pager: "#pagerHistoryData",
		rowNum: 200,
		loadComplete: function()
		{
			jQuery("#ControlPane").trigger('resize');
			fixDomainDataGridSizes();
		},
		
		onSelectRow: function(ids) 	
		{
		},
		
		beforeRequest: function() 
		{
			var lucode = 2;
			if(current_lookup_type == "gi")
				lucode = 32768;
			else if(current_lookup_type == "gpr")
				lucode = 32;
			var durl = "../historygrid.php?ecf=domain,ftype&ecv=" + current_selected_domain + "," + lucode + "&lut=" + current_lookup_type;
			jQuery("#HistoryDataTable").setGridParam({url:durl});
		},
		
		onSelectAll: function() 	{}
	}).navGrid('#pagerHistoryData',{add:false,edit:false,del:false,search:false});
	
	$("#ControlPane").bind('resize', function() { fixDomainDataGridSizes();	}).trigger('resize');
	
	jQuery("#DomainHistoryTable").jqGrid(
		'filterToolbar',{
			stringResult: true,searchOnEnter : false
		}
	);
	$('#DomainHistoryTabView').tabs();
	
	$("#lookup_type").change(function() 
	{
		var ftype = $("#lookup_type").val().toLowerCase();
		current_lookup_type = ftype;
		var label = "IP";
		if(ftype == "gi")
			label = "Google Index #";
		else if(ftype == "gpr")
			label = "Google PR";
		jQuery("#HistoryDataTable").jqGrid('setLabel', 2, label); 
		$("#HistoryDataTable").trigger('reloadGrid');
	});
	
	addCSVTableDownloadButton();
});


function selectDomain(ids)
{
	if(ids == null || ids == 0)
		current_selected_domain = "";
	else
	{
		current_selected_domain = jQuery("#DomainHistoryTable").getCell(ids, "domain"); 
		$("#HistoryDataTable").trigger('reloadGrid');
	}
}

function fixDomainDataGridSizes()
{
	var autoShrink = true;
	var bgap = 30+24;
	if($("#ControlPane").width() < 100)
		autoShrink = false;
	jQuery("#DomainHistoryTable").setGridWidth($("#ControlPane").width()-20, autoShrink); 
	jQuery("#DomainHistoryTable").setGridHeight($("#ControlPane").height()-66-bgap); 
	
	var cpheight = jQuery("#header").height() + 10;
	var dheight = $(window).height()-cpheight*4;
	jQuery("#HistoryDataTable").setGridWidth($("#ConfigPane").width()-50, autoShrink); 
	jQuery("#HistoryDataTable").setGridHeight(dheight-60); 
}

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

function addCSVTableDownloadButton()
{
	$("#DomainHistoryTable").navSeparatorAdd("#pagerHistoryData",{})
	.navButtonAdd('#pagerHistoryData',
	{
		caption:"", 
		buttonicon:"ui-icon-arrowthickstop-1-s", 
		onClickButton: function()
		{ 
			downloadRows('allrows');
			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("#HistoryDataTable").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")
			{
				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("#HistoryDataTable").getGridParam("selarrrow");
	else if(dlType == "allrows" || dlType == "alldomainnames")
		rowKey  = jQuery("#HistoryDataTable").getDataIDs(); 
	var rl = rowKey.length;
	for(i = 0; i < rl; i++)
	{
		var rowData = jQuery("#HistoryDataTable").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";
	}

	alert(rowText);
	var posturl = "../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; 
}

