

jQuery(document).ready(function() {
  doUserRequests();
  attachRollOverEvent(".header a img.logo");
  logOutPage();
  //moveFriendRequests();
});



/**
 * Check the Sitelife server to see if we're logged in and if so get
 * who we are, then do page initialisation bits where we need to
 * know that.
 */
function doUserRequests() {
  var requestBatch = new RequestBatch();
  requestBatch.AddToRequest(new UserKey(null));

  requestBatch.BeginRequest(serverUrl, function(response) {
    // Check we've got a response.
    if (response.Responses.length) {
      // Set global variables.
      user = response.Responses[0].User;
      loggedIn = user != null && user.DisplayName != 'anonymous';
      userId = user.UserKey.Key;
      jQuery.bmj.log("doUserRequests: loggedIn = {0}, userId = {1}".fmt(loggedIn, userId));

      jQuery.bmj.runEventHandlers("DoneLoginCheck", loggedIn, user || null);

      if (loggedIn) {
        // From requestHeaderlinks()
        jQuery("#headerlinks")
          .prepend("<li><a href='javascript:logOut()'>Logout</a></li><li><a href='/profile.html?userId=" + userId + "&plckPersonaPage=PersonaProfile'>Edit profile</a></li>");

        // From requestLogin()
        jQuery(".profilenav")
          .html("<a href='/profile.html?userId=" + userId + "' title='View my doc2doc profile'><span>My doc2doc</span></a>");
        jQuery(".myProfileLink").attr("href", "/profile.html?userId=" + userId);
        //jQuery(".banner")
        //  .html("<img src='/images/twitter-banner.gif' alt='Thank you for registering. Don't forget to tell your colleagues about doc 2 doc' />");

      }
      else {
        // From requestLogin()
        var returnURL = encodeURI(window.location.href),
         loginLink = jQuery.bmj.globalConfig.loginUrl;
         regLink = jQuery.bmj.globalConfig.registerUrl;

        jQuery(".homepagenav").addClass("loginnav");
        jQuery(".loginnav")
          .removeClass("homepagenav")
          .html("<ul class='clear'>" +
            "<li><a href='" + loginLink + "'><img src='images/button-login.gif' height='20' width='82' alt='Login' /></a></li>" +
            "<li><a href='" + regLink + "'><img src='images/button-register.gif' height='20' width='82' alt='Register' /></a></li>" +
            "</ul>");

        //jQuery(".banner")
        //  .html("<a href='" + regLink + "'><img src='images/twitter-banner.gif' alt='Register now to join the doc 2 doc community' title='Register now to join the doc2doc community' /></a>");
      }

      // From requestWelcome()
      if (user.DisplayName != 'anonymous') {
        jQuery("p.welcome")
          .text("Welcome " + user.DisplayName + ",");
      }

      // From requestCurrent()
      // Check for user id specified in current URL.
      var urlData = jQuery.parseuri();
      currentId =  urlData.queryKey.userId;

      if (currentId == userId) {
        if (jQuery("body").hasClass("people")) {
          jQuery("body").addClass("profile").removeClass("people");
        }
      }
    }
    else {
      jQuery.bmj.log("doUserRequests(): no responses received")
    }

  });
}



//-----------------------------------------------------

function attachRollOverEvent(imageId) {
  jQuery(imageId)
    .mouseover(function() {
      jQuery(this).attr("src", jQuery(this).attr("src").split('-off').join('-on'))
    })
    .mouseout(function() {
      jQuery(this).attr("src", jQuery(this).attr("src").split('-on').join('-off'))
    });
}


//-----------------------------------------------------

function logOutPage() {
  if (jQuery(".logOutPage").length > 0) {
    d2dCookie.setLoggedOut();
  }
}


//----------------------------------------------------- Generic functions ------------------------------------------------------------------

var d2dCookie = {
  setLoggedOut: function() {
    var cookie_date = new Date(); // current date & time
    cookie_date.setTime(cookie_date.getTime() - 1);
    document.cookie = 'HD=; expires=' + cookie_date.toGMTString() + '; path=/; domain=bmj.com';
    document.cookie = 'AT=; expires=' + cookie_date.toGMTString() + '; path=/; domain=bmj.com';
    document.cookie = 'ICSMarker=; expires=' + cookie_date.toGMTString() + '; path=/; domain=bmj.com';
  }
}

function logOut() {
  d2dCookie.setLoggedOut();
  window.location.reload();
}


/**
 * Generate Recent Discussions widget using Discovery.
 * @param {Number} ageOfItems Maximum age in days to get discussions for
 * @param {Number} numberOfItems Maximum number of items to get
 */
function requestRecentDiscussions(ageOfItems, numberOfItems) {
  var requestBatch = new RequestBatch();
  requestBatch.AddToRequest(new DiscoverContentAction([], [], [],
      new Activity("Recent"), new ContentType("Discussion"), ageOfItems, numberOfItems));
  requestBatch.BeginRequest(serverUrl, responseRecentDiscussions);
}

function responseRecentDiscussions(responseBatch) {
  var responseLength = responseBatch.Responses[0].DiscoverContentAction.DiscoveredContent.length

  var userDataHtml = '<div style="display: inline;">';
  userDataHtml += '<div class="Summary_Container">';
  userDataHtml += '<table cellspacing="0" cellpadding="0" class="Summary_DiscTable">';
  userDataHtml += '<tbody>';

  for (var i = 0; i < responseLength; i++) {
    var cur = responseBatch.Responses[0].DiscoverContentAction.DiscoveredContent[i];

    rebuiltUrl = jQuery.bmj.getGroupUrl(cur);

    if (i % 2) {
      userDataHtml += '<tr>';
    }
    else {
      userDataHtml += '<tr class="Summary_DiscAltTRColor">';
    }

    userDataHtml += '<td class="Summary_DiscTableLeft">';

    userDataHtml += '<a onclick="" href="' + cur.LastPostBy.PersonaUrl + '">';
    userDataHtml += '<img class="PluckUserAvatar" alt="" src="' + cur.LastPostBy.ImageUrl + '" id=""/>';
    userDataHtml += '</a>';
    userDataHtml += '</td>';
    userDataHtml += '<td class="Summary_DiscTableRight">';
    userDataHtml += '<div class="Summary_DiscTitle">';
    userDataHtml += '<a href="' + rebuiltUrl + '">' + cur.DiscussionTitle + '</a>';
    //userDataHtml += discBody.substr(0, 80)+'...</p>';
    userDataHtml += '</div>';
    userDataHtml += '<div class="Summary_DiscBy">';
    userDataHtml += 'By <a target="_parent" href="' + cur.LastPostBy.PersonaUrl + '" id="">' +
      cur.LastPostBy.DisplayName + '</a>';
    userDataHtml += '</div>';
    userDataHtml += '</td>';
    userDataHtml += '</tr>';
  }

  userDataHtml += '</tbody>';
  userDataHtml += '</table>';
  userDataHtml += '</div>';
  userDataHtml += '</div>';

  jQuery("#Summary_Container_Disc").append(userDataHtml);
}
