#!/usr/bin/perl -w
use lib "/usr/home/tphilli1/usr/local/lib/site_perl/" ;



#check for errors
use CGI::Carp qw(fatalsToBrowser);
###################################################################
#spaceweatherdotcom.pl, by joshua kitchener <joshua@spacescience.com>
###################################################################
#THIS SCRIPT SERVES AS THE SPACEWEATHER.COM HOMEPAGE
#
#THE SCRIPT IS BASICALLY A 4-STEP PROCESS:
#
#1. ASSEMBLE A FILENAME IN SPACEWEATHER ARCHIVE
#FORMAT BASED ON THE MENU SELECTIONS, OR LOAD INDEX.HTML
#IF NO PARAMETERS WERE SENT
#
#2. IF ITS INDEX.HTML, RUN THE CONTENTS THROUGH A CLEVER
#SSI REPLACE FUNCTION
#
#3. CREATE AN INSTANCE OF THE TREEBUILDER OBJECT AND SELECT
#THE IMPORTANT ELEMENTS OF THE FILE
#
#4. DISPLAY IT
#
#THAT'S REALLY IT, PLUS SOME FUNCTIONS TO CREATE
#DYNAMIC DROP MENUS, ETC.
#################################################################
#################################################################

#BE VERY CAREFUL USING FIND AND REPLACE SINCE THERE ARE STRINGS,
#SUCH AS 'IMAGES', IN THE LOGIC


#WE NEED TO PLACE THE TEXT/HTML HEADER AT THE TOP


#use warnings;
#use strict;
use LWP::UserAgent;
use CGI qw(:standard);
use HTML::TreeBuilder;

#this is for a date function
use POSIX qw(strftime);










#################################################################

# Exec: Usage: <!--#exec command -->
#$stuff =~s/<!--#exec (.*?) -->/`$1`/eg;




# Dain Bramaged Server Side Include Engine.  Only handles includes.
#
# ssi_replace("Some HTML Text, potentially with SSI")
sub ssi_replace($) {
        my $text = shift;

        $text =~ s/<!--#include file="(.*?)" ?-->/read_file("$1")/eg;

        return $text;
}



# $doc_root is nothing more than the document root for the webserver this is on...
# it's like a "Well, if hte file isn't right here, lets make a halfassed guess" kinda thing.
#
sub read_file {
        my $file = shift;
        my $html="";
		
		#this is my hack
		$doc_root = '..';

        if (!$file) { return "Readfile: Empty template filename"; }
        elsif ( $doc_root && ( -e "$doc_root/$file") ) { $file ="$doc_root/$file"; }

        if (open(FILE, "<$file") ) {
                $html =join ("", <FILE>);
                close(FILE);
                return $html;
        } else {
                return "Couldn't open file $file: $!\n";
        }
}

#################################################################




#################################################################
#these are our arrays and vars

%all_the_months = ('January' => '01', 'February' => '02', 'March' => '03', 'April' => '04', 'May' => '05', 'June' => '06', 'July' => '07', 'August' => '08', 'September' => '09', 'October' => '10', 'November' => '11', 'December' => '12');


@all_month_keys = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');


#@all_month_values = ('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');


#this is a list of all the years which have been archived
@all_the_years = (2000, 2001, 2002, 2003, 2004);


#learn to create a two-digit range...
@all_the_days = ('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', 
'21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31');



#################################################################
#THIS IS DAMN IMPORTANT
print "Content-type: text/html\n\n";
#################################################################





#set this to gmtime after testing
#why does setting to gmtime make it so people who enter
#todays date are taken to 1/1/2000?
$todays_date_string = strftime(qq(%Y %m %d), gmtime);
@todays_date_array = split(' ', $todays_date_string);

#print "todays year is $todays_date_array[0]";
$todays_day = $todays_date_array[2];
$todays_month = $todays_date_array[1];
$todays_year = $todays_date_array[0];





#WE NEED TO MAKE SURE THE INDEX PAGE LOADS IF THEY
#SELECT TODAY'S DATE

#this script is running as a cgi
if(param('view') && param('day').param('month').param('year') != $todays_day.$todays_month.$todays_year){ 

	

	#first, check if we received the pertinent variables
	#if we received date vars and the date is NOT todays date
	#if(!($day && $month && $year)){
		#print "Error: didn't receive day month and year";
		
		#CAN WE USE THIS IN PERL?
		#exit;
		#WERE
	#}



	
	$month = param('month');
	$day = param('day');
	$year = param('year');
	

	

	#create the url
	$url = 'index_'.$year.$month.$day.'.html';
	#print "URL is $url\n";
	

	
	
}


















#else it was not submitted but just called
#like with the view todays page link
else{

	#this is kind of a kludge - grrr
	$month = $todays_month;
	$day = $todays_day;
	$year = $todays_year;

	$url = 'index.html';

}

	
	
	#WHY MUST THIS URL BE ABSOLUTE??
	$absolute_url = 'http://207.44.247.128'.'/'.$url;
	
	

	##########################################
	#Commented out for now	
	#open the file
	#open (INFILE, "+<$url") || die("Couldn't open file\n");
    	#@contents_array = <INFILE>;
	#$contents = join(' ',@contents_array);
	##########################################

	



	##########################################
	#intialize the user agent
	$browser = LWP::UserAgent->new;


	$response = $browser->get("http://spaceweather.com/$url");

	##########################################
	

	


	#if it was successful fetching the file
	

	if($response->is_success){


		$contents = $response->content;

			
		#call stout's cool subroutine - commenting this out for now
		#$contents = ssi_replace($contents);


	
		#create a new treebuilder
		#IT MUST BE DONE THIS WAY TO BE ABLE TO USE STORE_COMMENTS - IMPORTANT
		$tree = HTML::TreeBuilder->new();
	
		$tree->store_comments(1);

		
		#Don't try to delete whitespace between block-level elements
		$tree->ignore_ignorable_whitespace(0);
  
		
		#Don't smash every whitespace sequences into a single space
		$tree->no_space_compacting(1);

	

		$tree->parse($contents);

	

	

	
	
		#################################################################
		#now we're finding the page elements
		#we have to search for each important element individually
		#because of a strange bug preventing me from just selecting the body element
		#we could just match the body element and use look_down()
	
		#this should be the small column
		$small_column = $tree->find_by_attribute('width', 181);

	
		#this is the large column
		$large_column = $tree->find_by_attribute('width', 418);

		#this homes in on the essential links table
		$essential_links_bg = $tree->find_by_attribute('bgcolor', '#002255');
		
		#now we have to go two parents up to select the whole essential links table
		$essential_links_parent = $essential_links_bg->parent();
		$essential_links_table = $essential_links_parent->parent();


		#the bottom of the page is the last <CENTER> element
		@bottom_table_arr = $tree->find_by_tag_name('center');


		#this is Tony's disclaimer, which apparently is always the last occurence of attribute CELLSPACING="2"
		@tony_disclaimer_arr = $tree->find_by_attribute('cellspacing', 2);

	
		#this is the top 100 graphics table - NOT ALL PAGES HAVE THIS
		#@top_graphics_arr = $tree->find_by_attribute('width', 486);



		#THESE ARE OUR MODIFICATIONS TO THE BASIC DESIGN

		#$large_column->attr('width', '435');
		$small_column->attr('width', '162');

		#now get rid of the black horizontal line
		$vertical_line_graphic = $tree->find_by_attribute('src', 'images/new/newdot.gif');
		$vertical_line_graphic->delete;


		# done parsing for this tree
		$tree->eof(  );
	
		#################################################################	



	}







	

	#else if it was not a successful fetch
	else{
		$error_message = "<table width='100%' border='0' cellspacing='0' cellpadding='0'>
            <tr> 
              <td><img src='temp_images/blankie.gif' width='10' height='25'></td>
            </tr>
          </table><b><font color='#FF0000'>I'm sorry, there is no archive available for the date you selected. Please choose another.</font> </b>";
	}
	






print "<html>
<head>
<title>SpaceWeather.com -- News and information about meteor showers, solar flares, auroras, and near-Earth asteroids</title>
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>
<link rel='stylesheet' href='swdotcom_new_styles.css' type='text/css'>
</head>

<body bgcolor='#FFFFFF' text='#000000' leftmargin='5' topmargin='2' marginwidth='5' marginheight='2'>
<form name='form1' method='post' action='perlpage.cgi'>
<div align='center'>
<img src='temp_images/narrow_spacew_header.gif' width='732' height='67'> 
<table width='737' border='0' cellspacing='0' cellpadding='0'>
  <tr> 
    <td valign='top'>
<table width='100%' border='0' cellspacing='5' cellpadding='0'>
<tr>"; 



	 
	#################################################################
	#CONTENTS ARE DISPLAYED HERE
	#print the error message if no edition is found
	if($error_message){
		print $error_message;
		
	}
	
	
	
	  
	else{
		print $small_column->as_HTML(), "\n";
		
		
		print $large_column->as_HTML(), "\n";


	}
	#################################################################



#this is needed to format the columns correctly
print "</tr>
</table>
<div align='center' >";


		

	#################################################################
	#MORE PAGE CONTENT HERE

		if(!($error_message)){
	
			print $essential_links_table->as_HTML(), "\n";



			print "<table width='100%' border='0' cellspacing='0' cellpadding='0'>
            	<tr> 
              	<td><img src='temp_images/blankie.gif' width='10' height='25'></td>
            	</tr>
          	</table>";


			print $tony_disclaimer_arr[-1]->as_HTML(), "\n";


			print "<table width='100%' border='0' cellspacing='0' cellpadding='0'>
            	<tr> 
              	<td><img src='temp_images/blankie.gif' width='10' height='25'></td>
            	</tr>
          	</table>";



			print $bottom_table_arr[-1]->as_HTML(), "\n";

		}


	#################################################################






print "</div>
	</td>
    <td width='137' valign='top'> 
      <div align='right'> 
        <table bgcolor='#ffffff' border='0' cellpadding='0' cellspacing='0' width='137'>
<table bgcolor='#ffffff' border='0' cellpadding='0' cellspacing='0' width='141'>



<!-- fwtable fwsrc='swdotcom_new_revers_slnotx2.png' fwbase='spacew_table.gif' fwstyle='Dreamweaver' fwdocid = '742308039' fwnested='0' -->
  <tr>
   <td><img src='temp_images/spacer.gif' width='4' height='1' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='10' height='1' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='97' height='1' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='12' height='1' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='18' height='1' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='1' height='1' border='0' alt=''></td>
  </tr>

  <tr>
   <td rowspan='11'><img name='spacew_table_r1_c1' src='temp_images/spacew_table_r1_c1.gif' width='4' height='3000' border='0' alt=''></td>
   <td colspan='4'><img name='spacew_table_r1_c2' src='temp_images/spacew_table_r1_c2.gif' width='137' height='5' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='1' height='5' border='0' alt=''></td>
  </tr>
  <tr>
   <td rowspan='2'><img name='spacew_table_r2_c2' src='temp_images/spacew_table_r2_c2.gif' width='10' height='34' border='0' alt=''></td>
    <td background='temp_images/spacew_table_r2_c3.gif'>
      <div align='center' class='viewArchive'>View archives:</div>
    </td>
   <td rowspan='2' colspan='2'><img name='spacew_table_r2_c4' src='temp_images/spacew_table_r2_c4.gif' width='30' height='34' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='1' height='20' border='0' alt=''></td>
  </tr>
  <tr>
   <td><img name='spacew_table_r3_c3' src='temp_images/spacew_table_r3_c3.gif' width='97' height='14' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='1' height='14' border='0' alt=''></td>
  </tr>
  <tr>
    <td colspan='3' background='temp_images/button_bg_swdotcom.gif'>
      <div align='center'>
	<select name='month' class='dropMenus'>";



#################################################################
#this displays dynamic menus
if(param('day') && param('month') && param('year')){

	foreach (@all_month_keys){
		if ($all_the_months{$_} == $month){

		#show it as the intial selection
		#notice the newlines at the end
		print "<option value='$all_the_months{$_}' selected>$_</option>\n";
		}														
		#else just show it as an select option
		else{
		print "<option value='$all_the_months{$_}'>$_</option>\n";
		}
	
	}

}


#else if they just loaded the page, so use today's month
else{
	foreach (@all_month_keys){
		if ($all_the_months{$_} == $todays_month){
			#show it as the intial selection
			#notice the newlines at the end
			print "<option value='$all_the_months{$_}' selected>$_</option>\n";
		}

		#else just show it as an select option
		else{
			print "<option value='$all_the_months{$_}'>$_</option>\n";
		}
	}

}
															#################################################################								






print "</select>
	</div>
    </td>
   <td rowspan='8'><img name='spacew_table_r4_c5' src='temp_images/spacew_table_r4_c5.gif' width='18' height='2961' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='1' height='25' border='0' alt=''></td>
  </tr>
  <tr>
   <td colspan='3'><img name='spacew_table_r5_c2' src='temp_images/spacew_table_r5_c2.gif' width='119' height='11' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='1' height='11' border='0' alt=''></td>
  </tr>
  <tr>
    <td colspan='3' background='temp_images/button_bg_swdotcom.gif'>
      <div align='center'>
	<select name='day' class='dropMenus'>";



#################################################################

if(param('day') && param('month') && param('year')){

	foreach (@all_the_days){
		if ($_ == $day){
		#show it as the intial selection
		#notice the newlines at the end
		print "<option value='$_' selected>$_</option>\n";
		}														
		#else just show it as an select option
		else{
		print "<option value='$_'>$_</option>\n";
		}
	
	}

}


#else if they just loaded the page, so use today's month
else{
	foreach (@all_the_days){
		if ($_ == $todays_day){
			#show it as the intial selection
			#notice the newlines at the end
			print "<option value='$_' selected>$_</option>\n";
		}

		#else just show it as an select option
		else{
			print "<option value='$_'>$_</option>\n";
		}
	}

}
														

#################################################################





print "</select>
	</div>
    </td>
   <td><img src='temp_images/spacer.gif' width='1' height='24' border='0' alt=''></td>
  </tr>
  <tr>
   <td colspan='3'><img name='spacew_table_r7_c2' src='temp_images/spacew_table_r7_c2.gif' width='119' height='11' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='1' height='11' border='0' alt=''></td>
  </tr>
  <tr>
    <td colspan='3' background='temp_images/button_bg_swdotcom.gif'>
      <div align='center'>
	<select name='year' class='dropMenus'>";





#################################################################

if(param('day') && param('month') && param('year')){

	foreach (@all_the_years){
		if ($_ == $year){
		#show it as the intial selection
		#notice the newlines at the end
		print "<option value='$_' selected>$_</option>\n";
		}														
		#else just show it as an select option
		else{
		print "<option value='$_'>$_</option>\n";
		}
	
	}

}


#else if they just loaded the page, so use today's month
else{
	foreach (@all_the_years){
		if ($_ == $todays_year){
			#show it as the intial selection
			#notice the newlines at the end
			print "<option value='$_' selected>$_</option>\n";
		}

		#else just show it as an select option
		else{
			print "<option value='$_'>$_</option>\n";
		}
	}

}
						

								
#################################################################




print "</select>
	</div>
    </td>
   <td><img src='temp_images/spacer.gif' width='1' height='24' border='0' alt=''></td>
  </tr>
  <tr>
   <td colspan='3'><img name='spacew_table_r9_c2' src='temp_images/spacew_table_r9_c2.gif' width='119' height='12' border='0' alt=''></td>
   <td><img src='temp_images/spacer.gif' width='1' height='12' border='0' alt=''></td>
  </tr>
  <tr>
    <td colspan='3' background='temp_images/button_bg_swdotcom.gif'>
      <div align='center'>";



#this is the submit button, obviously
print "<input type='submit' name='view' value='view' class='dropMenus'>";


print "</div>
    </td>
   <td><img src='temp_images/spacer.gif' width='1' height='24' border='0' alt=''></td>
  </tr>
  <tr>
    <td colspan='3' background='temp_images/spacew_table_r11_c2.gif' valign='top'>
      <table width='100%' border='0' cellspacing='0' cellpadding='0'>
        <tr> 
          <td><img src='temp_images/blankie.gif' width='10' height='20'></td>
        </tr>
      </table>
      <div align='center'><a href='perlpage.cgi?view_todays_page=1'><img src='temp_images/view_todays_button.gif' width='104' height='50' border='0'></a> 
        <table width='100%' border='0' cellspacing='0' cellpadding='0'>
          <tr> 
            <td><img src='temp_images/blankie.gif' width='10' height='25'></td>
          </tr>
        </table>
        <a href='submissions/index.php'><img src='temp_images/submit_your_images_button.gif' width='101' height='55' border='0'></a> 
        <table width='100%' border='0' cellspacing='0' cellpadding='0'>
          <tr> 
            <td><img src='temp_images/blankie.gif' width='10' height='25'></td>
          </tr>
        </table>
        <span class='redUmbrellaLink'>Support for SpaceWeather.com is provided 
        in part by:</span> 
        <table width='100%' border='0' cellspacing='0' cellpadding='0'>
          <tr> 
            <td><img src='temp_images/blankie.gif' width='10' height='3'></td>
          </tr>
        </table>
        <a href='http://science.nasa.gov'><img src='temp_images/sciatnasa_rebuilt.gif' width='101' height='107' border='0'></a> 
        <table width='100%' border='0' cellspacing='0' cellpadding='0'>
          <tr> 
            <td><img src='temp_images/blankie.gif' width='10' height='25'></td>
          </tr>
        </table>
        <a href='http://www.spaceweatherphone.com'><img src='temp_images/swphone_redgray_cresentban.gif' width='120' height='61' border='0'></a> 
        <table width='100%' border='0' cellspacing='0' cellpadding='0'>
          <tr> 
            <td><img src='temp_images/blankie.gif' width='10' height='25'></td>
          </tr>
        </table>
      </div>
      <table width='95%' border='0' cellspacing='0' cellpadding='0'>
        <tr> 
          <td> 
            <div align='center' class='redUmbrellaLink'>Software development and 
              graphics for Spaceweather.com is provided in part by<b><font color='#FF0000'> 
              <br>
              </font><a href='http://dot-comet.com'><font color='#FF0000'>Red 
              Umbrella</font></a>.</b></div>
          </td>
        </tr>
      </table>
    </td>
   <td><img src='temp_images/spacer.gif' width='1' height='2830' border='0' alt=''></td>
  </tr>
</table>




      </div>
    </td>
  </tr>
</table>
</div>
</form>
</body>
</html>";




	#################################################################
	#clear memory
	$tree->delete;