var ANS;
if(!ANS){
	ANS = {};
}

/**
 * This javascript is designed to notify users
 * when Ansha has posted a recent BLOG Post
 */

ANS.RecentBlogNotify = function(pConfig){
	this.config = pConfig;
	this.currentTime = new Date().getTime();
	this.hasNotified = false;
	this.blogCheckInterval = null;
	this.currentBlogPost = pConfig.currentBlogPost;
	this.triggerTimeMin = pConfig.triggerTimeMin;
}

ANS.RecentBlogNotify.prototype.run = function(){
	this.createInterval(this.triggerTimeMin);
}

ANS.RecentBlogNotify.prototype.displayNotification = function(latestPost){
	var blogPostUrl = "http://www.anshakotyk.com/blog/?p=" + latestPost.id;
	var sb = [];
	sb[sb.length] = "<span style='font-size:1.5em;'>Ansha's Blog</span>";
	sb[sb.length] = "<p>Ansha posted a recent blog entry</p>";
	sb[sb.length] = "<a href=\""+ blogPostUrl+"\">" + latestPost.title + "</a>";
	jQuery.jGrowl(sb.join(''), { life: 5000});
};

ANS.RecentBlogNotify.prototype.requestLatestBlogPost = function(previousPost){
	var that = this;
	$.ajax({
		  url: "/blogInfo.php",
		  type: "GET",
		  dataType: "json",
		  success: function(data){
			that.processLatestBlogRequest(data);
		  },
		  error: function(xhr, ajaxOptions, thrownError){
			  alert(xhr.status);
              alert(thrownError);
			  that.clearInterval();
		  }
		});
};

ANS.RecentBlogNotify.prototype.processLatestBlogRequest = function(latestBlogJSON){
	if(!this.isSameBlogPost(this.currentBlogPost, latestBlogJSON)){
		this.currentBlogPost = latestBlogJSON;
		this.displayNotification(latestBlogJSON);
	}
};

ANS.RecentBlogNotify.prototype.isSameBlogPost = function(previousPost, latestPost){
	return previousPost.id === latestPost.id;
};

ANS.RecentBlogNotify.prototype.createInterval = function(pTriggerTimeMin){
	var that = this;
	var timeInMs = pTriggerTimeMin * 60 * 1000;
	this.blogCheckInterval = setInterval(function(){
		try{
			that.requestLatestBlogPost(that.currentBlogPost);	
		} catch(ex){
			that.clearInterval();
		}
	}, timeInMs);
	
};

ANS.RecentBlogNotify.prototype.clearInterval = function(){
	clearInterval(this.blogCheckInterval);
};


