#!/usr/bin/perl
# (c) 2007 James Robson

use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);


use lib './Trillbox';
use Template::Recall;

# Load our TR widgets from here
use lib '.';
use Trillbox::SelectBox;
use Trillbox::DataTable;
use Trillbox::TextBox;
use Trillbox::AutoPost;
use Trillbox::Input;
use Trillbox::Calendar;
use Trillbox::ContentRotator;



print header;



# Show parameters:
my $form_data;
for (param) {
	$form_data .= "\t$_=" . param($_) . "\n";
}




# Setup AutoPost object

my $ap = Trillbox::AutoPost->new();






##################### Calendar widget

my $cal = Trillbox::Calendar->new();

# Custom link pattern (uses AutoPost):
$cal->set( linkpat => '<a href="javascript:' . $ap->autopost_code( 'date:<%DATE%>' ) . '"><%DAY%></a>'  );



# Set user selected date

my $selected_date;
if ( param('trillbox_autopost') =~ /^date:/ ) {
	my @t = split( /:/, param('trillbox_autopost') );
	$selected_date = $t[1];
}
else {		# Or, retain previously selected date:
	$selected_date = param('selected_date');
}



# Custom Autopost for month change

my $navpat = $cal->get('navpat');

my $chgmo = 'javascript:' . $ap->autopost_code( 'change_date:<%PREV%>' );
$navpat =~ s/\?tr_change=<%PREV%>/$chgmo/g;

$chgmo = 'javascript:' . $ap->autopost_code( 'change_date:<%NEXT%>' );
$navpat =~ s/\?tr_change=<%NEXT%>/$chgmo/g;

$cal->set( navpat => $navpat );

my $current_month;
if ( param('trillbox_autopost') =~ /^change_date:/ ) {
	my ($l, $r) = split(/:/, param('trillbox_autopost') );
	$current_month = $r;
}
else {
	$current_month = param('current_month');
}

$cal->set( change_month => $current_month ) if defined($current_month);








##################### Output selection boxes

my $sb1 = Trillbox::SelectBox->new();

$sb1->set(
	attrs => { 
		name => 'probcat',
		onChange => $ap->autopost_code('catchange')
	}
);


$sb1->set( sort_keys => 'y' );

$sb1->set( data => { '' => '', 'Web' => 'Web', 'Email' => 'Email' } );

$sb1->set( selected => param('probcat') );




my $sb2 = Trillbox::SelectBox->new();

$sb2->set( attrs => { 
			name => 'probsubcat',
			onChange => $ap->autopost_code('subcatchange'),
			size => '4'
		} 
);

my %subcats = (
	'CGI error' => 'Web - cgi',
	'Domain name' => 'Web - dns',
	'Connectivity' => 'All - network',
	'Hacked' => 'Web - hacked',			
	'Spam' => 'Email - spam',
	'Account problem' => 'All - accounts',
	'Mail client' => 'Email - mail client'
);
my %sc2; # Manipulated by cat_change()

$sb2->set( data => cat_change() );


#$sb2->set( data => undef );	# Show default output from widget
$sb2->set( selected => param('probsubcat') );





##################### Textbox input


# Simple input box

my $tb2 = Trillbox::TextBox->new();

$tb2->set( 
	attrs => {
		name => 'subject',
		style => 'font-family:sans-serif;font-size:10pt'
	}
);

$tb2->set( text => param('subject') );



# Textarea

my $tb1 = Trillbox::TextBox->new();



$tb1->set( multiline => 'true' );
$tb1->set( 
	attrs => {
		name => 'descript',
		#cols => '40',
		#rows => '10',
		#onChange => "javascript:alert('helo');",
		style => 'font-family:sans-serif;font-size:10pt;width:300px;height:150px'
	}
);

$tb1->set( text => param('descript') );





##################### Some additional options

my $inp = Trillbox::Input->new();

$inp->set(
	attrs => {
		name => 'severity',
		type => 'radio',
		#onChange => $ap->autopost_code('severitychange')
	}
);

my $severity;

my %sv = (
	1 => 'low',
	2 => 'moderate',
	3 => 'high',
	4 => 'higher',
	5 => 'highest'
);

for my $k (sort keys %sv) {
	$inp->set( 'text_on_right' => $sv{$k} );
	$inp->set( attrs => { value => $k } );

	if (param('severity') == $k) {
		$inp->set( attrs => { checked => 'checked' } )
	}
	else {
		$inp->clear_attr('checked');
	}

	$severity .= $inp->output();
}



##### Change input object to handle a checkbox from an array:

$inp->set(
	field_enum => 1,
	attrs => {
		name => 'sys_details',
		type => 'checkbox',
		#onChange => $ap->autopost_code('syschange')
	}
);


my @sys_details_opts = (
	'Windows', 'Linux', 'MacOS', 'Outlook', 'IE', 'Safari', 'Firefox', 'Thunderbird'
);

my $sys_details;

my $count = 1;


# Loop through array of options, build output based on options checked

for ( @sys_details_opts ) {
	$inp->set( 'text_on_right' => $_ );
	$inp->set( attrs => { value => $_ } );


	if (defined param('sys_details' . $count)) {
		$inp->set( attrs => { checked => 'checked' } )
	}
	else {
		$inp->clear_attr('checked');
	}	

	# Append for template output below

	$sys_details .= $inp->output();	
	$count++;
}






##################### Output data table

my $dt1 = Trillbox::DataTable->new();
$dt1->set( table_attrs => 'class="prevprob"' );
#print $dt1->get( 'template_path' );
$dt1->set( colnames => [ 'Category', 'Problem', 'Date', 'Description' ] );
$dt1->set( bind_data => form_submission() );







##################### Content rotation
my $cr = Trillbox::ContentRotator->new('controt');
#$cr->set( load => "sequential"); # Random, unless this is uncommented






##################### Output page with widgets

my $tr = Template::Recall->new( template_path => 'template1.html');

my %h = (
	'form_data' => $form_data,
	'trillbox autopost handler' => $ap->output_handler(),
	'trillbox flag field' => $ap->output_flag(),
	'trillbox autopost submit' => $ap->submit_button(),
	'submit handler' => 'default.cgi',
	'trouble category' => $sb1->output(),
	'trouble subcategory' => $sb2->output(),
	'previous tickets' => $dt1->output(),
	'description' => $tb1->output(),
	'subject' => $tb2->output(),
	'severity' => $severity,
	'sys_details' => $sys_details,
	'date_selector' => $cal->output(),
	'selected_date' => $cal->nm_date($selected_date),
	'current_month' => $current_month,
	'content_rotator' => $cr->output()
);

print $tr->render('main', \%h);








# Handles form submission (i.e. field trillbox_autopost = "submit")
# Add a row to previous tickets

sub form_submission {

	my @default_array = (
		['Web', 'hacked', '4/1/2007', 'Breached through forum' ],
		['Email', 'accounts', '4/1/2007', 'Time-outs' ]
	);

	if ( param('trillbox_autopost') eq 'submit' ) {

		# Handle system options:
		my @sys_det;
		for ( my $i=0; $i <= $#sys_details_opts; $i++ ) {
			if ( defined param('sys_details' . ($i+1) ) ) {
				push(@sys_det,  param( 'sys_details' . ($i+1) ) );
			}
		}

		push( @default_array, 
			[ 
				param('probcat'), 
				param('probsubcat'), 
				$cal->nm_date( param('selected_date') ), 
				
				'<u>' . param('subject') . ':</u> (' .
				'SEVERITY: ' . param('severity') . ')' .
				'<p>' . param('descript') . '</p>' .
				'[' . join(", ", @sys_det) . ']' ] )

	}

	return \@default_array;
}




# When category is changed, modify the "Problem", or 
# sub-category dropdown options

sub cat_change {
	return \%subcats if param('probcat') eq '';


	for my $k ( keys %subcats ) {
		my $p = param('probcat');
		next unless $subcats{$k} =~ /^$p|All/;
		$sc2{$k} = $subcats{$k};
	}

	return \%sc2;
}




syntax highlighted by Code2HTML, v. 0.9.1