//var $jQuery = jQuery.noConflict();  /* Remove Javascript libary conflicts between Prototype and jQuery */

// To catch debugging output in browsers without Firebug!
if (typeof(console) == "undefined") {
  var console = {
    group:function() {},
    groupEnd:function() {},
    dir:function() {},
    log:function() {},
    info:function() {},
    warn:function() {},
    error:function() {}
  };
}

/**
 * Functions for displaying debugging info. Off by default, use
 * dbg.start() to begin dispaying output.
 */
var dbg = {
  debuggingOn: false,

  start: function() {
    dbg.debuggingOn = true;
  },
  stop: function() {
    dbg.debuggingOn = false;
  },

  dump: function(obj, name) {
    if (!dbg.debuggingOn) return;
    n = name || "[" + typeof(obj) + "]";
    console.group(n);
    console.dir(obj);
    console.groupEnd();
  },

  logreq: function(req) { dbg.dump(req, "RequestBatch"); },
  logresp: function(resp) { dbg.dump(req, "RequestBatch"); },

  log: function() {
    if (dbg.debuggingOn)
      console.log.apply(arguments);
  },
  info: function() {
    if (dbg.debuggingOn)
      console.info.apply(arguments);
  },
  warn: function() {
    if (dbg.debuggingOn)
      console.warn.apply(arguments);
  },
  error: function() {
    if (dbg.debuggingOn)
      console.error.apply(arguments);
  }
};

/*
 * jQuery code.
 */
(function($) {

  $(document).ready(function() {
    populateElement('#search', 'Search the International Forum site');
    populateElement('#groupSearchGadget', 'Search all BMJ Products');

    popUp(); /* all A tags with a reference 'rel="external"' will be opened in a pop-up window */

    /*
        Script for doing clickable AJAX popups.
    */
    $(".clicky").click(function(e) {
      var ypos = $(document).scrollTop() + 50;
      $("#popupbox")
        .css("top", "ypos")
        .fadeIn("fast");
      $("#clickycontent")
        .load($(e.target).attr("href") + ' #content .plain', null, function() {
           $("#loadingclicky").hide();
        });

      $("#main").addClass("faded");
      return false;
    });

    $(".closeclicky").click(function() {
      $("#popupbox").fadeOut("fast", function() {
         $("#loadingclicky").show();
         $("#clickycontent").html("&nbsp;");
      });

      $("#main").removeClass("faded");
      return false;
    });

    /* Google Analytics tracker code */
    $.gaTracker('UA-2457497-2');
  });


  /* doc2doc JS */

  /*
   * Extra jQuery selector functions.
   */
  $.extend($.expr[":"], {

    /*
     * Match user data stored on elements using $().data -
     * :data(key) matches all elements with data stored under
     * the given key, :data matches elements with any data.
     */
    data: function(a, pos, m) {
      var e = $(a).get(0), cid = $.data(e), keys = $.keys($.cache[cid]);
      // Check there is a value set for the given key.
      return m[3] ? $.inArray(m[3], keys) : !!keys.length;
    },

    nodetype: function(elem, pos, matches) {
      return elem.nodeType && jQuery.inArray(String(elem.nodeType), matches[3].split(",")) != -1;
    }

  });

  $.each(["attrs", ["styles", "css"], "positions"], function(i, v) {
    if (typeof v == "string") {
      v = [v, v.substr(0, v.length - 1)];
    }
    //console.info("v0: %o, v1: %o", v[0], v[1]);

    $.fn[v[0]] = function() {
      var r = [], args = $.makeArray(arguments);
      this.each(function() {
        //console.log("this: %o, arguments: %o, v: %o", this, args, v);
        r.push($(this)[v[1]].apply($(this), args));
      });
      return r;
    }
  });

  /*
   * Global methods attached to jQuery object.
   */
  $.extend({

    isUndefined: function(obj) { return typeof obj == "undefined"; },
    isDefined: function(obj) { return typeof obj != "undefined"; },
    isObject: function(obj) { return typeof obj == "object"; },


    keys: function keys(obj) {
      if (typeof obj != "object") return [];
       var keys = [];
       for (var k in obj) { keys.push(k); }
       return keys;
    },

    // Return elements in first but not in second.
    diff: function(A, B) {
      if (!B) return A.slice(0);
      return $.grep(A, function(v) { return $.inArray(v, B) == -1; });
    },

    // Quick func to substitute values in strings.
    fmt: function fmt() {
      var a = $.makeArray(arguments), s = a.shift(), data = a.shift() || {};
      //console.log("s: %s, data: %o", s, data);
      return s.replace(/{([^{}]*)}/g, function(orig, k) {
        return k in data ? String(data[k]) : orig;
      });
    },

    parseuri: (function() {
      var parser = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/;
      var queryKeyParser = /(?:^|&)([^&=]*)=?([^&]*)/g;
      var keys = ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];

      return function(url) {
        var m = parser.exec(url || location.href), urlinfo = { }, i = keys.length + 1;

        while (--i) { urlinfo[keys[i]] = m[i] || ""; }

        urlinfo.queryKey = {};
        urlinfo.query.replace(queryKeyParser, function($0, $1, $2) {
          if ($1) urlinfo.queryKey[$1] = $2;
        });

        return urlinfo;
      };
    })(),

    uniqueId: (function() {
      var cur = 1000;

      return function(prefix) {
        return (prefix || "ixx") + cur++;
      }
    })(),

    pluckCommentWidget: {
      defaultOptions: {
        numberOfComments: 5
      }
    }
  });


  /*
   * New methods that apply to all elements currently selected.
   */

  /*
   * Include a new latest discussions widget into the selected
   * node e.g.
   *
   *   $("#discussions").latestDiscussions({ title: "Recent posts" });
   */
  $.fn.latestDiscussions = function(options) {
    var self = this, opt = $.extend({}, $.fn.latestDiscussions.prototype.defaultOptions, options);

    // Build widget on each matched element.
    this.each(function() {
      // Generate body of discussions widget.
      var h = "<div class='padding'><h2>{title}</h2>"
        + "<div class='rd-container'><table cellspacing='0' cellpadding='0' /></div>"
        + "<div class='more'><div><a target='_blank' href='{moreDiscussionsUrl}'>{moreDiscussionsText}</a></div></div>"
        + "</div>";
      h = $.fmt(h, opt);

      $(this)
        .addClass("recentdiscussions")
        .append($(h));
    });

    // Build request.
    var requestBatch = new RequestBatch();

    if (!opt.groupKeys) {
      // If no group keys are defined, search all forums for recent posts.
      requestBatch.AddToRequest(new DiscoverContentAction([], [], [],
        new Activity("Recent"), new ContentType("Discussion"),
        opt.ageOfItems, opt.numberOfItems));
    }
    else {
      // Only search the forums specified by the groupKeys array.
      for (var i = 0; i < opt["groupKeys"].length; i++) {
        requestBatch.AddToRequest(new CommunityGroupRecentForumDiscussions(
          new CommunityGroupKey(opt.groupKeys[i]), opt.ageOfItems, opt.numberOfItems));
      }
    }

    // Do request and process results.
    requestBatch.BeginRequest(serverUrl, function(response) {
      if (response.Responses.length == 0) return;
      var discussions = response.Responses[0].CommunityGroupRecentForumDiscussions.Discussions;

      for (var i = 0; i < discussions.length; i++) {
        var uri = $.parseuri(discussions[i].DiscussionUrl);

        // Extract group key from discussion url.
        var gk = unescape(uri.query).match(/CommGroup([a-f0-9-]{36})\|/)[1];

        // Hack a working url pointing to the discussion.
        var newurl = $.fmt("{protocol}://{host}/{path}?slPage=showDiscussionPost&", uri);
        newurl += $.fmt("slGroupKey={groupkey}&slForumPostKey={postkey}", {
          groupkey: gk,
          postkey: uri.queryKey.plckDiscussionId
        });

        // Add new row to discussions table.
        $("table", self).each(function() {
          var tr = "<tr><td class='tdright'><div class='discussion-title'>"
            + "<a href='{url}' target='{target}'>{title}...</a></div></td></tr>"
          tr = $.fmt(tr, {
            url: newurl,
            title: discussions[i].DiscussionTitle,
            target: opt.linkTarget
          });

          $(this).append($(tr));
        });
      }

      // Final bits of styling etc. now the entire component is built.
      $("tr:odd", self).addClass("td-altrow");
      $("a", self).attr("target", "_blank");
    });

    return this;
  }
  $.fn.latestDiscussions.prototype.defaultOptions = {
    title: "Latest discussions",
    moreDiscussionsUrl: "/forums.html",
    moreDiscussionsText: "More discussions >>",
    numberOfItems: 8,
    ageOfItems: 15,
    groupKeys: null,
    showAuthor: true,
    showAvatar: true,
    linkTarget: ""
  };

  /*
   * More initialisation once the page has loaded.
   */
  $(function() {
    // Recent discussions.
    $("<div id='recent-discussion-widget'></div>")
      .insertAfter("#right-column-button-box")
      .wrap("<div id='right-column-button-box'></div>")
      .latestDiscussions({
        title: "Discuss the International Forum on doc2doc",
        groupKeys: [ "f1ee0d38-22c5-450d-9f33-40bf110975f7" ],
        linkTarget: "tod2dforum",
        moreDiscussionsUrl: "http://doc2doc.bmj.com/forums.html?slPage=overview&slGroupKey=f1ee0d38-22c5-450d-9f33-40bf110975f7" //slAcceptInvitation=false
      });
  });

  /****************************************************************/

  /*
   * Inserts a new standard Pluck comments widget after each
   * selected element that hasn't already got one.
   */
  $.fn.addCommentWidgets = function(options) {
    var options = $.extend({}, this.defaultOptions, options);

    return this.each(function() {
      // Check for whether we've got a widget here already.
      var cid = $(this).data("pluck-comments-key");

      if ($.isUndefined(cid)) {
        // Generate a key for the new widget
        cid = options.keyfunc($(this).get(0));

        var wid = "Comments_Container" + ($.fn.addCommentWidgets.nextWidgetId++);
        //var html = , { id: wid });

        // Insert a new widget and store its unique key
        // in this element's user data.
        $(this)
          .data("pluck-comments-key", cid)
          .parent()
          .append($("<div class='comment_widget_container'></div>").attr("id", wid))
          .wrapInner("<div class='poster-link'></div>");

        // gSiteLife.GetComments(parentKeyType, parentKey, parentUrl, parentTitle, 0, pageSize, sort,
        //   showTabs, tab, hideView, hideInput, redirectToUrl, refreshPage, divId)
        gSiteLife.GetComments("ExternalResource", cid, undefined, undefined, undefined, options.numberOfComments,
          undefined, undefined, undefined, false, false, null, undefined, wid);
      }
    });
  }


  /*
   * More initialisation once the page has loaded.
   */
  $(function($) {

    function istext(n) { return n.nodeType == 3; }
    function iselem(n) { return n.nodeType == 1; }
    function istag(n, t) { return n.nodeType == 1 && n.tagName == t; }

    // Filters out text nodes containing only punctuation.
    function hasTextContent(n) {
      if (!istext(n))
        return true;
      return $.trim(n.wholeText).replace(/[^\w]/g, "").length > 0;
    }

    /*
     * If we're on a page which could have poster links, then
     * search for a <ul>...</ul> containing links to PDFs to process.
     */
    var u = $.parseuri(), options = $.pluckCommentWidget.defaultOptions;

    //if (u.path == "/about-the-forum/2008-forum/main-themes/comments-test") {
      $("#region-content div.plain ul").each(function() {
        if ($(this).find("a[href$=.pdf]").length == 0) {
          return;
        }

        $(this).children().each(function() {
          var hasPdfLink = $(this).children().filter("a[href$=.pdf]").length > 0;
          //console.group();
          //console.info("pdf: %s", hasPdfLink);

          // Filter out any word tags.
          var c = $(this).contents(":nodetype(1,3):not(link):not(style)"); /*.filter(function() {
            return istext(this) || (iselem(this) && $.inArray(this.tagName, ["LINK", "STYLE"]) == -1);
          });*/

          var title = $("<div class='poster-title'></div>");
          var details = $("<div class='poster-details'></div>");

          var container = $("<div class='poster-container'></div>")
            .append(title)
            .append(details)
            .appendTo("div.plain");

          if (hasPdfLink) {
            title.append("<img src='/images/icon-pdf.gif' />").append(c.slice(0, 2));

            // Get rid of rogue commas at the start of the details section.
            var sl = c.slice(2);
            if (!hasTextContent(sl[0]))
              sl = sl.slice(1);
            details.append(sl);

            var widgetid = $.uniqueId("Comments_Container"),
              commentKey = escape(u.host + "#" + unescape(c[1].href));
            //console.info("commentKey: %s", commentKey);
            //console.info("widgetid: %s, options: %o", widgetid, options);

            container.append("<div id='" + widgetid + "' class='comment_widget_container'></div>");

            gSiteLife.GetComments("ExternalResource", commentKey, undefined, undefined, undefined, options.numberOfComments,
              undefined, undefined, undefined, false, false, null, undefined, widgetid);
          }
          else {
            title.append(c[0]);
            details.append(c.slice(1));
          }

          //console.log("Title: %s", title.html());
          //console.log("Details: %s", details.html());
          //console.groupEnd();
        })
        .end().hide();
      });
    //}

  });

});

//added by dberhane for right column widget

$(function() {

populateElement('#search', 'Search the International Forum site');
	
populateElement('#groupSearchGadget', 'Search all BMJ Products');


popUp(); /* all A tags with a reference 'rel="external"' will be opened in a pop-up window */ 

var widget1 = new widget(
{

	'widget'	:	"feeds-widget1",
	'url'	:	"www.bmj.com/rss/recent.xml", 
	'track'	:	"w_bmjgblogs_latestbmj",
	'widget_title'	:	"Latest from BMJ",	
	'style'	:	"bmj",	
	'num_items':	"5"


}
)


var widget2 = new widget(
{
	'widget'	:	"feeds-widgetd2d",
	'url'	:	"http://sitelife.bmj.com/ver1.0/CommunityGroups/Rss?slGroupKey=f1ee0d38-22c5-450d-9f33-40bf110975f7",
	'track'	:	"w_int_forum",
	'widget_title'	:	"Latest discussions on doc2doc",	
    'desc_len': "0",
	'style'	:	"bmj",	
	'num_items':	"4"
})



})


// })($jQuery);
