/* jQuery Json Parser widget application developed by Ari Koinuma, September 2008.  
This script will parse an Json file and spits out a div which contains the listing of entries.  What gets displayed are user-configurable.  

Documentation: http://infoserverwiki.publicradio.org/index.php/JQuery
Dependency: jquery 1.2.6, feed_widget_class.js
*/

//This portion is the blog-specific code. 
//Here are blog-specific URLs.  Be sure to put the blog initials to the variable names in case there are more than one widget embedded on a page. 
var gpPrgUrl = 'http://marketplace.publicradio.org/';
var gpPrgLogoUrl = 'http://www.publicradio.org/columns/marketplace/gettingpersonal/feed_widget/mkp_logo.gif';
var gpCssUrl = 'http://www.publicradio.org/columns/marketplace/gettingpersonal/feed_widget/feed_widget.css'
var gpFormURL = "http://marketplace.publicradio.org/tools/widgets/getting_personal_feed_widget/";
var gpButtonURL = "http://www.publicradio.org/columns/marketplace/gettingpersonal/feed_widget/gp_widget_add_button.gif";
var gpTagLine = "Answers to your financial questions from Chris Farrell";

//Here's a blog-specific customizations

//check to see if the first letter in a string is a space
function filterFirstSpace(str) {
	if (str.slice(0,1) == " ") {
		str = str.slice(1);
	}
	return str;
}

//cut off the text at a set character number and insert "..." link. 
function truncate(content, number, link, title) {
	var moreLink = '<a href="'+link+'" title="'+title+'" class="moreLink">...</a>';
	if (content.length >= number) {
		content = content.slice(0, number);
		content = content+moreLink;
	}
	return content;
}


//Modifying the blogEntry object so that I can extract information needed to do the Q&A manipulation.
function blogEntry(id, title, desc, link, pubDate) {
	//Creating a blogEntry object.  
	this.id = id; //id of the entry.  Just a number.
	this.title = title;
	this.desc = desc;
	
	//check to see if the paragraph tags are already in the body.  If there is, the text was converted from markdown. 
	if (this.desc.search('<p>') == -1 ) {
		this.desc = this.desc.replace(/\n/g, '<br />'); //if not, then convert line breaks
	}
	
	this.link = link;
	this.pubDate = pubDate.slice(0, 16); //get rid of the time code and just have the date

	
	//First, figure out the codes for question and answer headings
	var qCode = '<p><strong>Question:</strong>'; 
	//accommodating variant codes
	if (this.desc.search(qCode) == -1 ) {
		qCode = '<p><strong>Question: </strong>';
	}
	if (this.desc.search(qCode) == -1 ) {
		qCode = '<p><strong>Question</strong>:';
	}

	var aCode = '<p><strong>Answer:</strong>'; 
	if (this.desc.search(aCode) == -1) {
		aCode = '<p><strong>Answer: </strong>';
	}
	if (this.desc.search(aCode) == -1) {
		aCode = '<p><strong>Answer</strong>:';
	}
	
	//find and figure out the positions of question and answer codes
	this.qPos = this.desc.search(qCode); 
	this.aPos = this.desc.search(aCode); 
	
	//if the code for question is found in the text, then splice the texts into question and answer.  Note, this strips out the first <p> tag before the question and answer, so you have to add them back in.
	if (this.qPos != -1) { 
		this.qStartPos = this.qPos+qCode.length; //the starting position of the question text is the qPos plus the length of the question code plus 1 for the space
		this.qText = this.desc.slice(this.qStartPos, this.aPos);
		this.qText = filterFirstSpace(this.qText); //if the first character in the string is a space, filter that out
		
		this.aStartPos = this.aPos+aCode.length;
		this.aText = this.desc.slice(this.aStartPos);
		this.aText = filterFirstSpace(this.aText);
	}
		 
}

//Modifying the buildEntry method to accommodate the Q&A manipulations
Widget.prototype.buildEntry = function(entry){ //entry is an blogEntryobject
	
		

	var entryDiv = $('<div></div>').addClass('feedEntry').attr('id', this.divIdPrefix+entry.id);
	
	if (this.headlineType != 'date') {
		var title = $('<h4 class="feedTitle"><a href="'+entry.link+' " title="'+ entry.title+'">'+entry.title+'</a></h4>');
		entryDiv.append(title); 
	}
	
	if (this.headlineType != 'title') {
		if (this.headlineType == 'date') { //if the headline type is date, then convert the date into a link to that entry
			var date = $('<h4 class="feedDate"><a href="'+entry.link+'" title="'+entry.pubDate+'">'+entry.pubDate+'</a></h4>');
		} else {
			var date = $('<h4 class=" feedDate feedDateSmaller">'+entry.pubDate+'</h4>');
		}
		entryDiv.append(date);
	}
	
	/* if (this.headlineType == 'title' || this.headlineType == 'both') {
		var title = $('<h4 class="feedTitle"><a href="'+entry.link+' " title="'+ entry.title+'">'+entry.title+'</a></h4>');
		entryDiv.append(title); 
	}
	
	if (this.headlineType == 'date') { //if the headline type is date, then convert the date into a link to that entry
		var date = $('<p class="feedDate"><a href="'+entry.link+'" title="'+entry.pubDate+'">'+entry.pubDate+'</a></p>');
	} else {
		if (this.headlineType == 'both') {
			var date = $('<p class=" feedDate">'+entry.pubDate+'</p>');
		}
	}
	entryDiv.append(date); */

	
	/* if (this.showText != false) {
		var description = $('<div class="feedDesc"></div>');
		if (this.limitText > 0){
				entry.desc = truncate(entry.desc, this.limitText, entry.link, entry.title);
			}
		description.append('<p>'+entry.desc+'</p>');

		entryDiv.append(description);
	} */
	
	if ((this.showQuestion == true) || (this.showAnswer == true)) {
		var description = $('<div class="feedDesc"></div>');
		if (entry.qText && entry.aText) { // Q&A format exists
			if (this.showQuestion == true) {
				if (this.limitText > 0 ){
					if ((this.limitType == 'both') || (this.limitType == 'question')) {
						entry.qText = truncate(entry.qText, this.limitText, entry.link, entry.title);
					}
				}
				
				//if neither the entry title nor the date are present, then turn the question into a link
				if (this.headlineType == "none") {
					var question = $('<span  class="question"><p><a href="'+entry.link+'" title="'+entry.title+'" style="font-weight: bold" class="questionLink">Question</a>: '+ entry.qText+'</span>');
				} else {
					var question = $('<span  class="question"><p><strong>Question:</strong> '+ entry.qText+'</span>');
				}
				description.append(question);
			}
			if (this.showAnswer == true) {
				if (this.limitText > 0 ){
					if ((this.limitType == 'both') || (this.limitType == 'answer')) {
						entry.aText = truncate(entry.aText, this.limitText, entry.link, entry.title);
					}
				}
				var answer = $('<span class="answer"><p><strong>Answer:</strong> '+entry.aText+'</span>');
				description.append(answer);
			}
		} else {
			if ((this.limitText > 0) && (this.limitType != 'none')){
				entry.desc = truncate(entry.desc, this.limitText, entry.link, entry.title);
			}
			
			//if 
			description.append('<p>'+entry.desc+'</p>');


		}
		entryDiv.append(description);
	}
	
	return entryDiv;		
}

	
	
	
Widget.prototype.buildWidget = function() {
	
	//first, check to make sure that all displays aren't turned off:
	if (this.headlineType == 'none' && this.showQuestion == false) {
			alert('You turned off all required fields.  The module will not display.');
			return;
	}
	
	//check to see if the default CSS is used
	if (this.useCss != false) {
		$('head').append(this.cssCode);
	} else {
		$('#'+this.cssId).remove();
	}
	
	//next, construct the global elements, such as blog title and link
	var moduleDiv = $('<div></div>').attr('id',this.widgetId).addClass('feedWidget');
	var blogURL = this.feed.channel.link;
	var blogTitle = this.feed.channel.title;

	//show the logo
	if (this.showLogo != false) {
		moduleDiv.append(this.prgLogoCode);
	}
	
	//show the "Get this Widget" button
	if (this.showGetButton != false) {
		var buttonCode = '<a class="getWidgetButton" href="'+this.formURL+'" title="Get This Widget"><img src="'+this.buttonURL+'" alt="Get This Widget" border="0"></a>'; // add code when it becomes available
		moduleDiv.append(buttonCode);
	}

	
//show the blog title
	if (this.showBlogTitle != false) {
		var titleBar = $('<div class="titleBar"></div>');
		if (this.showTagLine != false) {
			var moduleTitle = $('<div class="blogTitle"><a href="'+blogURL+'" title="'+blogTitle+'">'+blogTitle+'</a>:<div>');
		} else {
			var moduleTitle = $('<div class="blogTitle"><a href="'+blogURL+'" title="'+blogTitle+'">'+blogTitle+'</a></div>');
		}
		titleBar.append(moduleTitle);
		if (this.showTagLine != false) {
			var tagLine = 	'<div class="tagLine">'+this.tagLine+'</div>';
			titleBar.append(tagLine);
		}
		moduleDiv.append(titleBar);
	}	
	
	/* //show the logo
	if (this.showLogo != false) {
		moduleDiv.append(this.logoCode);
	}

	
	//show the blog title
	if (this.showBlogTitle != false) {
		var moduleTitle = $('<h3><a href="'+blogURL+'" title="'+blogTitle+'">'+blogTitle+'</a></h3>');			moduleDiv.append(moduleTitle);
	} */
	
	//Check to see if the number of entries to show is within range
	if ((this.numEntries >15) || (this.numEntries <= 0)) {
		this.numEntries = 15;
	}
	
	//build the entries
	for (var i=0; i<this.numEntries; i++)	{
		moduleDiv.append(this.buildEntry(this.entries[i]));
	}
	
	//hidden iFrame for tracking
	var trackFrame = $('<iframe src="http://www.publicradio.org/columns/feed_widget/tracker.html?blog='+this.widgetId+'" style="display: none;"></iframe>');
	moduleDiv.append(trackFrame);
	
	//Finally, append the whole thing to the target div.
	$('#'+this.targetId).append(moduleDiv);
}




//Construct the widget object.  But the actual displaying of the widget will be taken care of by the inline code user embeds. 
function gpExecute() {
	/*Here's the constructor of the widget object: widget(feed, feedId, cssUrl, logoCode, formURL, buttonURL)  feedId+Widget is the target div ID.  logoCode will be already assigned to a global variable by the class -- so it's going to be either apmLogo or mprLogo.*/
	var widgetName = new Widget(gpFeed, 'gpWidget', gpPrgUrl,gpPrgLogoUrl, gpCssUrl, gpFormURL, gpButtonURL, gpTagLine);
	widgetName.parseEntries();
	return widgetName;
}

//execute
var gpWidget = gpExecute();
