jQuery( document ).ready( trInitSimilarReports );

var trAdvancedSearchConfiguration = {
    fields: [
		{name:"title"},
		{name:"rating"},
		{name:"creation"},
		{name:"modified"},
		{name:"author"},
		{name:"space"}
		],
    types: ["page"], 
	showExcerpts: true, 
	sortField: "title", 
	sortDir: "asc", 
	maxResults: 10, 
	rateThreshold: 0, 
	debug: false
};

function trInitSimilarReports()
{
	tDebug( 'Run some checks' );
	// Only execute on reporting screens
	if ( ! jQuery( 'body.action-viewpage' ).length ) return;
	// Don't execute on non-reports
	if ( tPageHasLabel( 'non-report' ) ) return;
	
	return; // Currently this functionality is broken
	
	tDebug( "Init similar reports" );

	// Testing: Only continue if Firebug is active (i.e. just for Simon & Guy)!!!
	if ( typeof window.loadFirebugConsole == "undefined" ) {
		return;
	}
	
	tDebug( "Running" );

	// Get the template HTML
	jQuery.get( '/custom-resources/templates/similar-reports.html', null, trBuildSimilarReportsArea, 'html' );
}

function trBuildSimilarReportsArea( tpl )
{
	jQuery( '#atb-contentdiv .wiki-content' ).append( tpl );
	trAdvancedSearchSubmit();
}

function trAdvancedSearchSubmit(form) {
	var thisForm = form;
	// Data switch
	var excludeSpaceKeys = false; // TODO: Find out how to set this in the form?    
	// Build the data sets (spaceKeys, label, metadata, queries)
	// Current space key
	var spaceKeys = [ space_key ];
	var metadata = {}; // Empty. Am I bovvered? No...
	// ...because this string is going to be our sole source of queries
	var query = jQuery( '#atb-titlediv h1' ).text() + " ";
	// Strip quotes and replace with spaces
	query = tStripQuotes( query, ' ' );
	// Use John's clever search singleton to ORify the query
	// (Conf default search approach is to Boolean AND the terms, which is irritating)
//	query = SearchQueryParser.normalise( query );
	// TEMPORARILY OVERRIDE THE SEARCH QUERY
	query = "report";
	// All the labels for this page
	jQuery( '#labelsList a.label' ).each( function () { query += " OR labelText:" + jQuery( this ).text() + " "; } );
	// Cut out all other pages
	query += ' NOT label:(+global?non-report) ';
	// Cut out the page itself
	// N.B. This code does NOT cope with quotes in titles.
	query += ' NOT title:"' + jQuery( '#atb-titlediv h1' ).text() + '"';
	tDebug( "Query: " + query );
	var queries = [ query ];
	var labels = [];
	// Build the field names
	var fieldNames = [];
	for (var i=0; i<AdvancedSearchConfiguration.fields.length; i++) if (AdvancedSearchConfiguration.fields[i]) {
		fieldNames.push( AdvancedSearchConfiguration.fields[i].name );
	}
	// Call DWR
	SearchDWR.doSearch(
		spaceKeys, 
		excludeSpaceKeys, 
		trAdvancedSearchConfiguration.types, 
		labels, 
		metadata, 
		queries, 
		fieldNames, 
		trAdvancedSearchConfiguration.showExcerpts, 
		trAdvancedSearchConfiguration.maxResults, 
		trAdvancedSearchConfiguration.rateThreshold,
	    { 
	    	callback: function (resultSet) {
	            // Display the similar reports
				trDisplaySimilarReports( resultSet );
	        }, 
	        errorHandler: function(errorString, exception) {
	            // Display the error
				trSimilarReportsError( errorString );
			} 
		}
	);
}

function trDisplaySimilarReports( result_set )
{
	for ( var i = 0; i < result_set.count; i++ ) {
		var report = result_set.results[ i ];
		var new_li_html = '<li><a href="' + report.link + '">' + report.title + '</a> (created: ' + report.creation.format("dd NNN yy") + ', last modified: ' + report.modified.format("dd NNN yy") + ')</li>';
		jQuery( '#tr_similar_reports' ).append( new_li_html );
	}
}

function trSimilarReportsError( msg )
{
	jQuery( '#tr_similar_reports' ).append( '<li><strong>Error:</strong> ' + msg + '</li>' );
}

