// Javascript To Parse Blogger Content


//-------------  Date Class  -----------
var CalendarDate = new Class ({    
    initialize: function (dateString) {
        this.init(dateString);
    },	
    		
	init: function (dateString) {
		this._init();
		this.raw = dateString;		
		this._parseDate(this.raw);		
	},			
	
    _parseDate: function (val) {
		//expect date and time to be seperated by a space
		var parts = val.split(' ');
		
		//DATE
		this._parseDATE(parts[0]);
		
		//TIME
		this._parseTIME(parts[1]);
		
		if (parts.length >= 3) {
			if (parts[2].test("PM","i") && this.hours < 12) {
				this.hours += 12;
			}
		}
    },
	
	// PUBLIC METHODS
	toDate: function() {
		return new Date(this.year, this.month-1, this.day, this.hours, this.minutes, this.seconds, 0);		//need to adjust month to zero based
	},
	
	toStringBASIC: function() {
		return this.year + '.' + this._toTwoDigitString(this.month) + '.' + this._toTwoDigitString(this.day) + ' ' + this._toTwoDigitString(this.hours) + ':' + this._toTwoDigitString(this.minutes) + ':' + this._toTwoDigitString(this.seconds);		
	}, 
	
	toRelativeString: function(relativeTo) {
		if (!relativeTo) {
			relativeTo = new Date();	//now
		}
				
		var ONE_DAY = 1000*60*60*24; //milliseconds in one day
		
		var diffDays = Math.round((relativeTo.getTime() - this.toDate().getTime()) / ONE_DAY);

		if (diffDays <= 1) {
			if (this.day == relativeTo.getDay()+1) {
				return 'earlier today';
			} else {
				return 'yesterday';
			}
		} else if (diffDays < 7) {
			return diffDays + ' days ago';
		} else if (diffDays < 30) {
			var weeks = Math.round(diffDays/7);
			if (weeks == 1) {
				return 'last week';
			} else {
				return  weeks + ' weeks ago';
			}
		} else if (diffDays < 60) {
			return 'last month';
		} else if (diffDays < 150) {
			return Math.round(diffDays / 30) + ' months ago';
		} else if (diffDays < 365) {
			return 'last ' + this._getMonthString(this.month);
		} else {
			return this._getMonthString(this.month) + ', ' + this.year;
		}
	},
	
	// PRIVATE METHODS
    
	_parseDATE: function(val) {
		val = val.trim();	
		var delim = this._getDateDelim(val);
		if (delim) {
			var parts = val.split(delim);
			if (parts[0].length == 4) {
				//first is year so assuming YYYY MM DD
				this.year = parts[0].toInt();
				if (parts.length >= 2) {
					this.month = parts[1].toInt();
					if (parts.length >= 3) {
						this.day = parts[2].toInt();
					}
				}
			} else {
				//assuming MM DD YYYY (or MM YYYY)
				this.month = parts[0].toInt();
				if (parts.length >= 3) {
					//MM DD YYYY
					this.day = parts[1].toInt();
					this.year = parts[2].toInt();
				} else {
					this.year = parts[1].toInt();
				}
			}
		} else {
			//assumming YYYYMMDD or YYYYMM
			this.year = val.substr(0,4).toInt();
			this.month = val.substr(4,2).toInt();
			if (val.length == 8) {
				this.day = val.substr(6,2).toInt();
			}
		}
		
	},
	
	_parseTIME: function(val) {
		if (!val) { return; }
		var parts = val.split(":");
		if (parts.length >= 2) {
			this.hours = parts[0].toInt();
			this.minutes = parts[1].toInt();
			if (parts.length >= 3) {
				this.seconds = parts[2].toInt();
			}
		}
		
	},
	
	_init: function() {
		this.year = 0;
		this.month = 0;
		this.day = 0;
		this.hours = 0;
		this.minutes = 0;
		this.seconds = 0;
	},
	
	// HELPERS
	
	_toTwoDigitString: function(val) {
		if (val < 10) {
			return '0' + val;
		} else {
			return '' + val;
		}		
	},
	_getMonthString: function(month) {
		switch (month) {
			case 1 :
				return 'January'; break;
			case 2 :
				return 'February'; break;
			case 3 :
				return 'March'; break;
			case 4 :
				return 'April'; break;
			case 5 :
				return 'May'; break;
			case 6 :
				return 'June'; break;
			case 7 :
				return'July'; break;
			case 8 :
				return 'August'; break;
			case 9 :
				return 'September'; break;
			case 10 :
				return 'October'; break;
			case 11 :
				return 'November'; break;
			case 12 :
				return 'December'; break;
				
			default: 
				return '???'; break;
		}
	},
	_getDateDelim: function(dateString) {
		var delims = new Array('-','/','.');
		for (var i=0; i<delims.length; i++) {
			if (dateString.contains(delims[i])) { return delims[i]; }
		}
		return null;
	}
}); //end class CalendarDate


//-------------  Post Class  -----------
var Post = new Class({
    initialize: function (post, options) {
		this.post = post;
        this.init(options);
    },	
    		
	init: function (options) {
		this.options = Object.extend({
		    xHead: 'h3.post-title',
			xSummary: '.summary',
			xPostBody: 'div.post-body',
			xCommentLink: 'a.comment-link',
			xFooter: 'div.post-footer',
			headingText: 'Other Posts',
			maxSummaryLength: 100,
			imagePath: 'http://www.ibanning.com/digiwalks/images/art/categories/',
			imageExt: '.png',
			imageCategories: new Array('assessment','civics','collaboration','conferences','creativity','curious','ideas','leadership','professional+development','projects','digital+storytelling','tools','week-in-review'),
			imageGeneric: 'generic'
		}, options || {});	

		this.url = null;
		this.title = null;
		this.pubDate = null;
		this.categories = null;
		this.postBody = null;
		this.summary = null;
		this.commentCount = 0;
		this.commentLink = null;
		this.thumb = null;

		if (this.post) {
			this._parseTitle();
			this._parsePubDate();
			this._parseCategories();
			this._parseBody();
			this._parseComments();
		}
		
	},
	
	addHeading: function() {
		
		var li = new Element('li', {
					'class': 'more-posts'}).injectBefore(this.post);

		var h2 = new Element('h2').injectInside(li);
		
		new Element('span').setHTML(this.options.headingText).injectInside(h2);
		
	},
	
	updatePublished: function() {
		var ctrl = this.post.getElement(this.options.xHead + ' span.pubDate');
		if (ctrl && this.pubDate) { 
			ctrl.setHTML(this.pubDate.toRelativeString());
		}						
	},
	
	setupAsFull: function() {
	
		if (this.postBody && this.summary) {
			if (! this.summary.getElement('img')) {											
				//thumb
				new Element('img', {
						   'src': this.thumb,
						   'class': 'thumb',
						   'alt': 'post thumbnail'}).injectTop(this.summary);
			}
		}
	},

	setupAsTeaser: function() {
		this.post.addClass('teaser');
		
		if (this.postBody && this.summary) {
			var teaser = new Element('div');
			teaser.addClass('teaser');
					
			//thumb
			new Element('img', {
					   'src': this.thumb,
					   'class': 'teaser-thumb',
					   'alt': 'post thumbnail'}).injectTop(teaser);
			
			var summaryWrap = new Element('div', {
									  'class': 'teaser-summary'}).injectInside(teaser);
			
			// summary
			this.summary = this.summary.clone();
			this.summary.injectInside(summaryWrap);
			
			// meta wrapper
			var meta = new Element('div', {
								   'class': 'summary-meta'}).injectInside(summaryWrap);
			
			//read more
			new Element('a', {
						'href': this.url,
						'class': 'teaser-readmore'}).setHTML('read more').injectInside(meta);
			//comments
			new Element('a', {
						'href': this.commentLink,
						'class': 'teaser-comments'}).setHTML(this.commentCount + ' Comment' + (this.commentCount==1 ? '' : 's')).injectInside(meta);


			
			//clear the post body
			this.postBody.setHTML('');
			
			teaser.injectInside(this.postBody);	
			
			//remove footer
			var footer = this.post.getElement(this.options.xFooter);
			if (footer) { footer.remove(); }
			
		}	else {
		
			if (!this.postBody) { console.log('missing post body'); }
			if (!this.summary) { console.log('missing post summary'); }
		}
	},
	
	//---- parsing post to extract items -----
	_parseTitle: function() {
		var ctrl = this.post.getElement(this.options.xHead + ' a');
		if (ctrl) { 
			this.title = ctrl.innerHTML.trim();
			this.url = ctrl.getProperty('href');
		}		
	}, 
	_parsePubDate: function() {
		var ctrl = this.post.getElement(this.options.xHead + ' span.pubDate');
		if (ctrl) {
			this.pubDate = new CalendarDate(ctrl.innerHTML.trim());
		}
	}, 
	_parseCategories: function() {
		this.categories = new Array();
		var ctrl = this.post.getElement(this.options.xHead + ' span.categories');										
		if (ctrl) {
			ctrl.getElements('a').each( function(el) {
				this.categories.push(el.innerHTML.trim());
			 }, this);
		}
	},
	_parseComments: function() {
		var ctrl = this.post.getElement(this.options.xCommentLink);
		if (ctrl) {
			
			this.commentLink = ctrl.href;
			if (ctrl.rel) {	this.commentCount = ctrl.rel.toInt(); }
			else {
				//comment count is not in the 'rel' attribute
				//so check the first span
				ctrl = ctrl.getElement('span');
				if (ctrl) { this.commentCount = ctrl.innerHTML.trim().toInt(); }
			}
			
		} else {
			
			console.log('no comment block');
		
		this.commentLink = '';
		this.commentCount = 2;
			
		}
		
		
	},
	_parseBody: function() {
		var ctrl = this.post.getElement(this.options.xPostBody);
		if (ctrl) {
			this.postBody = ctrl;
			ctrl = this.postBody.getElement(this.options.xSummary);
			if (ctrl) { 
				this.summary = ctrl;
			} else {
				this._extractSummary(this.post.getElement('p'));	//use the first paragraph				
			}								
		}
		this.thumb = null;
		ctrl = null;
		if (this.summary) { 
			ctrl = this.summary.getElement('img.thumb');
			ctrl = ctrl ? ctrl : this.summary.getElement('img');	//if there is no img.thumb use any image
			if (ctrl) {
				this.thumb = ctrl.src;
				ctrl.remove();
			}
		}
		if (!this.thumb) {
			this.thumb = this.options.imagePath + this._getCategoryImageName().replace('+','-') + this.options.imageExt;
		}
	}, 
	
	_extractSummary: function(source) {
		this.summary = source;
		if (this.summary) {
			var html = this.summary.innerHTML;
			
			var checks = new Array("<br/>","<br>","<br />");
			for (var x=0; x<checks.length; x++) {
				for (var y=0; y<checks.length; y++) {
					if (html.test(checks[x] + checks[y])) { html = html.substr(0,html.indexOf(checks[x] + checks[y])); }
					if (x != y && html.test(checks[y] + checks[x])) { html = html.substr(0,html.indexOf(checks[y] + checks[x])); }
				}
			}
			if (html.length > this.options.maxSummaryLength) {
				var bCont = true;
				var i = 0;
				var count = 0;
				var inTag = 0;
				while (count < this.options.maxSummaryLength && i < html.length-1) {
					if (html.charAt(i) == "<") {
						if (html.charAt(i+1) == "/") {
							inTag -= 1;
						} else {
							inTag += 1;
						}
					} else if (html.charAt(i) == "/" && html.charAt(i+1) == ">") {
						inTag -= 1;						
					} else if (inTag == 0) {
						count += 1;
					}
					i += 1;					
				}
			}
			
			this.summary.setHTML(html);
		}
	},
	_getCategoryImageName: function() {
		var ret = null;
		if (this.categories) {
			this.categories.each(function (cat) {
				cat = cat.trim().toLowerCase();
				if (!ret && this.options.imageCategories.contains(cat)) { ret = cat; }				
			}, this);
		}
		return ret ? ret : this.options.imageGeneric;	//default iamge
	}

					 
});


function TestIt() {
	var iCount = 0;
	$$('ul#post-area li.post-area').each( function(el) {
		
		var x = new Post(el);
		x.updatePublished();
		iCount++;
		
		if (iCount == 1) { x.setupAsFull(); }
		if (iCount == 2) { x.addHeading(); }
		if (iCount > 1) { x.setupAsTeaser(); }
	});
	if (iCount == 0) {
		$$('#post-area').each( function(el) {
			var x = new Post(el);
			x.updatePublished();
			iCount++;
			
			if (iCount == 1) { x.setupAsFull(); }
		});
	}
}

window.addEvent('domready',TestIt);