RequestBatch.sitelifeBaseUrl = 'http://sitelifestage.bmj.com';
;(function(slBaseUrl, clientBaseUrl) {
  // utility functions
  function $(id) { return document.getElementById(id); }
  function addEvent(elem, eventName, fn) { if (elem.addEventListener) elem.addEventListener(eventName, fn, false); else if (elem.attachEvent) elem.attachEvent('on' + eventName, function() { fn(window.event); }); }
  function stopEvent(e) { if (e.preventDefault) { e.preventDefault(); } else e.returnValue = false; }
  
  var translations = {
    BlogPost: 'blog posts'
    ,Comment: 'comments'
    ,ForumPost: 'forum posts'
    ,User: 'members'
  };
  var regex = /^\s+|\s+$/g;
  function trim(str) { return str.replace(regex, ''); }
  
  var re = /[<&>]/g, replacements = {'<': '&lt;', '&': '&amp;', '>': '&gt;'};
  function encode(str) { return str ? str.replace(re, function(c) { return replacements[c]; }) : ''; }
  var convertDate = RequestBatch.convertDate = function(str, standardDates) {
    function s(count, text) { return count + ' ' + text + (count != 1 ? 's' : '') + ' ago'; }
    function prettyDate(time) {
      var date = new Date((time || '').replace(/-/g,'/').replace(/[TZ]/g,' ')),
        diff = ((new Date().getTime() - date.getTime()) / 1000) | 0,
        day_diff = Math.floor(diff /86400);
          
      if (isNaN(day_diff) || (day_diff < 0) || (day_diff >= 7))
        return time;
          
      return day_diff == 0 &&
        (
          (diff < 60 && 'just now') ||
          (diff < 120 && s(1, 'minute')) ||
          (diff < 3600 && s(Math.floor(diff /60), 'minute')) ||
          (diff < 7200 && s(1, 'hour')) ||
          (diff < 86400 && s(Math.floor(diff /3600), 'hour'))
        ) ||
        (day_diff == 1 && 'Yesterday') ||
        (day_diff < 7 && s(day_diff, 'day')) ||
        time;
    }
    var date = new Date(str || ''), ampm = 'AM', time = date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear() + ' ' + (date.getHours() > 12 ? (ampm = 'PM') && (date.getHours() - 12) : date.getHours()) + ':' + date.getMinutes() + ' ' + ampm;
    return (standardDates ? time : prettyDate(time));
  }
  
  var forEach = Array.prototype.forEach || function(fn, that /* reference to this */) {
    if (typeof fn != 'function') {
      throw new TypeError();
    }
    
    for (var i = 0, length = this.length; i < length; i++) {
      if (i in this) {
        fn.call(that, this[i], i, this);
      }
    }
  };
  
  // main
  function sendRequest(request, callback) {
    var batch = new RequestBatch();
    if (!(request instanceof Array))
      request = [request];
      
    for (var i = 0; i < request.length; i++)
      batch.AddToRequest(request[i]);
    
    batch.BeginRequest(serverUrl, callback);
  }
  function notify(msg) {
    var me = arguments.callee, elem = $('slNotification');
    if (me.timer) {
      clearTimeout(me.timer);
      me.timer = false;
    }
    elem.innerHTML = msg;
    elem.className = 'slAttention';
    elem.scrollIntoView(true);
    setTimeout(clearNotification, 3000);
  }
  
  function clearNotification() {
    var elem = $('slNotification');
    elem.className = elem.innerHTML = '';
  }
  
  function saveDialog(e) {
    var elem = e.target || e.srcElement,
      key = elem.getAttribute('rel') || elem.rel, 
      userKey = new UserKey(key), 
      text = $('slModalContent').value;
    var body = 'You have received a friend request on doc2doc.\n\n' + text + 
      '\n\nClick on the link below to login to doc2doc. Your friend request is on your doc2doc profile page.\n\nThanks,\ndoc2doc community management team\n\nhttp://group-registration.bmj.com/group-registration/servlet/GroupRegistrationServlet?doc2docUserType=login&action=doLookup&thankyou=register-confirmation-wf.jsp&sitePageCode=webForum&resDef=bmjpg%3Aweb-forum&returnUrl=' + encodeURIComponent('http://doc2doc.bmj.com/profile.html?userId=' + key);
    addFriendCallback.uid = key;
    //sendRequest([new AddFriendAction(userKey), new EmailContentWithUserIDAction(userKey, 'You have received a friend request on doc2doc', body)], addFriendCallback);
    sendRequest([ new AddFriendAction(userKey), 
                  new PrivateMessageSendAction('You have received a new friend request', body, [userKey])
                ],
                addFriendCallback);
    closeDialog(e);
  }
  
  function closeDialog(e) {
    if (e) {
      stopEvent(e);
      
      var elem = e.target || e.srcElement;
      if (elem)
        elem.blur();
    }
    document.documentElement.className = '';
    
    $('slModalContent').value = $('slModalDialog').style.display = $('slOverlay').style.display = '';
  }
  
  function createKey(type, key) {
    if (type == 'BlogPost')
      key = new BlogPostKey(key);
    else
      key = null;
    
    return key;
  }
/*
  DAAPI callbacks
*/
  function addFriendCallback(batch) {
    var errors = false, tmp;
    // error check and return
    for (var i = 0, messages = batch.Messages, msg; i < messages.length; i++) {
      msg = messages[i].Message;
      if ((msg != 'ok') && (msg != 'Pending') && (msg != 'AlreadyExists'))
        errors = true;
    }
    if (!errors)
      notify('Friend request sent');
      
    if ((tmp = arguments.callee.uid) && (tmp = $('slAction_' + tmp)) && tmp.firstChild) {
      arguments.callee.uid = null;
      tmp.replaceChild(document.createTextNode('Friendship pending'), tmp.firstChild);
    }
  }
  function memberCallback(batch) {
    if (batch.Responses.length == 0) {
      alert('ERROR: ' + batch.Messages[0].Message);
      return;
    }
    
    var current = batch.Responses[1].User.UserKey.Key;
    showResult(batch.Responses[0].SearchResult, current, current != 'anonymous');
    
    forEach.call(document.getElementsByClassName('slAddFriend'), function(element) {
      addEvent(element, 'click', function(e) {
        stopEvent(e);
        var elem = e.target || e.srcElement;
        $('slSubmit').setAttribute('rel', elem.getAttribute('rel') || elem.rel);
        document.documentElement.className = 'slOverlayMode';
        elem.blur();
      });
    });
    if (!arguments.callee.called) { // do once
      arguments.callee.called = 1;
      addEvent($('slSubmit'), 'click', saveDialog);
      addEvent($('slCancel'), 'click', closeDialog);
    }
  }
  
  function contentCallback(batch) {
    if (batch.Responses.length == 0) {
      alert('ERROR: ' + batch.Messages[0].Message);
      return;
    }
    
    var current = batch.Responses[1].User.UserKey.Key;
    showResult(batch.Responses[0].SearchResult, current, current != 'anonymous');
  }
  
  function showResult(result, current, loggedIn) {
    var doc = document, container = doc.getElementById('slSearchContainer'), sub = doc.createElement('div')
        ,results = result.SearchResults ,total = parseInt(result.NumberOfSearchResults, 10)
        ,pageNum = parseInt(result.OnPage, 10), perPage = parseInt(result.NumberPerPage, 10)
        ,min = ((pageNum -1) * perPage) + 1, max = Math.min((pageNum * perPage), total)
        ,type = result.SearchType, tmp;
    
    sub.id = 'slSearchContainer' + type;

    if (!$('slNotification')) {
      var notify =  container.appendChild(doc.createElement('div'));
      notify.id = 'slNotification';
    }
    
    if (total) {
      switch (type) {
        case 'User':
          forEach.call(results, function showUser(user) {
            if (!user || (user.IsBlocked == 'True')) return;
            
            var prof = user.ExtendedProfile, key = user.UserKey.Key, div = document.createElement('div');
            div.className = 'slContact';
            div.innerHTML = '<image id="slUserAvatar_' + key + '" src="' + slBaseUrl + '/ver1.0/Content/images/no-user-image.gif" rel="' + user.AvatarPhotoUrl + '" /><div class="slContent">' +
            '<div class="slName"><span class="title">Name:</span> <span class="data" id="slName_' + key + '">' + encode(prof.f) + ' ' + encode(prof.l) + '</span></div>' +
            '<div class="slSpeciality"><span class="title">Medical Specialty:</span> ' + encode(prof.s) + '</div>' +
            '<div class="slGrade"><span class="title">Grade:</span> ' + encode(prof.g) + '</div>' +
            '<div class="slLocation"><span class="title">Location:</span> ' + encode(prof.o) + '</div>' +
            (current != key ? '<div class="slActions" id="slAction_' + key + '" rel="' + encode(prof.f) + ' ' + encode(prof.l) + '"><a class="' + (loggedIn ? 'slAddFriend' : 'slLoginToAddFriend') + '" href="' + (loggedIn ? '#befriend' : 'http://group-registration.bmj.com/group-registration/servlet/GroupRegistrationServlet?doc2docUserType=login&action=doLookup&thankyou=register-confirmation-wf.jsp&sitePageCode=webForum&resDef=bmjpg%3Aweb-forum&returnUrl=' + encodeURIComponent(location.href)) + '" id="slAddFriend_' + key + '" rel="' + key + '">' + (loggedIn ? 'Friend request' : 'Log in to request friendship') + '</a></div>' : '') + 
            '</div>';
            sub.appendChild(div);
            
            // use IsFriend to show the avatar
            var userKey = new UserKey(user.UserKey.Key);
            sendRequest([new IsFriend(userKey), userKey /* new LiteUser(userKey)*/], function(isFriendResponse) {
              // will only have one message (result of IsFriend) and one response(possible friend)
              var possibleFriend = isFriendResponse.Responses[0].User
                  ,friendKey = possibleFriend.UserKey.Key
                  ,avatar = $('slUserAvatar_' + friendKey)
                  ,action = $('slAction_' + friendKey)
                  ,name = $('slName_' + friendKey);
              
              switch (isFriendResponse.Messages[0].Message) {
                case 'Friend':
                case 'Self':
                  var link = document.createElement('a'), link2;
                  link.href = clientBaseUrl + '/profile.html?userId=' + friendKey;
                  link2 = link.cloneNode(false);
                  link2.appendChild(name.firstChild);
                  name.parentNode.replaceChild(link2, name);
                  
                  if (avatar && possibleFriend.AvatarPhotoUrl) {
                    var img = link.appendChild(avatar.cloneNode(false));
                    img.src = possibleFriend.AvatarPhotoUrl;
                    link.className = 'slImage';
                    avatar.parentNode.replaceChild(link, avatar);
                  }
                  
                  if (action)
                    action.style.visibility = 'hidden';
                  break;
                  
                case 'Pending':
                  if (action && action.firstChild)
                    action.replaceChild(document.createTextNode('Friendship pending'), action.firstChild);
              }
            });
            // end of friend check code
          });
          break;
        
        case 'BlogPost':
          forEach.call(results, function showBlogPost(post) {
            if (!post || (post.IsPublished == 'False')) return;
            
            var user = post.PostAuthor, prof = user.ExtendedProfile, key = user.UserKey.Key, div = document.createElement('div');
            div.className = 'slBlogPost';
            div.innerHTML = '<image class="slImage" id="slPostAvatar_' + key + '" src="' + slBaseUrl + '/ver1.0/Content/images/no-user-image.gif" rel="' + user.AvatarPhotoUrl + '" />' + 
            '<div class="slPostContent">' +
            '<div class="slPostTitle"><a href="' + post.Url + '">' + post.PostTitle + '</a></div>' +
            '<div class="slPostUser"><span class="title">by:</span> <a class="slPersonaLink" href="' + user.PersonaUrl + '">' + user.DisplayName + '</a></div>' +
            '<div class="slPostDate"><span class="data">' + convertDate(post.PostDate) + '</div>' +
            '</div>';
            sub.appendChild(div);
          });
          break;
        
        case 'Comment':
          var requests = [];
          forEach.call(results, function preShowComment(comment) {
            requests.push(createKey(comment.CommentedOnType, comment.CommentedOnKey));
          });
          sendRequest(requests, function commentedContentReceived(batch) {
            var responses = batch.Responses;
            forEach.call(results, function showComment(comment, position) {
              if (!comment || (comment.ContentBlockingState != 'Unblocked')) return;
              
              var type = comment.CommentedOnType, content = responses[position][type], key = content[type + 'Key'].Key, div = document.createElement('div');
              div.className = 'slComment';
              div.innerHTML = '<image class="slImage" id="slPostAvatar_' + key + '" src="' + slBaseUrl + '/ver1.0/Content/images/no-user-image.gif" rel="' + user.AvatarPhotoUrl + '" />' + 
              '<div class="slPostContent">' +
              '<div class="slPostTitle"><a href="' + (content.Url || content.PageUrl || '#') + '">' + content.PostTitle + '</a></div>' +
              '<div class="slPostUser"><span class="title">by:</span> <a class="slPersonaLink" href="' + user.PersonaUrl + '">' + user.DisplayName + '</a></div>' +
              '<div class="slPostDate"><span class="data">' + convertDate(comment.PostedAtTime) + '</div>' +
              '</div>';
              sub.appendChild(div);
            });
          });
          break;
          
        case 'ForumPost':
          var requests = [];
          forEach.call(results, function preShowForumPost(post) {
            requests.push(new UserKey(post.UserKey.key));
          });
          sendRequest(requests, function forumUsersReceived(batch) {
            var responses = batch.Responses;
            forEach.call(results, function showForumPost(post, position) {
              if (!post || (post.IsPublished == 'False')) return;
              
              var user = responses[position].User, prof = user.ExtendedProfile, key = user.UserKey.Key, div = document.createElement('div');
              div.className = 'slBlogPost';
              div.innerHTML = '<image class="slImage" id="slPostAvatar_' + key + '" src="' + slBaseUrl + '/ver1.0/Content/images/no-user-image.gif" rel="' + user.AvatarPhotoUrl + '" />' + 
              '<div class="slPostContent">' +
              '<div class="slPostTitle"><a href="' + post.PostUrl + '">' + post.PostTitle + '</a></div>' +
              '<div class="slPostUser"><span class="title">by:</span> <a class="slPersonaLink" href="' + user.PersonaUrl + '">' + user.DisplayName + '</a></div>' +
              '<div class="slPostDate"><span class="data">' + convertDate(post.LastUpdated) + '</div>' +
              '</div>';
              sub.appendChild(div);
            });
          });
          break;
      }
      if (tmp = $(sub.id))
        tmp.parentNode.replaceChild(sub, tmp);
      else
        container.appendChild(sub);
      
      if (!$('slSearchSummaryContainer' + type)) {
      container.innerHTML += '<br style="clear: both"/>'+
        '<div id="slSearchSummaryContainer' + type + '" class="slSearchSummary">Results <span id="slSearchMin' + type + '">0</span> - <span id="slSearchMax' + type + '">0</span> of <span id="slSearchTotal' + type + '">0</span> ' + translations[type] + '</div>'+
        '<div id="slSearchNavContainer' + type + '" class="slSearchNav"><a style="display: none" href="#prev" rel="-1" id="slSearchPrev' + type + '">&laquo; Prev</a><a style="display: none" href="#next" rel="1" id="slSearchNext' + type + '">Next &raquo;</a></div>';
      }
      $('slSearchMin' + type).innerHTML = min;
      $('slSearchMax' + type).innerHTML = max;
      $('slSearchTotal' + type).innerHTML = total;
      
      $('slSearchNext' + type).parentNode.setAttribute('rel', pageNum);
      
      if (tmp = $('slSearchPrev' + type)) {
        //tmp.style.display = (pageNum > 1 ? '' : 'none');
        tmp.style.visibility = (pageNum > 1 ? 'visible' : 'hidden');
      }
      tmp.setAttribute('rel', pageNum -1);
      
      if (tmp = $('slSearchNext' + type)) {
        //tmp.style.display = (max < total ? '' : 'none');
        tmp.style.visibility = (max < total ? 'visible' : 'hidden');
      }
      tmp.setAttribute('rel', pageNum +1);
    }
    else {
      sub.innerHTML += '<span class="slNoSearchResults">Your search returned no results. Help doc2doc grow by telling your colleagues about it.</span>';
      
      if (tmp = $(sub.id))
        tmp.parentNode.replaceChild(sub, tmp);
      else
        container.appendChild(sub);
    }
    
    if (!$('slModalDialog')) {
      container.innerHTML += '<div id="slModalDialog"><h3>Attach a personal message:</h3><div id="slWarning">Please note that this message will include your email address.</div><textarea cols="50" rows="6" id="slModalContent"></textarea><div id="slModalControls"><button id="slSubmit">Submit</button><a href="#cancel" id="slCancel">Cancel</a></div></div>'
      // ie6 hacks for "position: fixed" and iframe shim
      + '<div id="slOverlay"><!--[if lte IE 6]><style type="text/css">#slOverlay, #slModalDialog { position: absolute !important; } .slOverlayMode #slModalDialog { top: expression((document.documentElement.scrollTop || document.body.scrollTop) + Math.round(15 * (document.documentElement.offsetHeight || document.body.clientHeight) / 100) + "px"); } .slOverlayMode #slOverlay { left: expression(ignoreMe = document.documentElement.scrollLeft + "px"); top: expression(ignoreMe = document.documentElement.scrollTop + "px"); width: expression(document.documentElement.clientWidth + "px"); height: expression(document.documentElement.clientHeight + "px"); } .slOverlayMode #slShim { display: block; z-index: 999; border: 0; filter: alpha(opacity=1); position: absolute; left: 0; top: 0; width: expression((document.documentElement.scrollLeft + document.documentElement.clientWidth) + "px"); height: expression((document.documentElement.scrollTop + document.documentElement.clientHeight) + "px"); }</style>'
      + '<iframe id="slShim" src="javascript:;"></iframe><![endif]--><div>';
    }
    
    var elements = ['slSearchNext', 'slSearchPrev'];
    for (var i = 0, element, length = elements.length; i < length; i++) {
      if (element = $(elements[i] + type)) {
        addEvent(element, 'click', function(e) {
          stopEvent(e);
          var elem = e.target || e.srcElement
              ,page = parseInt(elem.getAttribute('rel') || elem.rel, 10);
              
          if (!page || page < 1) return;
          sendRequest([new SearchAction(result.SearchType, result.SearchString, perPage, page), new UserKey(null)], (result.SearchType == 'User' ? memberCallback : contentCallback));
        });
      }
    }
  }
  
  (function addStyleToDocument(cssText) {
    var styles = SiteLifeProxy.stylesheet;
    if (!styles) {
      SiteLifeProxy.stylesheet = styles = document.documentElement.firstChild.appendChild(document.createElement('style'));
      if (styles.setAttribute) {
        styles.setAttribute('type', 'text\/css');
      }
      else {
        styles.type = 'text\/css';
      }
    }
    if (styles.styleSheet) {
      styles.styleSheet.cssText += cssText + '\n';
    }
    else {
      styles.appendChild(document.createTextNode(cssText + '\n'));
    }
  })(['.slContact { width: 300px; float: left; padding: 8px; margin: 0 10px 10px 0; border: 1px solid #ccc; }'
,'.slContact img, .slContact .slImage, .slBlogPost .slImage { float: left; }'
,'.slSearchSummary { padding-left: 1em; }'
,'#slSearchContainer .slContent { padding-left: 64px; }'
,'.slSearchNav { margin: 12px 0 20px 0; }'
,'.slSearchNav a { border: 1px solid #ccc; margin-right: 10px; font-size: 1em; padding: 6px; }'
,'#slSearchContainer { padding: 14px; }'
,'#slOverlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: black; z-index: 1001; -moz-opacity: 0.8; opacity:.80; filter: alpha(opacity=80); }'
,'#slModalDialog { display: none; position: fixed; top: 30%; left: 30%; width: 400px; height: 250px !important; padding: 16px; border: 1px solid orange; background-color: white; z-index: 1002; overflow: auto; }'
,'#slWarning { border: 2px solid #f99; font-size: 90%; font-weight: normal; background-color: #fdd; padding: 8px; margin: 8px 0; }'
,'#slModalContent { width: 98% }'
,'#slModalControls { margin-top: 10px; }'
,'#slCancel { margin-left: 10px; }'
,'.slOverlayMode #slOverlay, .slOverlayMode #slModalDialog { display: block !important; }'
,'#slNotification { text-align: center; font-weight: bold; height: 30px; font-size: 24px; margin: 10px 0; background-color: transparent !important; }'
,'#slNotification.slAttention { background-color: #F22E41 !important; color: #fff }'
/*
  Blog Posts 
*/
,'.slBlogPost { clear: both }'
// remove later
,'.slActions { display: block !important; }'
,'.slSearchNav a { display: inline !important; }'].join('\n'));
  function initSearch() {
    if (arguments.callee.called) return;
      arguments.callee.called = 1;
    
    var str = location.search, target = str.match(/[\?&]searchtext=([^&]+)/), type = str.match(/[\?&]searchtype=([^&]+)/), req = new RequestBatch();
    if (!target || !type) {
      var container = document.getElementById('slSearchContainer');
      if (container)
        container.innerHTML = '<span class="slNoSearchTerms">You can search for other doc2doc members by their real name. You can also search for people by specialty.<br/><br/>Click on friend request and you will be able to send them a message which will reach them via e-mail.</span>';
      return;
    }
    target = target[1];
    type = type[1];
    // Escape the search string in case there are quotes etc.
    //$('searchtext').value = target;
    
    if (type.toLowerCase() == 'member') {

      // Build up the fields we're going to search.
      
      // Everyone searches first and last
      var searchFields = ['l', 'f'];
      
      
      // If current is registered also search speciality, grade, location and about me
      // TODO: Add customer fields once BMJ have reviewed them
      if (document.cookie.indexOf('AT=') > -1)
        searchFields = searchFields.concat(['s', 'g', 'o', 'AboutMe', '4AE30964-B065-4d3d-8B40-7C93885EFC1E']); 
      
      // Now get the values we're going to search
      var searchValues = target.split('+'), params = [];

      // Go through each search field and add each search value to the search string
      var searchString = '';
      
      for (f = 0; f < searchFields.length; f++) {
        for (v = 0; v < searchValues.length; v ++) {
          searchString = searchString + searchFields[f] + ':' + searchValues[v] + ' ';
          params.push(searchFields[f] + ':' + searchValues[v]);
        }
      }
      sendRequest([new SearchAction('User', params.join(' '), 10, 1), new UserKey(null)], memberCallback);
    }
    else {
      var blogFields = ['Body', 'DisplayName', 'Tags', 'Title']
          ,forumFields = ['Body', 'DisplayName', 'Title']
          ,commentFields = ['Body', 'DisplayName'];
      sendRequest([new SearchAction('BlogPost', blogFields.join(':' + target + ' ') + ':' + target, 10, 1), new UserKey(null)], contentCallback);
      sendRequest([new SearchAction('Comment', commentFields.join(':' + target + ' ') + ':' + target, 10, 1), new UserKey(null)], contentCallback);
      sendRequest([new SearchAction('ForumPost', forumFields.join(':' + target + ' ') + ':' + target, 10, 1), new UserKey(null)], contentCallback);
    }
  }
  addEvent(document, 'DOMContentLoaded', initSearch);
  addEvent(window, 'load', initSearch);
})(RequestBatch.sitelifeBaseUrl || 'http://sitelife.bmj.com', RequestBatch.clientBaseUrl || 'http://doc2doc.bmj.com');