function LogComment(oFBResponse) {
    // esta sql no esta fina y tiene un bug: si en el mismo instante t se insertan 2 respuestas a comentarios, sólo saca la última. Si la corriges envíamela por email :)
    var commentQuery = FB.Data.query("SELECT text, fromid FROM comment WHERE (post_fbid='" + oFBResponse.commentID + "' AND (object_id IN (SELECT comments_fbid FROM link_stat WHERE url='" + oFBResponse.href + "')) OR object_id IN (SELECT post_fbid FROM comment WHERE object_id IN (SELECT comments_fbid FROM link_stat WHERE url='" + oFBResponse.href + "')) ) ORDER BY time DESC LIMIT 1");
    var userQuery = FB.Data.query("SELECT name, uid, email FROM user WHERE uid in (select fromid from {0})", commentQuery);

    FB.Data.waitOn([commentQuery, userQuery], function() { LogCommentToBD(1, oFBResponse.href, oFBResponse.commentID, commentQuery.value[0].text, userQuery.value[0].name, userQuery.value[0].uid, userQuery.value[0].email, 'http://graph.facebook.com/'+userQuery.value[0].uid+'/picture') });
}

function LogCommentToBD(iAction, sURL, sCommentID, sText, sName, sUID, sEmail, sPicture) {
    var ajax;
    if (window.XMLHttpRequest) ajax = new XMLHttpRequest();
    else ajax = new ActiveXObject("Msxml2.XMLHTTP");

    var oDate = new Date();
    var sajaxURL = '/ajax_functions.aspx?f=1&action=' + iAction + '&url=' + encodeURIComponent(sURL) + '&commentid=' + sCommentID + '&text=' + encodeURIComponent(sText) + '&name=' + encodeURIComponent(sName) + '&uid=' + sUID + '&email=' + encodeURIComponent(sEmail) + '&pic=' + encodeURIComponent(sPicture) + '&rnd=' + oDate.getHours() + oDate.getMinutes() + oDate.getSeconds() + oDate.getUTCMilliseconds();
    ajax.open("GET", sajaxURL, false);
    ajax.send(null);

}

function DelComment(oFBResponse) {
    LogCommentToBD(0, oFBResponse.href, oFBResponse.commentID, '', '', '', '', '');
}

window.fbAsyncInit = function() {
    FB.init({
        appId: '240222156034159',
        channelURL: '//www.alpel.es',
        status: true,
        cookie: true,
        oauth: true,
        xfbml: true
    });

    FB.Event.subscribe('comment.create', function(response) { LogComment(response)});

    FB.Event.subscribe('comment.remove', function(response) { DelComment(response) });

    FB.Event.subscribe('edge.create', function(targetUrl) { _gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]); });

    FB.Event.subscribe('edge.remove', function(targetUrl) { _gaq.push(['_trackSocial', 'facebook', 'unlike', targetUrl]); });

    FB.Event.subscribe('message.send', function(targetUrl) { _gaq.push(['_trackSocial', 'facebook', 'send', targetUrl]); });
};

(function(d) {
    var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/es_ES/all.js";
    d.getElementsByTagName('head')[0].appendChild(js);
} (document));
