function _fb_clicktrack(p) {
  path = '/facebook/'+p;
  if (typeof(urchinTracker) == 'function')
    urchinTracker(path);
  else if ((typeof(pageTracker) == 'object') && (typeof(pageTracker._trackPageview) == 'function'))
    pageTracker._trackPageview(path);
}

function _fb_onNotConnected() {
  _fb_replaceEmailButton();
}

function _fb_onConnected() {
  _fb_replaceEmailButton();
}

function _fb_streamCallback (post_id, exception) {
  if (exception) { 
    _fb_clicktrack('postFailed'+document.location.pathname+'/'+window.trackableLinkCode+'/'+exception);
  }
  if (post_id) { 
    window.last_post_id = post_id;
    _fb_clicktrack('post'+((post_id == 'null') ? 'Cancelled' : 'Succeeded')+document.location.pathname+'/'+window.trackableLinkCode+'/'+post_id);
    /* optionally, record this success within the app too */
  }
}

function _fb_getAbstractText() {
  var abstractText = '';
  var abstractDOMNode = document.body;
  var abstractNode = $(abstractDOMNode);
  if (document.location.pathname.indexOf('/content/') == 0) {
    if ($('#contribute-main > div[style^="border"][style$="red;"]').length) {
      abstractNode = $('#contribute-main > div:not([style^="border"])');
    } else {
      abstractNode = $('#contribute-main > div:not(#media-panel)');
    }
    abstractDOMNode = abstractNode[0];
  } else {
    abstractNode = $('div.content>div:not(.bookmarks) > div');
    abstractDOMNode = abstractNode[1];
  }
  abstractText = trim($(abstractDOMNode).text());
  // we'll assume the writers are using proper English sentence punctuation
  var abstractMax = 250;
  var abstractEnd = Math.max(abstractText.lastIndexOf('.', abstractMax),
                             abstractText.lastIndexOf('?', abstractMax),
                             abstractText.lastIndexOf('!', abstractMax))
  if (abstractEnd != -1) {
    abstractEnd++; // preserve the punctuation mark
  } else {
    var abstractEnd = Math.max(abstractText.lastIndexOf(' ', abstractMax),
                               abstractText.lastIndexOf(',', abstractMax))
    if (abstractEnd == -1) {
      abstractEnd = abstractMax;
    }
  }
  return abstractText.substr(0, abstractEnd);
}

function _fb_publish(mode) {
  window.trackableLinkCode = Math.floor(Math.random()*100);
  var trackableLink = document.location.protocol+'//'+document.location.host+document.location.pathname+'?fb='+window.trackableLinkCode;
  var trackableSite = document.location.protocol+'//'+document.location.host+'/'+'?fb='+window.trackableLinkCode;
  var action_links = [{ "text": "Visit Page",
                        "href":  trackableLink },
                      { "text": "Celebrations.com",
                        "href":  trackableSite }];
  var abstractText = _fb_getAbstractText();
  var attachment = { name: $('.title').text(),
                     href: trackableLink,
                  caption: 'By ' + $('#submitted a').text(),
              description: abstractText,
               properties: {'Source': action_links[1]},
                       fb: window.trackableLinkCode };
  var user_message_prompt;
  var user_message;
  if ((mode == 'comment') || (mode == 'firstContribution')) {
    user_message_prompt = ' ';
    user_message = 'I was reading “'+$('.title').text()+'” on Celebrations.com… ';
    attachment.media     = [{'type': 'image', 
                             'src' : $('.mediapanel_content img').attr('src'),
                             'href': trackableLink},
                            {'type': 'image',
                             'src' : $('.user-identity img').attr('src'),
                             'href': $('.user-identity a').attr('href')}];
    /* failsafe */
    if (!(attachment.media[0].src && attachment.media[0].href &&
          attachment.media[1].src && attachment.media[1].href)) {
      delete(attachment.media);
    } else {
      /* different UI? */
      attachment.media     = [{'type': 'image',
			       'src' : $('.mediapanel_content img').attr('src'),
			       'href': trackableLink}];
    }
    if (mode == 'firstContribution') {
      user_message_prompt = ' '
      user_message = 'I just contributed a new page about “'+$('.title').text()+'” on Celebrations.com… ';
    }
  } else if (mode == 'bookmark') {
    user_message_prompt = '';
    user_message = 'I\'m reading about "'+$('.title').text()+'" by '+$('#submitted a').text()+' on Celebrations.com... ';
  } else {
    user_message_prompt = document.title;
    user_message = '';
  }
  var target_id = null; // for directing a message to a specific friend
  var auto_publish = false; //otherwise you need the extended streamPublish permission for offline use
  FB.Connect.requireSession( function () {
    FB.Connect.streamPublish(user_message, attachment, action_links, target_id, user_message_prompt, _fb_streamCallback, auto_publish);
  });
  _fb_clicktrack('publisherCalled'+document.location.pathname);
}

function _fb_checkTrackablePage() {
  if (document.location.search.indexOf('fb=') != -1) {
    code = parseInt(document.location.search.substr(document.location.search.indexOf('fb=')+3));
    if (!isNaN(code)) {
      _fb_clicktrack('pageVisited'+document.location.pathname+'/'+code);
    }
  }
}

var _fb_runCheckOnce = 0;

function _fb_checkFirstContributionPage() {
  if (_fb_runCheckOnce) return;
  else _fb_runCheckOnce = true;
  if (document.location.search.indexOf('first=') != -1) {
    isFirst = parseInt(document.location.search.substr(document.location.search.indexOf('first=')+6));
    if (!isNaN(isFirst) && (isFirst==1)) {
      _fb_clicktrack('firstContributionPrompt'+document.location.pathname);
      _fb_publish('firstContribution');
    }
  }
}

function _fb_replaceEmailButton() {
  if ($('#emailButton')) {
    var oldOnClick = '';
    if ($('#emailButton')[0] && $('#emailButton')[0].getAttribute('onclick'))
	oldOnClick = $('#emailButton')[0].getAttribute('onclick');
    if (oldOnClick.indexOf('showLoginWarn') != -1) oldOnClick = '';
    $('#emailButton').removeAttr('onclick');
    $('#emailButton>img').attr('src','http://static.ak.fbcdn.net/rsrc.php/zBUQ9/hash/bjzz2c6x.gif').css({'padding': '2px 4px 2px 0px'});
    $('#emailButton').click(function (e) {
      _fb_publish('comment');
      //eval(oldOnClick);
    })
    _fb_checkFirstContributionPage();
  }
}

function _fb_facebookInit() {
  FB_RequireFeatures(["XFBML"], function() {
    FB.Facebook.init(
      "fe5f3fc39a2b6a3000c1b57461b11650",
      "/xd_receiver.html",
      {ifUserConnected: _fb_onConnected,
       ifUserNotConnected : _fb_onNotConnected});
    /* Add XFBML elements through JavaScript */
    FB.XFBML.Host.autoParseDomTree = false;
  });
}

document.write('<'+'div id="FB_HiddenContainer" style="position:absolute; top:-10000px; width:0px; height:0px;" ><'+'/div>')
$(document.body).ready(function () {
  $.getScript("http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php", _fb_facebookInit);
  _fb_checkTrackablePage();
});
