$(document).ready(function(){
   var SUBMIT_LOCATION = 'https://cgi.uwplatt.edu/cgi-bin/UWP/intercom/index.pl?display=newAnnouncement';
   var XML_FILE = 'http://www.uwplatt.edu/intercom/data/intercom.xml';

   function formatCategory(name){
      name = $.trim(name);
      name = name.replace(/_/gi, ' ');
      name = name.replace(/-/gi, '/');
      name = (name + '').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase ( ); } );
      return name;
   }

   function reverseFormatCategory(name){
      name = $.trim(name);
      name = name.replace(/ /gi, '_');
      name = name.replace(/\//gi, '-');
      return name.toLowerCase();
   }

   function getCategories(){
      var c = new Array();
      $(xml).find('category').each(function(){
         c.push( formatCategory( $(this).attr('title') ) );
      });
      return c.sort();
   }

   function createTabs(cats, all){
      $('#categories').append("<ul></ul>");
      if( all ){
         $('#categories>ul').append("<li id=\"catAll\" title=\"all\" class=\"catSelect\"><span class=\"ctop\"></span><span class=\"cbottom\"></span>All Categories</li>");
      }
      $(cats).each(function(){
         $('#categories>ul').append("<li title=\"" + reverseFormatCategory(this) + "\" class=\"catSelect\"><span class=\"ctop\"></span><span class=\"cbottom\"></span>" + this + "</li>");
      });

      // Add new tabs.
      $('#categories>ul').append("<li id=\"submitButton\"><span class=\"ctop\"></span><span class=\"cbottom\"></span><a href=\"https://cgi.uwplatt.edu/cgi-bin/UWP/intercom/index.pl?display=newAnnouncement\">Submit</a></li>");
      $('#categories>ul').append("<li id=\"helpButton\"><span class=\"ctop\"></span><span class=\"cbottom\"></span><a href=\"help.html\">Help</a></li>");
   }

   function getItems(cat){
      var items = new Array();
      $('[@title="' + cat + '"]', xml).find('item').each(function(){

         // Item Title
         var title = $.trim($(this).find('title').text());

         // Item Description
         var descr = $.trim($(this).find('description').text());

         // Item Start Date
         var startDate = new Date($.trim($(this).find('startDate').text()))
         startDate = $.datepicker.formatDate("M <span class=\"efg\">d</span><span class=\"hij\">, yy</span>", startDate);

         // Item End Date
         var endDate = new Date($.trim($(this).find('expirationDate').text()));
         endDate = $.datepicker.formatDate("M <span class=\"efg\">d</span><span class=\"hij\">, yy</span>", endDate);

         // Item Website
         var website = $.trim($(this).find('website').text());

         // Item Contact Array
         var contacts = new Array();

         // Search through all of them and add them to the array
         $(this).find('contact').each(function(){
            var contactName  = $(this).find('name').text();
            var contactEmail = $(this).find('email').text();
            var contactPhone = $(this).find('phone').text();

            contacts.push( {
               'name': $(this).find('name').text(),
               'email': $(this).find('email').text(),
               'phone': $(this).find('phone').text(),
            });
         });

         // Push all the found items into the 'items' array.
         items.push( {
            'title': title,
            'description': descr,
            'startDate': startDate,
            'endDate': endDate,
            'website': website,
            'contacts': contacts
         });
      });

      // Return all the items for the category.
      return items;
   }

   function createItems(items){
      if( $(items).length <= 0 ){
         // Create structure
         $('#contentum').append("<div id=\"noItem\" class=\"item\"><h3></h3><div><div class=\"descr\"></div><div class=\"website\"></div><div class=\"contacts\"></div></div></div>");

         // Add Title stating error.
         $('#contentum #noItem h3').append('No Items Found');

         // Add Description displaying error message.
         $('#contentum #noItem .descr').append('There are no items in this category at this time. Check back later.');
      } else {
         $('#contentum').append('<p id="instructions">Select a category; Click on a title for details; Columns are sortable.</p><div id="toggleAll" class="expandAll">Expand All</div><table id="items" class="tablesorter"><thead><tr><th>Start<br />Date</th><th>End<br />Date</th><th><strong>Announcement Title</strong></th></tr></thead><tbody></tbody></table>');
         var id = 0;
         $(items).each(function(){
            // IDs cannot start with an number, so adding 'i' in front. 'i' stands for item.
            var divId = 'i' + id;

            // Create structure
            $('#items>tbody').append("<tr id=\"" + divId + "\"><td class=\"startDate\"></td><td class=\"endDate\"></td><td class=\"item\"><h3></h3><div class=\"itemWrapper\"><div class=\"descr\"></div><div class=\"website\"></div><div class=\"contacts\"></div></div></td></tr>");

            // Add Title
            $('#items>tbody #' + divId + ' h3').append(this.title);

            // Add Description
            $('#items>tbody #' + divId + ' .descr').append(this.description);

            // Start Date
            $('#items>tbody #' + divId + ' .startDate').append(this.startDate);

            // End Date
            $('#items>tbody #' + divId + ' .endDate').append(this.endDate);

            // Add Website
            if( this.website.length > 0 ){
               $('#items>tbody #' + divId + ' .website').append("<strong>Website:</strong> <a href=\""+this.website+"\">"+this.website+"</a>");
            }

            // Add Contacts
            $(this.contacts).each(function(){

               var start = "<div class=\"contact vcard\"><p class=\"fn n\">";
               var text = "";
               var end = "</p></div>";

               if( this.email.length > 0 ){
                  text += "<a href=\"mailto:" + this.email + "\" class=\"email\">" + this.name + "</a>";
               } else {
                  text += this.name;
               }
               if( this.phone.length > 0 ){
                  text += "<span class=\"phone\"> " + this.phone + "</span>";
               }
               text = start + text + end;

               $('#items>tbody #' + divId + ' .contacts').append(text);
            });

            id++;
         });
      }

   }

   function clearItems(){
      $('#contentum').empty();
   }

   function updateItems(cat){
      clearItems();
      createItems(getItems(cat));

      // Hide all item information
      $('.itemWrapper').hide();

      // Now open the one that is clicked on.
      $(".item h3").click(function(){
         var id = $(this).parent().parent().get(0).id;
         $('#' + id + " .item .itemWrapper").slideToggle();
      });

      // Sort Table
      $.tablesorter.addParser({
         id: 'monthDayDate',
         is: function(s) {
            return s.match(/^[A-Za-z]{3,10}\s+<span.*>[0-9]{1,2}<\/span><span.*>,\s+[0-9]{4}<\/span>/i);
         },
         format: function(s) {
            var t = /^([A-Za-z]{3,10})\s+<span.*>([0-9]{1,2})<\/span><span.*>,\s+(\d{4})<\/span>/i.exec(s);
            return $.tablesorter.formatFloat(Date.parse(t[1] + ' ' + t[2] + ', ' + t[3]));
         },
         type: 'numeric'
      });

      // call the tablesorter plugin
      $("#items").tablesorter({
         headers: {
            0: {
               sorter:'monthDayDate'
               },
            1: {
               sorter:'monthDayDate'
               }
            },
         sortList: [[0,1]]
      });

      // Expand/Collapse all button
      $('#toggleAll').click(function(){
         if( $(this).text() == 'Collapse All' ) {
            $(this).text('Expand All');
            $('.itemWrapper').slideUp();
            $('#toggleAll').attr('class', 'expandAll');
         } else {
            $(this).text('Collapse All');
            $('.itemWrapper').slideDown();
            $('#toggleAll').attr('class', 'collapseAll');
         }
      });
   }

   function handleItemsXML(){

      updateItems('');
      createTabs(getCategories(xml), true);
      $('#catAll').attr('id', 'catActive');

      $('.catSelect').click(function(){
         // Remove all other ids
         $('.catSelect').each(function(){
            $(this).removeAttr('id');
         });

         if( this.title == 'all' ) {
            updateItems('');
            $(this).attr('id', 'catActive');
         } else {
            updateItems(this.title);
            $(this).attr('id', 'catActive');
         }
      });

      // Redirect Submit button
      $('#submitButton').click(function(){
         window.location = SUBMIT_LOCATION;
      });
   }


   // Starting point
   $.ajax({
      type: "GET",
      url: XML_FILE,
      dataType: "xml",
      success: function(response){
         xml = response;
         handleItemsXML();
      }
   });
});