/*
   COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved.

   This class builds the diary interface.

   @site http://www.javaika.com
   @author Alexander Wait
   @version 2012-05-05
*/



import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;



//ESCA-JAVA0137:
public class PersonalDiaryGui extends JApplet implements FocusListener, ComponentListener
{
   private static final String copyright = "Copyright (c) 2012 by Alexander Wait - All Rights Reserved";
   
   private static final long serialVersionUID = 1L;
   
   
   static boolean runRestricted = false;
   
   
   private static final int SQL_TABLE_COLUMN_A = 0;
   
   private static final int SQL_TABLE_COLUMN_B = 1;
   
   private static final int SQL_TABLE_COLUMN_C = 2;
   
   private static final int SQL_TABLE_COLUMN_D = 3;
   
   private static final int SQL_TABLE_COLUMN_E = 4;
   
   private static final int SQL_TABLE_COLUMN_F = 5;
   
   private static final int SQL_TABLE_COLUMN_G = 6;
   
   private static final int SQL_TABLE_COLUMN_H = 7;
   
   
   private static final String NEWLINE_FLAG = "~";
  
   private static final int FRAME_SIZE_X = 590; 
   
   private static final int FRAME_SIZE_Y = 535;
   
   private static final int START_YEAR = 2010; 

   private static final int WHITE_COMPONENT = 255;

   
   private static final String DIARY_CLEAR_ADDRESS = "http://" + Domain.getDomain() 
   
   + "/bridge/personal-diary-table-clear.php" + Domain.getPort(); // Port:80
  
   
   private static final String ENTRY_CLEAR_ADDRESS = "http://" + Domain.getDomain() 

   + "/bridge/personal-diary-entry-clear.php" + Domain.getPort(); // Port:80
   
   
   private static final String DIARY_WRITE_ADDRESS = "http://" + Domain.getDomain() 

   + "/bridge/personal-diary-table-write.php" + Domain.getPort(); // Port:80
   
   
   private static final String ENTRY_WRITE_ADDRESS = "http://" + Domain.getDomain() 

   + "/bridge/personal-diary-entry-write.php" + Domain.getPort(); // Port:80
   
   
   private static final String DIARY_READ_ADDRESS = "http://" + Domain.getDomain() 

   + "/bridge/personal-diary-table-read.php" + Domain.getPort(); // Port:80
   
   
   private static final String ENTRY_READ_ADDRESS = "http://" + Domain.getDomain() 

   + "/bridge/personal-diary-entry-read.php" + Domain.getPort(); // Port:80
   
   
   //************************************** START INITIALISATION CODE **************************************//

   
   /**
    * Browser constructor.
    */
   public void init()
   {  
      String copyrightParam = getParameter("copyright");
      
      if ((copyrightParam == null) || !copyrightParam.equals(copyright)) 
      {
         Message.showMessage("Invalid Copyright", "WARNING", "warning"); 
      }       
       
      else if (!getDocumentBase().getHost().equals(Domain.getDomain())) 
      {
         Message.showMessage("Unauthorised Applet Use", "ERROR", "error");
      }
  
      else
      {      
         try {getToolkit().getSystemClipboard();}
          
         catch (java.security.AccessControlException e) {runRestricted = true;} 
         

         userId = getParameter("id"); userPw = getParameter("pw");
         
         initialiser(); includeResizeEvent(); setJMenuBar(menuBar); 
         
         setSize(FRAME_SIZE_X,FRAME_SIZE_Y);
      }
   }
   
   
   
   /**
    * GUI initializer.
    * ESCA-JAVA0076
    */
   private void initialiser()
   {   
      diary = new PersonalDiary(DateAndTime.returnYear());
      
      
      
      // Initialize content pane and layout.
      
      contentPane = getContentPane(); contentPane.setLayout(new GridLayout(1,2));
      
      
      
      // Initialize border GIO components.
      
      Border etchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED); 
      
      Border calendarBorder = BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY);  
      
      
      
      // Initialize text pane GUI components.
      
      monthDisplay = new JTextPane(); monthDisplay.setEditable(false);
      
      monthDisplay.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); 
      
      monthDisplay.setFont(new Font("Dialog", Font.PLAIN, 17));
      
      monthDisplay.setText(diary.getMonth(diary.getCurrentWeek()));
      
      monthDisplay.setPreferredSize(new Dimension(269, 30));
      
      
      yearDisplay = new JTextPane(); yearDisplay.setEditable(false);
      
      yearDisplay.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
      
      yearDisplay.setFont(new Font("Dialog", Font.PLAIN, 17));
      
      yearDisplay.setText(Integer.toString(DateAndTime.returnYear()));
      
      yearDisplay.setPreferredSize(new Dimension(269, 30));
      
      
      
      // Initialize text area GUI components.
      
      monday = new JTextArea(5, 22); monday.addFocusListener(this);
      
      monday.setLineWrap(true); monday.setWrapStyleWord(true);
      
      monday.setFont(new Font("Dialog", Font.PLAIN, 12));
      
      
      tuesday = new JTextArea(5, 22); tuesday.addFocusListener(this);
      
      tuesday.setLineWrap(true); tuesday.setWrapStyleWord(true);
      
      tuesday.setFont(new Font("Dialog", Font.PLAIN, 12));   
      
      
      wednesday = new JTextArea(5, 22); wednesday.addFocusListener(this);
      
      wednesday.setLineWrap(true); wednesday.setWrapStyleWord(true);
      
      wednesday.setFont(new Font("Dialog", Font.PLAIN, 12)); 
      
      
      thursday = new JTextArea(5, 22); thursday.addFocusListener(this);
      
      thursday.setLineWrap(true); thursday.setWrapStyleWord(true);
      
      thursday.setFont(new Font("Dialog", Font.PLAIN, 12));
      
      
      friday = new JTextArea(5, 22); friday.addFocusListener(this);
      
      friday.setLineWrap(true); friday.setWrapStyleWord(true);
      
      friday.setFont(new Font("Dialog", Font.PLAIN, 12)); 
      
      
      saturday = new JTextArea(5, 22); saturday.addFocusListener(this);
      
      saturday.setLineWrap(true); saturday.setWrapStyleWord(true);
      
      saturday.setFont(new Font("Dialog", Font.PLAIN, 12)); 
      
      
      sunday = new JTextArea(5, 22); sunday.addFocusListener(this);
      
      sunday.setLineWrap(true); sunday.setWrapStyleWord(true);
      
      sunday.setFont(new Font("Dialog", Font.PLAIN, 12));
      
      
      weekDisplay = new JTextArea(); weekDisplay.setEditable(false);
      
      weekDisplay.setFont(new Font("Dialog", Font.PLAIN, 20));
      
      weekDisplay.setText("Week 1");
      
      
      dayDisplay = new JTextArea(); dayDisplay.setEditable(false);
      
      dayDisplay.setFont(new Font("Dialog", Font.PLAIN, 40)); 
      
      dayDisplay.setPreferredSize(new Dimension (130,55));
      
      
      
      // Initialize menu bar GUI components.
      
      menuBar = new JMenuBar(); menuBar.add(createFileMenu()); menuBar.add(createDisplayMenu());
      
      saveMenuItem.setEnabled(false); clearMenuItem.setEnabled(false);

      
      
      // Initialize scroll pane GUI components.
      
      mondayScroll = new JScrollPane(monday, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
      
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); mondayBorder = new TitledBorder("Monday");
      
      mondayBorder.setTitleColor(new Color(0,150,0));
      
      mondayScroll.setBorder(mondayBorder);   
      

      tuesdayScroll = new JScrollPane(tuesday, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
      
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); tuesdayBorder = new TitledBorder("Tuesday");
      
      tuesdayBorder.setTitleColor(new Color(0,150,0));
      
      tuesdayScroll.setBorder(tuesdayBorder);       
      

      wednesdayScroll = new JScrollPane(wednesday, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
      
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); wednesdayBorder = new TitledBorder("Wednesday");
      
      wednesdayBorder.setTitleColor(new Color(0,150,0));
      
      wednesdayScroll.setBorder(wednesdayBorder); 
      
     
      thursdayScroll = new JScrollPane(thursday, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
      
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); thursdayBorder = new TitledBorder("Thursday");
      
      thursdayBorder.setTitleColor(new Color(0,150,0));
      
      thursdayScroll.setBorder(thursdayBorder); 
      
      
      fridayScroll = new JScrollPane(friday, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
      
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); fridayBorder = new TitledBorder("Friday"); 
      
      fridayBorder.setTitleColor(new Color(0,150,0));
      
      fridayScroll.setBorder(fridayBorder);
      
      
      saturdayScroll = new JScrollPane(saturday, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
      
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); saturdayBorder = new TitledBorder("Saturday");
      
      saturdayBorder.setTitleColor(new Color(0,150,0));
      
      saturdayScroll.setBorder(saturdayBorder);
         
      
      sundayScroll = new JScrollPane(sunday, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
      
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); sundayBorder = new TitledBorder("Sunday");
      
      sundayBorder.setTitleColor(new Color(0,150,0));
      
      sundayScroll.setBorder(sundayBorder);
      
      
      
      // Initialize button GUI components.
      
      diaryBack = new JButton(new ImageIcon(this.getClass().getResource
      (
         "files/images/PersonalDiaryBackNormal.png"))
      ); 
      
      
      diaryBack.setRolloverIcon(new ImageIcon(this.getClass().getResource
      (
         "files/images/PersonalDiaryBackRollover.png"))
      );

      
      diaryBack.setPressedIcon(new ImageIcon(this.getClass().getResource
      (
         "files/images/PersonalDiaryBackPressed.png"))
      );
      
      
      diaryBack.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
      
      diaryBack.addActionListener(new DiaryBackHandler());
      
      
      diaryNext = new JButton(new ImageIcon(this.getClass().getResource
      (
         "files/images/PersonalDiaryNextNormal.png"))
      ); 
 
      
      diaryNext.setRolloverIcon(new ImageIcon(this.getClass().getResource
      (
         "files/images/PersonalDiaryNextRollover.png"))
      );

      
      diaryNext.setPressedIcon(new ImageIcon(this.getClass().getResource
      (
         "files/images/PersonalDiaryNextPressed.png"))
      );   
     
      
      diaryNext.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
      
      diaryNext.addActionListener(new DiaryNextHandler());
      
      
      
      // Initialize combo box GUI components.
      
      yearBox = new JComboBox(DateAndTime.returnYearChoices(START_YEAR));
      
      yearBox.setPreferredSize(new Dimension(60, 28));
      
      yearBox.setSelectedIndex(yearBox.getItemCount() -1); 
      
      yearBox.addActionListener(new YearBoxHandler());
      
      yearBox.setMaximumRowCount(3);
      
      
      dateBox = new JComboBox(DateAndTime.returnDateList(DateAndTime.returnYear(), null)); 
      
      dateBox.setSelectedIndex(0); dateBox.addActionListener(new DateBoxHandler());
      
      dateBox.setPreferredSize(new Dimension(60, 28));
      
      dateBox.setMaximumRowCount(3);
      
      
      
      // Initialize check box GUI components. 
      
      currentPage = new JCheckBox("Skip To The Current Week"); 
      
      currentPage.addItemListener(new CurrentPageHandler());
      
      currentPage.setFocusPainted(false);     
      
      
      
      // Initialize JPanel GUI components.

      calendarContainer = new JPanel(); calendarContainer.setLayout(new GridLayout(2,1));
      
      buttonContainer = new JPanel(); buttonContainer.setLayout(new GridLayout(2,1));
      
      navigationPanel = new JPanel(); navigationPanel.setLayout(new FlowLayout());
      
      buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(1,2)); 
      
      comboPanel = new JPanel(); comboPanel.setLayout(new GridLayout(2,1));
      
      calendarControl = new JPanel(); calendarControl.setLayout(new GridLayout(1,1));
      
      calendarDisplay = new JPanel(); calendarDisplay.setLayout(new GridLayout(1,1));
      
      leftContainer = new JPanel(); leftContainer.setLayout(new GridBagLayout());
      
      rightContainer = new JPanel(); rightContainer.setLayout(new GridBagLayout());
      
      
      calendarContainer.setBorder(calendarBorder);
      
      rightContainer.setBorder(etchedBorder);
      
      leftContainer.setBorder(etchedBorder); 
      

     
      // Add GUI components to JPanels.

      comboPanel.add(dateBox); comboPanel.add(yearBox); 
      
      buttonPanel.add(diaryBack); buttonPanel.add(diaryNext);
      
      contentPane.add(leftContainer); contentPane.add(rightContainer);

      buttonContainer.add(comboPanel); buttonContainer.add(buttonPanel);
      
      calendarControl.add(weekDisplay); calendarDisplay.add(dayDisplay); 

      navigationPanel.add(calendarContainer); navigationPanel.add(buttonContainer);
      
      calendarContainer.add(calendarControl); calendarContainer.add(calendarDisplay); 
      

      
      // Read settings from database if user logged in.
      
      if ((!(userId == null)) && (!userId.equals("NON_MEMBER")) && (!runRestricted)) 

      {saveMenuItem.setEnabled(true); clearMenuItem.setEnabled(true); readFromDatabase();}
      
      
      
      // Method calls for GUI initialization.

      gridBagConstraints(); setColors(); setGraphicIcons(); 
      
      initialiseHeaderStyle(); validateDaysOfWeek();
   }
   
   
   
   /**
    * Sets the background color.
    */
   private void setColors()
   {
      
      contentPane.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      leftContainer.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      rightContainer.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      calendarContainer.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      navigationPanel.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      currentPage.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      mondayScroll.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      tuesdayScroll.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      wednesdayScroll.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      thursdayScroll.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      fridayScroll.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      saturdayScroll.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
      sundayScroll.setBackground
      (
         new Color (WHITE_COMPONENT, WHITE_COMPONENT, WHITE_COMPONENT)
      );
      
   }
   
   
   
   /**
    * Sets icons for graphical elements.
    */
   private void setGraphicIcons()
   {
      currentPage.setIcon(new ImageIcon
      (this.getClass().getResource("files/images/CheckBoxNormalUnselected.png")));
             
      currentPage.setSelectedIcon(new ImageIcon
      (this.getClass().getResource("files/images/CheckBoxNormalSelected.png")));

      currentPage.setDisabledIcon(new ImageIcon
      (this.getClass().getResource("files/images/CheckBoxDisabledUnselected.png")));

      currentPage.setDisabledSelectedIcon(new ImageIcon
      (this.getClass().getResource("files/images/CheckBoxDisabledSelected.png")));
   }
   
   
   
   /**
    * Sets the grid bag layout.
    * ESCA-JAVA0076:
    */
   private void gridBagConstraints()
   {
      // Initialize grid bag layout of GUI.
      
      constraints = new GridBagConstraints();
      
      constraints.fill = GridBagConstraints.HORIZONTAL;
      
      
      
      // Grid bag constraints 1.
      
      constraints.insets = new Insets(5,0,0,0);
      
      
      constraints.ipadx = 0; 
      
      constraints.ipady = 0;

      constraints.gridwidth = 1;
      
      constraints.weightx = 0; 
      
      constraints.weighty = 0; 
      
      constraints.gridx = 0; 
      
      constraints.gridy = 0;
      
      
      leftContainer.add(monthDisplay, constraints);
      
      
      
      // Grid bag constraints 2.
      
      constraints.insets = new Insets(10,0,0,0);
      
      
      constraints.ipadx = 0; 
      
      constraints.ipady = 0;

      constraints.gridwidth = 1;
      
      constraints.weightx = 0; 
      
      constraints.weighty = 0; 
      
      constraints.gridx = 0; 
      
      constraints.gridy = 1;
      
      
      leftContainer.add(mondayScroll, constraints);
      
      
      
      // Grid bag constraints 3.
      
      constraints.insets = new Insets(5,0,0,0);
      
      
      constraints.ipadx = 0; 
      
      constraints.ipady = 0;

      constraints.gridwidth = 1;
      
      constraints.weightx = 0; 
      
      constraints.weighty = 0; 
      
      constraints.gridx = 0; 
      
      constraints.gridy = 2;
      
      
      leftContainer.add(tuesdayScroll, constraints);
      
      
      
      // Grid bag constraints 4.
      
      constraints.insets = new Insets(5,0,0,0);
      
      
      constraints.ipadx = 0; 
      
      constraints.ipady = 0;

      constraints.gridwidth = 1;
      
      constraints.weightx = 0; 
      
      constraints.weighty = 0; 
      
      constraints.gridx = 0; 
      
      constraints.gridy = 3;
      
      
      leftContainer.add(wednesdayScroll, constraints);
      
      
      
      // Grid bag constraints 5.
      
      constraints.insets = new Insets(5,0,0,0);
      
      
      constraints.ipadx = 0; 
      
      constraints.ipady = 0;

      constraints.gridwidth = 1;
      
      constraints.weightx = 0; 
      
      constraints.weighty = 0; 
      
      constraints.gridx = 0; 
      
      constraints.gridy = 4;
      
      
      leftContainer.add(thursdayScroll, constraints);
      
      
      
      // Grid bag constraints 6.
      
      constraints.insets = new Insets(5,0,0,0);
      
      
      constraints.ipadx = 0; 
      
      constraints.ipady = 0;

      constraints.gridwidth = 1;
      
      constraints.weightx = 0; 
      
      constraints.weighty = 0; 
      
      constraints.gridx = 0; 
      
      constraints.gridy = 5;
      
      
      leftContainer.add(currentPage, constraints);
      
      
      
      // Grid bag constraints 7.
      
      constraints.insets = new Insets(5,0,0,0);
      
      
      constraints.ipadx = 0; 
      
      constraints.ipady = 0;

      constraints.gridwidth = 1;
      
      constraints.weightx = 0; 
      
      constraints.weighty = 0; 
      
      constraints.gridx = 0; 
      
      constraints.gridy = 0;
      
      
      rightContainer.add(yearDisplay, constraints);
      
      
      
      // Grid bag constraints 8.
      
      constraints.insets = new Insets(10,0,0,0);
      
      
      constraints.ipadx = 0; 
      
      constraints.ipady = 0;

      constraints.gridwidth = 1;
      
      constraints.weightx = 0; 
      
      constraints.weighty = 0; 
      
      constraints.gridx = 0; 
      
      constraints.gridy = 1;
      
      
      rightContainer.add(fridayScroll, constraints);
      
      
      
      // Grid bag constraints 9.
      
      constraints.insets = new Insets(10,0,0,0);
      
      
      constraints.ipadx = 0; 
      
      constraints.ipady = 0;

      constraints.gridwidth = 1;
      
      constraints.weightx = 0; 
      
      constraints.weighty = 0; 
      
      constraints.gridx = 0; 
      
      constraints.gridy = 2;
      
      
      rightContainer.add(saturdayScroll, constraints);
      
      
      
      // Grid bag constraints 10.
      
      constraints.insets = new Insets(10,0,0,0);
      
      
      constraints.ipadx = 0; 
      
      constraints.ipady = 0;

      constraints.gridwidth = 1;
      
      constraints.weightx = 0; 
      
      constraints.weighty = 0; 
      
      constraints.gridx = 0; 
      
      constraints.gridy = 3;
      
      
      rightContainer.add(sundayScroll, constraints);
      
      
      
      // Grid bag constraints 11.
      
      constraints.insets = new Insets(10,0,0,0);
      
      
      constraints.ipadx = 0; 
      
      constraints.ipady = 0;

      constraints.gridwidth = 1;
      
      constraints.weightx = 0; 
      
      constraints.weighty = 0; 
      
      constraints.gridx = 0; 
      
      constraints.gridy = 4;
      
      
      rightContainer.add(navigationPanel, constraints);
   }
   
   
   //*************************************** END INITIALISATION CODE ***************************************//
   
   
   //************************************* START INTERFACE EVENT CODE **************************************//
   
   
   /**
    * Bold box listener. 
    */
   private class HeaderBoldHandler implements ItemListener
   {
      public void itemStateChanged(ItemEvent event)
      {
         headerBold();
      }
   }
   
   
   
   /**
    * Underline box listener. 
    */
   private class HeaderUnderlineHandler implements ItemListener
   {
      public void itemStateChanged(ItemEvent event)
      {
         headerUnderline(); 
      }
   }
   
   
   
   /**
    * Italic box listener. 
    */
   private class HeaderItalicHandler implements ItemListener
   {
      public void itemStateChanged(ItemEvent event)
      {
         headerItalic();
      }
   }
   
   
   
   /**
    * Bold box listener. 
    */
   private class CurrentPageHandler implements ItemListener
   {
      public void itemStateChanged(ItemEvent event)
      {
         if (currentPage.isSelected())
         {
            currentPage();         
         }
      }
   }
   
   
   
   /**
    * Color radio listener. 
    */
   private class HeaderRadioHandler implements ItemListener
   {
      
      public void itemStateChanged(ItemEvent event)
      {
         monthDisplay.setText(diary.getMonth(diary.getCurrentWeek())); 
        
         headerUnderline(); headerItalic();
         
         headerBold(); headerRadio();  
      }
   }
   
   
   
   /**
    * Color radio listener. 
    * ESCA-JAVA0076:
    */
   private class TitleRadioHandler implements ItemListener
   {
      
      public void itemStateChanged(ItemEvent event)
      {
         reinstantiateBorders(); 
     
      
         if (titleOrangeRadio.isSelected())
         { 
            mondayBorder.setTitleColor(Color.orange); 
            
            tuesdayBorder.setTitleColor(Color.orange); 
            
            wednesdayBorder.setTitleColor(Color.orange);
            
            thursdayBorder.setTitleColor(Color.orange);
            
            fridayBorder.setTitleColor(Color.orange);
           
            saturdayBorder.setTitleColor(Color.orange);
              
            sundayBorder.setTitleColor(Color.orange); 
         }
         
         if (titleBlueRadio.isSelected())
         { 
            mondayBorder.setTitleColor(Color.blue); 
            
            tuesdayBorder.setTitleColor(Color.blue); 
            
            wednesdayBorder.setTitleColor(Color.blue);
            
            thursdayBorder.setTitleColor(Color.blue);
            
            fridayBorder.setTitleColor(Color.blue);
           
            saturdayBorder.setTitleColor(Color.blue);
              
            sundayBorder.setTitleColor(Color.blue); 
         }
         
         if (titleGreenRadio.isSelected())
         { 
            mondayBorder.setTitleColor(new Color(0,150,0)); 
            
            tuesdayBorder.setTitleColor(new Color(0,150,0)); 
            
            wednesdayBorder.setTitleColor(new Color(0,150,0));
            
            thursdayBorder.setTitleColor(new Color(0,150,0));
            
            fridayBorder.setTitleColor(new Color(0,150,0));
           
            saturdayBorder.setTitleColor(new Color(0,150,0));
              
            sundayBorder.setTitleColor(new Color(0,150,0)); 
         }
         
         if (titleRedRadio.isSelected())
         { 
            mondayBorder.setTitleColor(Color.red); 
            
            tuesdayBorder.setTitleColor(Color.red); 
            
            wednesdayBorder.setTitleColor(Color.red);
            
            thursdayBorder.setTitleColor(Color.red);
            
            fridayBorder.setTitleColor(Color.red);
           
            saturdayBorder.setTitleColor(Color.red);
              
            sundayBorder.setTitleColor(Color.red); 
         }
         
         if (titleBlackRadio.isSelected())
         { 
            mondayBorder.setTitleColor(Color.black); 
            
            tuesdayBorder.setTitleColor(Color.black); 
            
            wednesdayBorder.setTitleColor(Color.black);
            
            thursdayBorder.setTitleColor(Color.black);
            
            fridayBorder.setTitleColor(Color.black);
           
            saturdayBorder.setTitleColor(Color.black);
              
            sundayBorder.setTitleColor(Color.black); 
         }
         
      }
   }
   
   
   
   public class YearBoxHandler implements ActionListener 
   {

      /** 
       * Listener for the year box. 
       */
      public void actionPerformed(ActionEvent event) 
      {
         dateBox.removeAllItems(); 
      
         
         int year = Integer.parseInt((String)yearBox.getSelectedItem());
         
         int length = DateAndTime.returnDateList(year, null).length;
         
         
         diary = new PersonalDiary(year);
         
         
         if (year != DateAndTime.returnYear())
         {
            currentPage.setEnabled(false);
         }
         
         else
         {
            currentPage.setEnabled(true); 
         }
         

         for (int i = 0; i < length; i ++)
         {
            dateBox.addItem(DateAndTime.returnDateList(year, null)[i]);
         }
         
         
         clearDaysOfWeek(); diaryWrite();
         
         
         if ((!(userId == null)) && (!userId.equals("NON_MEMBER")) && (!runRestricted)) 
         {
            readEntriesFromDatabase();
         }

         
         monthDisplay.setText(diary.getMonth(diary.getCurrentWeek()));
         
         weekDisplay.setText("Week " + diary.getCurrentWeek());
         
         yearDisplay.setText(Integer.toString(year));
         
         dayDisplay.setText(""); setScrollTop();
         
         
         headerUnderline(); headerItalic();
         
         headerBold(); headerRadio();
         
         
         validateDaysOfWeek();
         
      }
   
   }
   
   
   
   public class DateBoxHandler implements ActionListener 
   {

      /** 
       * Listener for the date skip box. 
       */
      public void actionPerformed(ActionEvent event) 
      {
         if (dateBox.getItemCount() != 0)
         {
            String date = (String)dateBox.getSelectedItem(); 
         
            diaryWrite(); diary.setSpecifiedWeek(date); diaryRead();
          
         
            monthDisplay.setText(diary.getMonth(diary.getCurrentWeek()));
          
            weekDisplay.setText("Week " + diary.getCurrentWeek()); 
            
            dayDisplay.setText(""); setScrollTop();
          
          
            headerUnderline(); headerItalic();
          
            headerBold(); headerRadio();
            
            
            validateDaysOfWeek();
            
         }
      }
   
   }
   
   
   
   public class DiaryBackHandler implements ActionListener 
   {

      /** 
       * Listener for the diary back button. 
       */
      public void actionPerformed(ActionEvent event) 
      {
         
         diaryWrite(); diary.decrementWeek(); diaryRead();
         
         monthDisplay.setText(diary.getMonth(diary.getCurrentWeek()));
         
         weekDisplay.setText("Week " + diary.getCurrentWeek()); 
         
         dayDisplay.setText(""); setScrollTop();
         
         
         headerUnderline(); headerItalic();
         
         headerBold(); headerRadio();
         
         
         validateDaysOfWeek();
         
      }
   
   }
   
   
   
   public class DiaryNextHandler implements ActionListener 
   {

      /** 
       * Listener for the diary next button. 
       */
      public void actionPerformed(ActionEvent event) 
      {
      
         diaryWrite(); diary.incrementWeek(); diaryRead();
         
         monthDisplay.setText(diary.getMonth(diary.getCurrentWeek()));
         
         weekDisplay.setText("Week " + diary.getCurrentWeek()); 
         
         dayDisplay.setText(""); setScrollTop();
         
         
         headerUnderline(); headerItalic();
         
         headerBold(); headerRadio();
         
         
         validateDaysOfWeek();
         
      }
   
   }
   
   
   
   /**
    * Focus listener to update the day of month display.
    * ESCA-JAVA0076:
    */
   public void focusGained(FocusEvent e) 
   {
   
      if (sunday.hasFocus())
      {
         dayDisplay.setText(diary.getDayOfMonth(diary.getCurrentWeek(), 1));
      }
      
      if (monday.hasFocus())
      {
         dayDisplay.setText(diary.getDayOfMonth(diary.getCurrentWeek(), 2));
      }
      
      if (tuesday.hasFocus())
      {
         dayDisplay.setText(diary.getDayOfMonth(diary.getCurrentWeek(), 3));
      }
      
      if (wednesday.hasFocus())
      {
         dayDisplay.setText(diary.getDayOfMonth(diary.getCurrentWeek(), 4));
      }
      
      if (thursday.hasFocus())
      {
         dayDisplay.setText(diary.getDayOfMonth(diary.getCurrentWeek(), 5));
      }
      
      if (friday.hasFocus())
      {
         dayDisplay.setText(diary.getDayOfMonth(diary.getCurrentWeek(), 6));
      }
      
      if (saturday.hasFocus())
      {
         dayDisplay.setText(diary.getDayOfMonth(diary.getCurrentWeek(), 7));
      }
       
   }
   
   

   public void focusLost(FocusEvent e) {}
   
   
   
   /**
    * Overrides ComponentListener.
    */
   public void componentMoved(ComponentEvent e) {}
   
   public void componentResized(ComponentEvent e) {}
   
   public void componentShown(ComponentEvent e) {setContentDisplay(true);}
   
   public void componentHidden(ComponentEvent e) {setContentDisplay(false);}
   
   
   //************************************** END INTERFACE EVENT CODE ***************************************//
   
   
   //**************************************** START PUBLIC METHODS *****************************************//
   
   
   /**
    * Displays or Hides contents of GUI.
    * @param shown
    */
   public void setContentDisplay(boolean shown)
   {
      menuBar.setVisible(shown);
         
      contentPane.setVisible(shown);
   }
   
   
   //***************************************** END PUBLIC METHODS ******************************************//


   //**************************************** START PRIVATE METHODS ****************************************//
   
   
   private void initialiseHeaderStyle()
   {
   
      Style monthStyle = monthDisplay.addStyle("Italic", null);
       
      Style yearStyle = yearDisplay.addStyle("Italic", null);
    
     
      StyleConstants.setItalic(monthStyle, true);
          
      StyleConstants.setItalic(yearStyle, true);
         
      StyleConstants.setBold(monthStyle, true);
          
      StyleConstants.setBold(yearStyle, true);
         
      StyleConstants.setForeground(monthStyle, Color.red);
          
      StyleConstants.setForeground(yearStyle, Color.red);


      StyledDocument monthDoc = monthDisplay.getStyledDocument();
       
      StyledDocument yearDoc = yearDisplay.getStyledDocument();

      monthDoc.setCharacterAttributes(0, monthDoc.getLength(), monthStyle, false);
  
      yearDoc.setCharacterAttributes(0, yearDoc.getLength(), monthStyle, false);  
      
      
      headerItalicCheck.setSelected(true);
      
      headerBoldCheck.setSelected(true);
      
      headerRedRadio.setSelected(true); 
      
      titleGreenRadio.setSelected(true);
   }
   
   
   
   /**
    * Validates the days of the week.
    * ESCA-JAVA0076:
    */
   private void validateDaysOfWeek()
   {
 
      if (diary.isValidDayOfWeek(diary.getCurrentWeek(), 1))
      {
         sunday.setEnabled(true);
         sundayScroll.setEnabled(true);
      }
      
      else
      {
         sunday.setEnabled(false);
         sundayScroll.setEnabled(false);
      }   
   
      if (diary.isValidDayOfWeek(diary.getCurrentWeek(), 2))
      {
         monday.setEnabled(true);
         mondayScroll.setEnabled(true);
      }
      
      else
      {
         monday.setEnabled(false);
         mondayScroll.setEnabled(false);
      }
      
      if (diary.isValidDayOfWeek(diary.getCurrentWeek(), 3))
      {
         tuesday.setEnabled(true);
         tuesdayScroll.setEnabled(true);
      }
      
      else
      {
         tuesday.setEnabled(false);
         tuesdayScroll.setEnabled(false);
      }
      
      if (diary.isValidDayOfWeek(diary.getCurrentWeek(), 4))
      {
         wednesday.setEnabled(true);
         wednesdayScroll.setEnabled(true);
      }
      
      else
      {
         wednesday.setEnabled(false);
         wednesdayScroll.setEnabled(false);
      }
      
      if (diary.isValidDayOfWeek(diary.getCurrentWeek(), 5))
      {
         thursday.setEnabled(true);
         thursdayScroll.setEnabled(true);
      }
      
      else
      {
         thursday.setEnabled(false);
         thursdayScroll.setEnabled(false);
      }
      
      if (diary.isValidDayOfWeek(diary.getCurrentWeek(), 6))
      {
         friday.setEnabled(true);
         fridayScroll.setEnabled(true);
      }
      
      else
      {
         friday.setEnabled(false);
         fridayScroll.setEnabled(false);
      }    
      
      if (diary.isValidDayOfWeek(diary.getCurrentWeek(), 7))
      {
         saturday.setEnabled(true);
         saturdayScroll.setEnabled(true);
      }
      
      else
      {
         saturday.setEnabled(false);
         saturdayScroll.setEnabled(false);
      }

   }
   
   
   
   /**
    * Header underline style.
    */
   private void headerUnderline()
   {
      Style monthStyle = monthDisplay.addStyle("Underline", null);
       
      Style yearStyle = yearDisplay.addStyle("Underline", null);
    
      if (headerUnderlineCheck.isSelected())
      {
         StyleConstants.setUnderline(monthStyle, true);
          
         StyleConstants.setUnderline(yearStyle, true);
      
      }
    
      else
      {
         StyleConstants.setUnderline(monthStyle, false);
          
         StyleConstants.setUnderline(yearStyle, false);
      
      }
    
      StyledDocument monthDoc = monthDisplay.getStyledDocument();
       
      StyledDocument yearDoc = yearDisplay.getStyledDocument();
      
      monthDoc.setCharacterAttributes(0, monthDoc.getLength(), monthStyle, false);
       
      yearDoc.setCharacterAttributes(0, yearDoc.getLength(), monthStyle, false);
   
   }
   
   
   
   /**
    * Header italic style.
    */
   private void headerItalic()
   {
      Style monthStyle = monthDisplay.addStyle("Italic", null);
       
      Style yearStyle = yearDisplay.addStyle("Italic", null);
    
      if (headerItalicCheck.isSelected())
      {
         StyleConstants.setItalic(monthStyle, true);
          
         StyleConstants.setItalic(yearStyle, true);
      
      }
    
      else
      {
         StyleConstants.setItalic(monthStyle, false);
          
         StyleConstants.setItalic(yearStyle, false);
      
      }
    
      StyledDocument monthDoc = monthDisplay.getStyledDocument();
       
      StyledDocument yearDoc = yearDisplay.getStyledDocument();
      
      monthDoc.setCharacterAttributes(0, monthDoc.getLength(), monthStyle, false);
  
      yearDoc.setCharacterAttributes(0, yearDoc.getLength(), monthStyle, false);  
   
   }
   
   
   
   /**
    * Skips to the current week.
    */
   private void currentPage()
   {
      int selectedYear = Integer.parseInt((String)yearBox.getSelectedItem());

      
      if (currentPage.isSelected() && (selectedYear == DateAndTime.returnYear()))
      {
         diaryWrite(); diary.setCurrentWeek(); diaryRead();
       
         monthDisplay.setText(diary.getMonth(diary.getCurrentWeek()));
        
         weekDisplay.setText("Week " + diary.getCurrentWeek()); 
        
         dayDisplay.setText(""); setScrollTop();
        
        
         headerUnderline(); headerItalic();
        
         headerBold(); headerRadio();
        
        
         validateDaysOfWeek();
      }
   }
   
   
   
   /**
    * Header bold style.
    */
   private void headerBold()
   {
      Style monthStyle = monthDisplay.addStyle("Bold", null);
       
      Style yearStyle = yearDisplay.addStyle("Bold", null);
    
      if (headerBoldCheck.isSelected())
      {
         StyleConstants.setBold(monthStyle, true);
          
         StyleConstants.setBold(yearStyle, true);
      
      }
    
      else
      {
         StyleConstants.setBold(monthStyle, false);
          
         StyleConstants.setBold(yearStyle, false);
      
      }
    
      StyledDocument monthDoc = monthDisplay.getStyledDocument();
       
      StyledDocument yearDoc = yearDisplay.getStyledDocument();
     
      monthDoc.setCharacterAttributes(0, monthDoc.getLength(), monthStyle, false);
  
      yearDoc.setCharacterAttributes(0, yearDoc.getLength(), monthStyle, false);
   }
   
   
   
   /**
    * Header color style.
    * ESCA-JAVA0076:
    */
   private void headerRadio()
   { 
      Style monthStyle = monthDisplay.addStyle("Color", null);
       
      Style yearStyle = yearDisplay.addStyle("Color", null);
      
      
      if (headerOrangeRadio.isSelected())
      {
         StyleConstants.setForeground(monthStyle, Color.orange);
          
         StyleConstants.setForeground(yearStyle, Color.orange);
      
      }
       
      if (headerGreenRadio.isSelected())
      {
         StyleConstants.setForeground(monthStyle, new Color(0,150,0));
          
         StyleConstants.setForeground(yearStyle, new Color(0,150,0));
      
      }
       
      if (headerBlueRadio.isSelected())
      {
         StyleConstants.setForeground(monthStyle, Color.blue);
          
         StyleConstants.setForeground(yearStyle, Color.blue);
      
      }
       
      if (headerRedRadio.isSelected())
      {
         StyleConstants.setForeground(monthStyle, Color.red);
          
         StyleConstants.setForeground(yearStyle, Color.red);
      
      }
       
      if (headerBlackRadio.isSelected())
      {
         StyleConstants.setForeground(monthStyle, Color.black);
          
         StyleConstants.setForeground(yearStyle, Color.black);
      
      }

      
      StyledDocument monthDoc = monthDisplay.getStyledDocument();
       
      StyledDocument yearDoc = yearDisplay.getStyledDocument();
     
      monthDoc.setCharacterAttributes(0, monthDoc.getLength(), monthStyle, false);
  
      yearDoc.setCharacterAttributes(0, yearDoc.getLength(), monthStyle, false);     
     
   }
   
   
   
   /**
    * Border redefine.
    */
   private void reinstantiateBorders()
   {
      mondayBorder = new TitledBorder("Monday");
      mondayScroll.setBorder(mondayBorder);
       
      tuesdayBorder = new TitledBorder("Tuesday");
      tuesdayScroll.setBorder(tuesdayBorder);
       
      wednesdayBorder = new TitledBorder("Wednesday");
      wednesdayScroll.setBorder(wednesdayBorder);
       
      thursdayBorder = new TitledBorder("Thursday");
      thursdayScroll.setBorder(thursdayBorder);
       
      fridayBorder = new TitledBorder("Friday");
      fridayScroll.setBorder(fridayBorder);
       
      saturdayBorder = new TitledBorder("Saturday");
      saturdayScroll.setBorder(saturdayBorder);
       
      sundayBorder = new TitledBorder("Sunday");
      sundayScroll.setBorder(sundayBorder);
   }
   
   
   
   /**
    * Clears the day of the week text areas.
    */
   private void clearDaysOfWeek()
   {
      monday.setText(null);
      
      tuesday.setText(null);
      
      wednesday.setText(null);
      
      thursday.setText(null);
      
      friday.setText(null);
      
      saturday.setText(null);
      
      sunday.setText(null);
   }
   

   
   /**
    * Writes entries to the diary.
    * ESCA-JAVA0076:
    */
   private void diaryWrite()
   {
      diary.insertEntry
      (
         diary.getCurrentWeek(), 2, DataFunctions.newlineFlagEncoding
         
         (monday.getText(), NEWLINE_FLAG)
      );
       
      diary.insertEntry
      (
         diary.getCurrentWeek(), 3, DataFunctions.newlineFlagEncoding
         
         (tuesday.getText(), NEWLINE_FLAG)
      );
      
      diary.insertEntry
      (
         diary.getCurrentWeek(), 4, DataFunctions.newlineFlagEncoding
         
         (wednesday.getText(), NEWLINE_FLAG)
      );
      
      diary.insertEntry
      (
         diary.getCurrentWeek(), 5, DataFunctions.newlineFlagEncoding
         
         (thursday.getText(), NEWLINE_FLAG)
      );
      
      diary.insertEntry
      (
         diary.getCurrentWeek(), 6, DataFunctions.newlineFlagEncoding
         
         (friday.getText(), NEWLINE_FLAG)
      );
      
      diary.insertEntry
      (
         diary.getCurrentWeek(), 7, DataFunctions.newlineFlagEncoding
         
         (saturday.getText(), NEWLINE_FLAG)
      );
      
      diary.insertEntry
      (
         diary.getCurrentWeek(), 1, DataFunctions.newlineFlagEncoding
         
         (sunday.getText(), NEWLINE_FLAG)
      );
   }
   
   
   
   /**
    * Reads entries from the diary.
    * ESCA-JAVA0076:
    */
   private void diaryRead()
   {
      monday.setText
      (
         DataFunctions.newlineFlagDecoding
         (
            diary.retrieveEntry(diary.getCurrentWeek(), 2), NEWLINE_FLAG
         )
      );
       
      tuesday.setText
      (
         DataFunctions.newlineFlagDecoding
         (
            diary.retrieveEntry(diary.getCurrentWeek(), 3), NEWLINE_FLAG
         )
      );
      
      wednesday.setText
      (
         DataFunctions.newlineFlagDecoding
         (
            diary.retrieveEntry(diary.getCurrentWeek(), 4), NEWLINE_FLAG
         )
      );
      
      thursday.setText
      (
         DataFunctions.newlineFlagDecoding
         (
            diary.retrieveEntry(diary.getCurrentWeek(), 5), NEWLINE_FLAG
         )
      );
      
      friday.setText
      (
         DataFunctions.newlineFlagDecoding
         (
            diary.retrieveEntry(diary.getCurrentWeek(), 6), NEWLINE_FLAG
         )
      );
      
      saturday.setText
      (
         DataFunctions.newlineFlagDecoding
         (
            diary.retrieveEntry(diary.getCurrentWeek(), 7), NEWLINE_FLAG
         )
      );
     
      sunday.setText
      (
         DataFunctions.newlineFlagDecoding
         (
            diary.retrieveEntry(diary.getCurrentWeek(), 1), NEWLINE_FLAG
         )
      );
      
   }
   
   
   
   /**
    * Reads the database.
    */
   private void readFromDatabase()
   {
   
      diaryReadSettings = new ArrayList();
   
      diaryReadSettings = Portal.phpToJavaGate(DIARY_READ_ADDRESS, userId, userPw, null);

      
      if (diaryReadSettings.size() != 0)
      { 
         setHeaderUnderline(diaryReadSettings.get(SQL_TABLE_COLUMN_A));
      
         setHeaderItalic(diaryReadSettings.get(SQL_TABLE_COLUMN_B));
      
         setHeaderBold(diaryReadSettings.get(SQL_TABLE_COLUMN_C));
         
         setHeaderColor(diaryReadSettings.get(SQL_TABLE_COLUMN_D));
         
         setTitleColor(diaryReadSettings.get(SQL_TABLE_COLUMN_E));
         
         setDiaryYear(diaryReadSettings.get(SQL_TABLE_COLUMN_G));
         
         setDiaryDate(diaryReadSettings.get(SQL_TABLE_COLUMN_H));
         
         setDiarySkip(diaryReadSettings.get(SQL_TABLE_COLUMN_F));
      }
      
      
      readEntriesFromDatabase();
   
   }
   
   
   
   /**
    * Transfer the settings to the database.
    */
   private void transferToDatabase()
   {

      writeEntriesToDatabase();

      
      writeSettings = new ArrayList();
     
      writeSettings.add(getHeaderUnderline());
      
      writeSettings.add(getHeaderItalic());
      
      writeSettings.add(getHeaderBold());
      
      writeSettings.add(getHeaderColor());
      
      writeSettings.add(getTitleColor());
      
      writeSettings.add(getDiarySkip());
      
      writeSettings.add(getDiaryYear());
      
      writeSettings.add(getDiaryDate());
      
      
      Portal.javaToPhpGate(DIARY_WRITE_ADDRESS, userId, userPw, writeSettings);

   }
   
   
   
   /**
    * Writes the diary entries to the database.
    */
   private void writeEntriesToDatabase()
   {

      diaryWrite(); entryWriteSettings = new ArrayList();
     
      
      for (int i = 0; i < diary.getRecords().length; i ++)
      {
      
         if (diary.getRecords()[i][1] != null 
         && diary.getRecords()[i][1].length() != 0)
         {
            entryWriteSettings.add(diary.getRecords()[i][0]);
              
            entryWriteSettings.add(diary.getRecords()[i][1]);
              
            Portal.javaToPhpGate(ENTRY_WRITE_ADDRESS, userId, userPw, entryWriteSettings);
         }
   
   
         entryWriteSettings.clear();  
      }
   }
   
   
   
   /**
    * Reads the diary entries from the database.
    */
   private void readEntriesFromDatabase()
   {
      final int INCREMENTATION = 2;
   
      entryReadSettings = Portal.phpToJavaGate(ENTRY_READ_ADDRESS, userId, userPw, null);
      
      
      for (int i = 0; i < entryReadSettings.size(); i += INCREMENTATION)
      {
         diary.setEntry(entryReadSettings.get(i), entryReadSettings.get(i +1));
      }
      
     
      diaryRead();
   
   }

   
   
   /**
    * Clears settings and records from the database.
    */
   private void clearDatabase()
   {   
      Portal.clearFromDatabase(DIARY_CLEAR_ADDRESS, userId, userPw, null); 
       
      Portal.clearFromDatabase(ENTRY_CLEAR_ADDRESS, userId, userPw, null); 
   }
   
   
   
   /**
    * Adds save mode menu item and listener that responds appropriately.
    * @return menuItem 
    */
   private JMenuItem saveMode() 
   {

      saveMenuItem = new JMenuItem("Save Workspace");
   
      class MenuItemListener implements ActionListener
      {
         public void actionPerformed(ActionEvent event)  
         {
            transferToDatabase();
         }
      }

      ActionListener listener = new MenuItemListener(); 
      
      saveMenuItem.addActionListener(listener);

      return saveMenuItem;
   }
   
   
   
   /**
    * Adds clear mode menu item and listener that responds appropriately.
    * @return menuItem 
    */
   private JMenuItem clearMode() 
   {

      clearMenuItem = new JMenuItem("Clear Workspace");
   
      class MenuItemListener implements ActionListener
      {
         public void actionPerformed(ActionEvent event)  
         {
            clearDatabase();
         }
      }

      ActionListener listener = new MenuItemListener(); 
      
      clearMenuItem.addActionListener(listener);

      return clearMenuItem;
   }
   
   
   
   /**
    * Adds a display menu. 
    * @return menu
    */
   private JMenu createDisplayMenu()
   {
      JMenu menu = new JMenu("Display"); 
      
      
      ButtonGroup headerGroup = new ButtonGroup();
      
      ButtonGroup titleGroup = new ButtonGroup();
      

      headerText = new JMenu("Header Text  ");
      
      
      headerUnderlineCheck = new JCheckBoxMenuItem("Under Line");
      
      headerUnderlineCheck.addItemListener(new HeaderUnderlineHandler());
      
      headerItalicCheck = new JCheckBoxMenuItem("Italic Font");
      
      headerItalicCheck.addItemListener(new HeaderItalicHandler());
      
      headerBoldCheck = new JCheckBoxMenuItem("Bold Font");
      
      headerBoldCheck.addItemListener(new HeaderBoldHandler());
      
      headerText.add(headerUnderlineCheck); headerText.add(headerItalicCheck);
      
      headerText.add(headerBoldCheck); headerText.addSeparator();
      
      
      headerOrangeRadio = new JRadioButtonMenuItem("Color Orange");
      
      headerOrangeRadio.addItemListener(new HeaderRadioHandler());
      
      headerBlueRadio = new JRadioButtonMenuItem("Color Blue");
      
      headerBlueRadio.addItemListener(new HeaderRadioHandler());
      
      headerGreenRadio = new JRadioButtonMenuItem("Color Green");
      
      headerGreenRadio.addItemListener(new HeaderRadioHandler());
      
      headerRedRadio = new JRadioButtonMenuItem("Color Red");
      
      headerRedRadio.addItemListener(new HeaderRadioHandler());
      
      headerBlackRadio = new JRadioButtonMenuItem("Color Black");
      
      headerBlackRadio.addItemListener(new HeaderRadioHandler());
      
      
      headerGroup.add(headerOrangeRadio); headerGroup.add(headerBlueRadio);
      
      headerGroup.add(headerGreenRadio); headerGroup.add(headerRedRadio); 
      
      headerGroup.add(headerBlackRadio); headerText.add(headerOrangeRadio);
      
      headerText.add(headerBlueRadio); headerText.add(headerGreenRadio);
      
      headerText.add(headerRedRadio); headerText.add(headerBlackRadio);
      
      
      //////////////////////////////////////////////////////////////
      
      
      titleText = new JMenu("Title Text  ");
      
      
      titleOrangeRadio = new JRadioButtonMenuItem("Color Orange");
      
      titleOrangeRadio.addItemListener(new TitleRadioHandler());
      
      titleBlueRadio = new JRadioButtonMenuItem("Color Blue");
      
      titleBlueRadio.addItemListener(new TitleRadioHandler());
      
      titleGreenRadio = new JRadioButtonMenuItem("Color Green");
      
      titleGreenRadio.addItemListener(new TitleRadioHandler());
      
      titleRedRadio = new JRadioButtonMenuItem("Color Red");
      
      titleRedRadio.addItemListener(new TitleRadioHandler());
      
      titleBlackRadio = new JRadioButtonMenuItem("Color Black");
      
      titleBlackRadio.addItemListener(new TitleRadioHandler());
      
      
      titleGroup.add(titleOrangeRadio); titleGroup.add(titleBlueRadio);
      
      titleGroup.add(titleGreenRadio); titleGroup.add(titleRedRadio); 
      
      titleGroup.add(titleBlackRadio); titleText.add(titleOrangeRadio);
      
      titleText.add(titleBlueRadio); titleText.add(titleGreenRadio);
      
      titleText.add(titleRedRadio); titleText.add(titleBlackRadio);
      
      
      menu.add(headerText); menu.add(titleText);
      
      
      return menu;
   }
   
   
   
   /**
    * Window resize event.
    */
   private void includeResizeEvent()
   {
      this.addComponentListener 
      (
         new ComponentAdapter() 
         {
            public void componentResized(ComponentEvent e) 
            {
               appletDisplayHandler();
            }
          
         }
      ); 
   }
   
   
   
   /**
    * Controls the JApplet component visibility. 
    * ESCA-JAVA0266:
    */
   private void appletDisplayHandler()
   {
      final String ZOOM_WARNING = 
   
      "It appears that web pages in your browser are zoomed out. \n\n" +
      "In order to display the applet, your browser needs to be set \n" +
      "at its default zoom level of 100% or greater. \n\n" +
      "Sorry about that.";
   
   
      if ((getWidth() < FRAME_SIZE_X) || (getHeight() < FRAME_SIZE_Y))
      {
         contentPane.setVisible(false); menuBar.setVisible(false);  
      
         
         if (!zoomWarningShown) 
         {
            Message.showMessage(ZOOM_WARNING, "Browser zoom setting", "warning");
            
            zoomWarningShown = true;
         } 
      }
       
      else 
      {
         contentPane.setVisible(true); menuBar.setVisible(true); 
      } 
   }
   
   
   
   /**
    * Adds a file menu. 
    * @return menu
    */
   private JMenu createFileMenu()
   {

      JMenu menu = new JMenu("File"); 
      
      menu.add(saveMode()); 
      
      menu.add(clearMode());

      return menu;
   }
   
   
   
   /**
    * Sets the caret position on top.
    */
   private void setScrollTop()
   {
      monday.setCaretPosition(0);
      
      tuesday.setCaretPosition(0);
      
      wednesday.setCaretPosition(0);
      
      thursday.setCaretPosition(0);
      
      friday.setCaretPosition(0);
      
      saturday.setCaretPosition(0);
      
      sunday.setCaretPosition(0);
   }
   
   
   
   /**
    * Sets the header underline settings.
    * @param value
    */
   private void setHeaderUnderline(String value)
   {
      if (value.equals("0"))
      {
         headerUnderlineCheck.setSelected(false);
      }
      
      if (value.equals("1"))
      {
         headerUnderlineCheck.setSelected(true);
      }
   }
   
   
   
   /**
    * Sets the header italic settings.
    * @param value
    */
   private void setHeaderItalic(String value)
   {
      if (value.equals("0"))
      {
         headerItalicCheck.setSelected(false);
      }
      
      if (value.equals("1"))
      {
         headerItalicCheck.setSelected(true);
      }
   }
   
   
   
   /**
    * Sets the header bold settings.
    * @param value
    */
   private void setHeaderBold(String value)
   {
      if (value.equals("0"))
      {
         headerBoldCheck.setSelected(false);
      }
      
      if (value.equals("1"))
      {
         headerBoldCheck.setSelected(true);
      }
   }
   
   
   
   /**
    * Sets the header color settings.
    * @param value
    */
   private void setHeaderColor(String value)
   {
      if (value.equals("ORANGE"))
      {
         headerOrangeRadio.setSelected(true);
      }
      
      if (value.equals("BLUE"))
      {
         headerBlueRadio.setSelected(true);
      }
      
      if (value.equals("GREEN"))
      {
         headerGreenRadio.setSelected(true);
      }
      
      if (value.equals("RED"))
      {
         headerRedRadio.setSelected(true);
      }
      
      if (value.equals("BLACK"))
      {
         headerBlackRadio.setSelected(true);
      }
   }
   
   
   
   /**
    * Sets the title color settings.
    * @param value
    */
   private void setTitleColor(String value)
   {
      if (value.equals("ORANGE"))
      {
         titleOrangeRadio.setSelected(true);
      }
      
      if (value.equals("BLUE"))
      {
         titleBlueRadio.setSelected(true);
      }
      
      if (value.equals("GREEN"))
      {
         titleGreenRadio.setSelected(true);
      }
      
      if (value.equals("RED"))
      {
         titleRedRadio.setSelected(true);
      }
      
      if (value.equals("BLACK"))
      {
         titleBlackRadio.setSelected(true);
      }
   }
   
   
   
   /**
    * Sets the current week check box.
    * @param value
    */
   private void setDiarySkip(String value)
   {
      if (value.equals("0"))
      {
         currentPage.setSelected(false);
      }
      
      if (value.equals("1"))
      {
         currentPage.setSelected(true);
      }
      
      
      currentPage();
   }
   
   
   
   /**
    * Sets the diary year.
    * @param value
    */
   private void setDiaryYear(String value)
   {
      yearBox.setSelectedItem(value);
   }
   
   
   
   /**
    * Sets the diary date.
    * @param value
    */
   private void setDiaryDate(String value)
   {
      dateBox.setSelectedItem(value);
   }
   
   
   
   /**
    * Gets the header underline settings.
    * @return
    */
   private String getHeaderUnderline()
   {
      String headerUnderline = "";
      
      
      if (headerUnderlineCheck.isSelected())
      {
         headerUnderline = "1";
      }
      
      else
      {
         headerUnderline = "0";
      }
      
      
      return headerUnderline;
      
   }
   
   
   
   /**
    * Gets the header italic settings.
    * @return
    */
   private String getHeaderItalic()
   {
      String headerItalic = "";
      
      
      if (headerItalicCheck.isSelected())
      {
         headerItalic = "1";
      }
      
      else
      {
         headerItalic = "0";
      }
      
      
      return headerItalic;
      
   }
   
   
   
   /**
    * Gets the header bold settings.
    * @return
    */
   private String getHeaderBold()
   {
      String headerBold = "";
      
      
      if (headerBoldCheck.isSelected())
      {
         headerBold = "1";
      }
      
      else
      {
         headerBold = "0";
      }
      
      
      return headerBold;
      
   }
   
   
   
   /**
    * Gets the header color settings.
    * @return
    */
   private String getHeaderColor()
   {
      String headerColor = "";
      
      
      if (headerOrangeRadio.isSelected())
      {
         headerColor = "ORANGE";
      }
      
      if (headerBlueRadio.isSelected())
      {
         headerColor = "BLUE";
      }
      
      if (headerGreenRadio.isSelected())
      {
         headerColor = "GREEN";
      }
      
      if (headerRedRadio.isSelected())
      {
         headerColor = "RED";
      }
      
      if (headerBlackRadio.isSelected())
      {
         headerColor = "BLACK";
      }
      
      return headerColor;
      
   }
   
   
   
   /**
    * Gets the title color settings.
    * @return
    */
   private String getTitleColor()
   {
      String titleColor = "";
      
      
      if (titleOrangeRadio.isSelected())
      {
         titleColor = "ORANGE";
      }
      
      if (titleBlueRadio.isSelected())
      {
         titleColor = "BLUE";
      }
      
      if (titleGreenRadio.isSelected())
      {
         titleColor = "GREEN";
      }
      
      if (titleRedRadio.isSelected())
      {
         titleColor = "RED";
      }
      
      if (titleBlackRadio.isSelected())
      {
         titleColor = "BLACK";
      }
      
      return titleColor;
      
   }
   
   
   
   /**
    * Gets the diary skip settings.
    * @return
    */
   private String getDiarySkip()
   {
      String diarySkip = "";
      
      
      if (currentPage.isSelected())
      {
         diarySkip = "1";
      }
      
      else
      {
         diarySkip = "0";
      }
      
      
      return diarySkip;
      
   }
   
   
   
   /**
    * Gets the diary year settings.
    * @return
    */
   private String getDiaryYear()
   {

      return ((String)yearBox.getSelectedItem());
   }
   
   
   
   /**
    * Gets the diary date settings.
    * @return
    */
   private String getDiaryDate()
   {

      return ((String)dateBox.getSelectedItem());
   }
   
   
   //***************************************** END PRIVATE METHODS *****************************************//
   
   
   
   /** 
    * ESCA-JAVA0007: 
    */
   public JFrame frame;

   private JMenuBar menuBar;
   private PersonalDiary diary;
   private String userId, userPw;
   private Container contentPane;
   private JCheckBox currentPage;
   private boolean zoomWarningShown;
   private JMenu headerText, titleText;
   private JButton diaryBack, diaryNext;
   private GridBagConstraints constraints;
   private JComboBox yearBox, dateBox;
   private JTextPane monthDisplay, yearDisplay;
   private JMenuItem saveMenuItem, clearMenuItem;
   
   private JScrollPane mondayScroll, tuesdayScroll, 
   wednesdayScroll, thursdayScroll, fridayScroll, saturdayScroll, sundayScroll;
   
   private TitledBorder mondayBorder, tuesdayBorder, 
   wednesdayBorder, thursdayBorder, fridayBorder, saturdayBorder, sundayBorder;

   private JCheckBoxMenuItem headerUnderlineCheck, headerItalicCheck, headerBoldCheck;
   
   private JPanel leftContainer, rightContainer, calendarContainer, buttonContainer, 
   buttonPanel, calendarControl, comboPanel, navigationPanel, calendarDisplay;
   
   private ArrayList writeSettings, diaryReadSettings, entryReadSettings, entryWriteSettings;
   
   private JRadioButtonMenuItem headerOrangeRadio, headerBlueRadio, headerBlackRadio, headerRedRadio, 
   headerGreenRadio, titleOrangeRadio, titleBlueRadio, titleBlackRadio, titleRedRadio, titleGreenRadio;
   
   private JTextArea monday, tuesday, wednesday, thursday, friday, saturday, sunday, weekDisplay, dayDisplay;
  
   
   //********************************************** END CLASS **********************************************//
   
}


/*
   COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved.

   This class reads and writes entries into the diary.

   @site http://www.javaika.com
   @author Alexander Wait
   @version 2012-05-05
*/



public class PersonalDiary 
{

   private static final int ARRAY_DIMENSION = 2;
   
   
   //************************************** START INITIALISATION CODE **************************************//

   
   /**
    * Class constructor.
    * @param year
    */
   public PersonalDiary(int year)
   {
      currentWeek = 1;
   
      calendar = new Calendar(year);
      
      days = DateAndTime.returnDays(year);
       
      record = new String[days][ARRAY_DIMENSION];
      
      
      addDates();
   }
   
   
   //*************************************** END INITIALISATION CODE ***************************************//
   
   
   //**************************************** START PUBLIC METHODS *****************************************//
   
   
   /**
    * Increments the current week by one.
    */
   public void incrementWeek()
   {
      if (currentWeek != getWeekTotal())
      { 
         currentWeek ++;
      }
   }
   
   
   
   /**
    * Increments the current week by one.
    */
   public void decrementWeek()
   {
      if (currentWeek != 1) 
      {
         currentWeek --;
      }
   }
   
   
   
   /**
    * Sets current week to the week of the actual date.
    */
   public void setCurrentWeek()
   {
      currentWeek = Integer.parseInt
      (calendar.getWeek(DateAndTime.returnTodaysDate(false)));
      
   }
   
   
   
   /**
    * Sets current week to a specified date.
    * @param date
    */
   public void setSpecifiedWeek(String date)
   {
      currentWeek = Integer.parseInt(calendar.getWeek(date));
      
   }
   
   
   
   /**
    * Adds an entry to the diary.
    * @param weekNumber
    * @param dayNumber
    * @param entry
    */
   public void insertEntry(int weekNumber, int dayNumber, String entry)
   {
      String date = calendar.getDate(weekNumber, dayNumber);
      
      
      for (int i = 0; i < days; i ++)
      {
         if (record[i][0].equals(date))
         {
            record[i][1] = entry;
         }
      }
   }
   
   
   
   /**
    * Sets an entry in the diary 
    * at a specified date.
    * ESCA-JAVA0270:
    * @param date
    * @param entry
    */
   public void setEntry(String date, String entry)
   { 
      for (int i = 0; i < record.length; i ++)
      {
         if (record[i][0].equals(date))
         {
            record[i][1] = entry;
         }
      }
   }
   
   
   
   /**
    * Return true if a day of the week exists in a week
    * for a previously defined year.
    * @param weekNumber
    * @param dayNumber
    * @return
    */
   public boolean isValidDayOfWeek(int weekNumber, int dayNumber)
   {
 
      return (calendar.isValid(weekNumber, dayNumber));
   }
   
   
   
   /**
    * Retrieves an entry from the diary.
    * @param weekNumber
    * @param dayNumber
    * @return entry
    */
   public String retrieveEntry(int weekNumber, int dayNumber)
   {
   
      String entry = null; 
      
      String date = calendar.getDate(weekNumber, dayNumber);
      
 
      for (int i = 0; i < days; i ++)
      {
         if (record[i][0].equals(date))
         {
            entry = record[i][1];
         }
      }
      
      
      return entry;
   }
   
   
   
   /**
    * Returns the month string of the week.
    * @param weekNumber
    * @return
    */
   public String getMonth(int weekNumber)
   {
    
      String monthString = null;
      
      int listSize = calendar.spanOfDates(weekNumber).size(); 

      
      String startMonth = DateAndTime.returnSplitDate
      (calendar.spanOfDates(weekNumber).get(0), DateAndTime.Elements.MONTH);
      
      String endMonth = DateAndTime.returnSplitDate
      (calendar.spanOfDates(weekNumber).get(listSize -1), DateAndTime.Elements.MONTH);
      

      if (startMonth.equals(endMonth))
      {
         monthString = DateAndTime.returnMonthName(Integer.parseInt(startMonth));
      }
      
      
      if (!startMonth.equals(endMonth))
      {
         monthString = DateAndTime.returnMonthName(Integer.parseInt(startMonth)) 
         
         + " - " + 
         
         DateAndTime.returnMonthName(Integer.parseInt(endMonth));
      }
      
      
      return monthString;
   }
   
   
   
   /**
    * Returns the day of the month.
    * @param weekNumber
    * @param dayNumber
    * @return
    */
   public String getDayOfMonth(int weekNumber, int dayNumber)
   {
     
      String dayOfMonth = DateAndTime.returnSplitDate
      (calendar.getDate(weekNumber, dayNumber), DateAndTime.Elements.DAY);
      
      
      return (Integer.toString(Integer.parseInt(dayOfMonth)));
   }
   
   
   
   /**
    * Returns the number of weeks for the year.
    * @return
    */
   public int getWeekTotal()
   {

      return (Integer.parseInt
      (
         calendar.week.get(calendar.week.size() - 1))
      );
   }
   
   
   
   /**
    * Returns the current week.
    * @return
    */
   public int getCurrentWeek()
   {

      return currentWeek;
   }
   
   
   
   /**
    * Returns the record array.
    * @return
    */
   public String[][] getRecords()
   {
      return record.clone();
   }
   
   
   //***************************************** END PUBLIC METHODS ******************************************//

   
   //**************************************** START PRIVATE METHODS ****************************************//
   
   
   /**
    * Populates the record array with dates.
    */
   private void addDates()
   {
      for (int i = 0; i < days; i ++)
      {
         record[i][0] = calendar.date.get(i);
      }
   }
   
   
   //***************************************** END PRIVATE METHODS *****************************************//

   
   private int days;
   
   private int currentWeek;
   
   private String[][] record;
   
   private Calendar calendar;
   
   
   //********************************************** END CLASS **********************************************//
   
}


/*
   COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved.

   This class provides calendar functions.

   @site http://www.javaika.com
   @author Alexander Wait
   @version 2012-05-05
*/



import java.util.ArrayList;



public class Calendar
{

   //************************************** START INITIALISATION CODE **************************************//


   /**
    * Class constructor.
    * @param year
    */
   public Calendar(int year) 
   {
      clearLists(); 
   
      initialiseDateArray(year);
      
      initialiseWeekArray(year);
      
      initialiseDayArray(year); 
          
   }
   
   
   //*************************************** END INITIALISATION CODE ***************************************//
   
   
   /**
    * Resets the array lists.
    */
   private void clearLists()
   {
      date.clear();
      
      week.clear();
      
      day.clear();  
   }
   
   
   //**************************************** START PUBLIC METHODS *****************************************//

   
   /**
    * Initializes the date array list.
    * @param year
    */
   public void initialiseDateArray(int year)
   {
      int days = DateAndTime.returnDateList(year, null).length;
   
      
      for (int i = 0; i < days; i ++)
      { 
         date.add(DateAndTime.returnDateList(year, null)[i]);
      }   
     
   }
   
   
   
   /**
    * Initializes the week array list.
    * ESCA-JAVA0119:
    * @param year
    */
   public void initialiseWeekArray(int year)
   {
      int counter = 0; int weekNumber = 1;
      
      int days = DateAndTime.returnDays(year);
      
      int startDay = DateAndTime.returnStartDayAsInt(year);
      
      
      for (int i = startDay; i <= DateAndTime.getDaysInWeek(); i ++)
      {
         if (i == 2) {weekNumber ++;}
      
         if (i == DateAndTime.getDaysInWeek()) {i = 0;}
    
         
         week.add(Integer.toString(weekNumber)); counter ++;
         
        
         if (counter == days) {break;}   
      }  
   }
   
   
   
   /**
    * Initializes the day array list.
    * ESCA-JAVA0119:
    * @param year
    */
   public void initialiseDayArray(int year)
   {
      int counter = 0; int days = DateAndTime.returnDays(year);
   
      int startDay = DateAndTime.returnStartDayAsInt(year);
      

      for (int i = startDay; i <= DateAndTime.getDaysInWeek(); i ++)
      {
         day.add(Integer.toString(i)); counter ++;
         
         
         if (i == DateAndTime.getDaysInWeek()) {i = 0;}
         
         if (counter == days) {break;}
         
      }  
   }
   
   
   
   /**
    * Returns true if a day of the given week exists.
    * On some occasions with week one of any year 
    * there can be transitions between the last 
    * years week days and week days that belong 
    * to the previous year are not valid for 
    * the year the calendar is set to.
    * @param weekNumber
    * @param dayNumber
    * @return
    */
   public boolean isValid(int weekNumber, int dayNumber)
   {
      boolean valid = false;
      
      
      for (int i = 0; i < week.size(); i ++)
      {
         if (week.get(i).equals(Integer.toString(weekNumber))
         && day.get(i).equals(Integer.toString(dayNumber)))
         {
            valid = true; 
         }
      }
      
      
      return valid;     
      
   }
   
   
   
   /**
    * Returns the date that matches the week number and the week day.
    * @param weekNumber
    * @param dayNumber
    * @return
    */
   public String getDate(int weekNumber, int dayNumber)
   {
      String dateMatch = null; 
      
 
      for (int i = 0; i < date.size(); i ++)
      {
          if ((week.get(i).equals(Integer.toString(weekNumber))) 
          && (day.get(i).equals(Integer.toString(dayNumber))))
          {
             dateMatch =  date.get(i);
          }
      }
      
      return dateMatch;
   
   }
   
   
   
   /**
    * Returns the week as a string given a date.
    * @param dateString
    * @return
    */
   public String getWeek(String dateString)
   {
      String weekString = null; 

      
      for (int i = 0; i < date.size(); i ++)
      {
         if (date.get(i).equals(dateString))
         {
            weekString = week.get(i);
         }
      }
      
      
      return weekString;
   }
   
   
   
   /**
    * Analyzes a week and returns the date at the start 
    * of the week and the date at the end of the week
    * and returns these dates in an array list.
    * @param weekNumber
    * @return
    */
   public ArrayList spanOfDates(int weekNumber)
   {
      ArrayList dateSpan = new ArrayList();
      
      for (int i = 0; i < week.size(); i ++)
      {
         if (week.get(i).equals(Integer.toString(weekNumber)))
         {
            dateSpan.add(date.get(i)); break;
         }
      }
      
      
      for (int i = week.size() - 1; i >= 0; i --)
      {
         if (week.get(i).equals(Integer.toString(weekNumber)))
         {
            dateSpan.add(date.get(i)); break;
         }
      }
      
  
      return dateSpan;
   }
   
   
   //***************************************** END PUBLIC METHODS ******************************************//

 
   ArrayList date = new ArrayList();
   
   ArrayList week = new ArrayList();
   
   ArrayList day = new ArrayList();
   
   
   //********************************************** END CLASS **********************************************//
  
}


/*
   COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved.

   This class performs particular functions on a supplied data set.

   @site http://www.javaika.com
   @author Alexander Wait
   @version 2010-07-18
*/



import java.util.*;



public class DataFunctions 
{ 

   private static final double EPSILON = 0;

   
   private DataFunctions() {}
   
   
   //**************************************** START PUBLIC METHODS *****************************************//
   
   
   /**
    * Encodes a text with line breaks using a specified flag
    * character. The same flag character can be used to
    * decode the text back to include line breaks.
    * @param text
    * @param flag
    * @return
    */
   public static String newlineFlagEncoding(String text, String flag)
   {
      if (text != null)
      {
         return text.replaceAll("\n", flag);
      }
      
      else
      {
         return null;
      }
   }
   
   
   
   /**
    * Decodes a text with line break flags to reconstruct the
    * original text with line breaks.
    * @param text
    * @param flag
    * @return
    */
   public static String newlineFlagDecoding(String text, String flag)
   {
      if (text != null)
      {
         return text.replaceAll(flag, "\n");
      }
      
      else
      {
         return null;
      }
   }
   
   
   
   /**
    * Returns a random number in a range. 
    * @param minimum 
    * @param maximum 
    * @return 
    */
   public static int random(int minimum, int maximum)
   {
      Random dice = new Random();

      return (minimum + dice.nextInt(maximum - minimum + 1));
   }



   /**
    * Returns how many values in the data set. 
    * @param array 
    * @return 
    */
   public static int returnCount(double[] array)
   {

      return array.length;
   }



   /**
    * Finds the range. 
    * @param array 
    * @return 
    */
   public static double returnRange(double[] array)
   {

      return (returnMaximum(array) - returnMinimum(array));
   }



   /**
    * Returns the data set.
    * @param array 
    * @return data
    */
   public static String printData(double[] array)
   {
      String data = "{ "; boolean executed = false;

      
      for (double element : array) 
      {
         if (executed) {data += (" , " + element);}

         else {data += element;}
         
         executed = true;
      }

      data += " }";

      return data;
   }



   /**
    * Returns the modes and mode frequency of a data set.
    * @param array  
    *  @return modes
    */
   public static String returnModes(double[] array)
   {
      String modes = "{ "; boolean executed = false; double data = 0;
      
      double[] occurances = new double[array.length]; int count = 0;

      
      for (int i = 0; i < array.length; i ++)
      {
         data = array[i];

         for (int j = i; j < array.length; j ++)
         {
            if (areDoublesEqual(array[j], data)) {count ++;}
         }

         occurances[i] = count; count = 0;
      }

      for (int i = 0; i < occurances.length; i ++)
      {
         if (areDoublesEqual(occurances[i], returnMaximum(occurances)))
         {
            if (executed) {modes += (" , " + array[i]);}
            
            else {modes += array[i];} executed = true;
         }
      }

      modes += (" }" + Tools.returnNewline(2) + "  The mode occurances are: " + 
      
      (int)returnMaximum(occurances));

      return modes;
   }



   /**
    * Finds the sum of all the values within the data set.
    * @param array 
    * @param squares 
    * @return sum
    */
   public static double returnSum(double[] array, boolean squares)
   {

      double sum = 0;

      
      for (double element : array) 
      {
         if (squares)
         {
            sum += Math.pow((element), 2);
         }

         else 
         {
            sum += element;
         }
      }

      return sum;
   }
   


   /**
    * Finds the mean.
    * @param array 
    * @param squares 
    * @return mean
    */
   public static double returnMean(double[] array, boolean squares)
   {
      double mean = 0;

      
      if (squares)
      {
         mean = returnSum(array, true) / array.length;
      }

      else 
      {
         mean = returnSum(array, false) / array.length;
      }

      return mean;
   }



   /**
    * Finds the variance or standard deviation.
    * @param array 
    * @param variance 
    * @return 
    * @return
    */
   public static double returnDeviationVariance(double[] array, boolean variance)
   {
      double deviationCount = 0;

      
      for (double element : array) 
      {
         deviationCount += (Math.pow((element - returnMean(array, false)), 2));
      }

      if (variance) 
      {
         return (deviationCount / array.length);
      }

      else 
      {
         return (Math.sqrt(deviationCount / (array.length - 1)));
      }
   }



   /**
    * Finds the maximum value.
    * @param array
    * @return maximum
    */
   public static double returnMaximum(double[] array)
   {
      double maximum = Double.NEGATIVE_INFINITY; 

      
      for (double element : array) 
      {
         if (element > maximum)
         {
            maximum = element;
         }
      }

      return maximum;
   }



   /**
    * Finds the minimum value.
    * @param array  
    * @return minimum
    */
   public static double returnMinimum(double[] array)
   {
      double minimum = Double.POSITIVE_INFINITY; 

      
      for (double element : array) 
      {
         if (element < minimum)
         {
            minimum = element;
         }
      }

      return minimum;
   }



   /**
    * Finds the median value.
    * @param array 
    * @return median
    */
   public static double returnMedian(double[] array)
   {
      double median = 0; double data = 0; double[] clone = new double[array.length]; 

      
      for (int i = 0; i < array.length; i ++) 
      {clone[i] = array[i];}

      for (int i = 0; i < clone.length; i ++)
      {
         for (int j = i; j < clone.length; j ++)
         {
            data = clone[i];

            if (clone[j] < clone[i])
            {
               clone[i] = clone[j]; 
               clone[j] = data;
            }
         }
      }

      if (clone.length % 2 == 0) 
      {median = (clone[(clone.length / 2) - 1] + clone[(clone.length / 2)]) / 2;}

      else {median = clone[(clone.length - 1) / 2];}

      return median;
   }



   /**
    * Finds the FIBONACCI number at a specified location. 
    * @param location 
    * @return current
    */
   public static long fibonacci(int location)
   {
      long secondPrevious = 0; long firstPrevious = 1; 
      
      long current = secondPrevious + firstPrevious;

      
      if (location == 0) {return secondPrevious;}

      else if (location == 1) {return firstPrevious;}

      else
      {
         for (int i = 1; i < location; i ++)
         {
            current = secondPrevious + firstPrevious;
            secondPrevious = firstPrevious;
            firstPrevious = current; 
         }

         return current;
      }
   }
   
   
   
   /**
    * Tests if a number is prime.
    * @param number
    * @return
    */
   public static boolean isPrime(int number)
   {
      boolean prime = true; final int first = 2;
      
      
      if (number > first)
      {
         for (int i = first; i < number; i ++)
         {
            if ((number % i) == 0)
            {
               prime = false; break;
            }
         }
      }
      
      if (number < first) {prime = false;}

      
      return prime;
   }



   /**
    * Tests if two double values are equal using a threshold value.
    * @param first
    * @param second
    * @return
    */
   public static boolean areDoublesEqual(double first, double second)
   {
      return (Math.abs(first - second) <= EPSILON);
   }
   
   
   
   /**
    * Tests if one double value is greater than another.
    * @param first
    * @param second
    * @return
    */
   public static boolean isDoubleGreater(double first, double second)
   {
      return (first > second);
   }
   
   
   //***************************************** END PUBLIC METHODS ******************************************//
   

   //********************************************** END CLASS **********************************************//
   
}


/*
   COPYRIGHT (C) 2010 -2013 by Alexander Wait. All Rights Reserved.

   This class returns date and time and provides functions relating to time.

   @site http://www.javaika.com
   @author Alexander Wait
   @version 2012-04-18
*/



import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;



public class DateAndTime 
{

   private static final int DAY_INDEX = 2; 
   private static final int MONTH_INDEX = 1; 
   private static final int YEAR_INDEX = 0; 
   
   private static final int MILLISECONDS_PER_SECOND = 1000;
   private static final int SECONDS_PER_MINUTE = 60;
   private static final int MINUTES_PER_HOUR = 60;
   private static final int HOURS_PER_DAY = 24;
   
   private static final int DAYS_IN_WEEK = 7;
   private static final int DAYS_IN_YEAR = 365;
   private static final int WEEKS_IN_YEAR = 52;   
   private static final int MONTHS_IN_YEAR = 12;
   private static final int FORTNIGHTS_IN_YEAR = 26;
   
   private static Calendar now = Calendar.getInstance();
   
   public static enum Elements {YEAR, MONTH, DAY}
   

   private DateAndTime() {}
   
   
   //**************************************** START PUBLIC METHODS *****************************************//
   
   
   /**
    * Tests and compares two dates.
    * @param dateFirst
    * @param dateSecond
    * @return
    */
   public static boolean dateComparison(String dateFirst, String dateSecond) 
   {
      String[] first = dateFirst.split("[-]", 0); 
      
      String[] second = dateSecond.split("[-]", 0);

      int firstDayInt = Integer.parseInt(first[DAY_INDEX]); 
      
      int firstMonthInt = Integer.parseInt(first[MONTH_INDEX]); 
      
      int firstYearInt = Integer.parseInt(first[YEAR_INDEX]); 
      
      int secondDayInt = Integer.parseInt(second[DAY_INDEX]); 
      
      int secondMonthInt = Integer.parseInt(second[MONTH_INDEX]); 
      
      int secondYearInt = Integer.parseInt(second[YEAR_INDEX]);

      return 
      
        compareDates(firstDayInt, firstMonthInt, 
        firstYearInt, secondDayInt, secondMonthInt, secondYearInt);
   }



   /**
    * Compares two dates to test if one date is more current than the other. 
    * @param fstDay
    * @param fstMonth
    * @param fstYear
    * @param sndDay
    * @param sndMonth
    * @param sndYear
    * @return
    */
   public static boolean compareDates(int fstDay, int fstMonth, 
   int fstYear, int sndDay, int sndMonth, int sndYear)
   {
      if (sndYear > fstYear) {return true;}

      else if (sndYear < fstYear) {return false;}

      else
      {
         if (sndMonth > fstMonth) {return true;}

         else if (sndMonth < fstMonth) {return false;}

         else 
         {
            if (sndDay >= fstDay) {return true;}

            else {return false;}
         }
      }
   }
   
   
   
   /**
    * Returns true if the time given is before current time.
    * @param hour
    * @param minute
    * @param second
    * @return
    */
   public static boolean isBeforeCurrentTime(int hour, int minute, int second)
   {
      
      if (returnHour() > hour) {return true;}
     
      else if (returnHour() < hour) {return false;}
  
      else 
      {
         if (returnMinute() > minute) {return true;}
         
         else if (returnMinute() < minute) {return false;}
       
         else 
         {
            if (returnSecond() > second) {return true;}
        
            else {return false;}
         }
      } 
  
   }
   
   
   
   /**
    * Returns true if the time to be tested is after the reference.
    * @param hour
    * @param minute
    * @param second
    * @param testHour
    * @param testMinute
    * @param testSecond
    * @return
    */
   public static boolean isAfterReferenceTime(int hour, int minute, 
   int second, int testHour, int testMinute, int testSecond)
   {
  
      if (hour < testHour) {return true;}
      
      else if (hour > testHour) {return false;}
   
      else 
      {
    
         if (minute < testMinute) {return true;}
         
         else if (minute > testMinute) {return false;}
         
         else 
         {
      
            if (second < testSecond) {return true;}
        
            else {return false;}
         }
      } 
  
   }
   
   
   
   /**
    * Finds the difference between two times in hours.
    * @param startHour
    * @param startMinute
    * @param endHour
    * @param endMinute
    * @return
    */
   public static double timeDifferenceHours(int startHour, 
   int startMinute, int endHour, int endMinute)
   {
      double endMinutes = endHour * MINUTES_PER_HOUR + endMinute;
      
      double startMinutes = startHour * MINUTES_PER_HOUR + startMinute;
   
      return ((endMinutes - startMinutes) / MINUTES_PER_HOUR);
   }

   
   
   /**
    * Returns true if a specified time is within one of a list of ranges.
    * @param startHour
    * @param startMinute
    * @param startSecond
    * @param finishHour
    * @param finishMinute
    * @param finishSecond
    * @param hour
    * @param minute
    * @param second
    * @param length
    * @return
    */
   public static boolean isOverlapped(ArrayList startHour, 
   ArrayList startMinute, ArrayList startSecond, 
   ArrayList finishHour, ArrayList finishMinute, 
   ArrayList finishSecond, int hour, int minute, 
   int second, int length)
   {

      boolean overlapped = false; 
   
      for (int i = 0; i < length; i ++)
      {
         if (isAfterReferenceTime
         (startHour.get(i), startMinute.get(i), 
         startSecond.get(i), hour, minute, second)
         
         && (!isAfterReferenceTime
         (finishHour.get(i), finishMinute.get(i), 
         finishSecond.get(i), hour, minute, second)))
         {
            overlapped = true;
            
         }
               
      }
      
     return overlapped;
     
   }
   
   
   
   /**
    * Tests if a year is a leap year.
    * @param year
    * @return
    */
   public static boolean isLeapYear(int year)
   {
      boolean leapYear = false;
      
      final int LEAP_DIVISOR_SHORT = 4;
      
      final int LEAP_DIVISOR_MIDDLE = 100;
      
      final int LEAP_DIVISOR_LONG = 400;
      
      
      if ((year % LEAP_DIVISOR_SHORT) == 0)
      {
         if ((year % LEAP_DIVISOR_MIDDLE) != 0)
         {
            leapYear = true;
         }
         
         if (((year % LEAP_DIVISOR_MIDDLE) == 0) 
         && ((year % LEAP_DIVISOR_LONG) == 0))
         {
            leapYear = true;
         }
         
      }
      
     
      return leapYear;

   }
   
   
   
   /**
    * Returns todays date.
    * @param includeTimeMask
    * @return
    */
   public static String returnTodaysDate(boolean includeTimeMask)
   {
      refreshCalendar(); now.getTime();
   
      
      String todaysDate = ""; String timeMask = "00:00:00";
      
      SimpleDateFormat date = new SimpleDateFormat("YYYY-MM-dd");
      
     
      if (includeTimeMask)
      {
         todaysDate = date.format(now.getTime()) + " " + timeMask;
      }
      
      else
      {
         todaysDate = date.format(now.getTime());
      }
      
      
      return todaysDate; 
   }
   
   
   
   /**
    * Returns a specific element of a date string.
    * @param date
    * @param component
    * @return
    */
   public static String returnSplitDate(String date, Elements component)
   {
      String element = null;
      
      
      String[] elementArray = date.split("-");
      
      
      if (component.equals(Elements.YEAR))
      {
         element = elementArray[0];
      }
      
      if (component.equals(Elements.MONTH))
      {
         element = elementArray[1];
      }
      
      if (component.equals(Elements.DAY))
      {
         element = elementArray[2];
      }

      
      return element;
      
   }
   

   
   /**
    * Returns the name of a month expressed as an integer.
    * ESCA-JAVA0076:
    * @param month
    * @return
    */
   public static String returnMonthName(int month)
   {
      String monthName = null;

      
      switch (month)
      {
         case 1: monthName = "January"; break;
         
         case 2: monthName = "February"; break;
         
         case 3: monthName = "March"; break;
         
         case 4: monthName = "April"; break;
         
         case 5: monthName = "May"; break;
           
         case 6: monthName = "June"; break;
         
         case 7: monthName = "July"; break;
         
         case 8: monthName = "August"; break;
         
         case 9: monthName = "September"; break;
         
         case 10: monthName = "October"; break;
         
         case 11: monthName = "November"; break;
         
         case 12: monthName = "December"; break;
      
         default: monthName = "Invalid Input"; break;
      }
      
      
      return monthName;
   }
   
   
   
   /**
    * Returns a list of dates.
    * @param year
    * @param heading
    * @return
    */
   public static String[] returnDateList(int year, String heading)
   {
   
      ArrayList list = new ArrayList();
     
      
      if (heading != null) {list.add(heading);}
      
      
      for (int i = 1; i <= MONTHS_IN_YEAR; i ++)
      {
         int bound = returndaysInMonth(i);
         
         
         if (isLeapYear(year) && (i == 2)) {bound ++;}
         
         
         for (int j = 1; j <= bound; j ++)
         {
            list.add(year + "-" + returnDigitMask(i, 2) + "-" + returnDigitMask(j, 2)); 
         }
        
      }
  
      
      String[] dates = new String[list.size()];
      
      list.toArray(dates);
      
      return dates;
   }
   
   
   
   /**
    * Returns the days of a specified month.
    * ESCA-JAVA0076:
    * @param month
    * @return
    */
   public static int returndaysInMonth(int month)
   {
      int days = -1; final int SHORT = 28; 
   
      final int MIDDLE = 30; final int LONG = 31;
  
      switch (month)
      {
         case 1: days = (LONG); break; case 2: days = (SHORT); break;
         
         case 3: days = (LONG); break; case 4: days = (MIDDLE); break;
         
         case 5: days = (LONG); break; case 6: days = (MIDDLE); break;
         
         case 7: days = (LONG); break; case 8: days = (LONG); break;
         
         case 9: days = (MIDDLE); break; case 10: days = (LONG); break;
         
         case 11: days = (MIDDLE); break; case 12: days = (LONG); break;  
      
         default: return days;         
      }
   
      return days;  
   }
   
   
   
   /**
    * Converts an integer to a mask.
    * ESCA-JAVA0076:
    * @param value
    * @param maxValueLength
    * @return
    */
   public static String returnDigitMask(int value, int maxValueLength)
   {     
      String digit = Integer.toString(value); String trailing = "";
      
      if (digit.length() == maxValueLength)
      {
         return digit;
      }
   
      else
      {
         for (int i = digit.length(); i < maxValueLength; i ++)
         {
            trailing += "0";
         }
     
         return (trailing + digit); 
      } 
   }
   
   
   
   /**
    * Returns the seconds elapsed in counter format (HH:MM:SS).
    * @param counter
    * @param millisecondCount
    * @return
    */
   public static String returnCounterTime(long counter, boolean millisecondCount)
   {
      String counterTime = ""; 
  
  
      setCounterHours((short)0); setCounterMinutes((short)0);
      
      setCounterSeconds((short)0); setCounterMilliseconds((short)0);
  
      
      final int DIGIT_LENGTH = 2; final double MILLIS_DIVISOR = 100;
      
   
      for (int i = 0; i < counter; i ++)
      {
         if (millisecondCount) {counterMilliseconds ++;} 
         
         else {counterSeconds ++;}
         
         
         if (counterMilliseconds == MILLISECONDS_PER_SECOND) 
         
         {setCounterMilliseconds((short)0); counterSeconds ++;}
         
         
         if (counterSeconds == SECONDS_PER_MINUTE) 
         
         {setCounterSeconds((short)0); counterMinutes ++;}
         
         if (counterMinutes == MINUTES_PER_HOUR) 
         
         {setCounterMinutes((short)0); counterHours ++;}
      }
      
      
      if (millisecondCount) 
      {
         counterTime = ":" + (int)Math.floor(getCounterMilliseconds() / MILLIS_DIVISOR);
      }
      
      
      counterTime = 
      (
         returnDigitMask(getCounterHours(), DIGIT_LENGTH) + ":" +
             
         returnDigitMask(getCounterMinutes(), DIGIT_LENGTH) + ":" +
     
         returnDigitMask(getCounterSeconds(), DIGIT_LENGTH) + counterTime
      );
      
      
      return counterTime;
      
   }
   
   
   
   /**
    * Returns the formatted time (24 hour or standard)
    * @param twentyFourHour
    * @return
    */
   public static String returnFormattedTime(boolean twentyFourHour)
   {
      refreshCalendar(); String time = ""; 
      
      
      DateFormat full = new SimpleDateFormat("HH:mm:ss");
      
      DateFormat standard = new SimpleDateFormat("h:mm:ss");
      
      
      if (twentyFourHour) {time = full.format(now.getTime());}
      
      else {time = standard.format(now.getTime());}
  
        
      return time;   
   }
   
   
   
   /**
    * Returns the day at the start of the given year.
    * ESCA-JAVA0076:
    * @param year
    * @return
    */
   public static int returnStartDayAsInt(int year)
   {
      Calendar cal = new GregorianCalendar(year, Calendar.JANUARY, 1);
  
      return (cal.get(Calendar.DAY_OF_WEEK));
   }
   
   
   
   /**
    * Returns the day at the start of the given year.
    * ESCA-JAVA0076:
    * @param year
    * @return
    */
   public static int returnEndDayAsInt(int year)
   {
      Calendar cal = new GregorianCalendar(year, Calendar.DECEMBER, 31);
  
      return (cal.get(Calendar.DAY_OF_WEEK));
   }
   
   
   
   /**
    * Returns the specific day of week as an integer.
    * 1 = Sunday, 2 = Monday, 3 = Tuesday ...
    * ESCA-JAVA0076:
    * @param year
    * @param month
    * @param day
    * @return
    */
   public static int returnDayOfWeekAsInt(int year, int month, int day)
   {
      Calendar cal = null; 

      
      switch (month)
      {
         case 1: cal = new GregorianCalendar(year, Calendar.JANUARY, day); break;
         
         case 2: cal = new GregorianCalendar(year, Calendar.FEBRUARY, day); break;
         
         case 3: cal = new GregorianCalendar(year, Calendar.MARCH, day); break;
         
         case 4: cal = new GregorianCalendar(year, Calendar.APRIL, day); break;
         
         case 5: cal = new GregorianCalendar(year, Calendar.MAY, day); break;  
        
         case 6: cal = new GregorianCalendar(year, Calendar.JUNE, day); break;
         
         case 7: cal = new GregorianCalendar(year, Calendar.JULY, day); break;
         
         case 8: cal = new GregorianCalendar(year, Calendar.AUGUST, day); break;
         
         case 9: cal = new GregorianCalendar(year, Calendar.SEPTEMBER, day); break;
         
         case 10: cal = new GregorianCalendar(year, Calendar.OCTOBER, day); break;
         
         case 11: cal = new GregorianCalendar(year, Calendar.NOVEMBER, day); break;
         
         case 12: cal = new GregorianCalendar(year, Calendar.DECEMBER, day); break;
         
         
         default: return (-1);
      
      }
      
  
      return (cal.get(Calendar.DAY_OF_WEEK));
   }
   
  
   
   /**
    * Returns a list of years between the given 
    * parameter and the current year.
    * @param year
    * @return
    */
   public static String[] returnYearChoices(int year)
   {
     
      int difference = Math.abs(returnYear() - year);
      
      String[] choices = new String[difference +1];
 
  
      if (year < returnYear())
      {
         for (int i = 0; i <= difference; i ++)
         {
            choices[i] = Integer.toString(year + i);
         }
      }
      
      if (year > returnYear())
      {
         for (int i = 0; i <= difference; i ++)
         {
            choices[i] = Integer.toString(returnYear() + i); 
         }
      }
      
      return choices;
      
   }
   

   
   /**
    * Returns a list for seconds.
    * @return
    */
   public static String[] returnSecondChoices()
   {
      
     
      String[] secondList = new String[SECONDS_PER_MINUTE];
   
      for (int i = 0; i < SECONDS_PER_MINUTE; i ++)  
      {
         secondList[i] = Integer.toString(i);
      
      }
      
      return secondList;
   }
   
   
   
   /**
    * Returns a list for minutes.
    * @return
    */
   public static String[] returnMinuteChoices()
   {
      
     
      String[] minuteList = new String[MINUTES_PER_HOUR];
   
      for (int i = 0; i < MINUTES_PER_HOUR; i ++)  
      {
         minuteList[i] = Integer.toString(i);
      
      }
      
      return minuteList;
   }
   
   
   
   /**
    * Returns a list for hours.
    * @return
    */
   public static String[] returnHourChoices()
   {
      String[] hourList = new String[HOURS_PER_DAY];
   
      for (int i = 0; i < HOURS_PER_DAY; i ++)  
      {
         hourList[i] = Integer.toString(i);
      
      }
      
      return hourList;
   }
   
   
   
   /**
    * Returns the current year.
    * @return
    */
   public static int returnYear()
   {
      refreshCalendar(); 

      return (now.get(Calendar.YEAR));
   }
   
   
   
   /**
    * Returns the current year.
    * @return
    */
   public static int returnMonth()
   {
      refreshCalendar(); 
 
      return (now.get(Calendar.MONTH) + 1);
   }
    
   
   
   /**
    * Returns the current year.
    * @return
    */
   public static int returnDay()
   { 
      refreshCalendar(); 
   
      return (now.get(Calendar.DATE));
   }
   
   
   
   /**
    * Returns the hour in double digits.
    * @return
    */
   public static String returnHourDouble()
   {
      return returnDigitMask(returnHour(), 2);
   }
   
   
   
   /**
    * Returns the minute in double digits.
    * @return
    */
   public static String returnMinuteDouble()
   {
      return returnDigitMask(returnMinute(), 2);
   }
   
   
   
   /**
    * Returns the second in double digits.
    * @return
    */
   public static String returnSecondDouble()
   {
      return returnDigitMask(returnSecond(), 2);
   }
   
   
 
   /**
    * Returns the hour.
    * @return
    */
   public static int returnHour()
   {
      refreshCalendar(); 
   
      DateFormat hours = new SimpleDateFormat("HH");
      
      return (Integer.parseInt(hours.format(now.getTime())));
   }

   
   
   /**
    * Returns the minutes.
    * @return
    */
   public static int returnMinute()
   {
      refreshCalendar(); 
   
      DateFormat minutes = new SimpleDateFormat("mm");
      
      return (Integer.parseInt(minutes.format(now.getTime())));
   }
   
   
   
   /**
    * Returns the seconds.
    * @return
    */
   public static int returnSecond()
   {
      refreshCalendar();  
   
      DateFormat seconds = new SimpleDateFormat("ss");
      
      return (Integer.parseInt(seconds.format(now.getTime())));
   }
   
   
   
   /**
    * Returns the current stage of the day as AM or PM.
    * @return
    */
   public static String returnAmOrPm()
   {
      refreshCalendar(); 
     
      DateFormat ampm = new SimpleDateFormat("a");
        
      return (ampm.format(now.getTime()));   
   }
   
   
   
   /**
    * Returns the days in a year.
    * @param year
    * @return
    */
   public static int returnDays(int year)
   {
      if (DateAndTime.isLeapYear(year))
      {
         return getDaysLeapYear();
      }
      
      else
      {
         return DateAndTime.getDaysNormalYear();
      }   
   }
   
   
   
   /**
    * Refreshes the calendar.
    */
   public static void refreshCalendar()
   {
      now = Calendar.getInstance();
   }
   
  
   
   /**
    * Sets the counter hours.
    * @param value
    */
   public static void setCounterHours(short value) {counterHours = value;}
   
   
   
   /**
    * Sets the counter minutes.
    * @param value
    */
   public static void setCounterMinutes(short value) {counterMinutes = value;}
   
   
   
   /**
    * Sets the counter seconds.
    * @param value
    */
   public static void setCounterSeconds(short value) {counterSeconds = value;}
   
   
   
   /**
    * Sets the counter milliseconds.
    * @param value
    */
   public static void setCounterMilliseconds(short value) {counterMilliseconds = value;}
   
   
   
   /**
    * Returns the counter hours.
    * @return
    */
   public static short getCounterHours() {return counterHours;}
   
   
   
   /**
    * Returns the counter minutes.
    * @return
    */
   public static short getCounterMinutes() {return counterMinutes;}
   
   
   
   /**
    * Returns the counter seconds.
    * @return
    */
   public static short getCounterSeconds() {return counterSeconds;}
   
   
   
   /**
    * Returns the counter milliseconds.
    * @return
    */
   public static short getCounterMilliseconds() {return counterMilliseconds;}
   
   
   
   /**
    * Returns the days in a week.
    * @return
    */
   public static int getDaysInWeek() {return DAYS_IN_WEEK;}

   
   /**
    * Returns the days in a year.
    * @return
    */
   public static int getDaysNormalYear() {return DAYS_IN_YEAR;}
   
   
   /**
    * Returns the days in a year.
    * @return
    */
   public static int getDaysLeapYear() {return (DAYS_IN_YEAR + 1);}
   
   
   /**
    * Returns the weeks in a year.
    * @return
    */
   public static int getWeeksInYear() {return WEEKS_IN_YEAR;}
   
   
   /**
    * Returns the fort-nights in a year.
    * @return
    */
   public static int getFortnightsInYear() {return FORTNIGHTS_IN_YEAR;}
   
   
   /**
    * Returns the months in a year.
    * @return
    */
   public static int getMonthsInYear() {return MONTHS_IN_YEAR;}
   
   
   /**
    * Returns the seconds per minute.
    * @return
    */
   public static int getSecondsPerMinute() {return SECONDS_PER_MINUTE;}
   
   
   /**
    * Returns the seconds per minute.
    * @return
    */
   public static int getHoursPerWeek() {return HOURS_PER_DAY * DAYS_IN_WEEK;}
   
   
   //***************************************** END PUBLIC METHODS ******************************************//
   
   
   
   private static short counterHours, counterMinutes, counterSeconds, counterMilliseconds;
   
   
   //********************************************** END CLASS **********************************************//
 
}


/*
   COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved.

   This class returns the domain attributes.

   @site http://www.javaika.com
   @author Alexander Wait
   @version 2012-07-06
*/



public class Domain 
{
  
   private static final String DOMAIN = "javaika.com";

   private static final boolean RUN_LOCAL = false; 
   
   private static final boolean prefix = true;
   
   private static final String PORT = "80";
   
   
   private Domain() {}
   
   
   //**************************************** START PUBLIC METHODS *****************************************//
   
   
   /**
    * Returns the domain name.
    * @return
    */
   public static final String getDomain()
   {
      if (prefix)
      {
         return ("www." + DOMAIN);
      }
      
      else
      {
         return (DOMAIN);
      }
   }
   
   
   
   /**
    * Returns the port number.
    * @return
    */
   public static final String getPort()
   {
      if (RUN_LOCAL)
      {
         return (":" + PORT);
         
      }
      
      else {return ("");} 
   }
   
   
   //***************************************** END PUBLIC METHODS ******************************************//
   
   
   //********************************************** END CLASS **********************************************//

}


/*
   COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved.

   This class displays message dialogs.

   @site http://www.javaika.com
   @author Alexander Wait
   @version 2011-07-18
*/



import javax.swing.*;



public class Message
{

   private Message(){}
   
   
   //**************************************** START PUBLIC METHODS *****************************************//


   /**
    * Displays a message dialog.
    * @param text
    * @param heading
    * @param type 
    */
   public static void showMessage(String text, String heading, String type)
   {
      new JOptionPane(); Object[] options = {}; 

      if (type.equals("error"))
      {
         JOptionPane.showOptionDialog(null, text, heading,  
         JOptionPane.YES_OPTION, JOptionPane.ERROR_MESSAGE, null, options, null);
      }

      if (type.equals("information"))
      {
         JOptionPane.showOptionDialog(null, text, heading, 
         JOptionPane.YES_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, null);
      }

      if (type.equals("warning"))
      {
         JOptionPane.showOptionDialog(null, text, heading, 
         JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE, null, options, null);
      }

      if (type.equals("question"))
      {
         JOptionPane.showOptionDialog(null, text, heading, 
         JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, null);
      }
   }
   
   
   //***************************************** END PUBLIC METHODS ******************************************//
   
   
   //********************************************** END CLASS **********************************************//
   
}


/*
   COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved.

   This class provides a bridge that connects java with PHP
   scripts on the server for writing information from the 
   java application to a remote database on the server. 
   The class also receives data from PHP server scripts
   upon request for this information.

   @site http://www.javaika.com
   @author Alexander Wait
   @version 2012-03-18
*/



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;



public class Portal
{
   
 
   private Portal(){}
   
   
   //**************************************** START PUBLIC METHODS *****************************************//
   

   /**
    * Sends data to a specified PHP script address.
    * ESCA-JAVA0266:
    * @param address
    * @param userId
    * @param userPw
    * @param data
    */
   public static void javaToPhpGate(String address, String userId, String userPw, ArrayList data) 
   {
      scriptAddress = address;


      try 
      {
         url = new URL(scriptAddress); conn = url.openConnection(); conn.setDoOutput(true); 
      

         dataSend = URLEncoder.encode("userId", "UTF-8") + "=" + URLEncoder.encode(userId, "UTF-8")

         + "&" + URLEncoder.encode("userPw", "UTF-8") + "=" + URLEncoder.encode(userPw, "UTF-8");
         
         
         if (data != null) {setVariableValues(data);} sendData(); 
         
         reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 


         while ((dataRecieve = reader.readLine()) != null) 
         {

            System.out.println(dataRecieve);
         }


         reader.close();
         
      }
      
      catch (IOException e) {System.out.println(Tools.thisPathAndLine() + e + "\n");}

   }
   
  
   
   /**
    * Receives data from a specified PHP script address.
    * ESCA-JAVA0266:
    * @param address
    * @param userId
    * @param userPw
    * @param data
    * @return
    */ 
   public static ArrayList phpToJavaGate(String address, String userId, String userPw, ArrayList data)
   { 
      scriptAddress = address; 

      ArrayList output = new ArrayList();
   

      try
      { 
         url = new URL(scriptAddress); conn = url.openConnection(); conn.setDoOutput(true);
     

         dataSend = URLEncoder.encode("userId", "UTF-8") + "=" + URLEncoder.encode(userId, "UTF-8")

         + "&" + URLEncoder.encode("userPw", "UTF-8") + "=" + URLEncoder.encode(userPw, "UTF-8");
         
         
         if (data != null) {setVariableValues(data);} sendData(); 
         
         reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
       
         
         while ((dataRecieve = reader.readLine()) != null) 
         {
            output.add(dataRecieve);
         }
        

         reader.close();
        
      }
      
      catch (IOException e) {System.out.println(Tools.thisPathAndLine() + e + "\n");}
      

      return output;
         
   }
   
   
   
   /**
    * Clears database records using a specified PHP script address.
    * ESCA-JAVA0266:
    * @param address
    * @param userId
    * @param userPw
    * @param data
    */
   public static void clearFromDatabase(String address, String userId, String userPw, ArrayList data) 
   {
      scriptAddress = address;


      try 
      {
         url = new URL(scriptAddress); conn = url.openConnection(); conn.setDoOutput(true); 
      

         dataSend = URLEncoder.encode("userId", "UTF-8") + "=" + URLEncoder.encode(userId, "UTF-8")

         + "&" + URLEncoder.encode("userPw", "UTF-8") + "=" + URLEncoder.encode(userPw, "UTF-8");
         
         
         if (data != null) {setVariableValues(data);} sendData();
         
         reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));


         while ((dataRecieve = reader.readLine()) != null) 
         {

            System.out.println(dataRecieve);
         }


         reader.close();
         
      }
      
      catch (IOException e) {System.out.println(Tools.thisPathAndLine() + e + "\n");}

   }
   
   
   //***************************************** END PUBLIC METHODS ******************************************//


   //**************************************** START PRIVATE METHODS ****************************************//

   
   /**
    * Sets the PHP variable values.
    * ESCA-JAVA0266:
    * @param data
    */
   private static void setVariableValues(ArrayList data)
   {
      try
      {
         for (int i = 0; i < data.size(); i ++)
         {
            String variableName = "variable_" + Integer.toString(i+1);
       
            dataSend += "&" + URLEncoder.encode(variableName, "UTF-8") +

            "=" + URLEncoder.encode(data.get(i), "UTF-8");
         } 
      }
      
      catch (UnsupportedEncodingException e) {System.out.println(Tools.thisPathAndLine() + e + "\n");}
   }

   
   
   /**
    * Sends data to the appropriate PHP script.
    * ESCA-JAVA0266:
    */
   private static void sendData()
   {
      try
      {    
         writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
  
         writer.write(dataSend); writer.flush(); writer.close();
      }
 
      catch (MalformedURLException e) {System.out.println(Tools.thisPathAndLine() + e + "\n");}

      catch (IOException e) {System.out.println(Tools.thisPathAndLine() + e + "\n");}
   
   }


   //***************************************** END PRIVATE METHODS *****************************************//
   
   
   private static URL url;
   private static String dataSend;
   private static URLConnection conn;
   private static String dataRecieve;
   private static String scriptAddress;
   private static BufferedReader reader;
   private static BufferedWriter writer;
   
   
   //********************************************** END CLASS **********************************************//
   
}


/*
   COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved.

   This class provides handy tools.

   @site http://www.javaika.com
   @author Alexander Wait
   @version 2012-02-01
*/



public class Tools 
{

   private static final int EXCEPTION_LINE_BEAK = 2;
   
   
   private Tools() {}
   
   
   //**************************************** START PUBLIC METHODS *****************************************//


   /**
    * This method returns the line number and path where it's called.
    * The syntax new Exception().getStackTrace()[0].getLineNumber() 
    * will only give the current line number of the source file.
    * @return
    */
   public static String thisPathAndLine()
   {
   
      String lineAndPath = ""; String stackTrace = "";
 
      stackTrace = new Exception().getStackTrace()[1].toString();
      
      
      for (int i = stackTrace.length()-1; i >= 0; i --)
      {
         if (stackTrace.charAt(i) == ')') {continue;} 
        
         else if (stackTrace.charAt(i) == '(') {break;}
        
         else {lineAndPath = (stackTrace.charAt(i) + lineAndPath);}
      }
         
      return lineAndPath + returnNewline(EXCEPTION_LINE_BEAK);
      
   }
   
   
   
   /**
    * Delays execution.
    * @param length
    */
   public static void delay(long length) 
   {
      for (long i = 0; i < length; i ++) {}
   }
   
  
 
   /**
    * This method returns a space.
    * @param length
    * @return
    */
   public static String returnSpace(int length)
   {
      String space = "";
      
      
      for (int i = 0; i < length; i ++)
      {
         space += " ";
      }
      
      return space;
   }
   
   
   
   /**
    * Assigns newlines to a string.
    * @param lines
    * @return
    */
   public static String returnNewline(int lines)
   {
      String newline = "";
      
      
      for (int i = 0; i < lines; i++)
      {
         newline += "\n";
      }
      
      
      return newline;
   
   }
   
   
   
   /**
    * Returns the users desktop path.
    * @return
    */
   public static String returnDesktopPath()
   {
      return (System.getProperty("user.home") + "/Desktop").replace("\\", "/") + "/"; 
   }
   

   //***************************************** END PUBLIC METHODS ******************************************//

   
   //********************************************** END CLASS **********************************************//
   
}