/*
 * JTicker 0.5 Beta
 * By Jason Levine (http://www.jasons-toolbox.com)
 * Modified by Josh Urbain for the Valley Vanguard
 * A ticker plugin for the jquery library.
 */
$.JTickerObjArray = new Array();
$.fn.jticker = function(passedOptions) {
	var options = {
	   TickerID: "",
	   id: "",
		delay: 1000,
		newwindow: false,
		url: "tickerdata.xml",
		transition: "slide",
		speed: "slow",
		contentcounter: -1,
		maxcontent: -1,
		ArrayIndex: -1,
		dataXML: {
		},

		timerid: -1,

		setRSS: function(ArrayIndex) {
			$("#" + options.TickerID).hide();
			// Load Data
         $.ajax({
            type: 'GET',
            url: options.url,
            dataType: 'xml',
            ifModified: true,
            success: function(xml) {
   				options.dataXML = xml;
   				options.contentcounter = -1;
   				options.FillSlide();
            }
			});

			// Set to refresh every 5 minutes
			var t = this;
         setTimeout(function() {
            t.setRSS(ArrayIndex);
         }, 300000);
		},


		FillSlide: function() {
			var Item, TickerHTML, Title, URL, Desc, Date;

			$("#" + options.TickerID).empty();

			options.contentcounter++;
			options.maxcontent = $("item", options.dataXML).length;
			if (options.contentcounter == options.maxcontent)
            options.contentcounter = 0;

			Item  = $("item", options.dataXML).get(options.contentcounter);
			Title = $("title", Item).text();
			URL   = $("link", Item).text();
			Desc  = $("description", Item).text();
			Date  = convertRSSDate($("pubDate", Item).text());

         TickerHTML = '<div class="' + options.id + 'block"><div style="margin-bottom: 3px;" class="' +
           options.id + 'message"><a ' + (options.newwindow ? ' target="_blank"' : '') + ' href="' + URL + '">' +
           Title + '</a><div class="date">' + Date + '</div><div><p>' +
           (Desc.length > 250 ? Desc.substring(0, 250) + '... <span class="more"><a href="' +
           URL + '"' + (options.newwindow ? ' target="_blank"' : '') + '>[more]</a></span>' : Desc) +
           '</p></div></div>';

			$("#" + options.TickerID).append(TickerHTML);
			options.EnterSlide();
		},

	    ExitSlide: function() {
  			if (options.maxcontent <= 1 && options.maxcontent != -1)
  			   return;

	      if (options.contentcounter > -1) {
				clearTimeout(options.timerid);
				switch (options.transition.toLowerCase()) {
					case "slide":
						$("#" + options.TickerID).slideUp(
							options.speed,
							options.ExitSlideStep2()
						);
						break;
					default:
						$("#" + options.TickerID).fadeOut(
							options.speed,
							options.ExitSlideStep2()
						);
						break;
				}
			} else {
				options.ExitSlideStep2(ArrayIndex);
			}
	    },
	    ExitSlideStep2: function() {
			var tempid;
			tempid = setTimeout("$.JTickerObjArray[" + options.ArrayIndex + "].FillSlide();", 500);
		},
	    EnterSlide: function() {
  			if (options.maxcontent <= 1 && options.maxcontent != -1) {
  			   switch (options.transition.toLowerCase()) {
  			      case "slide":
  			         $("#" + options.TickerID).slideDown(options.speed);
  			         break;
  			      default:
  			         $("#" + options.TickerID).fadeIn(options.speed);
  			         break;
  			   }
	         return;
  			}

	      var ArrayIndex = options.ArrayIndex;
			switch (options.transition.toLowerCase()) {
				case "slide":
					$("#" + options.TickerID).slideDown(
						options.speed,
						options.EnterSlideStep2()
					);
					break;
				default:
					$("#" + options.TickerID).fadeIn(
						options.speed,
   				   options.EnterSlideStep2()
					);
					break;
			}
	    },
	    EnterSlideStep2: function() {
			options.timerid = setTimeout("$.JTickerObjArray[" + options.ArrayIndex + "].ExitSlide();", options.delay);
		}
	};
	if (passedOptions) {
		$.extend(options, passedOptions);
	}

	return this.each(function(){
		options.TickerID = this.id;
		$.JTickerObjArray.push(options);
		options.ArrayIndex = $.JTickerObjArray.length - 1;
		$("#" + options.TickerID).hover(function() {
			clearTimeout(options.timerid);
		}, function() {
			options.timerid = setTimeout("$.JTickerObjArray[" + options.ArrayIndex + "].ExitSlide();", options.delay);
		});
		$.JTickerObjArray[options.ArrayIndex].setRSS(options.ArrayIndex);
	});
};

/**
 * Converts the RSS date/timestamp to logical format
 *
 * @access private
 * @param  string date  Date/timestamp string data
 * @return string       Logically-formatted date/timestamp
 **/
function convertRSSDate(date) {
   // Converts RFC 822 datestamp to readable data via regular expressions
   var ex = /^(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), )?(\d{1,2}) ([a-zA-Z]{3}) (\d{2,4}) (\d{2}):(\d{2})(?:[:]\d{2})? (UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|A|B|C|D|E|F|G|H|I|M|N|Y|Z|(?:[+-]\d{4}))\s*$/;
   // Execute the regular expression on the date string and place the results in m
   var m  = ex.exec(date);

   // If m is null, return nothing
   if (m == null)
      return '';
   // Otherwise, if it's an array, display the logical format
   else {
      // 1 = Day, 2 = Month, 3 = Year, 4 = Hour, 5 = Minutes, 6 = Time adjust
	   return translateMonth(m[2]) + ' ' + reduceNumbers(m[1]) +
	     ', ' + m[3] + ' ' + convertTime(m[4], m[5]);
   }
}

/**
 * Reduces a 0100 to 100, useful for displaying 09:30 => 9:30
 *
 * @param  string num  Number to reduce
 * @return string      Reduced number or original if is >09 or is one character
 **/
function reduceNumbers(num) {
	if (num.length == 1)
	   return num
	else
      return (num.substr(0, 1) == '0' ? num.substr(1, 1) : num)
}

/**
 * Translates the month from a shortened name or a numerical version into the full name
 *
 * @param  string shortmonth  The month data to parse
 * @return string             The full name month
 **/
function translateMonth(shortmonth) {
	switch(shortmonth) {
		case '01': case 'Jan':   return 'Jan.';
		case '02': case 'Feb':   return 'Feb.';
		case '03': case 'Mar':   return 'Mar.';
		case '04': case 'Apr':   return 'Apr.';
		case '05': case 'May':   return 'May';
		case '06': case 'Jun':   return 'June';
		case '07': case 'Jul':   return 'July';
		case '08': case 'Aug':   return 'Aug.';
		case '09': case 'Sep':   return 'Sept.';
		case '10': case 'Oct':   return 'Oct.';
		case '11': case 'Nov':   return 'Nov.';
		case '12': case 'Dec':   return 'Dec.';
		default:                 return '';
	}
}

/**
 * Converts the time from 24-hours to 12-hours with AM/PM
 *
 * @param  string  hours   Hours to convert
 * @param  string  minutes Minutes
 * @return string          Converted time
 **/
function convertTime(hours, minutes) {
   var ampm  = 'am';

   hours = parseInt(hours);
	if (hours > 11)
	   ampm   = 'pm';

	hours %= 12;
	if (hours == 0)
	   hours  = 12;

   return hours + ':' + minutes + ampm;
}