/*
 * Facebook Comments-Box email notifications v2.1
 * http://forum.developers.facebook.net/viewtopic.php?id=74644
 *
 * Copyright (c) 2011 Gil Goldshlager
 * http://facebook.com/gil.goldshlager
 * You can use this code as you want, but you must keep it free of charge!
 */

function fbCommentsEN(sendPath) {

	FB.Event.subscribe('comment.create', function(response) {
		// Site Name
		var siteName = $('meta[property="og:site_name"]').attr('content');
		if(siteName == undefined){
			siteName = $('title').html();
		}

		// Email message subject text
		var mailSubject = 'Facebookコメント通知';
		
		// Comment Page Title
		var pageTitle = $('.fbcomments').attr('title');
		if(pageTitle == undefined){
			pageTitle = $('meta[property="og:title"]').attr('content');
			if(pageTitle == undefined){
				pageTitle = $('title').html();
				if(pageTitle == undefined){pageTitle = 'エラー:ページタイトルが取得できません。';}
			}
		}

		// Comment Page URL
		var pageURL = $('.fbcomments[href]').attr('href');
		if(pageURL == undefined){pageURL = document.location.href;}

		// Querying the latest comment on the page
		FB.api({
			method: 'fql.multiquery',
			queries: {
				comment: 'SELECT xid, object_id, post_id, fromid, time, text, id, username, reply_xid, post_fbid FROM comment WHERE object_id IN (SELECT comments_fbid FROM link_stat WHERE url ="'+ pageURL +'") ORDER BY time desc LIMIT 1',
				user: 'SELECT id, name, url, pic_square FROM profile WHERE id IN (SELECT fromid FROM #comment)'
			}
		},
			function(response) {
				if (!response || response.error) {
					var message = "The response doesn't return.";
					if(response){message = response.error.message;}
					$(document).ready(function(){
						$.post(sendPath,{ fromName: siteName, pageTitle: pageTitle, subject: mailSubject, pageURL: pageURL, error: '1', message: message }, "html");
					});
				} else {
					comment = response[0].fql_result_set;
					user = response[1].fql_result_set;
					// Comment Date and Time
					var commentDate = new Date(comment[0].time*1000);
					var curr_date = commentDate.getDate();
					var curr_month = commentDate.getMonth();
					curr_month++;
					var curr_year = commentDate.getFullYear();
					var a_p = "";
					var curr_hour = commentDate.getHours();
					if (curr_hour < 12){a_p = "AM";}else{a_p = "PM";}if (curr_hour == 0){curr_hour = 12;}if (curr_hour > 12){curr_hour = curr_hour - 12;}
					var curr_min = commentDate.getMinutes();
					commentDate = curr_year + "/" + curr_month + "/" + curr_date + " at " + a_p + " " + curr_hour + ":" + curr_min;
					
					// Comment body text
					var commentText = comment[0].text;

					// Sending the data to the PHP file that includes the mail() function
					$(document).ready(function(){
						$.post(sendPath,{ fromName: siteName, pageTitle: pageTitle, subject: mailSubject, commentText: commentText, usrName: user[0].name, usrURL: user[0].url, pageURL: pageURL, commentDate: commentDate }, "html");
					});
				}
			}
		);
	});
}
