var PLC = (function($)
{
  return {
    init: function()
    {
      PLC.toggleAnswers();
      PLC.initAudioPlayer();
      PLC.initCalendarEvents();
      PLC.kiosk.go();
    },
    
    
    toggleAnswers: function()
    {
      var $answers = $('#50_questions *:not("h3")');
      $answers.hide();
      
      $('#show_answers').click(function(e)
      {
        e.preventDefault();
        var $this = $(this),
            hidden = $this.data('hidden');
        
        if (hidden == true || hidden == undefined)
        {
          $this.data('hidden', false).text('Hide Answers');
          $answers.show();
        }
        else if (hidden == false)
        {
          $this.data('hidden', true).text('Show Answers');
          $answers.hide();
        }
      });
    },
    
    
    // unobtrusiveley turn mp3 links 
    // into a flash audio player that loads the mp3
    initAudioPlayer: function()
    {
      $('a[href$="mp3"]').each(function()
      {
        var $this = $(this),
            title = $this.text(),
            mp3 = $this.attr('href'); //get the current link
        $this.after('<div></div>');
        var $player = $this.next();
        PLC.createAudioPlayer(mp3, $player);
        $player.before('<p class="audio_title">'+title+'</p>');
        $this.remove();
      });
    },


    createAudioPlayer: function(mp3, $player)
    {
      $player.flash(
        {
          src: '/flash/player.swf',
          //width: 200,
          height: 35,
          wmode: 'transparent',
          menu: false,
          flashvars:
          {
            soundFile: mp3,
            playerID: "1",
            autostart: 'no'
            // bg: "0x" + "89748F",
            // leftbg: "0x" + "604E65",
            // lefticon: "0x" + "ffffff",
            // rightbg: "0x" + "604E65",
            // rightbghover: "0x" + "79677F",
            // righticon: "0x" + "ffffff",
            // righticonhover: "0x" + "ffffff",
            // slider: "0x" + "bababa",
            // text: "0x" + "ffffff",
            // track: "0x" + "ffffff",
            // border: "0x" + "666666",
            // loader: "0x" + "7c7c7c"
          }
        },
        {
          version: 8, 
          update: false // don't replace anything if flash is not installed
        }
      );
    },


    initCalendarEvents: function()
    {
      //$.getScript('http://www.google.com/calendar/feeds/pilgrimlutheran.org_c6j22du4hgk4gu8ol9gukgpv1s@group.calendar.google.com/public/full?alt=json-in-script&callback=PLC.insertEvents&orderby=starttime&max-results=7&singleevents=true&sortorder=ascending&futureevents=true');
      
      var url = 'http://www.google.com/calendar/feeds/webmaster@pilgrimlutheran.org/public/full?' +
                'alt=json-in-script&' +
                'callback=PLC.insertWorship&' +
                'orderby=starttime&' +
                'max-results=4&' +
                'singleevents=true&' +
                'sortorder=ascending&' +
                'futureevents=true';
      
      var urlParts = {
        'alt'          : 'json-in-script',
        'callback'     : 'PLC.insertWorship',
        'orderby'      : 'starttime',
        'max-results'  : '3',
        'singleevents' : 'true',
        'sortorder'    : 'ascending',
        'futureevents' : 'true'
      };
      
      $.getScript(url);
    },
    
    /**
     * Callback functions for the GData json-in-script call
     * Inserts the supplied list of events into a div of a pre-defined name
     * 
     * @param {json} root is the JSON-formatted content from GData
     */
    insertEvents: function(json)
    {
      PLC.listEvents(json, $('#event_schedule'));
    },
    
    
    insertWorship: function(json)
    {
      PLC.listEvents(json, $('#worship_schedule'));
    },
    
    
    listEvents: function(json, $events)
    {
      var feed = json.feed;
    
      // create a new unordered list
      var ul = '<ul>';
    
      // loop through each event in the feed
      for (var i = 0; i < feed.entry.length; i++)
      {
        var entry = feed.entry[i],
            title = entry.title.$t,
            start = entry['gd$when'][0].startTime;
    
        // get the URL to link to the event
        // for (var linki = 0; linki < entry['link'].length; linki++)
        // {
        //   if (entry['link'][linki]['type'] == 'text/html' &&
        //       entry['link'][linki]['rel'] == 'alternate')
        //   {
        //     var entryLinkHref = entry['link'][linki]['href'];
        //   }
        // }
    
        var dateString = PLC.formatGCalTime(start),
            li = '<li>';
    
        // if we have a link to the event, create an 'a' element
        if (typeof entryLinkHref != 'undefined')
        {
          entryLink = '<a href="' + entryLinkHref + '">';
          entryLink += title;
          entryLink += '</a>';
          
          li += '<strong>'+ dateString +'</strong><br/>';
          li += entryLink;
          
        }
        else
        {
          li += '<strong>' + dateString + '</strong><br/>';
          li += title;
        }
        
        li += '</li>';
        // append the list item onto the unordered list
        ul += li;
      }
      ul += '</ul>';
      $events.html(ul);
    },
    
    
    /**
     * Converts an xs:date or xs:dateTime formatted string into the local timezone
     * and outputs a human-readable form of this date or date/time.
     *
     * @param {string} gCalTime is the xs:date or xs:dateTime formatted string
     * @return {string} is the human-readable date or date/time string
     */
    formatGCalTime: function(gCalTime)
    {
      // text for regex matches
      var remtxt = gCalTime;

      function consume(retxt) {
        var match = remtxt.match(new RegExp('^' + retxt));
        if (match) {
          remtxt = remtxt.substring(match[0].length);
          return match[0];
        }
        return '';
      }

      // minutes of correction between gCalTime and GMT
      var totalCorrMins = 0;

      var year = consume('\\d{4}');
      consume('-?');
      var month = consume('\\d{2}');
      consume('-?');
      var dateMonth = consume('\\d{2}');
      var timeOrNot = consume('T');

      // if a DATE-TIME was matched in the regex 
      if (timeOrNot == 'T')
      {
        var hours = consume('\\d{2}');
        consume(':?');
        var mins = consume('\\d{2}');
        consume('(:\\d{2})?(\\.\\d{3})?');
        var zuluOrNot = consume('Z');

        // if time from server is not already in GMT, calculate offset
        if (zuluOrNot != 'Z')
        {
          var corrPlusMinus = consume('[\\+\\-]');
          if (corrPlusMinus != '')
          {
            var corrHours = consume('\\d{2}');
            consume(':?');
            var corrMins = consume('\\d{2}');
            totalCorrMins = (corrPlusMinus=='-' ? 1 : -1) * 
              (Number(corrHours) * 60 + 
              (corrMins=='' ? 0 : Number(corrMins)));
          }
        } 

        // get time since epoch and apply correction, if necessary
        // relies upon Date object to convert the GMT time to the local
        // timezone
        var originalDateEpoch = Date.UTC(year, month - 1, dateMonth, hours, mins);
        var gmtDateEpoch = originalDateEpoch + totalCorrMins * 1000 * 60;
        var ld = new Date(gmtDateEpoch);

        // date is originally in YYYY-MM-DD format
        // time is originally in a 24-hour format
        // this converts it to MM/DD hh:mm (AM|PM) 
        dateString = (ld.getMonth() + 1) + '/' + ld.getDate() + ' ' + 
          ((ld.getHours()>12)?(ld.getHours()-12):(ld.getHours()===0?12:
          ld.getHours())) + ':' + ((ld.getMinutes()<10)?('0' + 
          ld.getMinutes()):(ld.getMinutes())) + ' ' + 
          ((ld.getHours()>=12)?'PM':'AM');
      }
      else
      {
        // if only a DATE was matched
        dateString =  parseInt(month, 10) + '/' + parseInt(dateMonth, 10);
      }
      
      return dateString;
    },
    
    kiosk: {
      go: function()
      {
        for (var i in PLC.kiosk.init)
        {
          PLC.kiosk.init[i]();
        }
      },
      
      init: {
        initClock: function()
        {
          $('#clock').jclock(
          {
            format: '%I:%M:%S'
          });
        },
        
        initSlideshow: function()
        {
          $('#slides').cycle(
          {
            timeout: PLC.kiosk.slideshow.defaultTimeout,
            speed:   500
            //before: PLC.kiosk.slideshow.onBefore
          });
        }
      },
      
      slideshow: {
        
        defaultTimeout: 15000, // 15 seconds for each slide
        
        // Stop the slideshow advancement
        // if the slide itself contains a slideshow
        onBefore: function()
        {
          $.fn.cycle.defaults.timeout = (false) ? 0 : PLC.kiosk.slideshow.defaultTimeout;
        }
      }
    }
  };
})(jQuery);