$(document).ready(function() {	
	var lcCount = 1;
				   
	$("#maintopright").hover(function() {
		$("#quick-link-bg").fadeTo("fast", 1.0);
      }, function() {
		$("#quick-link-bg").fadeTo("slow", 0.0);
      });

						   				 
   $("div#ll_ad_pns").html("<iframe id='ae76becb' name='ae76becb' src='http://banners.andomedia.com/openx_gm/www/delivery/afr.php?n=ae76becb&amp;zoneid=688&amp;cb=INSERT_RANDOM_NUMBER_HERE' framespacing='0' frameborder='no' scrolling='no' width='120' height='60'><a href='http://banners.andomedia.com/openx_gm/www/delivery/ck.php?n=a493e5c8&amp;cb=INSERT_RANDOM_NUMBER_HERE' target='_blank'><img src='http://banners.andomedia.com/openx_gm/www/delivery/avw.php?zoneid=688&amp;cb=INSERT_RANDOM_NUMBER_HERE&amp;n=a493e5c8' border='0' alt='' /></a></iframe><script type='text/javascript' src='http://banners.andomedia.com/openx_gm/www/delivery/ag.php'></script>");	
   $("div#bottom-banner_ps").html("<iframe id='aa58bb51' name='aa58bb51' src='http://banners.andomedia.com/openx_gm/www/delivery/afr.php?n=aa58bb51&amp;zoneid=689' framespacing='0' frameborder='no' scrolling='no' width='468' height='60'><a href='http://banners.andomedia.com/openx_gm/www/delivery/ck.php?n=aa6ba649&amp;cb=INSERT_RANDOM_NUMBER_HERE' target='_blank'><img src='http://banners.andomedia.com/openx_gm/www/delivery/avw.php?zoneid=689&amp;n=aa6ba649' border='0' alt='' /></a></iframe><script type='text/javascript' src='http://banners.andomedia.com/openx_gm/www/delivery/ag.php'></script>");		

$("div.agro_GM ul li").each(function() {
			var post = {"title" : $(this).find("h5 a").html()};					
			var title;
			var iconClass = "";
			var bracketText = [];
			title = post.title.replace(/\[([^\]]+)\]\s\-\s/g, function() {
			bracketText.push(arguments[1]);
			return "";
			});
									
			if (bracketText[0] != undefined)
			iconClass = bracketText[0];
			else 
			iconClass = "DISCUSSION";

			$(this).addClass("blogteaser").addClass("bt-" + iconClass);
									
			if(iconClass!='LINK' && iconClass!='GALLERY' && iconClass!='PLAYER') {
				$(this).find("h5 a").html(title);
			}
			else {
				var altLink = $(this).find("div.blurb a").attr("href");
				$(this).find("h5 a").html(title).attr({'href': altLink, target: "_blank"});
			}					
});


	$("div.agro_GM").after("<div class='button wide lg-text-btn show-more'><a href='#'>Get 15 More Items</a></div>");
	$("div.agro_GM").append("<div class='latest-crap-loader'></div>");
	$("div.show-more a").live("click", function(event){
			event.preventDefault;
			$("div.latest-crap-loader").addClass("loading");
			showMoreItems(lcCount);	
			if(pageTracker){
				pageTracker._trackEvent('Latest Crap', "Show 20 More", lcCount);
				lcCount++;
			}		
			return false;
	});




// Create the dummy search box in the "latest crap" box
$("div.agro_GM").before("<div id='lc-search-box'><form id='lc-search-form'><input type='text' id='q2' name='q2' class='googleCSEwatermark' /><input type='button' name='sa2' id='sa2' value='Search'/></form></div>");

// Mirror the text from the dummy search box in the real search box
$("div#lc-search-box input#q2").keyup(function() {
		var searchTerm = $(this).val();		
		$('input#q').val(searchTerm);
});

// Trigger the real search box when the "submit" button on the dummy search box is pressed
$("div#lc-search-box form#lc-search-form").bind("submit", function(event) {
		event.preventDefault();
		$("div#cse-search-box input:last").trigger('click');
});

$("div#lc-search-box form#lc-search-form input#sa2").bind("click", function(event) {
		event.preventDefault();
		$("div#cse-search-box input:last").trigger('click');
});

// Bio Page
$("div.bios").each(function() {
		$(this).truncate(350, {
        chars: /\s/,
        trail: [ " ( <a href='#' class='truncate_show'>more</a> . . . )", " ( . . . <a href='#' class='truncate_hide'>less</a> )" ]
    });
});
	
});

function showMoreItems(lcCount) {
	//Sends Element ID, Author Filter, Number of Entries to Query, Entries to Display, Display Date Boolean, and Archive Link
	getAuthorBlogs("div.blogs_aggregated.agro_GM ul.noImage", "All", 50, 15, false, "http://www.wmmr.com/shows/preston-and-steve/blogarchive.aspx", lcCount);
	
}

function getAuthorBlogs(element, authorFilter, entriesRequested, entriesToDisplay, displayDate, archiveLink, lcCount) {
		payload = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + 
		' xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> ' +
		 ' <soap:Body> ' +
		   '  <GetXMLBlogsContent xmlns="http://www.emmisinteractive.com/"> ' +
		   '   <BlogIDs>1001193, 1001194, 1001195, 1001196, 1001322</BlogIDs> ' +
		   '   <NumberOfItems>50</NumberOfItems>' +
		   '   <StartDate></StartDate> '+
			'</GetXMLBlogsContent>'+
		 ' </soap:Body>'+
		'</soap:Envelope>';
		var blogVariables = [];
		$.ajax({
			   type:'POST',
			   url:'http://' + window.location.hostname + '/_shared/content/public/blogservice.asmx?op=GetXMLBlogsContent',
			   dataType:"xml",
			   contentType: "text/xml; charset=\"utf-8\"",
			   data:payload,
			   success: function(xml){
			   		sortEntries(xml, element, authorFilter, entriesToDisplay, blogVariables, displayDate, archiveLink, lcCount);
					if(lcCount == 2) {
						$("div.show-more a").html("Browse the Archives").die("click", function(){
							showMoreItems(lcCount);	
						}).bind("click", function() { location.href="http://www.wmmr.com/shows/preston-and-steve/blogarchive.aspx"; });
					}
				
					$("div.latest-crap-loader").removeClass("loading");
			   },
			   error: function() {
					console.log("Error");
				}
			   }, "xml");
	}

function sortEntries(xml, element, authorFilter, entriesToDisplay, blogVariables, displayDate, archiveLink, lcCount) {
	
	//LOOPS BLOG ENTRIES + STORES ENTRY DATA INTO MASTER ARRAY
	$(xml).find("BlogEntries").find("BlogEntry").each(function(e){
		
		var iconClass = "";
		var bracketText = [];
		blogEntryTitle = $(this).attr("EntryTitle").replace(/\[([^\]]+)\]\s\-\s/g, function() {
		bracketText.push(arguments[1]);
		return "";
		});
		
		if (bracketText[0] != undefined)
		iconClass = bracketText[0];
		else 
		iconClass = "DISCUSSION";
		
		//PUSHES ENTRY VARIABLES/JSON OBJECT INTO MASTER ARRAY
		blogVariables.push( {	
				"blogURL": $(this).parents("Blog").attr("BlogURL"),
				"blogID" : $(this).parents("Blog").attr("BlogID"),
				"blogIMG"  : $(this).parents("Blog").attr("BlogImageURL"),
				"blogEntryURL": $(this).parents("Blog").attr("BlogEntryURL"),
				"blogName" : $(this).parents("Blog").attr("BlogName"),
				"blogEntryTitle": blogEntryTitle,
				"blogEntryID" : $(this).attr("BlogEntryID"),
				"blogEntryDate"  : $(this).attr("UTCDateTimePublished"),
				"blogEntryImage": $(this).find("Images").find("Image").attr("ReducedImageURL"),
				"blogAuthorName" : $(this).attr("AuthorName"),
				"blogEntryDescription" : "<div>" + $(this).find("EntryDescription").text() + "</div>",
				"blogIconClass" : iconClass }
		);
		
		
		if (blogVariables[e].blogName.search(" //") != -1) {
			blogVariables[e].blogName = blogVariables[e].blogName.slice( 0 , blogVariables[e].blogName.search(" //"));
		} else if ( blogVariables[e].blogName.search(" - ") != -1) {
			blogVariables[e].blogName = blogVariables[e].blogName.slice( blogVariables[e].blogName.search(" - ") + 3, blogVariables[e].blogName.length);
		}
		
	});

	//SORT ARRAY
	blogVariables.sort(function(a, b){
		a = a.blogEntryDate;
		b = b.blogEntryDate;
		
		return a == b ? 0 : (a < b ? 1 : -1);
	});

	var bPost;
	var ePost;

	if(lcCount == 1) {
		bPost = 20;
		ePost = 35;
	} else if(lcCount == 2) {
		bPost = 35;
		ePost = 50;
	}

	//LOOPS THROUGH EVERY ENTRY WITHIN ARRAY
	for (i=bPost; i < ePost; i++) {
	
		//Set Dynamic Regular expression for Author Match
		var authorMatch = new RegExp(authorFilter, 'gi');
		
		//Convert EMMIS UTC Date to a Readable timestamp using date.js
		var pubDate = blogVariables[i].blogEntryDate;
		/*pubDate = Date.parse(pubDate.slice(0, pubDate.search(/\T/gi)));
		pubDate = pubDate.toString('ddd, MMM d, yyyy');*/
		
		entryDate = "";
		entryBlogAuthor = "";
		entryLink = "<a href=\"" + blogVariables[i].blogEntryURL + "?BlogEntryID=" + blogVariables[i].blogEntryID + "\">";

		if (blogVariables[i].blogIconClass == "LINK" || blogVariables[i].blogIconClass == "GALLERY" || blogVariables[i].blogIconClass == "PAGE") {
			entryLink = "<a href=\"" + $(blogVariables[i].blogEntryDescription).find("a:eq(0)").attr("href") + "\" target=\"_blank\">";
		} else if (blogVariables[i].blogIconClass == "PLAYER") {
			entryLink = "<a class=\"popup av-popup\" href=\"" + $(blogVariables[i].blogEntryDescription).find("a:eq(0)").attr("href") + "\">";
		}
		
		entryListItem = "<li class=\"blogteaser bt-" + blogVariables[i].blogIconClass + "\"><h5>" + entryLink + blogVariables[i].blogEntryTitle + "</a>" + entryBlogAuthor + entryDate + "</h5></li>";
		
		$(element).append(entryListItem);
	
	}
	
	
}

String.prototype.cleanBlogTitle = function() {
	return this.replace(/\s/g,"-").replace('+', '').replace('%20', '').replace('*', '').replace('/', '').replace('@', '').replace('\'', '');
};
