// JQuery dependant JS trickery for the Reports space

jQuery( document ).ready( trInit );

function trInit()
{
	trInitNewReport();
	trInitAccreditedBadge();
}

// Prepare for someone adding a new report
function trInitNewReport()
{
	// Get the template HTML
	jQuery.get( '/custom-resources/templates/new-report.html', null, trBuildNewReportWizard, 'html' );
}

function trBuildNewReportWizard( tpl )
{
	// Ensure we have the relevant button present (i.e. we're not on an editing screen, or whatever)
	if ( ! jQuery( 'body.layout-REPORTS #t-new-page a' ).length ) return;
	// Change #t-new-page to #tr-new-report-wizard
	jQuery( '#t-new-page' ).attr( 'id', 'tr-new-report' );
	// Duplicate the new page button onto the right hand nav
	jQuery( '#t-tools ul' ).prepend( '<li><a href="' + jQuery( '#tr-new-report a' ).attr( 'href' ) + '" id="t-new-page-sidebar">Add a new page</a></li>' );
	// Add the wizard panel
	jQuery( 'body' ).prepend( tpl );
	// Encourage the user to check the link
	tr_old_link = '';
	jQuery( '#tr_report_link' ).blur( trEncourageLinkCheck );
	jQuery( '#tr_report_link' ).focus( function () { jQuery( '#tr_link_check' ).remove(); } );
	// Hide it initially
	jQuery( '#tr-new-report-wizard-outer' ).hide();
	// The new report button should launch the wizard
	jQuery( '#tr-new-report' ).click( trToggleWizard );
	// The cancel button should remove the wizard
	jQuery( '#tr_cancel_link' ).click( function () { jQuery( '#tr-new-report-wizard-outer' ).slideUp( 'fast' ); return false; } );
	// On focus of a field, highlight that row
	jQuery( '#tr-new-report-wizard input' ).add( '#tr-new-report-wizard textarea' ).focus( function() { jQuery( this ).parents( '.form-row' ).addClass( 'current-row' ); } );
	jQuery( '#tr-new-report-wizard input' ).add( '#tr-new-report-wizard textarea' ).blur( function() { jQuery( this ).parents( '.form-row' ).removeClass( 'current-row' ); } );
	// Add the values we know into the relevant hidden fields
	var page_title = jQuery.trim( jQuery( '#atb-titlediv h1' ).text() );
	jQuery( '#tr_parentPageString' ).val( page_title );
	jQuery( '#tr_spaceKey' ).val( space_key );
	jQuery( '#tr_newSpaceKey' ).val( space_key );
	jQuery( '#tr_fromPageId' ).val( ceo_id );
	// On submission we need to do some stuff
	jQuery( '#tr-new-report-wizard form' ).submit( trNewReportSubmission );
	return
}

function trToggleWizard( hide ) 
{
	jQuery( '#tr-new-report-wizard-outer' ).slideToggle( 'fast' ).toggleClass( 'shown' );
	tDebug( 'checking' );
	if ( jQuery( '#tr-new-report-wizard-outer' ).hasClass( 'shown' ) ) {
		tDebug( 'Focussing' );
		setTimeout( "jQuery( '#tr_report_title' ).focus()", 200);
	}
	return false; 
}

function trEncourageLinkCheck()
{
	// Has the link changed?
	var tr_link = jQuery( '#tr_report_link' ).val()
	var link_changed = ( tr_old_link != tr_link );
	// Save the current link, so we can check it again
	tr_old_link = jQuery( '#tr_report_link' ).val();
	// If the link hasn't changed there's no need to continue
	if ( ! link_changed ) return;
	// Otherwise we can add a new link check thingy
	// Is there an existing link check thingy? If not, then add one
	jQuery( '#tr_report_link' ).parents( '.form-row' ).append( '<div id="tr_link_check"></div>' );
	jQuery( '#tr_link_check' ).html( 'Please click this to check your link works: <a href="" target="_blank">link to your report</a>. If it doesn\'t work, please correct it and retry.' );
	jQuery( '#tr_link_check a' ).attr( 'href', tr_link );
}

function trNewReportSubmission()
{
	// Reset errors
	jQuery( '#tr-new-report-wizard .form-row-has-errors' ).removeClass( 'form-row-has-errors' );
	jQuery( '#tr-new-report-wizard ul.errors' ).remove();
	// Validate
	has_errors = trNewReportValidation();
	if ( has_errors ) return false;
	// Concatenate
	var link = jQuery( '#tr_report_link' ).val();
	var description = jQuery( '#tr_description' ).val();
	var content;
	content = "h2. Report Description\n\n";
	content += description + "\n\n";
	// Link deliberately after the description, so that when Conf autosummarises 
	// it will pick up the description and not a file path.
	content += "h2. Link to the report file\n\n";
	content += "[" + link + "]\n\n";
	content += "h2. Archived Reports\n\n";
	content += "* _None known. Please edit this page and add each as a bullet point, with a link, as they are created/discovered._\n\n";
	content += "h2. Related Reports\n\n";
	content += "* _None known. Please edit this page and add each parent/sibling/child report as a bullet point, with a link, as they are created/discovered._\n\n";
	// Shove the content into the hidden field
	jQuery( '#tr_content' ).val( content );
	// The form will now continue to submit... 
}

function trNewReportValidation()
{
	var has_errors = false;
	// Must have a title
	var title = jQuery( '#tr_report_title' ).val();
	if ( ! jQuery.trim( title ) ) has_errors = trSetError( jQuery( '#tr_report_title' ), 'You must provide a title for the report.' );
	// If it has  title, the title mustn't contain any of the Confluence nominated naughty characters
	if ( jQuery.trim( title ) && ! trIsValidTitle( title ) ) has_errors = trSetError( jQuery( '#tr_report_title' ), 'Sorry, report titles cannot contain the following characters (:, @, /, \, |, ^, #, ;, [, ], {, }, <, >) or start with ($, .., ~)..' );
	// Must have a link to the report
	var link = jQuery( '#tr_report_link' ).val();
	if ( ! jQuery.trim( link ) ) has_errors = trSetError( jQuery( '#tr_report_link' ), 'You must provide a link to the report.' );
	// Must have a description
	var description = jQuery( '#tr_description' ).val();
	if ( ! jQuery.trim( description ) ) has_errors = trSetError( jQuery( '#tr_description' ), 'You must provide a description of the report.' );
	// Must have four labels
	var labels = jQuery( '#tr_labels_string' ).val().split( ' ' );
	if ( labels.length < 4 ) has_errors = trSetError( jQuery( '#tr_labels_string' ), 'You must provide at least four labels.' );
	return has_errors;
}

function trSetError( jqe, msg )
{
	var form_row = jqe.parents( '.form-row' );
	if ( ! form_row.find( 'ul.errors' ).length ) jqe.before( '<ul class="errors"></ul>' );
	form_row.find( 'ul.errors' ).append( '<li>' + msg + '</li>' );
	form_row.addClass( 'form-row-has-errors' );
	return true;
}

function trResetErrors()
{
	jQuery( this );
	jQuery( this ).find( '.ul.errors' ).remove();
}

function trIsValidTitle( title )
{
	return ! ( title.match(/^(\$|\.\.|~)/) || title.match(/[\:\@\/\\\|\^\#\;\[\]\{\}\<\>]/) );
}

function trInitAccreditedBadge()
{
	// Get the incoming links
	jQuery( '#t-pages-linking ul a' ).each( trIsAccredited );
}

function trIsAccredited()
{
	// Only execute on reporting screens
	if ( ! jQuery( 'body.action-viewpage' ).length ) return;
	// Don't execute on non-reports
	if ( tPageHasLabel( 'non-report' ) ) return;
	// Check the incoming links for the presence of the accreditation page
	var href = jQuery( this ).attr( 'href' );
	if ( tMatchesIncomingLink( href, 'Finance Department Accredited Reports' ) ) {
		trDisplayAccreditation();
	}
}

function trDisplayAccreditation()
{
	jQuery( '#atb-titlediv h1' ).after( '<p class="accredited"><img alt="Single Source of Truth - Accredited Report" src="/download/attachments/1114119/finance-accredited.gif" width="100" height="77" /></p>' );
}


