var d = new Date();
var curr_year;

(function($) {

	$.fn.fdicWidget = function(options) {

		var id = $(this);
		var releaseYear;
		
		if(options.YEAR != null){
			//alert("!= null");
			curr_year = options.YEAR;
		}else{
			//alert("== null");
			curr_year = d.getFullYear();
		}
		
		releaseYear = curr_year + "";
		releaseYear = releaseYear.split("");
		releaseYear = releaseYear[2] + releaseYear[3];
		
		if(options.releaseType == "pr"){
			$.fn.fdicWidget.defaults = {
				releaseType : "pr",
				directory : "press",
				releaseTypeFullTitle : "Press Releases",
				file : "pressReleases.xml",
				location : "home",
				value : 3,
				YEAR : curr_year,
				releaseYear : releaseYear,
				truncation : 285,
				TYPE: "Release"
			}
		}else if(options.releaseType == "fil"){
			$.fn.fdicWidget.defaults = {
				releaseType : "fil",
				directory : "financial",
				releaseTypeFullTitle : "Financial Institution Letters",
				file : "filReleases.xml",
				location : "home",
				value : 6,
				YEAR : curr_year,
				releaseYear : releaseYear,
				truncation : 495,
				TYPE: "Release"
			}
		}else if(options.releaseType == "sa"){
			$.fn.fdicWidget.defaults = {
				releaseType : "sa",
				directory : "SpecialAlert",
				releaseTypeFullTitle : "Special Alerts",
				file : "saReleases.xml",
				location : "home",
				value : 6,
				YEAR : curr_year,
				releaseYear : releaseYear,
				truncation : 425,
				TYPE: "Release"
			}
		}else if(options.TYPE == "YouTube"){
			$.fn.fdicWidget.defaults = {
				userName : "fdicchannel",
				loadingText : "Loading...",
				location : "home",
				value : 5,
				truncation: 132
			}			
		}

		
		opts = $.extend({}, $.fn.fdicWidget.defaults, options);
		
		return this.each(function() {
			
			if (opts.userName != null) {			

				preLoaderHTML = $("<p class=\"loader\">" + opts.loadingText + "</p>");
				id.append(preLoaderHTML);

				$.getScript("http://gdata.youtube.com/feeds/users/" + opts.userName + "/uploads?alt=json-in-script&callback=__jQueryYouTubeChannelReceiveData&max-results=" + opts.value);
			}else{
				releaseAutomation(id, opts);
			}
		});
	};
})(jQuery);

function __jQueryYouTubeChannelReceiveData(data, id) {

	var counter = 1;
	
	if(counter < opts.value){
	
		//Accepts a str and converts to date in IE
		function parseISO8601(dateStringInRange) {
			var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
			date = new Date(NaN), month,
			parts = isoExp.exec(dateStringInRange);

			if(parts) {
				month = +parts[2];
				date.setFullYear(parts[1], month - 1, parts[3]);
				if(month != date.getMonth() + 1) {
					date.setTime(NaN);
				}
			}
			
			return date;
		}
	
		$.each(data.feed.entry, function(i,e) {
		
			var item = {
				title : e.title.$t,
				id : e.id.$t.split("/").pop(),
				href : "http://www.youtube.com/watch?v=" + e.id.$t.split("/").pop(),
				img : "http://img.youtube.com/vi/" + e.id.$t.split("/").pop() + "/default.jpg",
				pub : e.published.$t.split("T")[0],
				views: e['yt$statistics']['viewCount']
			}
			
			var yt_limit = opts.truncation;
			var allMonths = ["January","February","March","April","May","June","July","August","September","October","November","December"];
			var mydate = parseISO8601(item.pub);   
			var mydateformat =  allMonths[mydate.getMonth()] + " " + mydate.getDate() +", " + mydate.getFullYear();
	  
				
			var CharCount = Math.ceil(yt_limit / opts.value) - 4;
						
			if((item.title).length >= CharCount)
			{
				var str = item.title;           			// Getting the text
				var strtemp = str.substr(0,CharCount);   // Get the visible part of the string
				var ytstr = strtemp + "...";
								
			} else {
				var ytstr = item.title;
			}
			
			if(opts.location == "silo"){
			
				var content = "<li><img src=\"" + item.img + "\" alt=\"" + item.title + "\"><br/><a href=\"" + item.href + "\">" + ytstr + "</a><br /><span class=\"index_item_date\">Views: " + item.views + " | " + mydateformat + "</span></li>";
				
			} else if(opts.location == "home"){
			
				var dividerVID = (counter == opts.value) ? "" : "<hr />";
				
				if (counter == opts.value) {
					var content = "<tr><td valign=\"top\" width=\"62\"><img src=\"" + item.img + "\" alt=\"" + item.title + "\" width=\"60\" height=\"45\"></td><td valign=\"top\" width=\"100%\" class=\"con_titleYT\"><a href=\"" + item.href + "\">" + ytstr + "</a><br /><span class=\"con_style\">Views: " + item.views + "</span><br /><span class=\"con_date\">" + mydateformat + "</span></td></tr><tr><td colspan=\"2\"></td><td></td></tr>";
				} else {
					var content = "<tr><td valign=\"top\" width=\"62\"><img src=\"" + item.img + "\" alt=\"" + item.title + "\" width=\"60\" height=\"45\"></td><td valign=\"top\" width=\"100%\" class=\"con_titleYT\"><a href=\"" + item.href + "\">" + ytstr + "</a><br /><span class=\"con_style\">Views: " + item.views + "</span><br /><span class=\"con_date\">" + mydateformat + "</span></td></tr><tr><td colspan=\"2\"><hr /></td><td></td></tr>";
				}
			}
		   
			$('#videos2').append(content);
			counter += 1;
			
			// Remove the preloader and show the content
			$(preLoaderHTML).remove();
		});
	} else {
		return;
	}
}

//######################### Release Automation #########################//
//function releaseAutomation(releaseTypeFullTitle, releaseType, directory, file, location, value, YEAR, releaseYear, truncation){
function releaseAutomation(id, data){

	//alert("ReleaseType : " + data.releaseType + ", Directory : " + data.directory + ", Release Type Full Title : " + data.releaseTypeFullTitle + ", File : " + data.file + ", Location : " + data.location + ", Value : " + data.value  + ", YEAR : " + data.YEAR + ", Release Year : " + data.releaseYear + ", Trucation : " + data.truncation + ", TYPE : " + data.TYPE);
	
			
	//######################################################################################
	//Global Variables within releaseAutomation()
	//######################################################################################
	
	var counter;
	var notEnoughItems;
	var viewALLButton;
	var prevMonth;
	
	//######################################################################################
	
	if(data.TYPE == "Release"){
		$.ajax({
			type: "GET",
			url: "/news/news/" + data.directory + "/" + data.YEAR + "/" + data.file,
			dataType: "xml",
			cache: false,
            async: false,
			success: parseXml,
			error: undefinedXml
		});
	} else if(data.TYPE == "YouTube"){

	}
		function undefinedXml() {
			//alert('current year doesn\'t exist');
			data.YEAR = (data.YEAR-1);
			data.releaseYear = (data.releaseYear-1);
			$.ajax({
				type: "GET",
				url: "/news/news/" + data.directory + "/" + data.YEAR + "/" + data.file,
				dataType: "xml",
				cache: false,
				async: false,
				success: parseXml
			});
		}
		
    function parseXml(xml){
		
		//######################################################################################
		//location can = "home" || "quickPress" || "prIndex" || "filIndex" || "saIndex"
		//######################################################################################
		if(data.location == "home" || data.location == "quickPress" ||  data.location == "silo" || data.location == data.releaseType + "Index"){
			//######################################################################################
			//Checks to see if function parseXml(xml) has been called multiple times by the same
			//releaseType.  If so, sets the counter to the proper value.  A releaseTypes can either 
			//be a (pr, fil, sa).
			//######################################################################################

			if(notEnoughItems == null){
			//alert(releaseType + " : notEnoughItems == null, value = " + value);
				counter = 0;
			} else {
				notEnoughItems == null;
				counter = counter;
				//alert(releaseType + " : notEnoughItems != null, value = " + value);
			}		
			//######################################################################################
						
						
			//######################################################################################
			//Removes loading message when done.  Reason there is an (if else) statement for this is
			//because on the home page it is called 3 times by (#loading_PR, #loading_FIL, #loading_SA)
			//and you can't have the same div/span id listed more than once.  On any other page that
			//just loads one of the 3 will call the generic #loading id.
			//######################################################################################				
			if(data.location == "home"){
				$("#loading_" + data.releaseType.toUpperCase()).hide();
			} else {
				$("#loading").hide();
			}
			//######################################################################################
					
			$(xml).find("item").each(function() {

				if(data.location != data.releaseType + "Index" && counter < data.value || data.location == data.releaseType + "Index"){
					//find each instance of loc in xml file and wrap it in a link
					//extract title from xml and use regex to grab number and year           
					var newTitle = $(this).find("title").text();
					//######################################################################################
					//Determines which Regular Expression to use based upon the release type('releaseType') which
					//is being pulled through the releaseAutomation function paramotor
					//######################################################################################
					if(data.releaseType == "pr"){
						var match = /PR-\d{1,3}-\d\d\d\d/i.exec(newTitle);
						// added to deal with statements from the chairman that don't have a PR number
						if (match == null){
							siloPagePR = "Statement:";
						}
						else {
							var siloPagePR = match + ":";
						}
					} else if(data.releaseType == "fil"){
						var match = /FIL-\d{1,3}-\d\d\d\d/i.exec(newTitle);
					} else if(data.releaseType == "sa"){
						var match = /SA-\d{1,3}-\d\d\d\d/i.exec(newTitle);
					}
					//######################################################################################
									
					var matchstr = ("" + match).split("-");
					var translations = $(this).find("trans");
					var typeDate = $(this).find("date").text();
								
					//This object varible is dynamically updated based upon the releaseType being pulled through this
					//functions paramotors
					type = {
						loc: "/news/news/" + data.directory + "/" + data.YEAR + "/",
						title: newTitle,
						num: matchstr[1],
						year: data.YEAR,
						date: new Date(typeDate),
						month: typeDate.split(" ")[0],
						day: typeDate.split(" ")[1].split(",")[0]
					}
					
					var query = "#" + data.releaseType.toUpperCase() + type.month;
					var query2 = "#" + type.month + " tbody";
					var query3 = "#" + type.month;
								
					var formMonth = "" + (type.date.getMonth() + 1);
					var href = "";
									
					if (formMonth.length < 2){
						formMonth = "0" + formMonth;
					}
									
					var formatDate = type.month + ' ' + type.day + ', ' + type.year;
					var formDate2 = type.date.getFullYear() + "-" + formMonth + "-" + type.date.getDate();

					if(data.location == data.releaseType + "Index"){
						//Updates Year Listed in releaseObject for the following index.html pages 
						//prIndex, filIndex, saIndex
						if(counter < 1){
							$("#" + data.releaseType + "Year").append(data.YEAR);
							var updated_date = $(xml).find("update").text();
							$("#updated-date").html("Last Updated " + updated_date);
						}
						if (prevMonth != type.month){
							$(query).prepend("<font color=\"#003366\" face=\"Arial, Helvetica, sans-serif\" size=\"2\"><p><strong>" + type.month + "</strong></p></font>");
							prevMonth = type.month;
						}
					}
									
					if (type.num){
						if (type.num.length == 2){
							type.num = "0" + type.num;
							href = data.releaseType + data.releaseYear + type.num + ".html";
						} else if (type.num.length == 1){
							type.num = "00" + type.num;
							href = data.releaseType + data.releaseYear + type.num + ".html";
						} else if (type.num.length == 3){ href = data.releaseType + data.releaseYear + type.num + ".html"; }
					} else {
						href = $(this).find("title").attr("file");
					}
									
					if(data.location == "home" || data.location == "quickPress" || data.location == "silo"){
						//######################################################################################
						//Truncates title of Release if too long
						// max chars per item rounded down to the nearest whole number
						if(data.releaseType == "pr" || data.releaseType == "fil" || data.releaseType == "sa"){
									
							var maxChars = Math.ceil(data.truncation / data.value);
							var theTitle;
							var TitleTrunc;
											
							if (match){
								theTitle = type.title.replace((match + " "),"");
							} else {
								theTitle = type.title;
							}
											
							if(data.location == "home" && data.releaseType == "pr"){
								if (theTitle.length >= maxChars){        
									TitleTrunc = theTitle.substr(0, maxChars - 4) + "...";
								} else {
									TitleTrunc = theTitle;
								}
							}
						}
										
					} else if(data.location == data.releaseType + "Index"){
						//######################################################################################
						//Checks for translation such as (En Espanol, Chinese, etc..) on the Current Years PR 
						//index page
						if (translations.text()) {
						
							var transcat = "<ul>\n";
							
							$(translations).each(function() {
							
								var link_text = $(this).text();
								
								if (link_text == "Spanish") {
									link_text = "En Espa&#241;ol"
								}
								transcat += '<li><a href="' + $(this).attr("file") + '">' + link_text + '</a></li>\n';
							});
							
							transcat += '</ul>\n';
											
							var concat = '<tr>\n<td valign="top" width="30%">\n<ul>\n<li>' + formatDate +'</li>\n</ul>\n</td>\n<td valign="top"><a pub_date="' + formDate2 + '" href="' + href + '">' + type.title + '</a>' + transcat + '</td>\n</tr>';
											
							$(query2).append(concat);
						} else {
							if(data.location == "prIndex"){
								$(query2).append('<tr>\n<td valign="top" width="30%">\n<ul style="margin-top:0">\n<li>' + formatDate +'</li>\n</ul>\n</td>\n<td valign="top"><a pub_date="' + formDate2 + '" href="' + href + '">' + type.title + '</a></td>\n</tr>');
								//else = to "filIndex, saIndex"
							} else {
								$(query3).append("<li><font size=\"2\" face=\"Arial, Helvetica, sans-serif\"><a href=\"" + href + "\" pub_date=\"" + formDate2 + "\">" + type.title + "</a></font></li>");
							}
						}
						//#####################################################################################
					}

					if(data.location == "home" || data.location == "silo"){
									
						var typeNumber = theTitle.split(" ").splice(newTitle, 1);
						var typeTitleSplit = newTitle.split(" ");
						/*var typeTitleShift = typeTitleSplit.shift();
						var typeTitle = typeTitleSplit.join(" ");*/
						var typeTitle = typeTitleSplit.slice(1).join(" ");
										
						var $type_limit = data.truncation; 
						var CharCount = Math.ceil($type_limit / data.value) - 4;
						var TitleTrunc = (typeTitle.length > CharCount) ? (typeTitle.substr(0,CharCount)+ "...") : typeTitle;
										
						var pushOld;
						var pushPhase7;

						if(data.location == "home"){
							//######################################################################################
							//Creates PR String for PR Box on the /index.html AKA FDIC's homepage
							if(data.releaseType == "pr"){
								/*pushPhase7 = ("<div class='index_item'><h4 class='index_item_heading'>" + TitleTrunc + "</h4>" + "<span class='index_item_date'>" + formatDate + "</span><br />" + "<a href=\'/news/news/" + data.directory + "/" + data.YEAR + "/" + href + "\'" + "class='homeMoreLink' title=\'" + theTitle + "\'" + "\'>" + "<img src='/images/link_readMore.gif' width='56' height='10' border='0'" + "alt='" + theTitle + "'" + " />" + "</a>" + "</div>\n");*/
								/*pushPhase7 = ("<div class='index_item'><a href=\'/news/news/" + data.directory + "/" + data.YEAR + "/" + href + "\'" + "class='homeMoreLink' title=\'" + theTitle + "\'" + "\'><h4 class='index_item_heading'>" + TitleTrunc + "</h4></a><span class='index_item_date'>" + formatDate + "</span><br /></div>\n");*/
								/*pushPhase7 = ("<div class=\"index_item\"><h4 class=\"index_item_heading\"><span class=\"quick_links\"><a href=\"/news/news/" + data.directory + "/" + data.YEAR + "/" + href + "\"" + " title=\"" + theTitle + "\"" + " alt=\"" + theTitle + "\">" + TitleTrunc + "</a></span></h4><span class=\"index_item_date\">" + formatDate + "</span><br /></div>\n");*/
								/* WORKING pushPhase7 = ("<div class='index_item'><h4 class='index_item_heading'><span class='quick_links'><a href=\'/news/news/" + data.directory + "/" + data.YEAR + "/" + href + "\'" + " title=\'" + theTitle + "\'" + " alt=\'" + theTitle + "\'" + "\'>" + TitleTrunc + "</a></span></h4><span class='index_item_date'>" + formatDate + "</span><br /></div>\n");*/
								theTitle = theTitle.replace(/"/g,"\'");
								pushPhase7 = ('<div class=\"index_item\"><h4 class=\"index_item_heading\"><span class=\"quick_links\"><a href=\"/news/news/' + data.directory + '/' + data.YEAR + '/' + href + '\"' + ' title=\"' + theTitle + '\"' + '\">' + TitleTrunc + '</a></span></h4><span class=\"index_item_date\">' + formatDate + '</span><br /></div>\n');
							} else if(data.releaseType == "fil" || data.releaseType == "sa"){
													
								var typeLastLI = (counter==(data.value-1)) ? " style=\"border-bottom: 0;\" " : "";
								
								if (counter < data.value){

									if(typeTitle.length >= CharCount){
										var $str = typeTitle;           			// Getting the text
										var $strtemp = $str.substr(0,CharCount);    // Get the visible part of the string
										$str = $strtemp + "...";
													
										pushPhase7 = ('<li' + typeLastLI + '><h4 class=\"con_title\">' + typeNumber + '</h4>' + '<span class=\"con_style\">' + '<a href=\"/news/news/' + data.directory + '/' + data.YEAR + '/' + href + '\"' + 'title=\"' + typeTitle + '\"' + '\">' + $str + '</a>' + '</span>&nbsp;&nbsp;<br /><span class=\"con_date\">' + formatDate + '</span>' + '</li>');
									} else {
										pushPhase7 = ('<li' + typeLastLI + '><h4 class=\"con_title\">' + typeNumber + '</h4>' + '<span class=\"con_style\">' + '<a href=\"/news/news/' + data.directory + '/' + data.YEAR + '/' + href + '\"' + 'title=\"' + typeTitle + '\"' + '\">' + typeTitle + '</a>' + '</span>&nbsp;&nbsp;<br /><span class=\"con_date\">' + formatDate + '</span>' + '</li>');
									}
								}
							}
						} else if(data.location == "silo"){
						
							if(counter < data.value){
								var goToDivRight = Math.ceil(data.value / 2);
						 		if(data.releaseType == "pr"){
									/*pushPhase7 = ("<span class=\"con_silo_title\">" + siloPagePR + "</span><br/>" + "<span class=\"con_silo_style\">" + "<a href=" + type.loc + href + ' title="' + typeTitle + '"' + "\">" + TitleTrunc + "</a>" + "</span>&nbsp;&nbsp;<br/><span class=\"con_silo_date\">" + formatDate + "</span>" + "<br /><br />");*/
									altTitle = typeTitle.replace(/"/g,"'");
									pushPhase7 = ('<span class=\"con_silo_title\">' + siloPagePR + '</span><br/>' + '<span class=\"con_silo_style\">' + '<a href=' + type.loc + href + ' title=\"' + altTitle + '\"' + '\">' + TitleTrunc + '</a>' + '</span>&nbsp;&nbsp;<br/><span class=\"con_silo_date\">' + formatDate + "</span>" + "<br /><br />");
								} else if(data.releaseType == "fil"){
									pushPhase7 = ("<span class=\"con_silo_title\">" + typeNumber + "</span><br/>" + "<span class=\"con_silo_style\">" + "<a href=" + type.loc + href + ' title="' + typeTitle + '"' + "\">" + TitleTrunc + "</a>" + "</span>&nbsp;&nbsp;<br/><span class=\"con_silo_date\">" + formatDate + "</span>" + "<br /><br />");
								}
							}
						}
											
						if(counter < data.value){
							if(data.location == "silo"){
								if(counter < goToDivRight){
									$("#" + data.releaseType + "Left").append(pushPhase7);
								} else {
									$("#" + data.releaseType + "Right").append(pushPhase7);
								}
							} else {
								//alert(counter + ": " + data.releaseType + " : " + typeLastLI);
								$(id/*boxcontentpress*/).append(pushPhase7);   //THIS IS FOR THE NEW PHASE 7
							}
						}
						//######################################################################################
					}
					
					if(data.location == "quickPress"){
						//######################################################################################
						//Creates PR String for PR Box on the /quicklinks/press.html page				
						/*var prPush = ("<a href='/news/news/" + data.directory + "/" + data.YEAR + "/" + href + "' " + "title=\"" + theTitle + "\"" + "\"><div class='hSub'>" + theTitle + "<br />" + "</div></a>" + "<span class='date'>" + formatDate + "<br />" + "</span>" + "<br/>");*/
						/*var prPush = ("<h4 class='index_item_heading'><span class='quick_links'><a href='/news/news/" + data.directory + "/" + data.YEAR + "/" + href + "' " + "title=\"" + theTitle + "\"" + "\">" + theTitle + "<br />" + "</a></span></h4>" + "<span class='index_item_date'>" + formatDate + "<br />" + "</span>" + "<br/>");*/
						//theTitle = theTitle.replace(/"/g,"\'");
						altTitle = theTitle.replace(/"/g,"\'");
						var prPush = ('<h4 class=\"index_item_heading\"><span class=\"quick_links\"><a href=\"/news/news/' + data.directory + '/' + data.YEAR + '/' + href + '\" ' + 'title=\"' + altTitle + '\"' + '\">' + theTitle + '<br />' + '</a></span></h4>' + '<span class=\"index_item_date\">' + formatDate + '<br />' + '</span>' + '<br/>');

						if (counter < data.value){
							$(id /*quicklinksPress*/).append(prPush);
						}
						//######################################################################################
					}		
					
					counter += 1;
					
				} else {
					return;
				}
			});
						
			if(data.location == "home" || data.location == "silo"){
				var viewAllButtonOld;
				var viewAllButtonPhase7;
				
				if(counter <= data.value && counter != 0 || counter > data.value){
					//######################################################################################
					//Automates 'View All' button for PR Box on Home Page for the Current Year's PR's
					viewAllButtonPhase7 = "<a href=\"/news/news/" + data.directory + "/" + data.YEAR + "/index.html\" title=\"View All " + data.YEAR + " " + data.releaseTypeFullTitle + "\" alt=\"View All " + data.YEAR + " " + data.releaseTypeFullTitle + "\"><span>view all</span></a>";
					//######################################################################################
				}
				if(viewAllButtonPhase7 != undefined){
					if(viewALLButton == undefined){
						$("#" + data.releaseType + "ViewAll").append(viewAllButtonPhase7);
						viewALLButton = 1;
					}
				}
			}
						
			if(counter < data.value){
				//######################################################################################
				//Updates releaseAutomation() global variables (notEnoughItems, YEAR, releaseYear)
				//to grab releaseType(PR's, FIL's, SA's) from the previous year's xml file.
				//######################################################################################
				notEnoughItems = 1;
				data.YEAR = (data.YEAR-1);
				data.releaseYear = (data.releaseYear-1);
				//######################################################################################

				$.ajax({
					type: "GET",
					url: "/news/news/" + data.directory + "/" + data.YEAR + "/" + data.file,
					dataType: "xml",
					cache: false,
					async: false,
					success: parseXml
				});	
			}else{
				//alert(counter);
			}
		}
	}
}
