(function($)
{
  // Original Script written by Steve Fenton
  // Current Version by Jason Hubbard
  // http://www.stevefenton.co.uk/Content/Jquery-Constant-Footer/
  // Feel free to use this jQuery Plugin
  // Version: 3.0.1
  
  var nextSetIdentifier = 0;
  var classModifier = '';
  
  var feedItems;
  var feedIndex;
  var feedDelay = 10;
  var feedTimer;
  
  function CycleFeedList(feedList, i) {
    feedItems = feedList;
    feedIndex = i;
    ShowNextFeedItem();
  }
  
  function ShowNextFeedItem() {
    //put that feed content on the screen!
    $('.' + classModifier + ' .content').fadeOut(1000, function () {
      $('.' + classModifier + ' .content').html(feedItems[feedIndex]).fadeIn(1000);
      PadDocument();
      feedIndex++;
      if (feedIndex >= feedItems.length) {
        feedIndex = 0;
      }
      feedTimer = window.setTimeout(ShowNextFeedItem, (feedDelay * 1000));
    });
  }

  // Gets rid of CDATA sections
  function StripCdataEnclosure(string) {
    if (string.indexOf('<![CDATA[') > -1) {
      string = string.replace('<![CDATA[', '').replace(']]>', '');
    }
    return string;
  }

  // Add padding to the bottom of the document so it can be scrolled past the footer
  function PadDocument() {
    var paddingRequired = $('.' + classModifier).height();
    $('#' + classModifier + 'padding').css({ paddingTop: paddingRequired+'px'});
  }
  
  $.fn.constantfooter = function (settings) {
  
    var config = {
      classmodifier  : 'constantfooter',
      feed           : '',
      feedlink       : 'Read more &raquo;',
      opacity        : 0.8,
      showclose      : false,
      closebutton    : '[x]',
      closeCookie    : false, // If cookies should be used to remmember if the window was closed (see cookieSettings for more options)
      // Cookie settings are only used if closeCookie is true
      cookieSettings: {
        path         : '/', // Path for the cookie to be saved on (should be root domain in most cases)
        expires      : 0 // Expiration Date (in seconds), 0 (default) means it ends with the current session
      }
    };
    
    if (settings) {
      $.extend(config, settings);
    }

    return this.each(function () {
      
      classModifier = config.classmodifier;
      
      // Make sure opacity is a number between 0.1 and 1
      var opacity = parseFloat(config.opacity);
      if (opacity > 1) {
        opacity = 1;
      } else if (opacity < 0.1) {
        opacity = 0.1;
      }

      // Add a div used for body padding
      $(this).before('<div id="' + config.classmodifier + '-padding">&nbsp;</div>');
      
      // Hide it
      $(this).hide().addClass(classModifier).css({ position: 'fixed', bottom: '0px', left: '0px', width: '100%' })

      // If there is a feed, we will replace the footer HTML with the feed
      // if not - wrap everything inside with the div content tag
      if (config.feed.length > 0) {
        $(this).html('');
        $(this).append('<div class="' + config.classmodifier + '-content"></div>');
      } else {
        // wrap the current html in the .content class
        $(this).contents().wrapAll('<div class="' + config.classmodifier + '-content" />');
      }

      // Show a close button if required
      // changed from append to prepend so that no matter what, the [x] is on top
      if (config.showclose) {
        $(this).prepend('<div style="float: right;" class="' + classModifier + '-close">' + config.closebutton + '</div>');
        $('.' + classModifier + '-close').css({ cursor: 'pointer' });
        $('.' + classModifier + '-close').click( function () {
          $(this).parent().fadeOut();
          window.clearTimeout(feedTimer);
          if (config.closeCookie) _cookie(COOKIE_NAME,'true'); // Set close cookie for next run
        });
      }

// --------- added cookie for closing ----
    // If user can close and set to remember close, initiate cookie functions
    if (config.showclose && config.closeCookie) {
      var COOKIE_NAME = 'cf-close'; // Local global setting for the name of the cookie used

      // Cookies Function: Handles creating/retrieving/deleting cookies
      // Cookies are only used for opts.closeCookie parameter functionality
      var _cookie = function(name, value) {
        if (typeof value != 'undefined') {
          var expires = '';

          // Check if we need to set an expiration date
          if (config.cookieSettings.expires != 0) {
            var date = new Date();
            date.setTime(date.getTime()+(config.cookieSettings.expires));
            var expires = "; expires="+date.toGMTString();
          }

          // Get path from settings
          var path = config.cookieSettings.path || '/';

          // Set Cookie with parameters
          document.cookie = name+'='+encodeURIComponent(value == null ? '' : value)+expires+'; path='+path;
        }
        else { // Get cookie value
          var cookie,val = null;

          if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');

            // Loop through all cookie values
            for (var i = 0; i < cookies.length; ++i) {
              cookie = $.trim(cookies[i]);

              // Does this cookie string begin with the name we want?
              if (cookie.substring(0,name.length+1) == (name+'=')) {
                val = decodeURIComponent(cookie.substring(name.length+1));
                break;
              }
            }
          }

          return val; // Return cookie value
        }
      };

      // If cookie is set, return false and don't display rejection
      if (_cookie(COOKIE_NAME) != null) return false;
    }
// --------- added cookie for closing ----

      // Show it
      $(this).fadeTo(1000, opacity);
      
      // Pad the bottom of the document
      PadDocument();
      
      // Process any feeds
      if (config.feed.length > 0) {
    
        var feedList = new Array();
        
        $.get(config.feed, function(xmlDoc) {
          
          var itemList = xmlDoc.getElementsByTagName('item');
          
          for (var i = 1; i <= itemList.length; i++) {
          
            var title = xmlDoc.getElementsByTagName('title')[i].childNodes[0].nodeValue;
            var link = xmlDoc.getElementsByTagName('link')[i].childNodes[0].nodeValue;
            var description = xmlDoc.getElementsByTagName('description')[i].childNodes[0].nodeValue;
          
            var article = '<div class="item">';
            
            if (link != null) {
              article += '<a href="' + link + '">';
            }
            article += '<h2>' + title + '</h2>';
            if (link != null) {
              article += '</a>';
            }
            
            article += '<div class="description"><p>' + description + '</p></div>';
            
            if (link != null) {
              article += '<div class="link"><a href="' + link + '">' + config.feedlink + '</a></div>';
            }
            
            article += '</div>';
       
            feedList[feedList.length] = article;
          }
          
          if (feedList.length > 0) {
            CycleFeedList(feedList, 0);
          }
        });
      }
    });
  };
})(jQuery);
